You are here

public function Select::countQuery in Drupal driver for SQL Server and SQL Azure 8.2

Same name and namespace in other branches
  1. 8 drivers/lib/Drupal/Driver/Database/sqlsrv/Select.php \Drupal\Driver\Database\sqlsrv\Select::countQuery()

This is like the default countQuery, but does not optimize field (or expressions) that are being used in conditions.

Overrides Select::countQuery

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Select.php, line 425
Definition of Drupal\Driver\Database\sqlsrv\Select

Class

Select

Namespace

Drupal\Driver\Database\sqlsrv

Code

public function countQuery() {

  // Create our new query object that we will mutate into a count query.
  $count = clone $this;
  $group_by = $count
    ->getGroupBy();
  $having = $count
    ->havingConditions();
  if (!$count->distinct && !isset($having[0])) {
    $used_aliases = [];
    $this
      ->GetUsedAliases($count->condition, $used_aliases);

    // When not executing a distinct query, we can zero-out existing fields
    // and expressions that are not used by a GROUP BY or HAVING. Fields
    // listed in a GROUP BY or HAVING clause need to be present in the
    // query.
    $fields =& $count
      ->getFields();
    foreach ($fields as $field => $value) {
      if (empty($group_by[$field]) && !isset($used_aliases[$value['alias']])) {
        unset($fields[$field]);
      }
    }
    $expressions =& $count
      ->getExpressions();
    foreach ($expressions as $field => $value) {
      if (empty($group_by[$field]) && !isset($used_aliases[$value['alias']])) {
        unset($expressions[$field]);
      }
    }

    // Also remove 'all_fields' statements, which are expanded into tablename.*
    // when the query is executed.
    foreach ($count->tables as $alias => &$table) {
      unset($table['all_fields']);
    }
  }

  // If we've just removed all fields from the query, make sure there is at
  // least one so that the query still runs.
  $count
    ->addExpression('1');

  // Ordering a count query is a waste of cycles, and breaks on some
  // databases anyway.
  $orders =& $count
    ->getOrderBy();
  $orders = [];
  if ($count->distinct && !empty($group_by)) {

    // If the query is distinct and contains a GROUP BY, we need to remove the
    // distinct because SQL99 does not support counting on distinct multiple fields.
    $count->distinct = false;
  }
  $query = $this->connection
    ->select($count);
  $query
    ->addExpression('COUNT(*)');
  return $query;
}