You are here

public function Connection::query in Drupal driver for SQL Server and SQL Azure 4.2.x

Same name and namespace in other branches
  1. 3.1.x src/Driver/Database/sqlsrv/Connection.php \Drupal\sqlsrv\Driver\Database\sqlsrv\Connection::query()
  2. 4.0.x src/Driver/Database/sqlsrv/Connection.php \Drupal\sqlsrv\Driver\Database\sqlsrv\Connection::query()
  3. 4.1.x src/Driver/Database/sqlsrv/Connection.php \Drupal\sqlsrv\Driver\Database\sqlsrv\Connection::query()

Executes a query string against the database.

This method provides a central handler for the actual execution of every query. All queries executed by Drupal are executed as PDO prepared statements.

This method is overriden to manage EMULATE_PREPARE behaviour to prevent some compatibility issues with SQL Server.

Parameters

string|\Drupal\Core\Database\StatementInterface|\PDOStatement $query: The query to execute. In most cases this will be a string containing an SQL query with placeholders. An already-prepared instance of StatementInterface may also be passed in order to allow calling code to manually bind variables to a query. If a StatementInterface is passed, the $args array will be ignored. It is extremely rare that module code will need to pass a statement object to this method. It is used primarily for database drivers for databases that require special LOB field handling.

array $args: An array of arguments for the prepared statement. If the prepared statement uses ? placeholders, this array must be an indexed array. If it contains named placeholders, it must be an associative array.

mixed $options: An associative array of options to control how the query is run. The given options will be merged with self::defaultOptions(). See the documentation for self::defaultOptions() for details. Typically, $options['return'] will be set by a default or by a query builder, and should not be set by a user.

Return value

\Drupal\Core\Database\Statement|int|string|null This method will return one of the following:

  • If either $options['return'] === self::RETURN_STATEMENT, or $options['return'] is not set (due to self::defaultOptions()), returns the executed statement.
  • If $options['return'] === self::RETURN_AFFECTED, returns the number of rows affected by the query (not the number matched).
  • If $options['return'] === self::RETURN_INSERT_ID, returns the generated insert ID of the last query.
  • If either $options['return'] === self::RETURN_NULL, or an exception occurs and $options['throw_exception'] evaluates to FALSE, returns NULL.

Throws

\Drupal\Core\Database\DatabaseExceptionWrapper

\Drupal\Core\Database\IntegrityConstraintViolationException

\InvalidArgumentException

Overrides Connection::query

See also

\Drupal\Core\Database\Connection::defaultOptions()

2 calls to Connection::query()
Connection::queryRange in src/Driver/Database/sqlsrv/Connection.php
Runs a limited-range query on this database object.
Connection::queryTemporary in src/Driver/Database/sqlsrv/Connection.php
Runs a SELECT query and stores its results in a temporary table.

File

src/Driver/Database/sqlsrv/Connection.php, line 521

Class

Connection
Sqlsvr implementation of \Drupal\Core\Database\Connection.

Namespace

Drupal\sqlsrv\Driver\Database\sqlsrv

Code

public function query($query, array $args = [], $options = []) {

  // Use default values if not already set.
  $options += $this
    ->defaultOptions();
  assert(!isset($options['target']), 'Passing "target" option to query() has no effect. See https://www.drupal.org/node/2993033');

  // We allow either a pre-bound statement object (deprecated) or a literal
  // string. In either case, we want to end up with an executed statement
  // object, which we pass to StatementInterface::execute.
  if (is_string($query)) {
    $this
      ->expandArguments($query, $args);
    $emulate = isset($options['emulate_prepares']) ? $options['emulate_prepares'] : FALSE;

    // Try to detect duplicate place holders, this check's performance
    // is not a good addition to the driver, but does a good job preventing
    // duplicate placeholder errors.
    $argcount = count($args);
    if ($emulate === TRUE || $argcount >= 2100 || $argcount != substr_count($query, ':')) {
      $emulate = TRUE;
    }
    $options['emulate_prepares'] = $emulate;

    // Replace CONCAT_WS to ensure SQL Server 2016 compatibility.
    while (($pos1 = strpos($query, 'CONCAT_WS')) !== FALSE) {

      // We assume the the separator does not contain any single-quotes
      // and none of the arguments contain commas.
      $pos2 = $this
        ->findParenMatch($query, $pos1 + 9);
      $argument_list = substr($query, $pos1 + 10, $pos2 - 10 - $pos1);
      $arguments = explode(', ', $argument_list);
      $closing_quote_pos = stripos($argument_list, '\'', 1);
      $separator = substr($argument_list, 1, $closing_quote_pos - 1);
      $strings_list = substr($argument_list, $closing_quote_pos + 3);
      $arguments = explode(', ', $strings_list);
      $replace = "STUFF(";
      $coalesce = [];
      foreach ($arguments as $argument) {
        if (substr($argument, 0, 1) == ':') {
          $args[$argument . '_sqlsrv_concat'] = $args[$argument];
          $coalesce[] = "CASE WHEN {$argument} IS NULL THEN '' ELSE CONCAT('{$separator}', {$argument}_sqlsrv_concat) END";
        }
        else {
          $coalesce[] = "CASE WHEN {$argument} IS NULL THEN '' ELSE CONCAT('{$separator}', {$argument}) END";
        }
      }
      $coalesce_string = implode(' + ', $coalesce);
      $sep_len = strlen($separator);
      $replace = "STUFF({$coalesce_string}, 1, {$sep_len}, '')";
      $query = substr($query, 0, $pos1) . $replace . substr($query, $pos2 + 1);
    }
    $stmt = $this
      ->prepareStatement($query, $options);
  }
  elseif ($query instanceof StatementInterface) {
    @trigger_error('Passing a StatementInterface object as a $query argument to ' . __METHOD__ . ' is deprecated in drupal:9.2.0 and is removed in drupal:10.0.0. Call the execute method from the StatementInterface object directly instead. See https://www.drupal.org/node/3154439', E_USER_DEPRECATED);
    $stmt = $query;
  }
  elseif ($query instanceof \PDOStatement) {
    @trigger_error('Passing a \\PDOStatement object as a $query argument to ' . __METHOD__ . ' is deprecated in drupal:9.2.0 and is removed in drupal:10.0.0. Call the execute method from the StatementInterface object directly instead. See https://www.drupal.org/node/3154439', E_USER_DEPRECATED);
    $stmt = $query;
  }
  try {
    if (is_string($query)) {
      $stmt
        ->execute($args, $options);
    }
    elseif ($query instanceof StatementInterface) {
      $stmt
        ->execute(NULL, $options);
    }
    elseif ($query instanceof \PDOStatement) {
      $stmt
        ->execute();
    }

    // Depending on the type of query we may need to return a different value.
    // See DatabaseConnection::defaultOptions() for a description of each
    // value.
    switch ($options['return']) {
      case Database::RETURN_STATEMENT:
        return $stmt;
      case Database::RETURN_AFFECTED:
        $stmt->allowRowCount = TRUE;
        return $stmt
          ->rowCount();
      case Database::RETURN_INSERT_ID:
        $sequence_name = isset($options['sequence_name']) ? $options['sequence_name'] : NULL;
        return $this->connection
          ->lastInsertId($sequence_name);
      case Database::RETURN_NULL:
        return NULL;
      default:
        throw new \PDOException('Invalid return directive: ' . $options['return']);
    }
  } catch (\Exception $e) {

    // Most database drivers will return NULL here, but some of them
    // (e.g. the SQLite driver) may need to re-run the query, so the return
    // value will be the same as for static::query().
    if (is_string($query)) {
      return $this
        ->exceptionHandler()
        ->handleExecutionException($e, $stmt, $args, $options);
    }
    else {
      return $this
        ->handleQueryException($e, $query, $args, $options);
    }
  }
}