1. drupal
    1. 5
    2. 6
5 – 6 db_rewrite_sql($query, $primary_table = 'n', $primary_field = 'nid', $args = array())

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


$query Query to be rewritten.

$primary_table Name or alias of the table which has the primary key field for this query. Typical table names would be: {blocks}, {comments}, {forum}, {node}, {menu}, {term_data} or {vocabulary}. However, it is more common to use the the usual table aliases: b, c, f, n, m, t or v.

$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

▾ 44 functions call db_rewrite_sql()

block_list in modules/block/block.module
Return all blocks in the specified region for the current user.
blogapi_mt_validate_terms in modules/blogapi/blogapi.module
Blogging API helper - find allowed taxonomy terms for a node type.
blog_block in modules/blog/blog.module
Implementation of hook_block().
blog_feed_last in modules/blog/blog.pages.inc
Menu callback; displays an RSS feed containing recent blog entries of all users.
blog_feed_user in modules/blog/blog.pages.inc
Menu callback; displays an RSS feed containing recent blog entries of a given user.
blog_page_last in modules/blog/blog.pages.inc
Menu callback; displays a Drupal page containing recent blog entries of all users.
blog_page_user in modules/blog/blog.pages.inc
Menu callback; displays a Drupal page containing recent blog entries of a given user.
book_block in modules/book/book.module
Implementation of hook_block().
book_get_books in modules/book/book.module
Returns an array of all books.
comment_get_recent in modules/comment/comment.module
Find a number of recent comments. This is done in two steps. 1. Find the n (specified by $number) nodes that have the most recent comments. This is done by querying node_comment_statistics which has an index on last_comment_timestamp, and is thus a…
comment_render in modules/comment/comment.module
Renders comment(s).
forum_block in modules/forum/forum.module
Implementation of hook_block().
forum_get_forums in modules/forum/forum.module
Returns a list of all forums for a given taxonomy id
forum_get_topics in modules/forum/forum.module
forum_term_load in modules/forum/forum.module
Fetch a forum term.
menu_tree_check_access in includes/menu.inc
Check access and perform other dynamic operations for each link in the tree.
node_admin_nodes in modules/node/node.admin.inc
Form builder: Builds the node administration overview.
node_feed in modules/node/node.module
A generic function for generating RSS feeds from a set of nodes.
node_page_default in modules/node/node.module
Menu callback; Generate a listing of promoted nodes.
poll_block in modules/poll/poll.module
Implementation of hook_block().
poll_page in modules/poll/poll.pages.inc
Menu callback to provide a simple list of all polls available.
statistics_title_list in modules/statistics/statistics.module
Returns all time or today top or last viewed node(s).
taxonomy_autocomplete in modules/taxonomy/taxonomy.pages.inc
Helper function for autocompletion
taxonomy_form_alter in modules/taxonomy/taxonomy.module
Implementation of hook_form_alter(). Generate a form for selecting terms to associate with a node. We check for taxonomy_override_selector before loading the full vocabulary, so contrib modules can intercept before hook_form_alter and provide scalable…
taxonomy_get_children in modules/taxonomy/taxonomy.module
Find all children of a term ID.
taxonomy_get_parents in modules/taxonomy/taxonomy.module
Find all parents of a given term ID.
taxonomy_get_term_by_name in modules/taxonomy/taxonomy.module
Try to map a string to an existing term, as for glossary use.
taxonomy_get_tree in modules/taxonomy/taxonomy.module
Create a hierarchical representation of a vocabulary.
taxonomy_get_vocabularies in modules/taxonomy/taxonomy.module
Return an array of all vocabulary objects.
taxonomy_node_get_terms in modules/taxonomy/taxonomy.module
Find all terms associated with the given node, ordered by vocabulary and term weight.
taxonomy_node_get_terms_by_vocabulary in modules/taxonomy/taxonomy.module
Find all terms associated with the given node, within one vocabulary.
taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Form builder for the taxonomy terms overview.
taxonomy_select_nodes in modules/taxonomy/taxonomy.module
Finds all nodes that match selected taxonomy conditions.
taxonomy_term_count_nodes in modules/taxonomy/taxonomy.module
Count the number of published nodes classified by a term.
taxonomy_term_page in modules/taxonomy/taxonomy.pages.inc
Menu callback; displays all nodes associated with a term.
template_preprocess_forum_topic_navigation in modules/forum/forum.module
Preprocess variables to format the next/previous forum topic navigation links.
tracker_page in modules/tracker/tracker.pages.inc
Menu callback. Prints a listing of active nodes on the site.
translation_node_get_translations in modules/translation/translation.module
Get all nodes in a translation set, represented by $tnid.
_blog_post_exists in modules/blog/blog.module
Helper function to determine if a user has blog posts already.
_forum_new in modules/forum/forum.module
Finds the first unread node for a given forum.
_forum_topics_unread in modules/forum/forum.module
Calculate the number of nodes the user has not yet read and are newer than NODE_NEW_LIMIT.
_node_types_build in modules/node/node.module
Builds and returns the list of available node types.
_token_example_get_comment in examples/token_example/token_example.module
Build a list of available comments.
_token_example_get_node in examples/token_example/token_example.module
Build a list of available content.


includes/database.inc, line 328

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)) {
    $pattern = '{
      # Beginning of the string
        # Everything within this set of parentheses is named "anonymous view"
          [^()]++                   # anything not parentheses
          \( (?P>anonymous_view) \)          # an open parenthesis, more "anonymous view" and finally a close parenthesis.
    preg_match($pattern, $query, $matches);
    if (!$where) {
      $where = '1 = 1';
    if ($matches) {
      $n = strlen($matches[1]);
      $second_part = substr($query, $n);
      $first_part = substr($matches[1], 0, $n - 5) . " $join WHERE $where AND ( ";
      // PHP 4 does not support strrpos for strings. We emulate it.
      $haystack_reverse = strrev($second_part);
    else {
      $haystack_reverse = strrev($query);
    // No need to use strrev on the needle, we supply GROUP, ORDER, LIMIT
    // reversed.
    foreach (array('PUORG', 'REDRO', 'TIMIL') as $needle_reverse) {
      $pos = strpos($haystack_reverse, $needle_reverse);
      if ($pos !== FALSE) {
        // All needles are five characters long.
        $pos += 5;
    if ($matches) {
      if ($pos === FALSE) {
        $query = $first_part . $second_part . ')';
      else {
        $query = $first_part . substr($second_part, 0, -$pos) . ')' . substr($second_part, -$pos);
    elseif ($pos === FALSE) {
      $query .= " $join WHERE $where";
    else {
      $query = substr($query, 0, -$pos) . " $join WHERE $where " . substr($query, -$pos);

  return $query;