Definition

db_rewrite_sql($query, $primary_table = 'n', $primary_field = 'nid', $args = array())
drupal/includes/database.inc, line 236

Description

Rewrites node queries.

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, 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

Namesort iconDescription
Database abstraction layerAllow the use of different database servers using the same code base.

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) {
    $field_to_select = 'DISTINCT('. $primary_table .'.'. $primary_field .')';
    // (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT).
    $query = preg_replace('/(SELECT.*)('. $primary_table .'\.)?(?<!DISTINCT\()(?<!DISTINCT\('. $primary_table .'\.)'. $primary_field .'(.*FROM)/AUsi', '\1'. $field_to_select .'\3', $query);
  }

  if (!empty($join)) {
    $query = preg_replace('|FROM[^[:upper:]/,]+|','\0 '. $join .' ', $query);
  }

  if (!empty($where)) {
    if (strpos($query, 'WHERE')) {
      $replace = 'WHERE';
      $add = 'AND';
    }
    elseif (strpos($query, 'GROUP')) {
      $replace = 'GROUP';
      $add = 'GROUP';
    }
    elseif (strpos($query, 'ORDER')) {
      $replace = 'ORDER';
      $add = 'ORDER';
    }
    elseif (strpos($query, 'LIMIT')) {
      $replace = 'LIMIT';
      $add = 'LIMIT';
    }
    else {
      $query .= ' WHERE '. $where;
    }
    if (isset($replace)) {
      $query = str_replace($replace, 'WHERE  '. $where .' '. $add .' ', $query);
    }
  }

  return $query;
}