You are here

public static function Connection::open 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/Connection.php \Drupal\Driver\Database\sqlsrv\Connection::open()
  2. 3.0.x drivers/lib/Drupal/Driver/Database/sqlsrv/Connection.php \Drupal\Driver\Database\sqlsrv\Connection::open()

Opens a PDO connection.

Parameters

array $connection_options: The database connection settings array.

Return value

\PDO A \PDO object.

Overrides Connection::open

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Connection.php, line 104
Definition of Drupal\Driver\Database\sqlsrv\Connection

Class

Connection
Temporary tables: temporary table support is done by means of global temporary tables (#) to avoid the use of DIRECT QUERIES. You can enable and disable the use of direct queries with $this->driver_settings->defaultDirectQuery =…

Namespace

Drupal\Driver\Database\sqlsrv

Code

public static function open(array &$connection_options = []) {

  // Get driver settings.
  $driver_settings = ConnectionSettings::instanceFromData(\Drupal\Core\Site\Settings::get('mssql', []));

  // Build the DSN.
  $options = [];
  $options['Server'] = $connection_options['host'] . (!empty($connection_options['port']) ? ',' . $connection_options['port'] : '');

  // We might not have a database in the
  // connection options, for example, during
  // database creation in Install.
  if (!empty($connection_options['database'])) {
    $options['Database'] = $connection_options['database'];
  }

  // Set isolation level if specified.
  if ($level = $driver_settings
    ->GetDefaultIsolationLevel()) {
    $options['TransactionIsolation'] = $level;
  }

  // Disable MARS
  $options['MultipleActiveResultSets'] = 'false';

  // Build the DSN
  $dsn = $driver_settings
    ->buildDSN($options);

  // PDO Options are set at a connection level.
  // and apply to all statements.
  $connection_options['pdo'] = [];

  // Set proper error mode for all statements
  $connection_options['pdo'][PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;

  // Use native types. This makes fetches x3 faster!
  // @see https://github.com/Microsoft/msphpsql/issues/189
  $connection_options['pdo'][PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE] = true;
  $connection_options['pdo'][PDO::ATTR_STRINGIFY_FETCHES] = false;

  // Actually instantiate the PDO.
  try {
    $pdo = new ConnectionBase($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
  } catch (\Exception $e) {
    if ($e
      ->getCode() == static::DATABASE_NOT_FOUND) {
      throw new DatabaseNotFoundException($e
        ->getMessage(), $e
        ->getCode(), $e);
    }
    throw $e;
  }
  $connection_options['driver_settings'] = $driver_settings;
  return $pdo;
}