You are here

function db_rewrite_sql in Drupal 4

Same name and namespace in other branches
  1. 5 includes/database.inc \db_rewrite_sql()
  2. 6 includes/database.inc \db_rewrite_sql()

Rewrites node, taxonomy and comment queries. Use it for listing queries. Do not use FROM table1, table2 syntax, use JOIN instead.

Parameters

$query: Query to be rewritten.

$primary_table: Name or alias of the table which has the primary key field for this query. Possible values are: comments, forum, node, menu, term_data, vocabulary.

$primary_field: Name of the primary field.

$args: An array of arguments, passed to the implementations of hook_db_rewrite_sql.

Return value

The original query with JOIN and WHERE statements inserted from hook_db_rewrite_sql implementations. nid is rewritten if needed.

Related topics

48 calls to db_rewrite_sql()
archive_calendar in modules/archive.module
Generates a monthly calendar, for display in the archive block.
archive_page in modules/archive.module
Menu callback; lists all nodes posted on a given date.
blog_block in modules/blog.module
Implementation of hook_block().
blog_feed_last in modules/blog.module
Displays an RSS feed containing recent blog entries of all users.
blog_feed_user in modules/blog.module
Displays an RSS feed containing recent blog entries of a given user.

... See full list

File

includes/database.inc, line 277
Wrapper for database interface code.

Code

function db_rewrite_sql($query, $primary_table = 'n', $primary_field = 'nid', $args = array()) {
  list($join, $where, $distinct) = _db_rewrite_sql($query, $primary_table, $primary_field, $args);
  if ($distinct) {
    $query = db_distinct_field($primary_table, $primary_field, $query);
  }
  if (!empty($where) || !empty($join)) {
    if (!empty($where)) {
      $new = "WHERE {$where} ";
    }
    $new = " {$join} {$new}";
    if (strpos($query, 'WHERE')) {
      $query = str_replace('WHERE', $new . 'AND (', $query);
      $insert = ') ';
    }
    else {
      $insert = $new;
    }
    if (strpos($query, 'GROUP')) {
      $replace = 'GROUP';
    }
    elseif (strpos($query, 'ORDER')) {
      $replace = 'ORDER';
    }
    elseif (strpos($query, 'LIMIT')) {
      $replace = 'LIMIT';
    }
    else {
      $query .= $insert;
    }
    if (isset($replace)) {
      $query = str_replace($replace, $insert . $replace, $query);
    }
  }
  return $query;
}