You are here

public static function Connection::open in Drupal driver for SQL Server and SQL Azure 8

Same name and namespace in other branches
  1. 8.2 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 118
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.
  $driverSettings = DriverSettings::instanceFromSettings();

  // 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 = $driverSettings
    ->GetDefaultIsolationLevel()) {
    $options['TransactionIsolation'] = $level;
  }

  // Build the DSN.
  $dsn = 'sqlsrv:';
  foreach ($options as $key => $value) {
    $dsn .= (empty($key) ? '' : "{$key}=") . $value . ';';
  }

  // Allow PDO options to be overridden.
  $connection_options += [
    'pdo' => [],
  ];
  $connection_options['pdo'] += [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  ];

  // Set a Statement class, unless the driver opted out.
  // $connection_options['pdo'][PDO::ATTR_STATEMENT_CLASS] =
  // array(Statement::class, array(Statement::class));.
  // Actually instantiate the PDO.
  try {
    $pdo = new \PDO($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;
  }
  return $pdo;
}