Skip to content

Commit

Permalink
Mssql: Add support for PDO_SQLSRV
Browse files Browse the repository at this point in the history
  • Loading branch information
nilmerg committed Dec 13, 2022
1 parent 2386247 commit 119d3f3
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/Adapter/Mssql.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,27 @@ class Mssql extends BaseAdapter

public function getDsn(Config $config)
{
$drivers = array_intersect(['dblib', 'mssql', 'sybase'], PDO::getAvailableDrivers());
$drivers = array_intersect(['sqlsrv', 'dblib', 'mssql', 'sybase'], PDO::getAvailableDrivers());

if (empty($drivers)) {
throw new RuntimeException('No PDO driver available for connecting to a Microsoft SQL Server');
}

$dsn = "{$drivers[0]}:host={$config->host}";
$driver = reset($drivers); // array_intersect preserves keys, so the first may not be indexed at 0

$isSqlSrv = $driver === 'sqlsrv';
if ($isSqlSrv) {
$hostOption = 'Server';
$dbOption = 'Database';
} else {
$hostOption = 'host';
$dbOption = 'dbname';
}

$dsn = "{$driver}:{$hostOption}={$config->host}";

if (! empty($config->port)) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
if ($isSqlSrv || strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$seperator = ',';
} else {
$seperator = ':';
Expand All @@ -34,12 +45,20 @@ public function getDsn(Config $config)
$dsn .= "{$seperator}{$config->port}";
}

$dsn .= ";dbname={$config->dbname}";
$dsn .= ";{$dbOption}={$config->dbname}";

if (! empty($config->charset)) {
if (! empty($config->charset) && ! $isSqlSrv) {
$dsn .= ";charset={$config->charset}";
}

if (isset($config->use_ssl) && $isSqlSrv) {
$dsn .= ';Encrypt=' . ($config->use_ssl ? 'true' : 'false');
}

if (isset($config->ssl_do_not_verify_server_cert) && $isSqlSrv) {
$dsn .= ';TrustServerCertificate=' . ($config->ssl_do_not_verify_server_cert ? 'true' : 'false');
}

return $dsn;
}

Expand Down

0 comments on commit 119d3f3

Please sign in to comment.