Merge pull request #27 from helpfulrobot/convert-to-psr-2

Converted to PSR-2
This commit is contained in:
Damian Mooyman 2015-12-18 10:16:25 +13:00
commit 31eaa833ed
8 changed files with 2055 additions and 1845 deletions

View File

@ -18,7 +18,8 @@
* @author Sean Harvey <sean at silverstripe dot com> * @author Sean Harvey <sean at silverstripe dot com>
* @package mssql * @package mssql
*/ */
class MSSQLAzureDatabase extends MSSQLDatabase { class MSSQLAzureDatabase extends MSSQLDatabase
{
/** /**
* List of parameters used to create new Azure connections between databases * List of parameters used to create new Azure connections between databases
@ -27,11 +28,13 @@ class MSSQLAzureDatabase extends MSSQLDatabase {
*/ */
protected $parameters = array(); protected $parameters = array();
public function fullTextEnabled() { public function fullTextEnabled()
{
return false; return false;
} }
public function __construct($parameters) { public function __construct($parameters)
{
$this->connectDatabase($parameters); $this->connectDatabase($parameters);
} }
@ -44,7 +47,8 @@ class MSSQLAzureDatabase extends MSSQLDatabase {
* - database: The database to connect to * - database: The database to connect to
* - windowsauthentication: Not supported for Azure * - windowsauthentication: Not supported for Azure
*/ */
protected function connect($parameters) { protected function connect($parameters)
{
$this->parameters = $parameters; $this->parameters = $parameters;
$this->connectDatabase($parameters['database']); $this->connectDatabase($parameters['database']);
} }
@ -54,13 +58,14 @@ class MSSQLAzureDatabase extends MSSQLDatabase {
* *
* @param string $database * @param string $database
*/ */
protected function connectDatabase($database) { protected function connectDatabase($database)
{
$parameters = $this->parameters; $parameters = $this->parameters;
$parameters['database'] = $database; $parameters['database'] = $database;
$parameters['multipleactiveresultsets'] = 0; $parameters['multipleactiveresultsets'] = 0;
// Ensure that driver is available (required by PDO) // Ensure that driver is available (required by PDO)
if(empty($parameters['driver'])) { if (empty($parameters['driver'])) {
$parameters['driver'] = $this->getDatabaseServer(); $parameters['driver'] = $this->getDatabaseServer();
} }
@ -85,7 +90,8 @@ class MSSQLAzureDatabase extends MSSQLDatabase {
* @param type $create * @param type $create
* @param type $errorLevel * @param type $errorLevel
*/ */
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR) { public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR)
{
$this->fullTextEnabled = null; $this->fullTextEnabled = null;
if (!$this->schemaManager->databaseExists($name)) { if (!$this->schemaManager->databaseExists($name)) {
// Check DB creation permisson // Check DB creation permisson

View File

@ -38,7 +38,8 @@
* *
* @package mssql * @package mssql
*/ */
class MSSQLDatabase extends SS_Database { class MSSQLDatabase extends SS_Database
{
/** /**
* Words that will trigger an error if passed to a SQL Server fulltext search * Words that will trigger an error if passed to a SQL Server fulltext search
@ -69,7 +70,8 @@ class MSSQLDatabase extends SS_Database {
* *
* @param string $collation * @param string $collation
*/ */
public static function set_collation($collation) { public static function set_collation($collation)
{
Config::inst()->update('MSSQLDatabase', 'collation', $collation); Config::inst()->update('MSSQLDatabase', 'collation', $collation);
} }
@ -80,7 +82,8 @@ class MSSQLDatabase extends SS_Database {
* *
* @return string * @return string
*/ */
public static function get_collation() { public static function get_collation()
{
return Config::inst()->get('MSSQLDatabase', 'collation'); return Config::inst()->get('MSSQLDatabase', 'collation');
} }
@ -94,7 +97,8 @@ class MSSQLDatabase extends SS_Database {
* - windowsauthentication: Set to true to use windows authentication * - windowsauthentication: Set to true to use windows authentication
* instead of username/password * instead of username/password
*/ */
public function connect($parameters) { public function connect($parameters)
{
parent::connect($parameters); parent::connect($parameters);
// Configure the connection // Configure the connection
@ -108,8 +112,9 @@ class MSSQLDatabase extends SS_Database {
* *
* @return boolean * @return boolean
*/ */
public function fullTextEnabled() { public function fullTextEnabled()
if($this->fullTextEnabled === null) { {
if ($this->fullTextEnabled === null) {
$this->fullTextEnabled = $this->updateFullTextEnabled(); $this->fullTextEnabled = $this->updateFullTextEnabled();
} }
return $this->fullTextEnabled; return $this->fullTextEnabled;
@ -121,10 +126,13 @@ class MSSQLDatabase extends SS_Database {
* *
* @return boolean * @return boolean
*/ */
protected function updateFullTextEnabled() { protected function updateFullTextEnabled()
{
// Check if installed // Check if installed
$isInstalled = $this->query("SELECT fulltextserviceproperty('isfulltextinstalled')")->value(); $isInstalled = $this->query("SELECT fulltextserviceproperty('isfulltextinstalled')")->value();
if(!$isInstalled) return false; if (!$isInstalled) {
return false;
}
// Check if current database is enabled // Check if current database is enabled
$database = $this->getSelectedDatabase(); $database = $this->getSelectedDatabase();
@ -135,39 +143,46 @@ class MSSQLDatabase extends SS_Database {
return $enabledForDb; return $enabledForDb;
} }
public function supportsCollations() { public function supportsCollations()
{
return true; return true;
} }
public function supportsTimezoneOverride() { public function supportsTimezoneOverride()
{
return true; return true;
} }
public function getDatabaseServer() { public function getDatabaseServer()
{
return "sqlsrv"; return "sqlsrv";
} }
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR) { public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR)
{
$this->fullTextEnabled = null; $this->fullTextEnabled = null;
return parent::selectDatabase($name, $create, $errorLevel); return parent::selectDatabase($name, $create, $errorLevel);
} }
public function clearTable($table) { public function clearTable($table)
{
$this->query("TRUNCATE TABLE \"$table\""); $this->query("TRUNCATE TABLE \"$table\"");
} }
/** /**
* SQL Server uses CURRENT_TIMESTAMP for the current date/time. * SQL Server uses CURRENT_TIMESTAMP for the current date/time.
*/ */
function now() { public function now()
{
return 'CURRENT_TIMESTAMP'; return 'CURRENT_TIMESTAMP';
} }
/** /**
* Returns the database-specific version of the random() function * Returns the database-specific version of the random() function
*/ */
function random(){ public function random()
{
return 'RAND()'; return 'RAND()';
} }
@ -180,12 +195,20 @@ class MSSQLDatabase extends SS_Database {
* @param string $keywords Keywords as a space separated string * @param string $keywords Keywords as a space separated string
* @return object DataObjectSet of result pages * @return object DataObjectSet of result pages
*/ */
public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "Relevance DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false) { public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "Relevance DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false)
if(isset($objects)) $results = new ArrayList($objects); {
else $results = new ArrayList(); if (isset($objects)) {
$results = new ArrayList($objects);
} else {
$results = new ArrayList();
}
if (!$this->fullTextEnabled()) return $results; if (!$this->fullTextEnabled()) {
if (!in_array(substr($sortBy, 0, 9), array('"Relevanc', 'Relevance'))) user_error("Non-relevance sort not supported.", E_USER_ERROR); return $results;
}
if (!in_array(substr($sortBy, 0, 9), array('"Relevanc', 'Relevance'))) {
user_error("Non-relevance sort not supported.", E_USER_ERROR);
}
$allClassesToSearch = array(); $allClassesToSearch = array();
foreach ($classesToSearch as $class) { foreach ($classesToSearch as $class) {
@ -199,9 +222,11 @@ class MSSQLDatabase extends SS_Database {
// Sort the columns back into tables. // Sort the columns back into tables.
$tables = array(); $tables = array();
foreach($fulltextColumns as $column) { foreach ($fulltextColumns as $column) {
// Skip extension tables. // Skip extension tables.
if(substr($column['TABLE_NAME'], -5) == '_Live' || substr($column['TABLE_NAME'], -9) == '_versions') continue; if (substr($column['TABLE_NAME'], -5) == '_Live' || substr($column['TABLE_NAME'], -9) == '_versions') {
continue;
}
// Add the column to table. // Add the column to table.
$table = &$tables[$column['TABLE_NAME']]; $table = &$tables[$column['TABLE_NAME']];
@ -213,21 +238,23 @@ class MSSQLDatabase extends SS_Database {
} }
// Create one query per each table, $columns not used. We want just the ID and the ClassName of the object from this query. // Create one query per each table, $columns not used. We want just the ID and the ClassName of the object from this query.
foreach($tables as $tableName => $columns){ foreach ($tables as $tableName => $columns) {
$baseClass = ClassInfo::baseDataClass($tableName); $baseClass = ClassInfo::baseDataClass($tableName);
$join = $this->fullTextSearchMSSQL($tableName, $keywords); $join = $this->fullTextSearchMSSQL($tableName, $keywords);
if (!$join) return $results; // avoid "Null or empty full-text predicate" if (!$join) {
return $results;
} // avoid "Null or empty full-text predicate"
// Check if we need to add ShowInSearch // Check if we need to add ShowInSearch
$where = null; $where = null;
if(strpos($tableName, 'SiteTree') === 0) { if (strpos($tableName, 'SiteTree') === 0) {
$where = array("\"$tableName\".\"ShowInSearch\"!=0"); $where = array("\"$tableName\".\"ShowInSearch\"!=0");
} elseif(strpos($tableName, 'File') === 0) { } elseif (strpos($tableName, 'File') === 0) {
// File.ShowInSearch was added later, keep the database driver backwards compatible // File.ShowInSearch was added later, keep the database driver backwards compatible
// by checking for its existence first // by checking for its existence first
$fields = $this->fieldList($tableName); $fields = $this->fieldList($tableName);
if(array_key_exists('ShowInSearch', $fields)) { if (array_key_exists('ShowInSearch', $fields)) {
$where = array("\"$tableName\".\"ShowInSearch\"!=0"); $where = array("\"$tableName\".\"ShowInSearch\"!=0");
} }
} }
@ -261,7 +288,7 @@ class MSSQLDatabase extends SS_Database {
// Generate SQL // Generate SQL
$querySQLs = array(); $querySQLs = array();
$queryParameters = array(); $queryParameters = array();
foreach($queries as $query) { foreach ($queries as $query) {
$querySQLs[] = $query->sql($parameters); $querySQLs[] = $query->sql($parameters);
$queryParameters = array_merge($queryParameters, $parameters); $queryParameters = array_merge($queryParameters, $parameters);
} }
@ -284,8 +311,11 @@ class MSSQLDatabase extends SS_Database {
} }
} }
if(isset($objects)) $results = new ArrayList($objects); if (isset($objects)) {
else $results = new ArrayList(); $results = new ArrayList($objects);
} else {
$results = new ArrayList();
}
$list = new PaginatedList($results); $list = new PaginatedList($results);
$list->setPageStart($start); $list->setPageStart($start);
$list->setPageLength($pageLength); $list->setPageLength($pageLength);
@ -300,7 +330,8 @@ class MSSQLDatabase extends SS_Database {
* @param $table The name of the table to have PK editing allowed on * @param $table The name of the table to have PK editing allowed on
* @param $allow True to start, false to finish * @param $allow True to start, false to finish
*/ */
function allowPrimaryKeyEditing($table, $allow = true) { public function allowPrimaryKeyEditing($table, $allow = true)
{
$this->query("SET IDENTITY_INSERT \"$table\" " . ($allow ? "ON" : "OFF")); $this->query("SET IDENTITY_INSERT \"$table\" " . ($allow ? "ON" : "OFF"));
} }
@ -313,15 +344,18 @@ class MSSQLDatabase extends SS_Database {
* *
* @returns null if keyword set is empty or the string with JOIN clause to be added to SQL query * @returns null if keyword set is empty or the string with JOIN clause to be added to SQL query
*/ */
public function fullTextSearchMSSQL($tableName, $keywords, $fields = null) { public function fullTextSearchMSSQL($tableName, $keywords, $fields = null)
{
// Make sure we are getting an array of fields // Make sure we are getting an array of fields
if (isset($fields) && !is_array($fields)) $fields = array($fields); if (isset($fields) && !is_array($fields)) {
$fields = array($fields);
}
// Strip unfriendly characters, SQLServer "CONTAINS" predicate will crash on & and | and ignore others anyway. // Strip unfriendly characters, SQLServer "CONTAINS" predicate will crash on & and | and ignore others anyway.
if (function_exists('mb_ereg_replace')) { if (function_exists('mb_ereg_replace')) {
$keywords = mb_ereg_replace('[^\w\s]', '', trim($keywords)); $keywords = mb_ereg_replace('[^\w\s]', '', trim($keywords));
} else { } else {
$keywords = $this->escapeString(str_replace(array('&','|','!','"','\''), '', trim($keywords))); $keywords = $this->escapeString(str_replace(array('&', '|', '!', '"', '\''), '', trim($keywords)));
} }
// Remove stopwords, concat with ANDs // Remove stopwords, concat with ANDs
@ -330,11 +364,16 @@ class MSSQLDatabase extends SS_Database {
// remove any empty values from the array // remove any empty values from the array
$keywordList = array_filter($keywordList); $keywordList = array_filter($keywordList);
if(empty($keywordList)) return null; if (empty($keywordList)) {
return null;
}
$keywords = implode(' AND ', $keywordList); $keywords = implode(' AND ', $keywordList);
if ($fields) $fieldNames = '"' . implode('", "', $fields) . '"'; if ($fields) {
else $fieldNames = "*"; $fieldNames = '"' . implode('", "', $fields) . '"';
} else {
$fieldNames = "*";
}
return "CONTAINSTABLE(\"$tableName\", ($fieldNames), '$keywords')"; return "CONTAINSTABLE(\"$tableName\", ($fieldNames), '$keywords')";
} }
@ -346,10 +385,13 @@ class MSSQLDatabase extends SS_Database {
* *
* @return array $keywords with stopwords removed * @return array $keywords with stopwords removed
*/ */
public function removeStopwords($keywords) { public function removeStopwords($keywords)
{
$goodKeywords = array(); $goodKeywords = array();
foreach($keywords as $keyword) { foreach ($keywords as $keyword) {
if (in_array($keyword, self::$noiseWords)) continue; if (in_array($keyword, self::$noiseWords)) {
continue;
}
$goodKeywords[] = trim($keyword); $goodKeywords[] = trim($keyword);
} }
return $goodKeywords; return $goodKeywords;
@ -358,7 +400,8 @@ class MSSQLDatabase extends SS_Database {
/** /**
* Does this database support transactions? * Does this database support transactions?
*/ */
public function supportsTransactions(){ public function supportsTransactions()
{
return $this->supportsTransactions; return $this->supportsTransactions;
} }
@ -371,70 +414,79 @@ class MSSQLDatabase extends SS_Database {
* could be one of partitions, tablespaces, or clustering * could be one of partitions, tablespaces, or clustering
* @return boolean Flag indicating support for all of the above * @return boolean Flag indicating support for all of the above
*/ */
public function supportsExtensions($extensions = array('partitions', 'tablespaces', 'clustering')){ public function supportsExtensions($extensions = array('partitions', 'tablespaces', 'clustering'))
if(isset($extensions['partitions'])) {
if (isset($extensions['partitions'])) {
return false; return false;
elseif(isset($extensions['tablespaces'])) } elseif (isset($extensions['tablespaces'])) {
return false; return false;
elseif(isset($extensions['clustering'])) } elseif (isset($extensions['clustering'])) {
return false; return false;
else } else {
return false; return false;
} }
}
/** /**
* Start transaction. READ ONLY not supported. * Start transaction. READ ONLY not supported.
*/ */
public function transactionStart($transactionMode = false, $sessionCharacteristics = false){ public function transactionStart($transactionMode = false, $sessionCharacteristics = false)
if($this->connector instanceof SQLServerConnector) { {
if ($this->connector instanceof SQLServerConnector) {
$this->connector->transactionStart(); $this->connector->transactionStart();
} else { } else {
$this->query('BEGIN TRANSACTION'); $this->query('BEGIN TRANSACTION');
} }
} }
public function transactionSavepoint($savepoint){ public function transactionSavepoint($savepoint)
{
$this->query("SAVE TRANSACTION \"$savepoint\""); $this->query("SAVE TRANSACTION \"$savepoint\"");
} }
public function transactionRollback($savepoint = false) { public function transactionRollback($savepoint = false)
if($savepoint) { {
if ($savepoint) {
$this->query("ROLLBACK TRANSACTION \"$savepoint\""); $this->query("ROLLBACK TRANSACTION \"$savepoint\"");
} elseif($this->connector instanceof SQLServerConnector) { } elseif ($this->connector instanceof SQLServerConnector) {
$this->connector->transactionRollback(); $this->connector->transactionRollback();
} else { } else {
$this->query('ROLLBACK TRANSACTION'); $this->query('ROLLBACK TRANSACTION');
} }
} }
public function transactionEnd($chain = false) { public function transactionEnd($chain = false)
if($this->connector instanceof SQLServerConnector) { {
if ($this->connector instanceof SQLServerConnector) {
$this->connector->transactionEnd(); $this->connector->transactionEnd();
} else { } else {
$this->query('COMMIT TRANSACTION'); $this->query('COMMIT TRANSACTION');
} }
} }
public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false) { public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false)
if($exact) { {
if ($exact) {
$comp = ($negate) ? '!=' : '='; $comp = ($negate) ? '!=' : '=';
} else { } else {
$comp = 'LIKE'; $comp = 'LIKE';
if($negate) $comp = 'NOT ' . $comp; if ($negate) {
$comp = 'NOT ' . $comp;
}
} }
// Field definitions are case insensitive by default, // Field definitions are case insensitive by default,
// change used collation for case sensitive searches. // change used collation for case sensitive searches.
$collateClause = ''; $collateClause = '';
if($caseSensitive === true) { if ($caseSensitive === true) {
if(self::get_collation()) { if (self::get_collation()) {
$collation = preg_replace('/_CI_/', '_CS_', self::get_collation()); $collation = preg_replace('/_CI_/', '_CS_', self::get_collation());
} else { } else {
$collation = 'Latin1_General_CS_AS'; $collation = 'Latin1_General_CS_AS';
} }
$collateClause = ' COLLATE ' . $collation; $collateClause = ' COLLATE ' . $collation;
} elseif($caseSensitive === false) { } elseif ($caseSensitive === false) {
if(self::get_collation()) { if (self::get_collation()) {
$collation = preg_replace('/_CS_/', '_CI_', self::get_collation()); $collation = preg_replace('/_CS_/', '_CI_', self::get_collation());
} else { } else {
$collation = 'Latin1_General_CI_AS'; $collation = 'Latin1_General_CI_AS';
@ -443,7 +495,9 @@ class MSSQLDatabase extends SS_Database {
} }
$clause = sprintf("%s %s %s", $field, $comp, $parameterised ? '?' : "'$value'"); $clause = sprintf("%s %s %s", $field, $comp, $parameterised ? '?' : "'$value'");
if($collateClause) $clause .= $collateClause; if ($collateClause) {
$clause .= $collateClause;
}
return $clause; return $clause;
} }
@ -463,17 +517,22 @@ class MSSQLDatabase extends SS_Database {
* %U = unix timestamp, can only be used on it's own * %U = unix timestamp, can only be used on it's own
* @return string SQL datetime expression to query for a formatted datetime * @return string SQL datetime expression to query for a formatted datetime
*/ */
function formattedDatetimeClause($date, $format) { public function formattedDatetimeClause($date, $format)
{
preg_match_all('/%(.)/', $format, $matches); preg_match_all('/%(.)/', $format, $matches);
foreach($matches[1] as $match) if(array_search($match, array('Y','m','d','H','i','s','U')) === false) user_error('formattedDatetimeClause(): unsupported format character %' . $match, E_USER_WARNING); foreach ($matches[1] as $match) {
if (array_search($match, array('Y', 'm', 'd', 'H', 'i', 's', 'U')) === false) {
user_error('formattedDatetimeClause(): unsupported format character %' . $match, E_USER_WARNING);
}
}
if(preg_match('/^now$/i', $date)) { if (preg_match('/^now$/i', $date)) {
$date = "CURRENT_TIMESTAMP"; $date = "CURRENT_TIMESTAMP";
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) { } elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
$date = "'$date.000'"; $date = "'$date.000'";
} }
if($format == '%U') { if ($format == '%U') {
return "DATEDIFF(s, '1970-01-01 00:00:00', DATEADD(hour, DATEDIFF(hour, GETDATE(), GETUTCDATE()), $date))"; return "DATEDIFF(s, '1970-01-01 00:00:00', DATEADD(hour, DATEDIFF(hour, GETDATE(), GETUTCDATE()), $date))";
} }
@ -488,15 +547,15 @@ class MSSQLDatabase extends SS_Database {
$strings = array(); $strings = array();
$buffer = $format; $buffer = $format;
while(strlen($buffer)) { while (strlen($buffer)) {
if(substr($buffer,0,1) == '%') { if (substr($buffer, 0, 1) == '%') {
$f = substr($buffer,1,1); $f = substr($buffer, 1, 1);
$flen = $f == 'Y' ? 4 : 2; $flen = $f == 'Y' ? 4 : 2;
$strings[] = "RIGHT('0' + CAST(DATEPART({$trans[$f]},$date) AS VARCHAR), $flen)"; $strings[] = "RIGHT('0' + CAST(DATEPART({$trans[$f]},$date) AS VARCHAR), $flen)";
$buffer = substr($buffer, 2); $buffer = substr($buffer, 2);
} else { } else {
$pos = strpos($buffer, '%'); $pos = strpos($buffer, '%');
if($pos === false) { if ($pos === false) {
$strings[] = $buffer; $strings[] = $buffer;
$buffer = ''; $buffer = '';
} else { } else {
@ -507,7 +566,6 @@ class MSSQLDatabase extends SS_Database {
} }
return '(' . implode(' + ', $strings) . ')'; return '(' . implode(' + ', $strings) . ')';
} }
/** /**
@ -526,7 +584,8 @@ class MSSQLDatabase extends SS_Database {
* This includes the singular forms as well * This includes the singular forms as well
* @return string SQL datetime expression to query for a datetime (YYYY-MM-DD hh:mm:ss) which is the result of the addition * @return string SQL datetime expression to query for a datetime (YYYY-MM-DD hh:mm:ss) which is the result of the addition
*/ */
function datetimeIntervalClause($date, $interval) { public function datetimeIntervalClause($date, $interval)
{
$trans = array( $trans = array(
'year' => 'yy', 'year' => 'yy',
'month' => 'mm', 'month' => 'mm',
@ -538,14 +597,16 @@ class MSSQLDatabase extends SS_Database {
$singularinterval = preg_replace('/(year|month|day|hour|minute|second)s/i', '$1', $interval); $singularinterval = preg_replace('/(year|month|day|hour|minute|second)s/i', '$1', $interval);
if( if (
!($params = preg_match('/([-+]\d+) (\w+)/i', $singularinterval, $matches)) || !($params = preg_match('/([-+]\d+) (\w+)/i', $singularinterval, $matches)) ||
!isset($trans[strtolower($matches[2])]) !isset($trans[strtolower($matches[2])])
) user_error('datetimeIntervalClause(): invalid interval ' . $interval, E_USER_WARNING); ) {
user_error('datetimeIntervalClause(): invalid interval ' . $interval, E_USER_WARNING);
}
if(preg_match('/^now$/i', $date)) { if (preg_match('/^now$/i', $date)) {
$date = "CURRENT_TIMESTAMP"; $date = "CURRENT_TIMESTAMP";
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) { } elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
$date = "'$date'"; $date = "'$date'";
} }
@ -560,17 +621,17 @@ class MSSQLDatabase extends SS_Database {
* @param string $date2 to be substracted of $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"' * @param string $date2 to be substracted of $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
* @return string SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the substraction * @return string SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the substraction
*/ */
function datetimeDifferenceClause($date1, $date2) { public function datetimeDifferenceClause($date1, $date2)
{
if(preg_match('/^now$/i', $date1)) { if (preg_match('/^now$/i', $date1)) {
$date1 = "CURRENT_TIMESTAMP"; $date1 = "CURRENT_TIMESTAMP";
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date1)) { } elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date1)) {
$date1 = "'$date1'"; $date1 = "'$date1'";
} }
if(preg_match('/^now$/i', $date2)) { if (preg_match('/^now$/i', $date2)) {
$date2 = "CURRENT_TIMESTAMP"; $date2 = "CURRENT_TIMESTAMP";
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date2)) { } elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date2)) {
$date2 = "'$date2'"; $date2 = "'$date2'";
} }

View File

@ -8,9 +8,11 @@
* *
* @package mssql * @package mssql
*/ */
class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper { class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper
{
protected function isAzure($databaseConfig) { protected function isAzure($databaseConfig)
{
return $databaseConfig['type'] === 'MSSQLAzureDatabase'; return $databaseConfig['type'] === 'MSSQLAzureDatabase';
} }
@ -21,10 +23,11 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
* @param string $error Error message passed by value * @param string $error Error message passed by value
* @return mixed|null Either the connection object, or null if error * @return mixed|null Either the connection object, or null if error
*/ */
protected function createConnection($databaseConfig, &$error) { protected function createConnection($databaseConfig, &$error)
{
$error = null; $error = null;
try { try {
switch($databaseConfig['type']) { switch ($databaseConfig['type']) {
case 'MSSQLDatabase': case 'MSSQLDatabase':
case 'MSSQLAzureDatabase': case 'MSSQLAzureDatabase':
$parameters = array( $parameters = array(
@ -33,17 +36,19 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
); );
// Azure has additional parameter requirements // Azure has additional parameter requirements
if($this->isAzure($databaseConfig)) { if ($this->isAzure($databaseConfig)) {
$parameters['database'] = $databaseConfig['database']; $parameters['database'] = $databaseConfig['database'];
$parameters['multipleactiveresultsets'] = 0; $parameters['multipleactiveresultsets'] = 0;
} }
$conn = @sqlsrv_connect($databaseConfig['server'], $parameters); $conn = @sqlsrv_connect($databaseConfig['server'], $parameters);
if($conn) return $conn; if ($conn) {
return $conn;
}
// Get error // Get error
if($errors = sqlsrv_errors()) { if ($errors = sqlsrv_errors()) {
$error = ''; $error = '';
foreach($errors as $detail) { foreach ($errors as $detail) {
$error .= "{$detail['message']}\n"; $error .= "{$detail['message']}\n";
} }
} else { } else {
@ -53,7 +58,7 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
case 'MSSQLPDODatabase': case 'MSSQLPDODatabase':
// May throw a PDOException if fails // May throw a PDOException if fails
$conn = @new PDO('sqlsrv:Server='.$databaseConfig['server'], $databaseConfig['username'], $databaseConfig['password']); $conn = @new PDO('sqlsrv:Server='.$databaseConfig['server'], $databaseConfig['username'], $databaseConfig['password']);
if($conn) { if ($conn) {
return $conn; return $conn;
} else { } else {
$error = 'Unknown connection error'; $error = 'Unknown connection error';
@ -63,7 +68,7 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
$error = 'Invalid connection type'; $error = 'Invalid connection type';
return null; return null;
} }
} catch(Exception $ex) { } catch (Exception $ex) {
$error = $ex->getMessage(); $error = $ex->getMessage();
return null; return null;
} }
@ -76,10 +81,11 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
* @param string $value Value to quote * @param string $value Value to quote
* @return string Quoted strieng * @return string Quoted strieng
*/ */
protected function quote($conn, $value) { protected function quote($conn, $value)
if($conn instanceof PDO) { {
if ($conn instanceof PDO) {
return $conn->quote($value); return $conn->quote($value);
} elseif(is_resource($conn)) { } elseif (is_resource($conn)) {
$value = str_replace("'", "''", $value); $value = str_replace("'", "''", $value);
$value = str_replace("\0", "[NULL]", $value); $value = str_replace("\0", "[NULL]", $value);
return "N'$value'"; return "N'$value'";
@ -95,28 +101,35 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
* @param string $sql SQL string to execute * @param string $sql SQL string to execute
* @return array List of first value from each resulting row * @return array List of first value from each resulting row
*/ */
protected function query($conn, $sql) { protected function query($conn, $sql)
{
$items = array(); $items = array();
if($conn instanceof PDO) { if ($conn instanceof PDO) {
$result = $conn->query($sql); $result = $conn->query($sql);
if($result) foreach($result as $row) { if ($result) {
foreach ($result as $row) {
$items[] = $row[0]; $items[] = $row[0];
} }
} elseif(is_resource($conn)) { }
} elseif (is_resource($conn)) {
$result = sqlsrv_query($conn, $sql); $result = sqlsrv_query($conn, $sql);
if($result) while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) { if ($result) {
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) {
$items[] = $row[0]; $items[] = $row[0];
} }
} }
}
return $items; return $items;
} }
public function requireDatabaseFunctions($databaseConfig) { public function requireDatabaseFunctions($databaseConfig)
{
$data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']); $data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']);
return !empty($data['supported']); return !empty($data['supported']);
} }
public function requireDatabaseServer($databaseConfig) { public function requireDatabaseServer($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error); $conn = $this->createConnection($databaseConfig, $error);
$success = !empty($conn); $success = !empty($conn);
@ -126,7 +139,8 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
); );
} }
public function requireDatabaseConnection($databaseConfig) { public function requireDatabaseConnection($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error); $conn = $this->createConnection($databaseConfig, $error);
$success = !empty($conn); $success = !empty($conn);
@ -137,7 +151,8 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
); );
} }
public function getDatabaseVersion($databaseConfig) { public function getDatabaseVersion($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error); $conn = $this->createConnection($databaseConfig, $error);
$result = $this->query($conn, "SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))"); $result = $this->query($conn, "SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))");
return empty($result) ? 0 : reset($result); return empty($result) ? 0 : reset($result);
@ -150,14 +165,15 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
* @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc * @param array $databaseConfig Associative array of db configuration, e.g. "server", "username" etc
* @return array Result - e.g. array('success' => true, 'error' => 'details of error') * @return array Result - e.g. array('success' => true, 'error' => 'details of error')
*/ */
public function requireDatabaseVersion($databaseConfig) { public function requireDatabaseVersion($databaseConfig)
{
$success = false; $success = false;
$error = ''; $error = '';
$version = $this->getDatabaseVersion($databaseConfig); $version = $this->getDatabaseVersion($databaseConfig);
if($version) { if ($version) {
$success = version_compare($version, '10.00.2531', '>='); $success = version_compare($version, '10.00.2531', '>=');
if(!$success) { if (!$success) {
$error = "Your SQL Server version is $version. It's recommended you use at least 10.00.2531 (SQL Server 2008 SP1)."; $error = "Your SQL Server version is $version. It's recommended you use at least 10.00.2531 (SQL Server 2008 SP1).";
} }
} else { } else {
@ -170,19 +186,20 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
); );
} }
public function requireDatabaseOrCreatePermissions($databaseConfig) { public function requireDatabaseOrCreatePermissions($databaseConfig)
{
$conn = $this->createConnection($databaseConfig, $error); $conn = $this->createConnection($databaseConfig, $error);
if(empty($conn)) { if (empty($conn)) {
$success = false; $success = false;
$alreadyExists = false; $alreadyExists = false;
} elseif($databaseConfig['type'] == 'MSSQLAzureDatabase') { } elseif ($databaseConfig['type'] == 'MSSQLAzureDatabase') {
// Don't bother with DB selection for azure, as it's not supported // Don't bother with DB selection for azure, as it's not supported
$success = true; $success = true;
$alreadyExists = true; $alreadyExists = true;
} else { } else {
// does this database exist already? // does this database exist already?
$list = $this->query($conn, 'SELECT NAME FROM sys.sysdatabases'); $list = $this->query($conn, 'SELECT NAME FROM sys.sysdatabases');
if(in_array($databaseConfig['database'], $list)) { if (in_array($databaseConfig['database'], $list)) {
$success = true; $success = true;
$alreadyExists = true; $alreadyExists = true;
} else { } else {
@ -198,11 +215,12 @@ class MSSQLDatabaseConfigurationHelper implements DatabaseConfigurationHelper {
); );
} }
public function requireDatabaseAlterPermissions($databaseConfig) { public function requireDatabaseAlterPermissions($databaseConfig)
{
$success = false; $success = false;
$conn = $this->createConnection($databaseConfig, $error); $conn = $this->createConnection($databaseConfig, $error);
if(!empty($conn)) { if (!empty($conn)) {
if(!$this->isAzure($databaseConfig)) { if (!$this->isAzure($databaseConfig)) {
// Make sure to select the current database when checking permission against this database // Make sure to select the current database when checking permission against this database
$this->query($conn, "USE \"{$databaseConfig['database']}\""); $this->query($conn, "USE \"{$databaseConfig['database']}\"");
} }

View File

@ -5,16 +5,18 @@
* *
* @package mssql * @package mssql
*/ */
class MSSQLQueryBuilder extends DBQueryBuilder { class MSSQLQueryBuilder extends DBQueryBuilder
{
protected function buildSelectQuery(SQLSelect $query, array &$parameters) { protected function buildSelectQuery(SQLSelect $query, array &$parameters)
{
list($limit, $offset) = $this->parseLimit($query); list($limit, $offset) = $this->parseLimit($query);
// If not using ofset then query generation is quite straightforward // If not using ofset then query generation is quite straightforward
if(empty($offset)) { if (empty($offset)) {
$sql = parent::buildSelectQuery($query, $parameters); $sql = parent::buildSelectQuery($query, $parameters);
// Inject limit into SELECT fragment // Inject limit into SELECT fragment
if(!empty($limit)) { if (!empty($limit)) {
$sql = preg_replace('/^(SELECT (DISTINCT)?)/i', '${1} TOP '.$limit, $sql); $sql = preg_replace('/^(SELECT (DISTINCT)?)/i', '${1} TOP '.$limit, $sql);
} }
return $sql; return $sql;
@ -27,15 +29,15 @@ class MSSQLQueryBuilder extends DBQueryBuilder {
// workaround for subselect not working with alias functions // workaround for subselect not working with alias functions
// just use the function directly in the order by instead of the alias // just use the function directly in the order by instead of the alias
$selects = $query->getSelect(); $selects = $query->getSelect();
foreach($orderby as $field => $dir) { foreach ($orderby as $field => $dir) {
if(preg_match('/_SortColumn/', $field)) { if (preg_match('/_SortColumn/', $field)) {
unset($orderby[$field]); unset($orderby[$field]);
$orderby[$selects[str_replace('"', '', $field)]] = $dir; $orderby[$selects[str_replace('"', '', $field)]] = $dir;
} }
} }
// Create order expression, using the first column if none explicitly specified // Create order expression, using the first column if none explicitly specified
if($orderby) { if ($orderby) {
// Simple implementation of buildOrderByFragment // Simple implementation of buildOrderByFragment
$statements = array(); $statements = array();
foreach ($orderby as $clause => $dir) { foreach ($orderby as $clause => $dir) {
@ -55,7 +57,7 @@ class MSSQLQueryBuilder extends DBQueryBuilder {
$sql = preg_replace('/^(SELECT (DISTINCT)?)/i', '${1} ROW_NUMBER() OVER ('.$orderByClause.') AS Number, ', $sql); $sql = preg_replace('/^(SELECT (DISTINCT)?)/i', '${1} ROW_NUMBER() OVER ('.$orderByClause.') AS Number, ', $sql);
// Sub-query this SQL // Sub-query this SQL
if(empty($limit)) { if (empty($limit)) {
$limitCondition = "Number > ?"; $limitCondition = "Number > ?";
$parameters[] = $offset; $parameters[] = $offset;
} else { } else {
@ -66,15 +68,17 @@ class MSSQLQueryBuilder extends DBQueryBuilder {
return "SELECT * FROM ($sql) AS Numbered WHERE $limitCondition ORDER BY Number"; return "SELECT * FROM ($sql) AS Numbered WHERE $limitCondition ORDER BY Number";
} }
public function buildLimitFragment(SQLSelect $query, array &$parameters) { public function buildLimitFragment(SQLSelect $query, array &$parameters)
{
// Limit is handled at the buildSelectQuery level // Limit is handled at the buildSelectQuery level
return ''; return '';
} }
public function buildOrderByFragment(SQLSelect $query, array &$parameters) { public function buildOrderByFragment(SQLSelect $query, array &$parameters)
{
// If doing a limit/offset at the same time then don't build the orde by fragment here // If doing a limit/offset at the same time then don't build the orde by fragment here
list($offset, $limit) = $this->parseLimit($query); list($offset, $limit) = $this->parseLimit($query);
if(empty($offset) || empty($limit)) { if (empty($offset) || empty($limit)) {
return parent::buildOrderByFragment($query, $parameters); return parent::buildOrderByFragment($query, $parameters);
} }
return ''; return '';
@ -87,21 +91,25 @@ class MSSQLQueryBuilder extends DBQueryBuilder {
* @return array Two item array with $limit and $offset as values * @return array Two item array with $limit and $offset as values
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
protected function parseLimit(SQLSelect $query) { protected function parseLimit(SQLSelect $query)
{
$limit = ''; $limit = '';
$offset = '0'; $offset = '0';
if(is_array($query->getLimit())) { if (is_array($query->getLimit())) {
$limitArr = $query->getLimit(); $limitArr = $query->getLimit();
if(isset($limitArr['limit'])) $limit = $limitArr['limit']; if (isset($limitArr['limit'])) {
if(isset($limitArr['start'])) $offset = $limitArr['start']; $limit = $limitArr['limit'];
} else if(preg_match('/^([0-9]+) offset ([0-9]+)$/i', trim($query->getLimit()), $matches)) { }
if (isset($limitArr['start'])) {
$offset = $limitArr['start'];
}
} elseif (preg_match('/^([0-9]+) offset ([0-9]+)$/i', trim($query->getLimit()), $matches)) {
$limit = $matches[1]; $limit = $matches[1];
$offset = $matches[2]; $offset = $matches[2];
} else { } else {
//could be a comma delimited string //could be a comma delimited string
$bits = explode(',', $query->getLimit()); $bits = explode(',', $query->getLimit());
if(sizeof($bits) > 1) { if (sizeof($bits) > 1) {
list($offset, $limit) = $bits; list($offset, $limit) = $bits;
} else { } else {
$limit = $bits[0]; $limit = $bits[0];

View File

@ -5,7 +5,8 @@
* *
* @package mssql * @package mssql
*/ */
class MSSQLSchemaManager extends DBSchemaManager { class MSSQLSchemaManager extends DBSchemaManager
{
/** /**
* Stores per-request cached constraint checks that come from the database. * Stores per-request cached constraint checks that come from the database.
@ -22,7 +23,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $prefix The optional prefix for the index. Defaults to "ix" for indexes. * @param string $prefix The optional prefix for the index. Defaults to "ix" for indexes.
* @return string The name of the index * @return string The name of the index
*/ */
function buildMSSQLIndexName($tableName, $indexName, $prefix = 'ix') { public function buildMSSQLIndexName($tableName, $indexName, $prefix = 'ix')
{
// Cleanup names of namespaced tables // Cleanup names of namespaced tables
$tableName = str_replace('\\', '_', $tableName); $tableName = str_replace('\\', '_', $tableName);
@ -37,9 +39,12 @@ class MSSQLSchemaManager extends DBSchemaManager {
* *
* @param string $name Name of full text catalog to use * @param string $name Name of full text catalog to use
*/ */
function createFullTextCatalog($name = 'ftCatalog') { public function createFullTextCatalog($name = 'ftCatalog')
{
$result = $this->fullTextCatalogExists(); $result = $this->fullTextCatalogExists();
if(!$result) $this->query("CREATE FULLTEXT CATALOG \"$name\" AS DEFAULT;"); if (!$result) {
$this->query("CREATE FULLTEXT CATALOG \"$name\" AS DEFAULT;");
}
} }
/** /**
@ -48,7 +53,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $name Name of full text catalog to use * @param string $name Name of full text catalog to use
* @return boolean * @return boolean
*/ */
public function fullTextCatalogExists($name = 'ftCatalog') { public function fullTextCatalogExists($name = 'ftCatalog')
{
return (bool) $this->preparedQuery( return (bool) $this->preparedQuery(
"SELECT name FROM sys.fulltext_catalogs WHERE name = ?;", "SELECT name FROM sys.fulltext_catalogs WHERE name = ?;",
array($name) array($name)
@ -64,14 +70,17 @@ class MSSQLSchemaManager extends DBSchemaManager {
* *
* @param int $maxWaitingTime Time in seconds to wait for the database. * @param int $maxWaitingTime Time in seconds to wait for the database.
*/ */
function waitUntilIndexingFinished($maxWaitingTime = 15) { public function waitUntilIndexingFinished($maxWaitingTime = 15)
if(!$this->database->fullTextEnabled()) return; {
if (!$this->database->fullTextEnabled()) {
return;
}
$this->query("EXEC sp_fulltext_catalog 'ftCatalog', 'Rebuild';"); $this->query("EXEC sp_fulltext_catalog 'ftCatalog', 'Rebuild';");
// Busy wait until it's done updating, but no longer than 15 seconds. // Busy wait until it's done updating, but no longer than 15 seconds.
$start = time(); $start = time();
while(time() - $start < $maxWaitingTime) { while (time() - $start < $maxWaitingTime) {
$status = $this->query("EXEC sp_help_fulltext_catalogs 'ftCatalog';")->first(); $status = $this->query("EXEC sp_help_fulltext_catalogs 'ftCatalog';")->first();
if (isset($status['STATUS']) && $status['STATUS'] == 0) { if (isset($status['STATUS']) && $status['STATUS'] == 0) {
@ -88,9 +97,12 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $tableName * @param string $tableName
* @return boolean TRUE index exists | FALSE index does not exist | NULL no support * @return boolean TRUE index exists | FALSE index does not exist | NULL no support
*/ */
function fulltextIndexExists($tableName) { public function fulltextIndexExists($tableName)
{
// Special case for no full text index support // Special case for no full text index support
if(!$this->database->fullTextEnabled()) return null; if (!$this->database->fullTextEnabled()) {
return null;
}
return (bool) $this->preparedQuery(" return (bool) $this->preparedQuery("
SELECT 1 FROM sys.fulltext_indexes i SELECT 1 FROM sys.fulltext_indexes i
@ -107,11 +119,12 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $tableName Name of table with primary key column "ID" * @param string $tableName Name of table with primary key column "ID"
* @return string Internal identifier for primary key * @return string Internal identifier for primary key
*/ */
function getPrimaryKey($tableName){ public function getPrimaryKey($tableName)
{
$indexes = $this->query("EXEC sp_helpindex '$tableName';"); $indexes = $this->query("EXEC sp_helpindex '$tableName';");
$indexName = ''; $indexName = '';
foreach($indexes as $index) { foreach ($indexes as $index) {
if($index['index_keys'] == 'ID') { if ($index['index_keys'] == 'ID') {
$indexName = $index['index_name']; $indexName = $index['index_name'];
break; break;
} }
@ -126,7 +139,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $tableName * @param string $tableName
* @return string|null * @return string|null
*/ */
function getIdentityColumn($tableName) { public function getIdentityColumn($tableName)
{
return $this->preparedQuery(" return $this->preparedQuery("
SELECT SELECT
TABLE_NAME + '.' + COLUMN_NAME, TABLE_NAME + '.' + COLUMN_NAME,
@ -140,23 +154,29 @@ class MSSQLSchemaManager extends DBSchemaManager {
", array('dbo', $tableName))->value(); ", array('dbo', $tableName))->value();
} }
public function createDatabase($name) { public function createDatabase($name)
{
$this->query("CREATE DATABASE \"$name\""); $this->query("CREATE DATABASE \"$name\"");
} }
public function dropDatabase($name) { public function dropDatabase($name)
{
$this->query("DROP DATABASE \"$name\""); $this->query("DROP DATABASE \"$name\"");
} }
public function databaseExists($name) { public function databaseExists($name)
{
$databases = $this->databaseList(); $databases = $this->databaseList();
foreach($databases as $dbname) { foreach ($databases as $dbname) {
if($dbname == $name) return true; if ($dbname == $name) {
return true;
}
} }
return false; return false;
} }
public function databaseList() { public function databaseList()
{
return $this->query('SELECT NAME FROM sys.sysdatabases')->column(); return $this->query('SELECT NAME FROM sys.sysdatabases')->column();
} }
@ -170,12 +190,17 @@ class MSSQLSchemaManager extends DBSchemaManager {
* - 'temporary' - If true, then a temporary table will be created * - 'temporary' - If true, then a temporary table will be created
* @return The table name generated. This may be different from the table name, for example with temporary tables. * @return The table name generated. This may be different from the table name, for example with temporary tables.
*/ */
public function createTable($tableName, $fields = null, $indexes = null, $options = null, $advancedOptions = null) { public function createTable($tableName, $fields = null, $indexes = null, $options = null, $advancedOptions = null)
{
$fieldSchemas = $indexSchemas = ""; $fieldSchemas = $indexSchemas = "";
if($fields) foreach($fields as $k => $v) $fieldSchemas .= "\"$k\" $v,\n"; if ($fields) {
foreach ($fields as $k => $v) {
$fieldSchemas .= "\"$k\" $v,\n";
}
}
// Temporary tables start with "#" in MSSQL-land // Temporary tables start with "#" in MSSQL-land
if(!empty($options['temporary'])) { if (!empty($options['temporary'])) {
// Randomize the temp table name to avoid conflicts in the tempdb table which derived databases share // Randomize the temp table name to avoid conflicts in the tempdb table which derived databases share
$tableName = "#$tableName" . '-' . rand(1000000, 9999999); $tableName = "#$tableName" . '-' . rand(1000000, 9999999);
} }
@ -187,11 +212,15 @@ class MSSQLSchemaManager extends DBSchemaManager {
//we need to generate indexes like this: CREATE INDEX IX_vault_to_export ON vault (to_export); //we need to generate indexes like this: CREATE INDEX IX_vault_to_export ON vault (to_export);
//This needs to be done AFTER the table creation, so we can set up the fulltext indexes correctly //This needs to be done AFTER the table creation, so we can set up the fulltext indexes correctly
if($indexes) foreach($indexes as $k => $v) { if ($indexes) {
foreach ($indexes as $k => $v) {
$indexSchemas .= $this->getIndexSqlDefinition($tableName, $k, $v) . "\n"; $indexSchemas .= $this->getIndexSqlDefinition($tableName, $k, $v) . "\n";
} }
}
if($indexSchemas) $this->query($indexSchemas); if ($indexSchemas) {
$this->query($indexSchemas);
}
return $tableName; return $tableName;
} }
@ -204,23 +233,40 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param $alteredFields Updated fields, a map of field name => field schema * @param $alteredFields Updated fields, a map of field name => field schema
* @param $alteredIndexes Updated indexes, a map of index name => index type * @param $alteredIndexes Updated indexes, a map of index name => index type
*/ */
public function alterTable($tableName, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions=null, $advancedOptions=null) { public function alterTable($tableName, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions=null, $advancedOptions=null)
{
$alterList = array(); $alterList = array();
// drop any fulltext indexes that exist on the table before altering the structure // drop any fulltext indexes that exist on the table before altering the structure
if($this->fullTextIndexExists($tableName)) { if ($this->fullTextIndexExists($tableName)) {
$alterList[] = "\nDROP FULLTEXT INDEX ON \"$tableName\";"; $alterList[] = "\nDROP FULLTEXT INDEX ON \"$tableName\";";
} }
if($newFields) foreach($newFields as $k => $v) $alterList[] = "ALTER TABLE \"$tableName\" ADD \"$k\" $v"; if ($newFields) {
foreach ($newFields as $k => $v) {
$alterList[] = "ALTER TABLE \"$tableName\" ADD \"$k\" $v";
}
}
if($alteredFields) foreach($alteredFields as $k => $v) $alterList[] = $this->alterTableAlterColumn($tableName, $k, $v); if ($alteredFields) {
if($alteredIndexes) foreach($alteredIndexes as $k => $v) $alterList[] = $this->getIndexSqlDefinition($tableName, $k, $v); foreach ($alteredFields as $k => $v) {
if($newIndexes) foreach($newIndexes as $k => $v) $alterList[] = $this->getIndexSqlDefinition($tableName, $k, $v); $alterList[] = $this->alterTableAlterColumn($tableName, $k, $v);
}
}
if ($alteredIndexes) {
foreach ($alteredIndexes as $k => $v) {
$alterList[] = $this->getIndexSqlDefinition($tableName, $k, $v);
}
}
if ($newIndexes) {
foreach ($newIndexes as $k => $v) {
$alterList[] = $this->getIndexSqlDefinition($tableName, $k, $v);
}
}
if($alterList) { if ($alterList) {
foreach($alterList as $alteration) { foreach ($alterList as $alteration) {
if($alteration != '') { if ($alteration != '') {
$this->query($alteration); $this->query($alteration);
} }
} }
@ -235,7 +281,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $columnName Column name the constraint is for * @param string $columnName Column name the constraint is for
* @return string|null * @return string|null
*/ */
public function getConstraintName($tableName, $columnName) { public function getConstraintName($tableName, $columnName)
{
return $this->preparedQuery(" return $this->preparedQuery("
SELECT CONSTRAINT_NAME SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
@ -256,10 +303,11 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $columnName Column name the constraint is for * @param string $columnName Column name the constraint is for
* @return string The check string * @return string The check string
*/ */
public function getConstraintCheckClause($tableName, $columnName) { public function getConstraintCheckClause($tableName, $columnName)
{
// Check already processed table columns // Check already processed table columns
if(isset(self::$cached_checks[$tableName])) { if (isset(self::$cached_checks[$tableName])) {
if(!isset(self::$cached_checks[$tableName][$columnName])) { if (!isset(self::$cached_checks[$tableName][$columnName])) {
return null; return null;
} }
return self::$cached_checks[$tableName][$columnName]; return self::$cached_checks[$tableName][$columnName];
@ -267,7 +315,7 @@ class MSSQLSchemaManager extends DBSchemaManager {
// Regenerate cehcks for this table // Regenerate cehcks for this table
$checks = array(); $checks = array();
foreach($this->preparedQuery(" foreach ($this->preparedQuery("
SELECT CAST(CHECK_CLAUSE AS TEXT) AS CHECK_CLAUSE, COLUMN_NAME SELECT CAST(CHECK_CLAUSE AS TEXT) AS CHECK_CLAUSE, COLUMN_NAME
FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS AS CC FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS AS CC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CCU ON CCU.CONSTRAINT_NAME = CC.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CCU ON CCU.CONSTRAINT_NAME = CC.CONSTRAINT_NAME
@ -290,7 +338,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $colName Name of the column * @param string $colName Name of the column
* @return string|null * @return string|null
*/ */
protected function defaultConstraintName($tableName, $colName) { protected function defaultConstraintName($tableName, $colName)
{
return $this->preparedQuery(" return $this->preparedQuery("
SELECT s.name --default name SELECT s.name --default name
FROM sys.sysobjects s FROM sys.sysobjects s
@ -309,12 +358,13 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $clause Check clause to parse values from * @param string $clause Check clause to parse values from
* @return array Enum values * @return array Enum values
*/ */
protected function enumValuesFromCheckClause($clause) { protected function enumValuesFromCheckClause($clause)
{
$segments = preg_split('/ +OR *\[/i', $clause); $segments = preg_split('/ +OR *\[/i', $clause);
$constraints = array(); $constraints = array();
foreach($segments as $segment) { foreach ($segments as $segment) {
$bits = preg_split('/ *= */', $segment); $bits = preg_split('/ *= */', $segment);
for($i = 1; $i < sizeof($bits); $i += 2) { for ($i = 1; $i < sizeof($bits); $i += 2) {
array_unshift($constraints, substr(rtrim($bits[$i], ')'), 1, -1)); array_unshift($constraints, substr(rtrim($bits[$i], ')'), 1, -1));
} }
} }
@ -329,7 +379,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $colSpec String which contains conditions for a column * @param string $colSpec String which contains conditions for a column
* @return string * @return string
*/ */
protected function alterTableAlterColumn($tableName, $colName, $colSpec){ protected function alterTableAlterColumn($tableName, $colName, $colSpec)
{
// First, we split the column specifications into parts // First, we split the column specifications into parts
// TODO: this returns an empty array for the following string: int(11) not null auto_increment // TODO: this returns an empty array for the following string: int(11) not null auto_increment
@ -344,34 +395,34 @@ class MSSQLSchemaManager extends DBSchemaManager {
// drop *ALL* indexes on a table before proceeding // drop *ALL* indexes on a table before proceeding
// this won't drop primary keys, though // this won't drop primary keys, though
$indexes = $this->indexNames($tableName); $indexes = $this->indexNames($tableName);
foreach($indexes as $indexName) { foreach ($indexes as $indexName) {
$alterQueries[] = "DROP INDEX \"$indexName\" ON \"$tableName\";"; $alterQueries[] = "DROP INDEX \"$indexName\" ON \"$tableName\";";
} }
$prefix = "ALTER TABLE \"$tableName\" "; $prefix = "ALTER TABLE \"$tableName\" ";
// Remove the old default prior to adjusting the column. // Remove the old default prior to adjusting the column.
if($defaultConstraintName = $this->defaultConstraintName($tableName, $colName)) { if ($defaultConstraintName = $this->defaultConstraintName($tableName, $colName)) {
$alterQueries[] = "$prefix DROP CONSTRAINT \"$defaultConstraintName\";"; $alterQueries[] = "$prefix DROP CONSTRAINT \"$defaultConstraintName\";";
} }
if(isset($matches['definition'])) { if (isset($matches['definition'])) {
//We will prevent any changes being made to the ID column. Primary key indexes will have a fit if we do anything here. //We will prevent any changes being made to the ID column. Primary key indexes will have a fit if we do anything here.
if($colName != 'ID'){ if ($colName != 'ID') {
// SET null / not null // SET null / not null
$nullFragment = empty($matches['null']) ? '' : " {$matches['null']}"; $nullFragment = empty($matches['null']) ? '' : " {$matches['null']}";
$alterQueries[] = "$prefix ALTER COLUMN \"$colName\" {$matches['definition']}$nullFragment;"; $alterQueries[] = "$prefix ALTER COLUMN \"$colName\" {$matches['definition']}$nullFragment;";
// Add a default back // Add a default back
if(!empty($matches['default'])) { if (!empty($matches['default'])) {
$alterQueries[] = "$prefix ADD {$matches['default']} FOR \"$colName\";"; $alterQueries[] = "$prefix ADD {$matches['default']} FOR \"$colName\";";
} }
// SET check constraint (The constraint HAS to be dropped) // SET check constraint (The constraint HAS to be dropped)
if(!empty($matches['check'])) { if (!empty($matches['check'])) {
$constraint = $this->getConstraintName($tableName, $colName); $constraint = $this->getConstraintName($tableName, $colName);
if($constraint) { if ($constraint) {
$alterQueries[] = "$prefix DROP CONSTRAINT {$constraint};"; $alterQueries[] = "$prefix DROP CONSTRAINT {$constraint};";
} }
@ -384,7 +435,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
return implode("\n", $alterQueries); return implode("\n", $alterQueries);
} }
public function renameTable($oldTableName, $newTableName) { public function renameTable($oldTableName, $newTableName)
{
$this->query("EXEC sp_rename \"$oldTableName\", \"$newTableName\""); $this->query("EXEC sp_rename \"$oldTableName\", \"$newTableName\"");
} }
@ -395,11 +447,13 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @var string $tableName The name of the table. * @var string $tableName The name of the table.
* @return boolean Return true if the table has integrity after the method is complete. * @return boolean Return true if the table has integrity after the method is complete.
*/ */
public function checkAndRepairTable($tableName) { public function checkAndRepairTable($tableName)
{
return true; return true;
} }
public function createField($tableName, $fieldName, $fieldSpec) { public function createField($tableName, $fieldName, $fieldSpec)
{
$this->query("ALTER TABLE \"$tableName\" ADD \"$fieldName\" $fieldSpec"); $this->query("ALTER TABLE \"$tableName\" ADD \"$fieldName\" $fieldSpec");
} }
@ -409,15 +463,18 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $fieldName The name of the field to change. * @param string $fieldName The name of the field to change.
* @param string $fieldSpec The new field specification * @param string $fieldSpec The new field specification
*/ */
public function alterField($tableName, $fieldName, $fieldSpec) { public function alterField($tableName, $fieldName, $fieldSpec)
{
$this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec"); $this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec");
} }
public function renameField($tableName, $oldName, $newName) { public function renameField($tableName, $oldName, $newName)
{
$this->query("EXEC sp_rename @objname = '$tableName.$oldName', @newname = '$newName', @objtype = 'COLUMN'"); $this->query("EXEC sp_rename @objname = '$tableName.$oldName', @newname = '$newName', @objtype = 'COLUMN'");
} }
public function fieldList($table) { public function fieldList($table)
{
//This gets us more information than we need, but I've included it all for the moment.... //This gets us more information than we need, but I've included it all for the moment....
$fieldRecords = $this->preparedQuery("SELECT ordinal_position, column_name, data_type, column_default, $fieldRecords = $this->preparedQuery("SELECT ordinal_position, column_name, data_type, column_default,
is_nullable, character_maximum_length, numeric_precision, numeric_scale, collation_name is_nullable, character_maximum_length, numeric_precision, numeric_scale, collation_name
@ -430,46 +487,46 @@ class MSSQLSchemaManager extends DBSchemaManager {
// will cause subsequent queries to fail in this method // will cause subsequent queries to fail in this method
$fields = array(); $fields = array();
$output = array(); $output = array();
foreach($fieldRecords as $record) { foreach ($fieldRecords as $record) {
$fields[] = $record; $fields[] = $record;
} }
foreach($fields as $field) { foreach ($fields as $field) {
// Update the data_type field to be a complete column definition string for use by // Update the data_type field to be a complete column definition string for use by
// SS_Database::requireField() // SS_Database::requireField()
switch($field['data_type']){ switch ($field['data_type']) {
case 'int': case 'int':
case 'bigint': case 'bigint':
case 'numeric': case 'numeric':
case 'float': case 'float':
case 'bit': case 'bit':
if($field['data_type'] != 'bigint' && $field['data_type'] != 'int' && $sizeSuffix = $field['numeric_precision']) { if ($field['data_type'] != 'bigint' && $field['data_type'] != 'int' && $sizeSuffix = $field['numeric_precision']) {
$field['data_type'] .= "($sizeSuffix)"; $field['data_type'] .= "($sizeSuffix)";
} }
if($field['is_nullable'] == 'YES') { if ($field['is_nullable'] == 'YES') {
$field['data_type'] .= ' null'; $field['data_type'] .= ' null';
} else { } else {
$field['data_type'] .= ' not null'; $field['data_type'] .= ' not null';
} }
if($field['column_default']) { if ($field['column_default']) {
$default=substr($field['column_default'], 2, -2); $default=substr($field['column_default'], 2, -2);
$field['data_type'] .= " default $default"; $field['data_type'] .= " default $default";
} }
break; break;
case 'decimal': case 'decimal':
if($field['numeric_precision']) { if ($field['numeric_precision']) {
$sizeSuffix = $field['numeric_precision'] . ',' . $field['numeric_scale']; $sizeSuffix = $field['numeric_precision'] . ',' . $field['numeric_scale'];
$field['data_type'] .= "($sizeSuffix)"; $field['data_type'] .= "($sizeSuffix)";
} }
if($field['is_nullable'] == 'YES') { if ($field['is_nullable'] == 'YES') {
$field['data_type'] .= ' null'; $field['data_type'] .= ' null';
} else { } else {
$field['data_type'] .= ' not null'; $field['data_type'] .= ' not null';
} }
if($field['column_default']) { if ($field['column_default']) {
$default=substr($field['column_default'], 2, -2); $default=substr($field['column_default'], 2, -2);
$field['data_type'] .= " default $default"; $field['data_type'] .= " default $default";
} }
@ -479,7 +536,7 @@ class MSSQLSchemaManager extends DBSchemaManager {
case 'varchar': case 'varchar':
//Check to see if there's a constraint attached to this column: //Check to see if there's a constraint attached to this column:
$clause = $this->getConstraintCheckClause($table, $field['column_name']); $clause = $this->getConstraintCheckClause($table, $field['column_name']);
if($clause) { if ($clause) {
$constraints = $this->enumValuesFromCheckClause($clause); $constraints = $this->enumValuesFromCheckClause($clause);
$default=substr($field['column_default'], 2, -2); $default=substr($field['column_default'], 2, -2);
$field['data_type'] = $this->enum(array( $field['data_type'] = $this->enum(array(
@ -493,23 +550,24 @@ class MSSQLSchemaManager extends DBSchemaManager {
default: default:
$sizeSuffix = $field['character_maximum_length']; $sizeSuffix = $field['character_maximum_length'];
if($sizeSuffix == '-1') $sizeSuffix = 'max'; if ($sizeSuffix == '-1') {
if($sizeSuffix) { $sizeSuffix = 'max';
}
if ($sizeSuffix) {
$field['data_type'] .= "($sizeSuffix)"; $field['data_type'] .= "($sizeSuffix)";
} }
if($field['is_nullable'] == 'YES') { if ($field['is_nullable'] == 'YES') {
$field['data_type'] .= ' null'; $field['data_type'] .= ' null';
} else { } else {
$field['data_type'] .= ' not null'; $field['data_type'] .= ' not null';
} }
if($field['column_default']) { if ($field['column_default']) {
$default=substr($field['column_default'], 2, -2); $default=substr($field['column_default'], 2, -2);
$field['data_type'] .= " default '$default'"; $field['data_type'] .= " default '$default'";
} }
} }
$output[$field['column_name']] = $field; $output[$field['column_name']] = $field;
} }
return $output; return $output;
@ -521,7 +579,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $indexName The name of the index. * @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see SS_Database::requireIndex() for more details. * @param string $indexSpec The specification of the index, see SS_Database::requireIndex() for more details.
*/ */
public function createIndex($tableName, $indexName, $indexSpec) { public function createIndex($tableName, $indexName, $indexSpec)
{
$this->query($this->getIndexSqlDefinition($tableName, $indexName, $indexSpec)); $this->query($this->getIndexSqlDefinition($tableName, $indexName, $indexSpec));
} }
@ -534,7 +593,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* or parsed array form * or parsed array form
* @return string The SQL required to generate this index * @return string The SQL required to generate this index
*/ */
protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec) { protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec)
{
// Determine index name // Determine index name
$index = $this->buildMSSQLIndexName($tableName, $indexName); $index = $this->buildMSSQLIndexName($tableName, $indexName);
@ -545,25 +605,26 @@ class MSSQLSchemaManager extends DBSchemaManager {
$drop = "IF EXISTS (SELECT name FROM sys.indexes WHERE name = '$index') DROP INDEX $index ON \"$tableName\";"; $drop = "IF EXISTS (SELECT name FROM sys.indexes WHERE name = '$index') DROP INDEX $index ON \"$tableName\";";
// create a type-specific index // create a type-specific index
if($indexSpec['type'] == 'fulltext' && $this->database->fullTextEnabled()) { if ($indexSpec['type'] == 'fulltext' && $this->database->fullTextEnabled()) {
// enable fulltext on this table // enable fulltext on this table
$this->createFullTextCatalog(); $this->createFullTextCatalog();
$primary_key = $this->getPrimaryKey($tableName); $primary_key = $this->getPrimaryKey($tableName);
if($primary_key) { if ($primary_key) {
return "$drop CREATE FULLTEXT INDEX ON \"$tableName\" ({$indexSpec['value']})" return "$drop CREATE FULLTEXT INDEX ON \"$tableName\" ({$indexSpec['value']})"
. "KEY INDEX $primary_key WITH CHANGE_TRACKING AUTO;"; . "KEY INDEX $primary_key WITH CHANGE_TRACKING AUTO;";
} }
} }
if($indexSpec['type'] == 'unique') { if ($indexSpec['type'] == 'unique') {
return "$drop CREATE UNIQUE INDEX $index ON \"$tableName\" ({$indexSpec['value']});"; return "$drop CREATE UNIQUE INDEX $index ON \"$tableName\" ({$indexSpec['value']});";
} }
return "$drop CREATE INDEX $index ON \"$tableName\" ({$indexSpec['value']});"; return "$drop CREATE INDEX $index ON \"$tableName\" ({$indexSpec['value']});";
} }
public function alterIndex($tableName, $indexName, $indexSpec) { public function alterIndex($tableName, $indexName, $indexSpec)
{
$this->createIndex($tableName, $indexName, $indexSpec); $this->createIndex($tableName, $indexName, $indexSpec);
} }
@ -572,13 +633,14 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @param string $table The table name. * @param string $table The table name.
* @return array * @return array
*/ */
public function indexList($table) { public function indexList($table)
{
$indexes = $this->query("EXEC sp_helpindex '$table';"); $indexes = $this->query("EXEC sp_helpindex '$table';");
$indexList = array(); $indexList = array();
// Enumerate all basic indexes // Enumerate all basic indexes
foreach($indexes as $index) { foreach ($indexes as $index) {
if(strpos($index['index_description'], 'unique') !== false) { if (strpos($index['index_description'], 'unique') !== false) {
$indexType = 'unique '; $indexType = 'unique ';
} else { } else {
$indexType = 'index '; $indexType = 'index ';
@ -598,18 +660,18 @@ class MSSQLSchemaManager extends DBSchemaManager {
} }
// Now we need to check to see if we have any fulltext indexes attached to this table: // Now we need to check to see if we have any fulltext indexes attached to this table:
if($this->database->fullTextEnabled()) { if ($this->database->fullTextEnabled()) {
$result = $this->query('EXEC sp_help_fulltext_columns;'); $result = $this->query('EXEC sp_help_fulltext_columns;');
// Extract columns from this fulltext definition // Extract columns from this fulltext definition
$columns = array(); $columns = array();
foreach($result as $row) { foreach ($result as $row) {
if($row['TABLE_NAME'] == $table) { if ($row['TABLE_NAME'] == $table) {
$columns[] = $row['FULLTEXT_COLUMN_NAME']; $columns[] = $row['FULLTEXT_COLUMN_NAME'];
} }
} }
if(!empty($columns)) { if (!empty($columns)) {
$indexList['SearchFields'] = $this->parseIndexSpec('SearchFields', array( $indexList['SearchFields'] = $this->parseIndexSpec('SearchFields', array(
'name' => 'SearchFields', 'name' => 'SearchFields',
'value' => $this->implodeColumnList($columns), 'value' => $this->implodeColumnList($columns),
@ -627,7 +689,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* *
* @return array * @return array
*/ */
public function indexNames($tableName) { public function indexNames($tableName)
{
return $this->preparedQuery(' return $this->preparedQuery('
SELECT ind.name FROM sys.indexes ind SELECT ind.name FROM sys.indexes ind
INNER JOIN sys.tables t ON ind.object_id = t.object_id INNER JOIN sys.tables t ON ind.object_id = t.object_id
@ -636,9 +699,10 @@ class MSSQLSchemaManager extends DBSchemaManager {
)->column(); )->column();
} }
public function tableList() { public function tableList()
{
$tables = array(); $tables = array();
foreach($this->query("EXEC sp_tables @table_owner = 'dbo';") as $record) { foreach ($this->query("EXEC sp_tables @table_owner = 'dbo';") as $record) {
$tables[strtolower($record['TABLE_NAME'])] = $record['TABLE_NAME']; $tables[strtolower($record['TABLE_NAME'])] = $record['TABLE_NAME'];
} }
return $tables; return $tables;
@ -651,7 +715,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function boolean($values) { public function boolean($values)
{
$default = ($values['default']) ? '1' : '0'; $default = ($values['default']) ? '1' : '0';
return 'bit not null default ' . $default; return 'bit not null default ' . $default;
} }
@ -662,7 +727,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function date($values) { public function date($values)
{
return 'date null'; return 'date null';
} }
@ -672,16 +738,17 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function decimal($values) { public function decimal($values)
{
// Avoid empty strings being put in the db // Avoid empty strings being put in the db
if($values['precision'] == '') { if ($values['precision'] == '') {
$precision = 1; $precision = 1;
} else { } else {
$precision = $values['precision']; $precision = $values['precision'];
} }
$defaultValue = '0'; $defaultValue = '0';
if(isset($values['default']) && is_numeric($values['default'])) { if (isset($values['default']) && is_numeric($values['default'])) {
$defaultValue = $values['default']; $defaultValue = $values['default'];
} }
@ -694,7 +761,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function enum($values) { public function enum($values)
{
// Enums are a bit different. We'll be creating a varchar(255) with a constraint of all the // Enums are a bit different. We'll be creating a varchar(255) with a constraint of all the
// usual enum options. // usual enum options.
// NOTE: In this one instance, we are including the table name in the values array // NOTE: In this one instance, we are including the table name in the values array
@ -709,7 +777,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
/** /**
* @todo Make this work like {@link MySQLDatabase::set()} * @todo Make this work like {@link MySQLDatabase::set()}
*/ */
public function set($values) { public function set($values)
{
return $this->enum($values); return $this->enum($values);
} }
@ -719,7 +788,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function float($values) { public function float($values)
{
return 'float(53) not null default ' . $values['default']; return 'float(53) not null default ' . $values['default'];
} }
@ -729,7 +799,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function int($values) { public function int($values)
{
return 'int not null default ' . (int) $values['default']; return 'int not null default ' . (int) $values['default'];
} }
@ -739,7 +810,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function bigint($values) { public function bigint($values)
{
return 'bigint not null default ' . (int) $values['default']; return 'bigint not null default ' . (int) $values['default'];
} }
@ -750,7 +822,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function ss_datetime($values) { public function ss_datetime($values)
{
return 'datetime null'; return 'datetime null';
} }
@ -760,7 +833,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function text($values) { public function text($values)
{
$collation = MSSQLDatabase::get_collation(); $collation = MSSQLDatabase::get_collation();
$collationSQL = $collation ? " COLLATE $collation" : ""; $collationSQL = $collation ? " COLLATE $collation" : "";
return "nvarchar(max)$collationSQL null"; return "nvarchar(max)$collationSQL null";
@ -772,7 +846,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function time($values){ public function time($values)
{
return 'time null'; return 'time null';
} }
@ -782,7 +857,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* @params array $values Contains a tokenised list of info about this data type * @params array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function varchar($values) { public function varchar($values)
{
$collation = MSSQLDatabase::get_collation(); $collation = MSSQLDatabase::get_collation();
$collationSQL = $collation ? " COLLATE $collation" : ""; $collationSQL = $collation ? " COLLATE $collation" : "";
return "nvarchar(" . $values['precision'] . ")$collationSQL null"; return "nvarchar(" . $values['precision'] . ")$collationSQL null";
@ -792,7 +868,8 @@ class MSSQLSchemaManager extends DBSchemaManager {
* Return a 4 digit numeric type. * Return a 4 digit numeric type.
* @return string * @return string
*/ */
public function year($values) { public function year($values)
{
return 'numeric(4)'; return 'numeric(4)';
} }
@ -800,17 +877,19 @@ class MSSQLSchemaManager extends DBSchemaManager {
* This returns the column which is the primary key for each table * This returns the column which is the primary key for each table
* @return string * @return string
*/ */
function IdColumn($asDbValue = false, $hasAutoIncPK = true){ public function IdColumn($asDbValue = false, $hasAutoIncPK = true)
if($asDbValue) { {
if ($asDbValue) {
return 'int not null'; return 'int not null';
} else if($hasAutoIncPK) { } elseif ($hasAutoIncPK) {
return 'int identity(1,1)'; return 'int identity(1,1)';
} else { } else {
return 'int not null'; return 'int not null';
} }
} }
function hasTable($tableName) { public function hasTable($tableName)
{
return (bool)$this->preparedQuery( return (bool)$this->preparedQuery(
"SELECT table_name FROM information_schema.tables WHERE table_name = ?", "SELECT table_name FROM information_schema.tables WHERE table_name = ?",
array($tableName) array($tableName)
@ -821,12 +900,13 @@ class MSSQLSchemaManager extends DBSchemaManager {
* Returns the values of the given enum field * Returns the values of the given enum field
* NOTE: Experimental; introduced for db-abstraction and may changed before 2.4 is released. * NOTE: Experimental; introduced for db-abstraction and may changed before 2.4 is released.
*/ */
public function enumValuesForField($tableName, $fieldName) { public function enumValuesForField($tableName, $fieldName)
{
$classes = array(); $classes = array();
// Get the enum of all page types from the SiteTree table // Get the enum of all page types from the SiteTree table
$clause = $this->getConstraintCheckClause($tableName, $fieldName); $clause = $this->getConstraintCheckClause($tableName, $fieldName);
if($clause) { if ($clause) {
$classes = $this->enumValuesFromCheckClause($clause); $classes = $this->enumValuesFromCheckClause($clause);
} }
@ -839,18 +919,20 @@ class MSSQLSchemaManager extends DBSchemaManager {
* For instance, MSSQL uses 'BIGINT', while MySQL uses 'UNSIGNED' * For instance, MSSQL uses 'BIGINT', while MySQL uses 'UNSIGNED'
* and PostgreSQL uses 'INT'. * and PostgreSQL uses 'INT'.
*/ */
function dbDataType($type){ public function dbDataType($type)
{
$values = array( $values = array(
'unsigned integer'=>'BIGINT' 'unsigned integer'=>'BIGINT'
); );
if(isset($values[$type])) { if (isset($values[$type])) {
return $values[$type]; return $values[$type];
} else { } else {
return ''; return '';
} }
} }
protected function indexKey($table, $index, $spec) { protected function indexKey($table, $index, $spec)
{
return $index; return $index;
} }
} }

View File

@ -5,7 +5,8 @@
* *
* @package mssql * @package mssql
*/ */
class SQLServerConnector extends DBConnector { class SQLServerConnector extends DBConnector
{
/** /**
* Connection to the DBMS. * Connection to the DBMS.
@ -30,9 +31,10 @@ class SQLServerConnector extends DBConnector {
*/ */
protected $selectedDatabase = null; protected $selectedDatabase = null;
public function connect($parameters, $selectDB = false) { public function connect($parameters, $selectDB = false)
{
// Disable default warnings as errors behaviour for sqlsrv to keep it in line with mssql functions // Disable default warnings as errors behaviour for sqlsrv to keep it in line with mssql functions
if(ini_get('sqlsrv.WarningsReturnAsErrors')) { if (ini_get('sqlsrv.WarningsReturnAsErrors')) {
ini_set('sqlsrv.WarningsReturnAsErrors', 'Off'); ini_set('sqlsrv.WarningsReturnAsErrors', 'Off');
} }
@ -45,7 +47,7 @@ class SQLServerConnector extends DBConnector {
'MultipleActiveResultSets' => $multiResultSets 'MultipleActiveResultSets' => $multiResultSets
); );
if( !(defined('MSSQL_USE_WINDOWS_AUTHENTICATION') && MSSQL_USE_WINDOWS_AUTHENTICATION == true) if (!(defined('MSSQL_USE_WINDOWS_AUTHENTICATION') && MSSQL_USE_WINDOWS_AUTHENTICATION == true)
&& empty($parameters['windowsauthentication']) && empty($parameters['windowsauthentication'])
) { ) {
$options['UID'] = $parameters['username']; $options['UID'] = $parameters['username'];
@ -53,15 +55,15 @@ class SQLServerConnector extends DBConnector {
} }
// Required by MS Azure database // Required by MS Azure database
if($selectDB && !empty($parameters['database'])) { if ($selectDB && !empty($parameters['database'])) {
$options['Database'] = $parameters['database']; $options['Database'] = $parameters['database'];
} }
$this->dbConn = sqlsrv_connect($parameters['server'], $options); $this->dbConn = sqlsrv_connect($parameters['server'], $options);
if(empty($this->dbConn)) { if (empty($this->dbConn)) {
$this->databaseError("Couldn't connect to SQL Server database"); $this->databaseError("Couldn't connect to SQL Server database");
} elseif($selectDB && !empty($parameters['database'])) { } elseif ($selectDB && !empty($parameters['database'])) {
// Check selected database (Azure) // Check selected database (Azure)
$this->selectedDatabase = $parameters['database']; $this->selectedDatabase = $parameters['database'];
} }
@ -70,7 +72,8 @@ class SQLServerConnector extends DBConnector {
/** /**
* Start transaction. READ ONLY not supported. * Start transaction. READ ONLY not supported.
*/ */
public function transactionStart(){ public function transactionStart()
{
$result = sqlsrv_begin_transaction($this->dbConn); $result = sqlsrv_begin_transaction($this->dbConn);
if (!$result) { if (!$result) {
$this->databaseError("Couldn't start the transaction."); $this->databaseError("Couldn't start the transaction.");
@ -80,7 +83,8 @@ class SQLServerConnector extends DBConnector {
/** /**
* Commit everything inside this transaction so far * Commit everything inside this transaction so far
*/ */
public function transactionEnd() { public function transactionEnd()
{
$result = sqlsrv_commit($this->dbConn); $result = sqlsrv_commit($this->dbConn);
if (!$result) { if (!$result) {
$this->databaseError("Couldn't commit the transaction."); $this->databaseError("Couldn't commit the transaction.");
@ -92,44 +96,51 @@ class SQLServerConnector extends DBConnector {
* If you encounter a problem at any point during a transaction, you may * If you encounter a problem at any point during a transaction, you may
* need to rollback that particular query, or return to a savepoint * need to rollback that particular query, or return to a savepoint
*/ */
public function transactionRollback(){ public function transactionRollback()
{
$result = sqlsrv_rollback($this->dbConn); $result = sqlsrv_rollback($this->dbConn);
if (!$result) { if (!$result) {
$this->databaseError("Couldn't rollback the transaction."); $this->databaseError("Couldn't rollback the transaction.");
} }
} }
public function affectedRows() { public function affectedRows()
{
return $this->lastAffectedRows; return $this->lastAffectedRows;
} }
public function getLastError() { public function getLastError()
{
$errorMessages = array(); $errorMessages = array();
$errors = sqlsrv_errors(); $errors = sqlsrv_errors();
if($errors) foreach($errors as $info) { if ($errors) {
foreach ($errors as $info) {
$errorMessages[] = implode(', ', array($info['SQLSTATE'], $info['code'], $info['message'])); $errorMessages[] = implode(', ', array($info['SQLSTATE'], $info['code'], $info['message']));
} }
}
return implode('; ', $errorMessages); return implode('; ', $errorMessages);
} }
public function isActive() { public function isActive()
{
return $this->dbConn && $this->selectedDatabase; return $this->dbConn && $this->selectedDatabase;
} }
public function preparedQuery($sql, $parameters, $errorLevel = E_USER_ERROR) { public function preparedQuery($sql, $parameters, $errorLevel = E_USER_ERROR)
{
// Reset state // Reset state
$this->lastAffectedRows = 0; $this->lastAffectedRows = 0;
// Run query // Run query
$parsedParameters = $this->parameterValues($parameters); $parsedParameters = $this->parameterValues($parameters);
if(empty($parsedParameters)) { if (empty($parsedParameters)) {
$handle = sqlsrv_query($this->dbConn, $sql); $handle = sqlsrv_query($this->dbConn, $sql);
} else { } else {
$handle = sqlsrv_query($this->dbConn, $sql, $parsedParameters); $handle = sqlsrv_query($this->dbConn, $sql, $parsedParameters);
} }
// Check for error // Check for error
if(!$handle) { if (!$handle) {
$this->databaseError($this->getLastError(), $errorLevel, $sql, $parsedParameters); $this->databaseError($this->getLastError(), $errorLevel, $sql, $parsedParameters);
return null; return null;
} }
@ -139,36 +150,43 @@ class SQLServerConnector extends DBConnector {
return new SQLServerQuery($this, $handle); return new SQLServerQuery($this, $handle);
} }
public function query($sql, $errorLevel = E_USER_ERROR) { public function query($sql, $errorLevel = E_USER_ERROR)
{
return $this->preparedQuery($sql, array(), $errorLevel); return $this->preparedQuery($sql, array(), $errorLevel);
} }
public function selectDatabase($name) { public function selectDatabase($name)
{
$this->query("USE \"$name\""); $this->query("USE \"$name\"");
$this->selectedDatabase = $name; $this->selectedDatabase = $name;
return true; return true;
} }
public function __destruct() { public function __destruct()
if(is_resource($this->dbConn)) { {
if (is_resource($this->dbConn)) {
sqlsrv_close($this->dbConn); sqlsrv_close($this->dbConn);
} }
} }
public function getVersion() { public function getVersion()
{
// @todo - use sqlsrv_server_info? // @todo - use sqlsrv_server_info?
return trim($this->query("SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))")->value()); return trim($this->query("SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))")->value());
} }
public function getGeneratedID($table) { public function getGeneratedID($table)
{
return $this->query("SELECT IDENT_CURRENT('$table')")->value(); return $this->query("SELECT IDENT_CURRENT('$table')")->value();
} }
public function getSelectedDatabase() { public function getSelectedDatabase()
{
return $this->selectedDatabase; return $this->selectedDatabase;
} }
public function unloadDatabase() { public function unloadDatabase()
{
$this->selectDatabase('Master'); $this->selectDatabase('Master');
$this->selectedDatabase = null; $this->selectedDatabase = null;
} }
@ -180,11 +198,13 @@ class SQLServerConnector extends DBConnector {
* @param string $string String to be encoded * @param string $string String to be encoded
* @return string Processed string ready for DB * @return string Processed string ready for DB
*/ */
public function quoteString($value) { public function quoteString($value)
{
return "N'" . $this->escapeString($value) . "'"; return "N'" . $this->escapeString($value) . "'";
} }
public function escapeString($value) { public function escapeString($value)
{
$value = str_replace("'", "''", $value); $value = str_replace("'", "''", $value);
$value = str_replace("\0", "[NULL]", $value); $value = str_replace("\0", "[NULL]", $value);
return $value; return $value;

View File

@ -5,7 +5,8 @@
* *
* @package mssql * @package mssql
*/ */
class SQLServerQuery extends SS_Query { class SQLServerQuery extends SS_Query
{
/** /**
* The SQLServerConnector object that created this result set. * The SQLServerConnector object that created this result set.
@ -26,42 +27,55 @@ class SQLServerQuery extends SS_Query {
* @param SQLServerConnector $connector The database object that created this query. * @param SQLServerConnector $connector The database object that created this query.
* @param resource $handle the internal mssql handle that is points to the resultset. * @param resource $handle the internal mssql handle that is points to the resultset.
*/ */
public function __construct(SQLServerConnector $connector, $handle) { public function __construct(SQLServerConnector $connector, $handle)
{
$this->connector = $connector; $this->connector = $connector;
$this->handle = $handle; $this->handle = $handle;
} }
public function __destruct() { public function __destruct()
if(is_resource($this->handle)) { {
if (is_resource($this->handle)) {
sqlsrv_free_stmt($this->handle); sqlsrv_free_stmt($this->handle);
} }
} }
public function seek($row) { public function seek($row)
if(!is_resource($this->handle)) return false; {
if (!is_resource($this->handle)) {
return false;
}
user_error('MSSQLQuery::seek() not supported in sqlsrv', E_USER_WARNING); user_error('MSSQLQuery::seek() not supported in sqlsrv', E_USER_WARNING);
} }
public function numRecords() { public function numRecords()
if(!is_resource($this->handle)) return false; {
if (!is_resource($this->handle)) {
return false;
}
// WARNING: This will only work if the cursor type is scrollable! // WARNING: This will only work if the cursor type is scrollable!
if(function_exists('sqlsrv_num_rows')) { if (function_exists('sqlsrv_num_rows')) {
return sqlsrv_num_rows($this->handle); return sqlsrv_num_rows($this->handle);
} else { } else {
user_error('MSSQLQuery::numRecords() not supported in this version of sqlsrv', E_USER_WARNING); user_error('MSSQLQuery::numRecords() not supported in this version of sqlsrv', E_USER_WARNING);
} }
} }
public function nextRecord() { public function nextRecord()
if(!is_resource($this->handle)) return false; {
if (!is_resource($this->handle)) {
return false;
}
if($data = sqlsrv_fetch_array($this->handle, SQLSRV_FETCH_ASSOC)) { if ($data = sqlsrv_fetch_array($this->handle, SQLSRV_FETCH_ASSOC)) {
// special case for sqlsrv - date values are DateTime coming out of the sqlsrv drivers, // special case for sqlsrv - date values are DateTime coming out of the sqlsrv drivers,
// so we convert to the usual Y-m-d H:i:s value! // so we convert to the usual Y-m-d H:i:s value!
foreach($data as $name => $value) { foreach ($data as $name => $value) {
if($value instanceof DateTime) $data[$name] = $value->format('Y-m-d H:i:s'); if ($value instanceof DateTime) {
$data[$name] = $value->format('Y-m-d H:i:s');
}
} }
return $data; return $data;
} else { } else {
@ -72,5 +86,4 @@ class SQLServerQuery extends SS_Query {
return false; return false;
} }
} }

View File

@ -1,5 +1,6 @@
<?php <?php
class MSSQLDatabaseQueryTest extends SapphireTest { class MSSQLDatabaseQueryTest extends SapphireTest
{
public static $fixture_file = 'MSSQLDatabaseQueryTest.yml'; public static $fixture_file = 'MSSQLDatabaseQueryTest.yml';
@ -7,22 +8,23 @@ class MSSQLDatabaseQueryTest extends SapphireTest {
'MSSQLDatabaseQueryTestDataObject' 'MSSQLDatabaseQueryTestDataObject'
); );
public function testDateValueFormatting() { public function testDateValueFormatting()
{
$obj = $this->objFromFixture('MSSQLDatabaseQueryTestDataObject', 'test-data-1'); $obj = $this->objFromFixture('MSSQLDatabaseQueryTestDataObject', 'test-data-1');
$this->assertEquals('2012-01-01', $obj->obj('TestDate')->Format('Y-m-d'), 'Date field value is formatted correctly (Y-m-d)'); $this->assertEquals('2012-01-01', $obj->obj('TestDate')->Format('Y-m-d'), 'Date field value is formatted correctly (Y-m-d)');
} }
public function testDatetimeValueFormatting() { public function testDatetimeValueFormatting()
{
$obj = $this->objFromFixture('MSSQLDatabaseQueryTestDataObject', 'test-data-1'); $obj = $this->objFromFixture('MSSQLDatabaseQueryTestDataObject', 'test-data-1');
$this->assertEquals('2012-01-01 10:30:00', $obj->obj('TestDatetime')->Format('Y-m-d H:i:s'), 'Datetime field value is formatted correctly (Y-m-d H:i:s)'); $this->assertEquals('2012-01-01 10:30:00', $obj->obj('TestDatetime')->Format('Y-m-d H:i:s'), 'Datetime field value is formatted correctly (Y-m-d H:i:s)');
} }
} }
class MSSQLDatabaseQueryTestDataObject extends DataObject implements TestOnly { class MSSQLDatabaseQueryTestDataObject extends DataObject implements TestOnly
{
public static $db = array( public static $db = array(
'TestDate' => 'Date', 'TestDate' => 'Date',
'TestDatetime' => 'SS_Datetime' 'TestDatetime' => 'SS_Datetime'
); );
} }