You are here

public function SelectQuery_sqlsrv::preExecute in Drupal driver for SQL Server and SQL Azure 7

Same name and namespace in other branches
  1. 7.3 sqlsrv/select.inc \SelectQuery_sqlsrv::preExecute()
  2. 7.2 sqlsrv/select.inc \SelectQuery_sqlsrv::preExecute()

Override for SelectQuery::preExecute().

Ensure that all the fields in ORDER BY and GROUP BY are part of the main query.

Overrides SelectQuery::preExecute

File

sqlsrv/select.inc, line 11

Class

SelectQuery_sqlsrv

Code

public function preExecute(SelectQueryInterface $query = NULL) {

  // If no query object is passed in, use $this.
  if (!isset($query)) {
    $query = $this;
  }

  // Only execute this once.
  if ($this
    ->isPrepared()) {
    return TRUE;
  }

  // Execute standard pre-execution first.
  parent::preExecute($query);
  if ($this->distinct || $this->group) {

    // When the query is DISTINCT or contains GROUP BY fields, all the fields
    // in the GROUP BY and ORDER BY clauses must appear in the returned
    // columns.
    $columns = $this->order + array_flip($this->group);
    $counter = 0;
    foreach ($columns as $field => $dummy) {
      if (!isset($this->fields[$field]) && !isset($this->expressions[$field])) {
        $alias = '_field_' . $counter++;
        $this
          ->addExpression($field, $alias);
        $this->queryOptions['sqlsrv_drop_columns'][] = $alias;
      }
    }

    // More over, GROUP BY columns cannot use aliases, so expand them to
    // their full expressions.
    foreach ($this->group as $key => &$group_field) {

      // Expand an alias on a field.
      if (isset($this->fields[$group_field])) {
        $field = $this->fields[$group_field];
        $group_field = (isset($field['table']) ? $this->connection
          ->escapeTable($field['table']) . '.' : '') . $this->connection
          ->escapeField($field['field']);
      }
      else {
        if (isset($this->expressions[$group_field])) {
          $expression = $this->expressions[$group_field];
          $group_field = $expression['expression'];

          // If the expression has arguments, we now
          // have duplicate placeholders. Run as insecure.
          if (is_array($expression['arguments'])) {
            $this->queryOptions['insecure'] = TRUE;
          }
        }
      }
    }
  }
  return $this->prepared;
}