From 993ea0c6c5a07cf9c2edadf2c0f6a378cde56acb Mon Sep 17 00:00:00 2001 From: Dries Buytaert Date: Sat, 29 Jan 2005 22:02:37 +0000 Subject: - Patch #16111 by chx: generalized node_rewrite_query to db_rewrite_query. --- includes/database.inc | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) (limited to 'includes/database.inc') diff --git a/includes/database.inc b/includes/database.inc index 0148f328d..e2d8057b6 100644 --- a/includes/database.inc +++ b/includes/database.inc @@ -168,6 +168,98 @@ function db_queryd($query) { return _db_query($query, 1); } +/** + * Helper function for db_rewrite_sql. + * + * Collects JOIN and WHERE statements via hook_sql. + * Decides whether to select primary_key or DISTINCT(primary_key) + * + * @param $query + * query to be rewritten + * @param $primary_table + * Name or alias of the table which has the primary key field for this query. Possible values are: comments, forum, node, taxonomy, vocabulary + * @param $primary_key + * name of the primary key field. + * @param $args + * array of additional args + * @return + * An array: join statements, where statements, field or DISTINCT(field) + */ +function _db_rewrite_sql($query = '', $primary_table = 'n', $primary_key = 'nid', $args = array()) { + $where = array(); + $join = array(); + $distinct = FALSE; + foreach (module_implements('db_rewrite_sql') as $module) { + $result = module_invoke($module, 'db_rewrite_sql', $query, $primary_table, $primary_key, $args); + if (is_array($result)) { + if (isset($result['where'])) { + $where[] .= $result['where']; + } + if (isset($result['join'])) { + $join[] .= $result['join']; + } + if (isset($result['distinct']) && $result['distinct']) { + $distinct = TRUE; + } + } + elseif (isset($result)) { + $where[] .= $result; + } + } + + $where = empty($where) ? '' : '('. implode(') AND (',$where).')'; + $join = empty($join) ? '' : implode(' ',$join); + $field = $primary_table .'.'. $primary_key; + + return array($join, $where, $distinct ? 'DISTINCT('. $field .')' : $field); +} + +/** + * Rewrites node queries. + * + * @param $query + * query to be rewritten + * @param $primary_table + * Name or alias of the table which has the primary key field for this query. Possible values are: comments, forum, node, taxonomy, vocabulary + * @param $primary_key + * name of the primary key field. + * @param $args + * an array of arguments, passed to the implementations of hook_db_rewrite_sql + * @return + * The original query with JOIN and WHERE statements inserted from hook_db_rewrite_sql implementations. nid is rewritten if needed. + */ +function db_rewrite_sql($query, $primary_table = 'n', $primary_key = 'nid', $args = array()) { + list($join, $where, $field_to_select) = _db_rewrite_sql($query, $primary_table, $primary_key, $args); + + // (?