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,88 +18,94 @@
* @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
* *
* @var array * @var array
*/ */
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);
}
/** /**
* Connect to a SQL Azure database with the given parameters. * Connect to a SQL Azure database with the given parameters.
* @param array $parameters Connection parameters set by environment * @param array $parameters Connection parameters set by environment
* - server: The server, eg, localhost * - server: The server, eg, localhost
* - username: The username to log on with * - username: The username to log on with
* - password: The password to log on with * - password: The password to log on with
* - 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->connectDatabase($parameters['database']); $this->parameters = $parameters;
} $this->connectDatabase($parameters['database']);
}
/** /**
* Connect to a database using the provided parameters * Connect to a database using the provided parameters
* *
* @param string $database * @param string $database
*/ */
protected function connectDatabase($database) { protected function connectDatabase($database)
$parameters = $this->parameters; {
$parameters['database'] = $database; $parameters = $this->parameters;
$parameters['multipleactiveresultsets'] = 0; $parameters['database'] = $database;
$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();
} }
// Notify connector of parameters, instructing the connector // Notify connector of parameters, instructing the connector
// to connect immediately to the Azure database // to connect immediately to the Azure database
$this->connector->connect($parameters, true); $this->connector->connect($parameters, true);
// Configure the connection // Configure the connection
$this->query('SET QUOTED_IDENTIFIER ON'); $this->query('SET QUOTED_IDENTIFIER ON');
$this->query('SET TEXTSIZE 2147483647'); $this->query('SET TEXTSIZE 2147483647');
} }
/** /**
* Switches to the given database. * Switches to the given database.
* *
* IMPORTANT: SQL Azure doesn't support "USE", so we need * IMPORTANT: SQL Azure doesn't support "USE", so we need
* to reinitialize the database connection with the requested * to reinitialize the database connection with the requested
* database name. * database name.
* @see http://msdn.microsoft.com/en-us/library/windowsazure/ee336288.aspx * @see http://msdn.microsoft.com/en-us/library/windowsazure/ee336288.aspx
* *
* @param type $name The database name to switch to * @param type $name The database name to switch to
* @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; {
if (!$this->schemaManager->databaseExists($name)) { $this->fullTextEnabled = null;
// Check DB creation permisson if (!$this->schemaManager->databaseExists($name)) {
if (!$create) { // Check DB creation permisson
if ($errorLevel !== false) { if (!$create) {
user_error("Attempted to connect to non-existing database \"$name\"", $errorLevel); if ($errorLevel !== false) {
} user_error("Attempted to connect to non-existing database \"$name\"", $errorLevel);
// Unselect database }
$this->connector->unloadDatabase(); // Unselect database
return false; $this->connector->unloadDatabase();
} return false;
$this->schemaManager->createDatabase($name); }
} $this->schemaManager->createDatabase($name);
$this->connectDatabase($name); }
return true; $this->connectDatabase($name);
} return true;
}
} }

View File

@ -38,542 +38,603 @@
* *
* @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
public static $noiseWords = array('about', '1', 'after', '2', 'all', 'also', '3', 'an', '4', 'and', '5', 'another', '6', 'any', '7', 'are', '8', 'as', '9', 'at', '0', 'be', '$', 'because', 'been', 'before', 'being', 'between', 'both', 'but', 'by', 'came', 'can', 'come', 'could', 'did', 'do', 'does', 'each', 'else', 'for', 'from', 'get', 'got', 'has', 'had', 'he', 'have', 'her', 'here', 'him', 'himself', 'his', 'how', 'if', 'in', 'into', 'is', 'it', 'its', 'just', 'like', 'make', 'many', 'me', 'might', 'more', 'most', 'much', 'must', 'my', 'never', 'no', 'now', 'of', 'on', 'only', 'or', 'other', 'our', 'out', 'over', 're', 'said', 'same', 'see', 'should', 'since', 'so', 'some', 'still', 'such', 'take', 'than', 'that', 'the', 'their', 'them', 'then', 'there', 'these', 'they', 'this', 'those', 'through', 'to', 'too', 'under', 'up', 'use', 'very', 'want', 'was', 'way', 'we', 'well', 'were', 'what', 'when', 'where', 'which', 'while', 'who', 'will', 'with', 'would', 'you', 'your', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); */
public static $noiseWords = array('about', '1', 'after', '2', 'all', 'also', '3', 'an', '4', 'and', '5', 'another', '6', 'any', '7', 'are', '8', 'as', '9', 'at', '0', 'be', '$', 'because', 'been', 'before', 'being', 'between', 'both', 'but', 'by', 'came', 'can', 'come', 'could', 'did', 'do', 'does', 'each', 'else', 'for', 'from', 'get', 'got', 'has', 'had', 'he', 'have', 'her', 'here', 'him', 'himself', 'his', 'how', 'if', 'in', 'into', 'is', 'it', 'its', 'just', 'like', 'make', 'many', 'me', 'might', 'more', 'most', 'much', 'must', 'my', 'never', 'no', 'now', 'of', 'on', 'only', 'or', 'other', 'our', 'out', 'over', 're', 'said', 'same', 'see', 'should', 'since', 'so', 'some', 'still', 'such', 'take', 'than', 'that', 'the', 'their', 'them', 'then', 'there', 'these', 'they', 'this', 'those', 'through', 'to', 'too', 'under', 'up', 'use', 'very', 'want', 'was', 'way', 'we', 'well', 'were', 'what', 'when', 'where', 'which', 'while', 'who', 'will', 'with', 'would', 'you', 'your', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
/**
* Transactions will work with FreeTDS, but not entirely with sqlsrv driver on Windows with MARS enabled. /**
* TODO: * Transactions will work with FreeTDS, but not entirely with sqlsrv driver on Windows with MARS enabled.
* - after the test fails with open transaction, the transaction should be rolled back, * TODO:
* otherwise other tests will break claiming that transaction is still open. * - after the test fails with open transaction, the transaction should be rolled back,
* - figure out SAVEPOINTS * otherwise other tests will break claiming that transaction is still open.
* - READ ONLY transactions * - figure out SAVEPOINTS
*/ * - READ ONLY transactions
protected $supportsTransactions = true; */
protected $supportsTransactions = true;
/**
* Cached flag to determine if full-text is enabled. This is set by /**
* {@link MSSQLDatabase::fullTextEnabled()} * Cached flag to determine if full-text is enabled. This is set by
* * {@link MSSQLDatabase::fullTextEnabled()}
* @var boolean *
*/ * @var boolean
protected $fullTextEnabled = null; */
protected $fullTextEnabled = null;
/**
* Set the default collation of the MSSQL nvarchar fields that we create. /**
* We don't apply this to the database as a whole, so that we can use unicode collations. * Set the default collation of the MSSQL nvarchar fields that we create.
* * We don't apply this to the database as a whole, so that we can use unicode collations.
* @param string $collation *
*/ * @param string $collation
public static function set_collation($collation) { */
Config::inst()->update('MSSQLDatabase', 'collation', $collation); public static function set_collation($collation)
} {
Config::inst()->update('MSSQLDatabase', 'collation', $collation);
/** }
* The default collation of the MSSQL nvarchar fields that we create.
* We don't apply this to the database as a whole, so that we can use /**
* unicode collations. * The default collation of the MSSQL nvarchar fields that we create.
* * We don't apply this to the database as a whole, so that we can use
* @return string * unicode collations.
*/ *
public static function get_collation() { * @return string
return Config::inst()->get('MSSQLDatabase', 'collation'); */
} public static function get_collation()
{
/** return Config::inst()->get('MSSQLDatabase', 'collation');
* Connect to a MS SQL database. }
* @param array $parameters An map of parameters, which should include:
* - server: The server, eg, localhost /**
* - username: The username to log on with * Connect to a MS SQL database.
* - password: The password to log on with * @param array $parameters An map of parameters, which should include:
* - database: The database to connect to * - server: The server, eg, localhost
* - windowsauthentication: Set to true to use windows authentication * - username: The username to log on with
* instead of username/password * - password: The password to log on with
*/ * - database: The database to connect to
public function connect($parameters) { * - windowsauthentication: Set to true to use windows authentication
parent::connect($parameters); * instead of username/password
*/
// Configure the connection public function connect($parameters)
$this->query('SET QUOTED_IDENTIFIER ON'); {
$this->query('SET TEXTSIZE 2147483647'); parent::connect($parameters);
}
// Configure the connection
/** $this->query('SET QUOTED_IDENTIFIER ON');
* Checks whether the current SQL Server version has full-text $this->query('SET TEXTSIZE 2147483647');
* support installed and full-text is enabled for this database. }
*
* @return boolean /**
*/ * Checks whether the current SQL Server version has full-text
public function fullTextEnabled() { * support installed and full-text is enabled for this database.
if($this->fullTextEnabled === null) { *
$this->fullTextEnabled = $this->updateFullTextEnabled(); * @return boolean
} */
return $this->fullTextEnabled; public function fullTextEnabled()
} {
if ($this->fullTextEnabled === null) {
/** $this->fullTextEnabled = $this->updateFullTextEnabled();
* Checks whether the current SQL Server version has full-text }
* support installed and full-text is enabled for this database. return $this->fullTextEnabled;
* }
* @return boolean
*/ /**
protected function updateFullTextEnabled() { * Checks whether the current SQL Server version has full-text
// Check if installed * support installed and full-text is enabled for this database.
$isInstalled = $this->query("SELECT fulltextserviceproperty('isfulltextinstalled')")->value(); *
if(!$isInstalled) return false; * @return boolean
*/
// Check if current database is enabled protected function updateFullTextEnabled()
$database = $this->getSelectedDatabase(); {
$enabledForDb = $this->preparedQuery( // Check if installed
"SELECT is_fulltext_enabled FROM sys.databases WHERE name = ?", $isInstalled = $this->query("SELECT fulltextserviceproperty('isfulltextinstalled')")->value();
array($database) if (!$isInstalled) {
)->value(); return false;
return $enabledForDb; }
}
// Check if current database is enabled
public function supportsCollations() { $database = $this->getSelectedDatabase();
return true; $enabledForDb = $this->preparedQuery(
} "SELECT is_fulltext_enabled FROM sys.databases WHERE name = ?",
array($database)
public function supportsTimezoneOverride() { )->value();
return true; return $enabledForDb;
} }
public function getDatabaseServer() { public function supportsCollations()
return "sqlsrv"; {
} return true;
}
public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR) {
$this->fullTextEnabled = null; public function supportsTimezoneOverride()
{
return parent::selectDatabase($name, $create, $errorLevel); return true;
} }
public function clearTable($table) { public function getDatabaseServer()
$this->query("TRUNCATE TABLE \"$table\""); {
} return "sqlsrv";
}
/**
* SQL Server uses CURRENT_TIMESTAMP for the current date/time. public function selectDatabase($name, $create = false, $errorLevel = E_USER_ERROR)
*/ {
function now() { $this->fullTextEnabled = null;
return 'CURRENT_TIMESTAMP';
} return parent::selectDatabase($name, $create, $errorLevel);
}
/**
* Returns the database-specific version of the random() function public function clearTable($table)
*/ {
function random(){ $this->query("TRUNCATE TABLE \"$table\"");
return 'RAND()'; }
}
/**
/** * SQL Server uses CURRENT_TIMESTAMP for the current date/time.
* The core search engine configuration. */
* Picks up the fulltext-indexed tables from the database and executes search on all of them. public function now()
* Results are obtained as ID-ClassName pairs which is later used to reconstruct the DataObjectSet. {
* return 'CURRENT_TIMESTAMP';
* @param array classesToSearch computes all descendants and includes them. Check is done via WHERE clause. }
* @param string $keywords Keywords as a space separated string
* @return object DataObjectSet of result pages /**
*/ * Returns the database-specific version of the random() function
public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "Relevance DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false) { */
if(isset($objects)) $results = new ArrayList($objects); public function random()
else $results = new ArrayList(); {
return 'RAND()';
if (!$this->fullTextEnabled()) return $results; }
if (!in_array(substr($sortBy, 0, 9), array('"Relevanc', 'Relevance'))) user_error("Non-relevance sort not supported.", E_USER_ERROR);
/**
$allClassesToSearch = array(); * The core search engine configuration.
foreach ($classesToSearch as $class) { * Picks up the fulltext-indexed tables from the database and executes search on all of them.
$allClassesToSearch = array_merge($allClassesToSearch, array_values(ClassInfo::dataClassesFor($class))); * Results are obtained as ID-ClassName pairs which is later used to reconstruct the DataObjectSet.
} *
$allClassesToSearch = array_unique($allClassesToSearch); * @param array classesToSearch computes all descendants and includes them. Check is done via WHERE clause.
* @param string $keywords Keywords as a space separated string
//Get a list of all the tables and columns we'll be searching on: * @return object DataObjectSet of result pages
$fulltextColumns = $this->query('EXEC sp_help_fulltext_columns'); */
$queries = array(); public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "Relevance DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false)
{
// Sort the columns back into tables. if (isset($objects)) {
$tables = array(); $results = new ArrayList($objects);
foreach($fulltextColumns as $column) { } else {
// Skip extension tables. $results = new ArrayList();
if(substr($column['TABLE_NAME'], -5) == '_Live' || substr($column['TABLE_NAME'], -9) == '_versions') continue; }
// Add the column to table. if (!$this->fullTextEnabled()) {
$table = &$tables[$column['TABLE_NAME']]; return $results;
if (!$table) { }
$table = array($column['FULLTEXT_COLUMN_NAME']); if (!in_array(substr($sortBy, 0, 9), array('"Relevanc', 'Relevance'))) {
} else { user_error("Non-relevance sort not supported.", E_USER_ERROR);
array_push($table, $column['FULLTEXT_COLUMN_NAME']); }
}
} $allClassesToSearch = array();
foreach ($classesToSearch as $class) {
// Create one query per each table, $columns not used. We want just the ID and the ClassName of the object from this query. $allClassesToSearch = array_merge($allClassesToSearch, array_values(ClassInfo::dataClassesFor($class)));
foreach($tables as $tableName => $columns){ }
$baseClass = ClassInfo::baseDataClass($tableName); $allClassesToSearch = array_unique($allClassesToSearch);
$join = $this->fullTextSearchMSSQL($tableName, $keywords); //Get a list of all the tables and columns we'll be searching on:
if (!$join) return $results; // avoid "Null or empty full-text predicate" $fulltextColumns = $this->query('EXEC sp_help_fulltext_columns');
$queries = array();
// Check if we need to add ShowInSearch
$where = null; // Sort the columns back into tables.
if(strpos($tableName, 'SiteTree') === 0) { $tables = array();
$where = array("\"$tableName\".\"ShowInSearch\"!=0"); foreach ($fulltextColumns as $column) {
} elseif(strpos($tableName, 'File') === 0) { // Skip extension tables.
// File.ShowInSearch was added later, keep the database driver backwards compatible if (substr($column['TABLE_NAME'], -5) == '_Live' || substr($column['TABLE_NAME'], -9) == '_versions') {
// by checking for its existence first continue;
$fields = $this->fieldList($tableName); }
if(array_key_exists('ShowInSearch', $fields)) {
$where = array("\"$tableName\".\"ShowInSearch\"!=0"); // Add the column to table.
} $table = &$tables[$column['TABLE_NAME']];
} if (!$table) {
$table = array($column['FULLTEXT_COLUMN_NAME']);
$queries[$tableName] = DataList::create($tableName)->where($where, '')->dataQuery()->query(); } else {
$queries[$tableName]->setOrderBy(array()); array_push($table, $column['FULLTEXT_COLUMN_NAME']);
}
// Join with CONTAINSTABLE, a full text searcher that includes relevance factor }
$queries[$tableName]->setFrom(array("\"$tableName\" INNER JOIN $join AS \"ft\" ON \"$tableName\".\"ID\"=\"ft\".\"KEY\""));
// Join with the base class if needed, as we want to test agains the ClassName // Create one query per each table, $columns not used. We want just the ID and the ClassName of the object from this query.
if ($tableName != $baseClass) { foreach ($tables as $tableName => $columns) {
$queries[$tableName]->setFrom("INNER JOIN \"$baseClass\" ON \"$baseClass\".\"ID\"=\"$tableName\".\"ID\""); $baseClass = ClassInfo::baseDataClass($tableName);
}
$join = $this->fullTextSearchMSSQL($tableName, $keywords);
$queries[$tableName]->setSelect(array("\"$tableName\".\"ID\"")); if (!$join) {
$queries[$tableName]->selectField("'$tableName'", 'Source'); return $results;
$queries[$tableName]->selectField('Rank', 'Relevance'); } // avoid "Null or empty full-text predicate"
if ($extraFilter) {
$queries[$tableName]->addWhere($extraFilter); // Check if we need to add ShowInSearch
} $where = null;
if (count($allClassesToSearch)) { if (strpos($tableName, 'SiteTree') === 0) {
$classesPlaceholder = DB::placeholders($allClassesToSearch); $where = array("\"$tableName\".\"ShowInSearch\"!=0");
$queries[$tableName]->addWhere(array( } elseif (strpos($tableName, 'File') === 0) {
"\"$baseClass\".\"ClassName\" IN ($classesPlaceholder)" => // File.ShowInSearch was added later, keep the database driver backwards compatible
$allClassesToSearch // by checking for its existence first
)); $fields = $this->fieldList($tableName);
} if (array_key_exists('ShowInSearch', $fields)) {
// Reset the parameters that would get in the way $where = array("\"$tableName\".\"ShowInSearch\"!=0");
} }
}
// Generate SQL
$querySQLs = array(); $queries[$tableName] = DataList::create($tableName)->where($where, '')->dataQuery()->query();
$queryParameters = array(); $queries[$tableName]->setOrderBy(array());
foreach($queries as $query) {
$querySQLs[] = $query->sql($parameters); // Join with CONTAINSTABLE, a full text searcher that includes relevance factor
$queryParameters = array_merge($queryParameters, $parameters); $queries[$tableName]->setFrom(array("\"$tableName\" INNER JOIN $join AS \"ft\" ON \"$tableName\".\"ID\"=\"ft\".\"KEY\""));
} // Join with the base class if needed, as we want to test agains the ClassName
if ($tableName != $baseClass) {
// Unite the SQL $queries[$tableName]->setFrom("INNER JOIN \"$baseClass\" ON \"$baseClass\".\"ID\"=\"$tableName\".\"ID\"");
$fullQuery = implode(" UNION ", $querySQLs) . " ORDER BY $sortBy"; }
// Perform the search $queries[$tableName]->setSelect(array("\"$tableName\".\"ID\""));
$result = $this->preparedQuery($fullQuery, $queryParameters); $queries[$tableName]->selectField("'$tableName'", 'Source');
$queries[$tableName]->selectField('Rank', 'Relevance');
// Regenerate DataObjectSet - watch out, numRecords doesn't work on sqlsrv driver on Windows. if ($extraFilter) {
$current = -1; $queries[$tableName]->addWhere($extraFilter);
$objects = array(); }
foreach ($result as $row) { if (count($allClassesToSearch)) {
$current++; $classesPlaceholder = DB::placeholders($allClassesToSearch);
$queries[$tableName]->addWhere(array(
// Select a subset for paging "\"$baseClass\".\"ClassName\" IN ($classesPlaceholder)" =>
if ($current >= $start && $current < $start + $pageLength) { $allClassesToSearch
$objects[] = DataObject::get_by_id($row['Source'], $row['ID']); ));
} }
} // Reset the parameters that would get in the way
}
if(isset($objects)) $results = new ArrayList($objects);
else $results = new ArrayList(); // Generate SQL
$list = new PaginatedList($results); $querySQLs = array();
$list->setPageStart($start); $queryParameters = array();
$list->setPageLength($pageLength); foreach ($queries as $query) {
$list->setTotalItems($current+1); $querySQLs[] = $query->sql($parameters);
return $list; $queryParameters = array_merge($queryParameters, $parameters);
} }
/** // Unite the SQL
* Allow auto-increment primary key editing on the given table. $fullQuery = implode(" UNION ", $querySQLs) . " ORDER BY $sortBy";
* Some databases need to enable this specially.
* // Perform the search
* @param $table The name of the table to have PK editing allowed on $result = $this->preparedQuery($fullQuery, $queryParameters);
* @param $allow True to start, false to finish
*/ // Regenerate DataObjectSet - watch out, numRecords doesn't work on sqlsrv driver on Windows.
function allowPrimaryKeyEditing($table, $allow = true) { $current = -1;
$this->query("SET IDENTITY_INSERT \"$table\" " . ($allow ? "ON" : "OFF")); $objects = array();
} foreach ($result as $row) {
$current++;
/**
* Returns a SQL fragment for querying a fulltext search index // Select a subset for paging
* if ($current >= $start && $current < $start + $pageLength) {
* @param $tableName specific - table name $objects[] = DataObject::get_by_id($row['Source'], $row['ID']);
* @param $keywords string The search query }
* @param $fields array The list of field names to search on, or null to include all }
*
* @returns null if keyword set is empty or the string with JOIN clause to be added to SQL query if (isset($objects)) {
*/ $results = new ArrayList($objects);
public function fullTextSearchMSSQL($tableName, $keywords, $fields = null) { } else {
// Make sure we are getting an array of fields $results = new ArrayList();
if (isset($fields) && !is_array($fields)) $fields = array($fields); }
$list = new PaginatedList($results);
// Strip unfriendly characters, SQLServer "CONTAINS" predicate will crash on & and | and ignore others anyway. $list->setPageStart($start);
if (function_exists('mb_ereg_replace')) { $list->setPageLength($pageLength);
$keywords = mb_ereg_replace('[^\w\s]', '', trim($keywords)); $list->setTotalItems($current+1);
} else { return $list;
$keywords = $this->escapeString(str_replace(array('&','|','!','"','\''), '', trim($keywords))); }
}
/**
// Remove stopwords, concat with ANDs * Allow auto-increment primary key editing on the given table.
$keywordList = explode(' ', $keywords); * Some databases need to enable this specially.
$keywordList = $this->removeStopwords($keywordList); *
* @param $table The name of the table to have PK editing allowed on
// remove any empty values from the array * @param $allow True to start, false to finish
$keywordList = array_filter($keywordList); */
if(empty($keywordList)) return null; public function allowPrimaryKeyEditing($table, $allow = true)
{
$keywords = implode(' AND ', $keywordList); $this->query("SET IDENTITY_INSERT \"$table\" " . ($allow ? "ON" : "OFF"));
if ($fields) $fieldNames = '"' . implode('", "', $fields) . '"'; }
else $fieldNames = "*";
/**
return "CONTAINSTABLE(\"$tableName\", ($fieldNames), '$keywords')"; * Returns a SQL fragment for querying a fulltext search index
} *
* @param $tableName specific - table name
/** * @param $keywords string The search query
* Remove stopwords that would kill a MSSQL full-text query * @param $fields array The list of field names to search on, or null to include all
* *
* @param array $keywords * @returns null if keyword set is empty or the string with JOIN clause to be added to SQL query
* */
* @return array $keywords with stopwords removed public function fullTextSearchMSSQL($tableName, $keywords, $fields = null)
*/ {
public function removeStopwords($keywords) { // Make sure we are getting an array of fields
$goodKeywords = array(); if (isset($fields) && !is_array($fields)) {
foreach($keywords as $keyword) { $fields = array($fields);
if (in_array($keyword, self::$noiseWords)) continue; }
$goodKeywords[] = trim($keyword);
} // Strip unfriendly characters, SQLServer "CONTAINS" predicate will crash on & and | and ignore others anyway.
return $goodKeywords; if (function_exists('mb_ereg_replace')) {
} $keywords = mb_ereg_replace('[^\w\s]', '', trim($keywords));
} else {
/** $keywords = $this->escapeString(str_replace(array('&', '|', '!', '"', '\''), '', trim($keywords)));
* Does this database support transactions? }
*/
public function supportsTransactions(){ // Remove stopwords, concat with ANDs
return $this->supportsTransactions; $keywordList = explode(' ', $keywords);
} $keywordList = $this->removeStopwords($keywordList);
/** // remove any empty values from the array
* This is a quick lookup to discover if the database supports particular extensions $keywordList = array_filter($keywordList);
* Currently, MSSQL supports no extensions if (empty($keywordList)) {
* return null;
* @param array $extensions List of extensions to check for support of. The key of this array }
* will be an extension name, and the value the configuration for that extension. This
* could be one of partitions, tablespaces, or clustering $keywords = implode(' AND ', $keywordList);
* @return boolean Flag indicating support for all of the above if ($fields) {
*/ $fieldNames = '"' . implode('", "', $fields) . '"';
public function supportsExtensions($extensions = array('partitions', 'tablespaces', 'clustering')){ } else {
if(isset($extensions['partitions'])) $fieldNames = "*";
return false; }
elseif(isset($extensions['tablespaces']))
return false; return "CONTAINSTABLE(\"$tableName\", ($fieldNames), '$keywords')";
elseif(isset($extensions['clustering'])) }
return false;
else /**
return false; * Remove stopwords that would kill a MSSQL full-text query
} *
* @param array $keywords
/** *
* Start transaction. READ ONLY not supported. * @return array $keywords with stopwords removed
*/ */
public function transactionStart($transactionMode = false, $sessionCharacteristics = false){ public function removeStopwords($keywords)
if($this->connector instanceof SQLServerConnector) { {
$this->connector->transactionStart(); $goodKeywords = array();
} else { foreach ($keywords as $keyword) {
$this->query('BEGIN TRANSACTION'); if (in_array($keyword, self::$noiseWords)) {
} continue;
} }
$goodKeywords[] = trim($keyword);
public function transactionSavepoint($savepoint){ }
$this->query("SAVE TRANSACTION \"$savepoint\""); return $goodKeywords;
} }
public function transactionRollback($savepoint = false) { /**
if($savepoint) { * Does this database support transactions?
$this->query("ROLLBACK TRANSACTION \"$savepoint\""); */
} elseif($this->connector instanceof SQLServerConnector) { public function supportsTransactions()
$this->connector->transactionRollback(); {
} else { return $this->supportsTransactions;
$this->query('ROLLBACK TRANSACTION'); }
}
} /**
* This is a quick lookup to discover if the database supports particular extensions
public function transactionEnd($chain = false) { * Currently, MSSQL supports no extensions
if($this->connector instanceof SQLServerConnector) { *
$this->connector->transactionEnd(); * @param array $extensions List of extensions to check for support of. The key of this array
} else { * will be an extension name, and the value the configuration for that extension. This
$this->query('COMMIT TRANSACTION'); * could be one of partitions, tablespaces, or clustering
} * @return boolean Flag indicating support for all of the above
} */
public function supportsExtensions($extensions = array('partitions', 'tablespaces', 'clustering'))
public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false) { {
if($exact) { if (isset($extensions['partitions'])) {
$comp = ($negate) ? '!=' : '='; return false;
} else { } elseif (isset($extensions['tablespaces'])) {
$comp = 'LIKE'; return false;
if($negate) $comp = 'NOT ' . $comp; } elseif (isset($extensions['clustering'])) {
} return false;
} else {
// Field definitions are case insensitive by default, return false;
// change used collation for case sensitive searches. }
$collateClause = ''; }
if($caseSensitive === true) {
if(self::get_collation()) { /**
$collation = preg_replace('/_CI_/', '_CS_', self::get_collation()); * Start transaction. READ ONLY not supported.
} else { */
$collation = 'Latin1_General_CS_AS'; public function transactionStart($transactionMode = false, $sessionCharacteristics = false)
} {
$collateClause = ' COLLATE ' . $collation; if ($this->connector instanceof SQLServerConnector) {
} elseif($caseSensitive === false) { $this->connector->transactionStart();
if(self::get_collation()) { } else {
$collation = preg_replace('/_CS_/', '_CI_', self::get_collation()); $this->query('BEGIN TRANSACTION');
} else { }
$collation = 'Latin1_General_CI_AS'; }
}
$collateClause = ' COLLATE ' . $collation; public function transactionSavepoint($savepoint)
} {
$this->query("SAVE TRANSACTION \"$savepoint\"");
$clause = sprintf("%s %s %s", $field, $comp, $parameterised ? '?' : "'$value'"); }
if($collateClause) $clause .= $collateClause;
public function transactionRollback($savepoint = false)
return $clause; {
} if ($savepoint) {
$this->query("ROLLBACK TRANSACTION \"$savepoint\"");
/** } elseif ($this->connector instanceof SQLServerConnector) {
* Function to return an SQL datetime expression for MSSQL $this->connector->transactionRollback();
* used for querying a datetime in a certain format } else {
* $this->query('ROLLBACK TRANSACTION');
* @param string $date to be formated, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"' }
* @param string $format to be used, supported specifiers: }
* %Y = Year (four digits)
* %m = Month (01..12) public function transactionEnd($chain = false)
* %d = Day (01..31) {
* %H = Hour (00..23) if ($this->connector instanceof SQLServerConnector) {
* %i = Minutes (00..59) $this->connector->transactionEnd();
* %s = Seconds (00..59) } else {
* %U = unix timestamp, can only be used on it's own $this->query('COMMIT TRANSACTION');
* @return string SQL datetime expression to query for a formatted datetime }
*/ }
function formattedDatetimeClause($date, $format) {
preg_match_all('/%(.)/', $format, $matches); public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null, $parameterised = false)
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 ($exact) {
if(preg_match('/^now$/i', $date)) { $comp = ($negate) ? '!=' : '=';
$date = "CURRENT_TIMESTAMP"; } else {
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) { $comp = 'LIKE';
$date = "'$date.000'"; if ($negate) {
} $comp = 'NOT ' . $comp;
}
if($format == '%U') { }
return "DATEDIFF(s, '1970-01-01 00:00:00', DATEADD(hour, DATEDIFF(hour, GETDATE(), GETUTCDATE()), $date))";
} // Field definitions are case insensitive by default,
// change used collation for case sensitive searches.
$trans = array( $collateClause = '';
'Y' => 'yy', if ($caseSensitive === true) {
'm' => 'mm', if (self::get_collation()) {
'd' => 'dd', $collation = preg_replace('/_CI_/', '_CS_', self::get_collation());
'H' => 'hh', } else {
'i' => 'mi', $collation = 'Latin1_General_CS_AS';
's' => 'ss', }
); $collateClause = ' COLLATE ' . $collation;
} elseif ($caseSensitive === false) {
$strings = array(); if (self::get_collation()) {
$buffer = $format; $collation = preg_replace('/_CS_/', '_CI_', self::get_collation());
while(strlen($buffer)) { } else {
if(substr($buffer,0,1) == '%') { $collation = 'Latin1_General_CI_AS';
$f = substr($buffer,1,1); }
$flen = $f == 'Y' ? 4 : 2; $collateClause = ' COLLATE ' . $collation;
$strings[] = "RIGHT('0' + CAST(DATEPART({$trans[$f]},$date) AS VARCHAR), $flen)"; }
$buffer = substr($buffer, 2);
} else { $clause = sprintf("%s %s %s", $field, $comp, $parameterised ? '?' : "'$value'");
$pos = strpos($buffer, '%'); if ($collateClause) {
if($pos === false) { $clause .= $collateClause;
$strings[] = $buffer; }
$buffer = '';
} else { return $clause;
$strings[] = "'".substr($buffer, 0, $pos)."'"; }
$buffer = substr($buffer, $pos);
} /**
} * Function to return an SQL datetime expression for MSSQL
} * used for querying a datetime in a certain format
*
return '(' . implode(' + ', $strings) . ')'; * @param string $date to be formated, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
* @param string $format to be used, supported specifiers:
} * %Y = Year (four digits)
* %m = Month (01..12)
/** * %d = Day (01..31)
* Function to return an SQL datetime expression for MSSQL. * %H = Hour (00..23)
* used for querying a datetime addition * %i = Minutes (00..59)
* * %s = Seconds (00..59)
* @param string $date, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"' * %U = unix timestamp, can only be used on it's own
* @param string $interval to be added, use the format [sign][integer] [qualifier], e.g. -1 Day, +15 minutes, +1 YEAR * @return string SQL datetime expression to query for a formatted datetime
* supported qualifiers: */
* - years public function formattedDatetimeClause($date, $format)
* - months {
* - days preg_match_all('/%(.)/', $format, $matches);
* - hours foreach ($matches[1] as $match) {
* - minutes if (array_search($match, array('Y', 'm', 'd', 'H', 'i', 's', 'U')) === false) {
* - seconds user_error('formattedDatetimeClause(): unsupported format character %' . $match, E_USER_WARNING);
* 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 }
*/
function datetimeIntervalClause($date, $interval) { if (preg_match('/^now$/i', $date)) {
$trans = array( $date = "CURRENT_TIMESTAMP";
'year' => 'yy', } elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
'month' => 'mm', $date = "'$date.000'";
'day' => 'dd', }
'hour' => 'hh',
'minute' => 'mi', if ($format == '%U') {
'second' => 'ss', return "DATEDIFF(s, '1970-01-01 00:00:00', DATEADD(hour, DATEDIFF(hour, GETDATE(), GETUTCDATE()), $date))";
); }
$singularinterval = preg_replace('/(year|month|day|hour|minute|second)s/i', '$1', $interval); $trans = array(
'Y' => 'yy',
if( 'm' => 'mm',
!($params = preg_match('/([-+]\d+) (\w+)/i', $singularinterval, $matches)) || 'd' => 'dd',
!isset($trans[strtolower($matches[2])]) 'H' => 'hh',
) user_error('datetimeIntervalClause(): invalid interval ' . $interval, E_USER_WARNING); 'i' => 'mi',
's' => 'ss',
if(preg_match('/^now$/i', $date)) { );
$date = "CURRENT_TIMESTAMP";
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) { $strings = array();
$date = "'$date'"; $buffer = $format;
} while (strlen($buffer)) {
if (substr($buffer, 0, 1) == '%') {
return "CONVERT(VARCHAR, DATEADD(" . $trans[strtolower($matches[2])] . ", " . (int)$matches[1] . ", $date), 120)"; $f = substr($buffer, 1, 1);
} $flen = $f == 'Y' ? 4 : 2;
$strings[] = "RIGHT('0' + CAST(DATEPART({$trans[$f]},$date) AS VARCHAR), $flen)";
/** $buffer = substr($buffer, 2);
* Function to return an SQL datetime expression for MSSQL. } else {
* used for querying a datetime substraction $pos = strpos($buffer, '%');
* if ($pos === false) {
* @param string $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"' $strings[] = $buffer;
* @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"' $buffer = '';
* @return string SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the substraction } else {
*/ $strings[] = "'".substr($buffer, 0, $pos)."'";
function datetimeDifferenceClause($date1, $date2) { $buffer = substr($buffer, $pos);
}
if(preg_match('/^now$/i', $date1)) { }
$date1 = "CURRENT_TIMESTAMP"; }
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date1)) {
$date1 = "'$date1'"; return '(' . implode(' + ', $strings) . ')';
} }
if(preg_match('/^now$/i', $date2)) { /**
$date2 = "CURRENT_TIMESTAMP"; * Function to return an SQL datetime expression for MSSQL.
} else if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date2)) { * used for querying a datetime addition
$date2 = "'$date2'"; *
} * @param string $date, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'
* @param string $interval to be added, use the format [sign][integer] [qualifier], e.g. -1 Day, +15 minutes, +1 YEAR
return "DATEDIFF(s, $date2, $date1)"; * supported qualifiers:
} * - years
* - months
* - days
* - hours
* - minutes
* - seconds
* 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
*/
public function datetimeIntervalClause($date, $interval)
{
$trans = array(
'year' => 'yy',
'month' => 'mm',
'day' => 'dd',
'hour' => 'hh',
'minute' => 'mi',
'second' => 'ss',
);
$singularinterval = preg_replace('/(year|month|day|hour|minute|second)s/i', '$1', $interval);
if (
!($params = preg_match('/([-+]\d+) (\w+)/i', $singularinterval, $matches)) ||
!isset($trans[strtolower($matches[2])])
) {
user_error('datetimeIntervalClause(): invalid interval ' . $interval, E_USER_WARNING);
}
if (preg_match('/^now$/i', $date)) {
$date = "CURRENT_TIMESTAMP";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date)) {
$date = "'$date'";
}
return "CONVERT(VARCHAR, DATEADD(" . $trans[strtolower($matches[2])] . ", " . (int)$matches[1] . ", $date), 120)";
}
/**
* Function to return an SQL datetime expression for MSSQL.
* used for querying a datetime substraction
*
* @param string $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
*/
public function datetimeDifferenceClause($date1, $date2)
{
if (preg_match('/^now$/i', $date1)) {
$date1 = "CURRENT_TIMESTAMP";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date1)) {
$date1 = "'$date1'";
}
if (preg_match('/^now$/i', $date2)) {
$date2 = "CURRENT_TIMESTAMP";
} elseif (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/i', $date2)) {
$date2 = "'$date2'";
}
return "DATEDIFF(s, $date2, $date1)";
}
} }

View File

@ -8,211 +8,229 @@
* *
* @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';
}
/** /**
* Create a connection of the appropriate type * Create a connection of the appropriate type
* *
* @param array $databaseConfig * @param array $databaseConfig
* @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; {
try { $error = null;
switch($databaseConfig['type']) { try {
case 'MSSQLDatabase': switch ($databaseConfig['type']) {
case 'MSSQLAzureDatabase': case 'MSSQLDatabase':
$parameters = array( case 'MSSQLAzureDatabase':
'UID' => $databaseConfig['username'], $parameters = array(
'PWD' => $databaseConfig['password'] 'UID' => $databaseConfig['username'],
); 'PWD' => $databaseConfig['password']
);
// 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 {
$error = 'Unknown connection error'; $error = 'Unknown connection error';
} }
return null; return null;
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';
return null; return null;
} }
default: default:
$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;
} }
} }
/** /**
* Helper function to quote a string value * Helper function to quote a string value
* *
* @param mixed $conn Connection object/resource * @param mixed $conn Connection object/resource
* @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) { {
return $conn->quote($value); if ($conn instanceof PDO) {
} elseif(is_resource($conn)) { return $conn->quote($value);
$value = str_replace("'", "''", $value); } elseif (is_resource($conn)) {
$value = str_replace("\0", "[NULL]", $value); $value = str_replace("'", "''", $value);
return "N'$value'"; $value = str_replace("\0", "[NULL]", $value);
} else { return "N'$value'";
user_error('Invalid database connection', E_USER_ERROR); } else {
} user_error('Invalid database connection', E_USER_ERROR);
} }
}
/** /**
* Helper function to execute a query * Helper function to execute a query
* *
* @param mixed $conn Connection object/resource * @param mixed $conn Connection object/resource
* @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(); {
if($conn instanceof PDO) { $items = array();
$result = $conn->query($sql); if ($conn instanceof PDO) {
if($result) foreach($result as $row) { $result = $conn->query($sql);
$items[] = $row[0]; if ($result) {
} foreach ($result as $row) {
} elseif(is_resource($conn)) { $items[] = $row[0];
$result = sqlsrv_query($conn, $sql); }
if($result) while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) { }
$items[] = $row[0]; } elseif (is_resource($conn)) {
} $result = sqlsrv_query($conn, $sql);
} if ($result) {
return $items; while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) {
} $items[] = $row[0];
}
}
}
return $items;
}
public function requireDatabaseFunctions($databaseConfig) { public function requireDatabaseFunctions($databaseConfig)
$data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']); {
return !empty($data['supported']); $data = DatabaseAdapterRegistry::get_adapter($databaseConfig['type']);
} return !empty($data['supported']);
}
public function requireDatabaseServer($databaseConfig) { public function requireDatabaseServer($databaseConfig)
$conn = $this->createConnection($databaseConfig, $error); {
$success = !empty($conn); $conn = $this->createConnection($databaseConfig, $error);
$success = !empty($conn);
return array( return array(
'success' => $success, 'success' => $success,
'error' => $error 'error' => $error
); );
} }
public function requireDatabaseConnection($databaseConfig) { public function requireDatabaseConnection($databaseConfig)
$conn = $this->createConnection($databaseConfig, $error); {
$success = !empty($conn); $conn = $this->createConnection($databaseConfig, $error);
$success = !empty($conn);
return array( return array(
'success' => $success, 'success' => $success,
'connection' => $conn, 'connection' => $conn,
'error' => $error 'error' => $error
); );
} }
public function getDatabaseVersion($databaseConfig) { public function getDatabaseVersion($databaseConfig)
$conn = $this->createConnection($databaseConfig, $error); {
$result = $this->query($conn, "SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))"); $conn = $this->createConnection($databaseConfig, $error);
return empty($result) ? 0 : reset($result); $result = $this->query($conn, "SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))");
} return empty($result) ? 0 : reset($result);
}
/** /**
* Ensure that the SQL Server version is at least 10.00.2531 (SQL Server 2008 SP1). * Ensure that the SQL Server version is at least 10.00.2531 (SQL Server 2008 SP1).
* *
* @see http://www.sqlteam.com/article/sql-server-versions * @see http://www.sqlteam.com/article/sql-server-versions
* @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; {
$error = ''; $success = false;
$version = $this->getDatabaseVersion($databaseConfig); $error = '';
$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 {
$error = "Your SQL Server version could not be determined."; $error = "Your SQL Server version could not be determined.";
} }
return array( return array(
'success' => $success, 'success' => $success,
'error' => $error 'error' => $error
); );
} }
public function requireDatabaseOrCreatePermissions($databaseConfig) { public function requireDatabaseOrCreatePermissions($databaseConfig)
$conn = $this->createConnection($databaseConfig, $error); {
if(empty($conn)) { $conn = $this->createConnection($databaseConfig, $error);
$success = false; if (empty($conn)) {
$alreadyExists = false; $success = false;
} elseif($databaseConfig['type'] == 'MSSQLAzureDatabase') { $alreadyExists = false;
// Don't bother with DB selection for azure, as it's not supported } elseif ($databaseConfig['type'] == 'MSSQLAzureDatabase') {
$success = true; // Don't bother with DB selection for azure, as it's not supported
$alreadyExists = true; $success = true;
} else { $alreadyExists = true;
// does this database exist already? } else {
$list = $this->query($conn, 'SELECT NAME FROM sys.sysdatabases'); // does this database exist already?
if(in_array($databaseConfig['database'], $list)) { $list = $this->query($conn, 'SELECT NAME FROM sys.sysdatabases');
$success = true; if (in_array($databaseConfig['database'], $list)) {
$alreadyExists = true; $success = true;
} else { $alreadyExists = true;
$permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions('','') where permission_name like 'CREATE ANY DATABASE' or permission_name like 'CREATE DATABASE';"); } else {
$success = $permissions[0] > 0; $permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions('','') where permission_name like 'CREATE ANY DATABASE' or permission_name like 'CREATE DATABASE';");
$alreadyExists = false; $success = $permissions[0] > 0;
} $alreadyExists = false;
} }
}
return array( return array(
'success' => $success, 'success' => $success,
'alreadyExists' => $alreadyExists 'alreadyExists' => $alreadyExists
); );
} }
public function requireDatabaseAlterPermissions($databaseConfig) { public function requireDatabaseAlterPermissions($databaseConfig)
$success = false; {
$conn = $this->createConnection($databaseConfig, $error); $success = false;
if(!empty($conn)) { $conn = $this->createConnection($databaseConfig, $error);
if(!$this->isAzure($databaseConfig)) { if (!empty($conn)) {
// Make sure to select the current database when checking permission against this database if (!$this->isAzure($databaseConfig)) {
$this->query($conn, "USE \"{$databaseConfig['database']}\""); // Make sure to select the current database when checking permission against this database
} $this->query($conn, "USE \"{$databaseConfig['database']}\"");
$permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions(NULL,'DATABASE') WHERE permission_name like 'create table';"); }
$success = $permissions[0] > 0; $permissions = $this->query($conn, "select COUNT(*) from sys.fn_my_permissions(NULL,'DATABASE') WHERE permission_name like 'create table';");
} $success = $permissions[0] > 0;
}
return array( return array(
'success' => $success, 'success' => $success,
'applies' => true 'applies' => true
); );
} }
} }

View File

@ -5,108 +5,116 @@
* *
* @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;
} }
// When using offset we must use a subselect // When using offset we must use a subselect
// @see http://stackoverflow.com/questions/2135418/equivalent-of-limit-and-offset-for-sql-server // @see http://stackoverflow.com/questions/2135418/equivalent-of-limit-and-offset-for-sql-server
$orderby = $query->getOrderBy(); $orderby = $query->getOrderBy();
// 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) {
$statements[] = trim("$clause $dir"); $statements[] = trim("$clause $dir");
} }
$orderByClause = "ORDER BY " . implode(', ', $statements); $orderByClause = "ORDER BY " . implode(', ', $statements);
} else { } else {
$selects = $query->getSelect(); $selects = $query->getSelect();
$firstCol = reset($selects); $firstCol = reset($selects);
$orderByClause = "ORDER BY $firstCol"; $orderByClause = "ORDER BY $firstCol";
} }
// Build main query SQL // Build main query SQL
$sql = parent::buildSelectQuery($query, $parameters); $sql = parent::buildSelectQuery($query, $parameters);
// Inject row number into selection // Inject row number into selection
$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 {
$limitCondition = "Number BETWEEN ? AND ?"; $limitCondition = "Number BETWEEN ? AND ?";
$parameters[] = $offset + 1; $parameters[] = $offset + 1;
$parameters[] = $offset + $limit; $parameters[] = $offset + $limit;
} }
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 {
return ''; // Limit is handled at the buildSelectQuery level
} 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 {
list($offset, $limit) = $this->parseLimit($query); // If doing a limit/offset at the same time then don't build the orde by fragment here
if(empty($offset) || empty($limit)) { list($offset, $limit) = $this->parseLimit($query);
return parent::buildOrderByFragment($query, $parameters); if (empty($offset) || empty($limit)) {
} return parent::buildOrderByFragment($query, $parameters);
return ''; }
} return '';
}
/** /**
* Extracts the limit and offset from the limit clause * Extracts the limit and offset from the limit clause
* *
* @param SQLSelect $query * @param SQLSelect $query
* @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)) { }
$limit = $matches[1]; if (isset($limitArr['start'])) {
$offset = $matches[2]; $offset = $limitArr['start'];
} else { }
//could be a comma delimited string } elseif (preg_match('/^([0-9]+) offset ([0-9]+)$/i', trim($query->getLimit()), $matches)) {
$bits = explode(',', $query->getLimit()); $limit = $matches[1];
if(sizeof($bits) > 1) { $offset = $matches[2];
list($offset, $limit) = $bits; } else {
} else { //could be a comma delimited string
$limit = $bits[0]; $bits = explode(',', $query->getLimit());
} if (sizeof($bits) > 1) {
} list($offset, $limit) = $bits;
return array($limit, $offset); } else {
} $limit = $bits[0];
}
}
return array($limit, $offset);
}
} }

View File

@ -5,129 +5,143 @@
* *
* @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.
* *
* @var array * @var array
*/ */
protected static $cached_checks = array(); protected static $cached_checks = array();
/** /**
* Builds the internal MS SQL Server index name given the silverstripe table and index name * Builds the internal MS SQL Server index name given the silverstripe table and index name
* *
* @param string $tableName * @param string $tableName
* @param string $indexName * @param string $indexName
* @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);
$indexName = str_replace('\\', '_', $indexName); $indexName = str_replace('\\', '_', $indexName);
return "{$prefix}_{$tableName}_{$indexName}"; return "{$prefix}_{$tableName}_{$indexName}";
} }
/** /**
* This will set up the full text search capabilities. * This will set up the full text search capabilities.
* *
* @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(); {
if(!$result) $this->query("CREATE FULLTEXT CATALOG \"$name\" AS DEFAULT;"); $result = $this->fullTextCatalogExists();
} if (!$result) {
$this->query("CREATE FULLTEXT CATALOG \"$name\" AS DEFAULT;");
}
}
/** /**
* Check that a fulltext catalog has been created yet. * Check that a fulltext catalog has been created yet.
* *
* @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( {
"SELECT name FROM sys.fulltext_catalogs WHERE name = ?;", return (bool) $this->preparedQuery(
array($name) "SELECT name FROM sys.fulltext_catalogs WHERE name = ?;",
)->value(); array($name)
} )->value();
}
/** /**
* Sleep until the catalog has been fully rebuilt. This is a busy wait designed for situations * Sleep until the catalog has been fully rebuilt. This is a busy wait designed for situations
* when you need to be sure the index is up to date - for example in unit tests. * when you need to be sure the index is up to date - for example in unit tests.
* *
* TODO: move this to Database class? Can we assume this will be useful for all databases? * TODO: move this to Database class? Can we assume this will be useful for all databases?
* Also see the wrapper functions "waitUntilIndexingFinished" in SearchFormTest and TranslatableSearchFormTest * Also see the wrapper functions "waitUntilIndexingFinished" in SearchFormTest and TranslatableSearchFormTest
* *
* @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) {
// Idle! // Idle!
break; break;
} }
sleep(1); sleep(1);
} }
} }
/** /**
* Check if a fulltext index exists on a particular table name. * Check if a fulltext index exists on a particular table name.
* *
* @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 {
if(!$this->database->fullTextEnabled()) return null; // Special case for no full text index support
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
JOIN sys.objects o ON i.object_id = o.object_id JOIN sys.objects o ON i.object_id = o.object_id
WHERE o.name = ?", WHERE o.name = ?",
array($tableName) array($tableName)
)->value(); )->value();
} }
/** /**
* MSSQL stores the primary key column with an internal identifier, * MSSQL stores the primary key column with an internal identifier,
* so a lookup needs to be done to determine it. * so a lookup needs to be done to determine it.
* *
* @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';"); {
$indexName = ''; $indexes = $this->query("EXEC sp_helpindex '$tableName';");
foreach($indexes as $index) { $indexName = '';
if($index['index_keys'] == 'ID') { foreach ($indexes as $index) {
$indexName = $index['index_name']; if ($index['index_keys'] == 'ID') {
break; $indexName = $index['index_name'];
} break;
} }
}
return $indexName; return $indexName;
} }
/** /**
* Gets the identity column of a table * Gets the identity column of a table
* *
* @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,
TABLE_NAME TABLE_NAME
@ -138,160 +152,195 @@ class MSSQLSchemaManager extends DBSchemaManager {
COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 AND COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 AND
TABLE_NAME = ? TABLE_NAME = ?
", 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(); {
foreach($databases as $dbname) { $databases = $this->databaseList();
if($dbname == $name) return true; foreach ($databases as $dbname) {
} if ($dbname == $name) {
return false; return true;
} }
}
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();
}
/** /**
* Create a new table. * Create a new table.
* @param $tableName The name of the table * @param $tableName The name of the table
* @param $fields A map of field names to field types * @param $fields A map of field names to field types
* @param $indexes A map of indexes * @param $indexes A map of indexes
* @param $options An map of additional options. The available keys are as follows: * @param $options An map of additional options. The available keys are as follows:
* - 'MSSQLDatabase'/'MySQLDatabase'/'PostgreSQLDatabase' - database-specific options such as "engine" for MySQL. * - 'MSSQLDatabase'/'MySQLDatabase'/'PostgreSQLDatabase' - database-specific options such as "engine" for MySQL.
* - '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 = ""; {
if($fields) foreach($fields as $k => $v) $fieldSchemas .= "\"$k\" $v,\n"; $fieldSchemas = $indexSchemas = "";
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);
} }
$this->query("CREATE TABLE \"$tableName\" ( $this->query("CREATE TABLE \"$tableName\" (
$fieldSchemas $fieldSchemas
primary key (\"ID\") primary key (\"ID\")
);"); );");
//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) {
$indexSchemas .= $this->getIndexSqlDefinition($tableName, $k, $v) . "\n"; foreach ($indexes as $k => $v) {
} $indexSchemas .= $this->getIndexSqlDefinition($tableName, $k, $v) . "\n";
}
}
if($indexSchemas) $this->query($indexSchemas); if ($indexSchemas) {
$this->query($indexSchemas);
}
return $tableName; return $tableName;
} }
/** /**
* Alter a table's schema. * Alter a table's schema.
* @param $table The name of the table to alter * @param $table The name of the table to alter
* @param $newFields New fields, a map of field name => field schema * @param $newFields New fields, a map of field name => field schema
* @param $newIndexes New indexes, a map of index name => index type * @param $newIndexes New indexes, a map of index name => index type
* @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);
} }
} }
} }
} }
/** /**
* Given the table and column name, retrieve the constraint name for that column * Given the table and column name, retrieve the constraint name for that column
* in the table. * in the table.
* *
* @param string $tableName Table name column resides in * @param string $tableName Table name column resides in
* @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
WHERE TABLE_NAME = ? AND COLUMN_NAME = ?", WHERE TABLE_NAME = ? AND COLUMN_NAME = ?",
array($tableName, $columnName) array($tableName, $columnName)
)->value(); )->value();
} }
/** /**
* Given a table and column name, return a check constraint clause for that column in * Given a table and column name, return a check constraint clause for that column in
* the table. * the table.
* *
* This is an expensive query, so it is cached per-request and stored by table. The initial * This is an expensive query, so it is cached per-request and stored by table. The initial
* call for a table that has not been cached will query all columns and store that * call for a table that has not been cached will query all columns and store that
* so subsequent calls are fast. * so subsequent calls are fast.
* *
* @param string $tableName Table name column resides in * @param string $tableName Table name column resides in
* @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 {
if(isset(self::$cached_checks[$tableName])) { // Check already processed table columns
if(!isset(self::$cached_checks[$tableName][$columnName])) { if (isset(self::$cached_checks[$tableName])) {
return null; if (!isset(self::$cached_checks[$tableName][$columnName])) {
} return null;
return self::$cached_checks[$tableName][$columnName]; }
} return self::$cached_checks[$tableName][$columnName];
}
// 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
WHERE TABLE_NAME = ?", WHERE TABLE_NAME = ?",
array($tableName) array($tableName)
) as $record) { ) as $record) {
$checks[$record['COLUMN_NAME']] = $record['CHECK_CLAUSE']; $checks[$record['COLUMN_NAME']] = $record['CHECK_CLAUSE'];
} }
self::$cached_checks[$tableName] = $checks; self::$cached_checks[$tableName] = $checks;
// Return via cached records // Return via cached records
return $this->getConstraintCheckClause($tableName, $columnName); return $this->getConstraintCheckClause($tableName, $columnName);
} }
/** /**
* Return the name of the default constraint applied to $tableName.$colName. * Return the name of the default constraint applied to $tableName.$colName.
* Will return null if no such constraint exists * Will return null if no such constraint exists
* *
* @param string $tableName Name of the table * @param string $tableName Name of the table
* @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
join sys.syscolumns c ON s.parent_obj = c.id join sys.syscolumns c ON s.parent_obj = c.id
@ -299,558 +348,591 @@ class MSSQLSchemaManager extends DBSchemaManager {
and c.cdefault = s.id and c.cdefault = s.id
and parent_obj = OBJECT_ID(?) and parent_obj = OBJECT_ID(?)
and c.name = ?", and c.name = ?",
array($tableName, $colName) array($tableName, $colName)
)->value(); )->value();
} }
/** /**
* Get enum values from a constraint check clause. * Get enum values from a constraint check clause.
* *
* @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); {
$constraints = array(); $segments = preg_split('/ +OR *\[/i', $clause);
foreach($segments as $segment) { $constraints = array();
$bits = preg_split('/ *= */', $segment); foreach ($segments as $segment) {
for($i = 1; $i < sizeof($bits); $i += 2) { $bits = preg_split('/ *= */', $segment);
array_unshift($constraints, substr(rtrim($bits[$i], ')'), 1, -1)); for ($i = 1; $i < sizeof($bits); $i += 2) {
} array_unshift($constraints, substr(rtrim($bits[$i], ')'), 1, -1));
} }
return $constraints; }
} return $constraints;
}
/* /*
* Creates an ALTER expression for a column in MS SQL * Creates an ALTER expression for a column in MS SQL
* *
* @param string $tableName Name of the table to be altered * @param string $tableName Name of the table to be altered
* @param string $colName Name of the column to be altered * @param string $colName Name of the column to be altered
* @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
// on second thoughts, why is an auto_increment field being passed through? // on second thoughts, why is an auto_increment field being passed through?
$pattern = '/^(?<definition>[\w()]+)\s?(?<null>(?:not\s)?null)?\s?(?<default>default\s[\w\']+)?\s?(?<check>check\s?[\w()\'",\s]+)?$/i'; $pattern = '/^(?<definition>[\w()]+)\s?(?<null>(?:not\s)?null)?\s?(?<default>default\s[\w\']+)?\s?(?<check>check\s?[\w()\'",\s]+)?$/i';
$matches = array(); $matches = array();
preg_match($pattern, $colSpec, $matches); preg_match($pattern, $colSpec, $matches);
// drop the index if it exists // drop the index if it exists
$alterQueries = array(); $alterQueries = array();
// 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};";
} }
//NOTE: 'with nocheck' seems to solve a few problems I've been having for modifying existing tables. //NOTE: 'with nocheck' seems to solve a few problems I've been having for modifying existing tables.
$alterQueries[] = "$prefix WITH NOCHECK ADD CONSTRAINT \"{$tableName}_{$colName}_check\" {$matches['check']};"; $alterQueries[] = "$prefix WITH NOCHECK ADD CONSTRAINT \"{$tableName}_{$colName}_check\" {$matches['check']};";
} }
} }
} }
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\"");
}
/** /**
* Checks a table's integrity and repairs it if necessary. * Checks a table's integrity and repairs it if necessary.
* NOTE: MSSQL does not appear to support any vacuum or optimise commands * NOTE: MSSQL does not appear to support any vacuum or optimise commands
* *
* @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");
}
/** /**
* Change the database type of the given field. * Change the database type of the given field.
* @param string $tableName The name of the tbale the field is in. * @param string $tableName The name of the tbale the field is in.
* @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.... {
$fieldRecords = $this->preparedQuery("SELECT ordinal_position, column_name, data_type, column_default, //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,
is_nullable, character_maximum_length, numeric_precision, numeric_scale, collation_name is_nullable, character_maximum_length, numeric_precision, numeric_scale, collation_name
FROM information_schema.columns WHERE table_name = ? FROM information_schema.columns WHERE table_name = ?
ORDER BY ordinal_position;", ORDER BY ordinal_position;",
array($table) array($table)
); );
// Cache the records from the query - otherwise a lack of multiple active result sets // Cache the records from the query - otherwise a lack of multiple active result sets
// 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";
} }
break; break;
case 'nvarchar': case 'nvarchar':
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(
'default' => $default, 'default' => $default,
'name' => $field['column_name'], 'name' => $field['column_name'],
'enums' => $constraints, 'enums' => $constraints,
'table' => $table 'table' => $table
)); ));
break; break;
} }
default: default:
$sizeSuffix = $field['character_maximum_length']; $sizeSuffix = $field['character_maximum_length'];
if($sizeSuffix == '-1') $sizeSuffix = 'max'; if ($sizeSuffix == '-1') {
if($sizeSuffix) { $sizeSuffix = 'max';
$field['data_type'] .= "($sizeSuffix)"; }
} if ($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; /**
} * Create an index on a table.
* @param string $tableName The name of the table.
* @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see SS_Database::requireIndex() for more details.
*/
public function createIndex($tableName, $indexName, $indexSpec)
{
$this->query($this->getIndexSqlDefinition($tableName, $indexName, $indexSpec));
}
/** /**
* Create an index on a table. * Return SQL for dropping and recreating an index
* @param string $tableName The name of the table. *
* @param string $indexName The name of the index. * @param string $tableName Name of table to create this index against
* @param string $indexSpec The specification of the index, see SS_Database::requireIndex() for more details. * @param string $indexName Name of this index
*/ * @param array|string $indexSpec Index specification, either as a raw string
public function createIndex($tableName, $indexName, $indexSpec) { * or parsed array form
$this->query($this->getIndexSqlDefinition($tableName, $indexName, $indexSpec)); * @return string The SQL required to generate this index
} */
protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec)
{
/** // Determine index name
* Return SQL for dropping and recreating an index $index = $this->buildMSSQLIndexName($tableName, $indexName);
*
* @param string $tableName Name of table to create this index against
* @param string $indexName Name of this index
* @param array|string $indexSpec Index specification, either as a raw string
* or parsed array form
* @return string The SQL required to generate this index
*/
protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec) {
// Determine index name // Consolidate/Cleanup spec into array format
$index = $this->buildMSSQLIndexName($tableName, $indexName); $indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
// Consolidate/Cleanup spec into array format $drop = "IF EXISTS (SELECT name FROM sys.indexes WHERE name = '$index') DROP INDEX $index ON \"$tableName\";";
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
$drop = "IF EXISTS (SELECT name FROM sys.indexes WHERE name = '$index') DROP INDEX $index ON \"$tableName\";"; // create a type-specific index
if ($indexSpec['type'] == 'fulltext' && $this->database->fullTextEnabled()) {
// enable fulltext on this table
$this->createFullTextCatalog();
$primary_key = $this->getPrimaryKey($tableName);
// create a type-specific index if ($primary_key) {
if($indexSpec['type'] == 'fulltext' && $this->database->fullTextEnabled()) { return "$drop CREATE FULLTEXT INDEX ON \"$tableName\" ({$indexSpec['value']})"
// enable fulltext on this table . "KEY INDEX $primary_key WITH CHANGE_TRACKING AUTO;";
$this->createFullTextCatalog(); }
$primary_key = $this->getPrimaryKey($tableName); }
if($primary_key) { if ($indexSpec['type'] == 'unique') {
return "$drop CREATE FULLTEXT INDEX ON \"$tableName\" ({$indexSpec['value']})" return "$drop CREATE UNIQUE INDEX $index ON \"$tableName\" ({$indexSpec['value']});";
. "KEY INDEX $primary_key WITH CHANGE_TRACKING AUTO;"; }
}
}
if($indexSpec['type'] == 'unique') { return "$drop CREATE 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']});"; public function alterIndex($tableName, $indexName, $indexSpec)
} {
$this->createIndex($tableName, $indexName, $indexSpec);
}
public function alterIndex($tableName, $indexName, $indexSpec) { /**
$this->createIndex($tableName, $indexName, $indexSpec); * Return the list of indexes in a table.
} * @param string $table The table name.
* @return array
*/
public function indexList($table)
{
$indexes = $this->query("EXEC sp_helpindex '$table';");
$indexList = array();
/** // Enumerate all basic indexes
* Return the list of indexes in a table. foreach ($indexes as $index) {
* @param string $table The table name. if (strpos($index['index_description'], 'unique') !== false) {
* @return array $indexType = 'unique ';
*/ } else {
public function indexList($table) { $indexType = 'index ';
$indexes = $this->query("EXEC sp_helpindex '$table';"); }
$indexList = array();
// Enumerate all basic indexes // Extract name from index
foreach($indexes as $index) { $baseIndexName = $this->buildMSSQLIndexName($table, '');
if(strpos($index['index_description'], 'unique') !== false) { $indexName = substr($index['index_name'], strlen($baseIndexName));
$indexType = 'unique ';
} else {
$indexType = 'index ';
}
// Extract name from index // Extract columns
$baseIndexName = $this->buildMSSQLIndexName($table, ''); $columns = $this->quoteColumnSpecString($index['index_keys']);
$indexName = substr($index['index_name'], strlen($baseIndexName)); $indexList[$indexName] = $this->parseIndexSpec($indexName, array(
'name' => $indexName,
'value' => $columns,
'type' => $indexType
));
}
// Extract columns // Now we need to check to see if we have any fulltext indexes attached to this table:
$columns = $this->quoteColumnSpecString($index['index_keys']); if ($this->database->fullTextEnabled()) {
$indexList[$indexName] = $this->parseIndexSpec($indexName, array( $result = $this->query('EXEC sp_help_fulltext_columns;');
'name' => $indexName,
'value' => $columns,
'type' => $indexType
));
}
// Now we need to check to see if we have any fulltext indexes attached to this table: // Extract columns from this fulltext definition
if($this->database->fullTextEnabled()) { $columns = array();
$result = $this->query('EXEC sp_help_fulltext_columns;'); foreach ($result as $row) {
if ($row['TABLE_NAME'] == $table) {
$columns[] = $row['FULLTEXT_COLUMN_NAME'];
}
}
// Extract columns from this fulltext definition if (!empty($columns)) {
$columns = array(); $indexList['SearchFields'] = $this->parseIndexSpec('SearchFields', array(
foreach($result as $row) { 'name' => 'SearchFields',
if($row['TABLE_NAME'] == $table) { 'value' => $this->implodeColumnList($columns),
$columns[] = $row['FULLTEXT_COLUMN_NAME']; 'type' => 'fulltext'
} ));
} }
}
if(!empty($columns)) { return $indexList;
$indexList['SearchFields'] = $this->parseIndexSpec('SearchFields', array( }
'name' => 'SearchFields',
'value' => $this->implodeColumnList($columns),
'type' => 'fulltext'
));
}
}
return $indexList; /**
} * For a given table name, get all the internal index names,
* except for those that are primary keys and fulltext indexes.
/** *
* For a given table name, get all the internal index names, * @return array
* except for those that are primary keys and fulltext indexes. */
* public function indexNames($tableName)
* @return array {
*/ return $this->preparedQuery('
public function indexNames($tableName) {
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
WHERE is_primary_key = 0 AND t.name = ?', WHERE is_primary_key = 0 AND t.name = ?',
array($tableName) array($tableName)
)->column(); )->column();
} }
public function tableList() { public function tableList()
$tables = array(); {
foreach($this->query("EXEC sp_tables @table_owner = 'dbo';") as $record) { $tables = array();
$tables[strtolower($record['TABLE_NAME'])] = $record['TABLE_NAME']; foreach ($this->query("EXEC sp_tables @table_owner = 'dbo';") as $record) {
} $tables[strtolower($record['TABLE_NAME'])] = $record['TABLE_NAME'];
return $tables; }
} return $tables;
}
/** /**
* Return a boolean type-formatted string * Return a boolean type-formatted string
* We use 'bit' so that we can do numeric-based comparisons * We use 'bit' so that we can do numeric-based comparisons
* *
* @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'; {
return 'bit not null default ' . $default; $default = ($values['default']) ? '1' : '0';
} return 'bit not null default ' . $default;
}
/** /**
* Return a date type-formatted string. * Return a date type-formatted string.
* *
* @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';
}
/** /**
* Return a decimal type-formatted string * Return a decimal type-formatted string
* *
* @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 {
if($values['precision'] == '') { // Avoid empty strings being put in the db
$precision = 1; if ($values['precision'] == '') {
} else { $precision = 1;
$precision = $values['precision']; } else {
} $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'];
} }
return "decimal($precision) not null default $defaultValue"; return "decimal($precision) not null default $defaultValue";
} }
/** /**
* Return a enum type-formatted string * Return a enum type-formatted string
* *
* @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 {
// usual enum options. // Enums are a bit different. We'll be creating a varchar(255) with a constraint of all the
// NOTE: In this one instance, we are including the table name in the values array // usual enum options.
// NOTE: In this one instance, we are including the table name in the values array
$maxLength = max(array_map('strlen', $values['enums'])); $maxLength = max(array_map('strlen', $values['enums']));
return "varchar($maxLength) not null default '" . $values['default'] return "varchar($maxLength) not null default '" . $values['default']
. "' check(\"" . $values['name'] . "\" in ('" . implode("','", $values['enums']) . "' check(\"" . $values['name'] . "\" in ('" . implode("','", $values['enums'])
. "'))"; . "'))";
} }
/** /**
* @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);
}
/** /**
* Return a float type-formatted string. * Return a float type-formatted string.
* *
* @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'];
}
/** /**
* Return a int type-formatted string * Return a int type-formatted string
* *
* @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'];
}
/** /**
* Return a bigint type-formatted string * Return a bigint type-formatted string
* *
* @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'];
}
/** /**
* Return a datetime type-formatted string * Return a datetime type-formatted string
* For MS SQL, we simply return the word 'timestamp', no other parameters are necessary * For MS SQL, we simply return the word 'timestamp', no other parameters are necessary
* *
* @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';
}
/** /**
* Return a text type-formatted string * Return a text type-formatted string
* *
* @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(); {
$collationSQL = $collation ? " COLLATE $collation" : ""; $collation = MSSQLDatabase::get_collation();
return "nvarchar(max)$collationSQL null"; $collationSQL = $collation ? " COLLATE $collation" : "";
} return "nvarchar(max)$collationSQL null";
}
/** /**
* Return a time type-formatted string. * Return a time type-formatted string.
* *
* @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';
}
/** /**
* Return a varchar type-formatted string * Return a varchar type-formatted string
* *
* @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(); {
$collationSQL = $collation ? " COLLATE $collation" : ""; $collation = MSSQLDatabase::get_collation();
return "nvarchar(" . $values['precision'] . ")$collationSQL null"; $collationSQL = $collation ? " COLLATE $collation" : "";
} return "nvarchar(" . $values['precision'] . ")$collationSQL null";
}
/** /**
* 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)';
}
/** /**
* 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) { {
return 'int not null'; if ($asDbValue) {
} else if($hasAutoIncPK) { return 'int not null';
return 'int identity(1,1)'; } elseif ($hasAutoIncPK) {
} else { return 'int identity(1,1)';
return 'int not null'; } else {
} return 'int not null';
} }
}
function hasTable($tableName) { public function hasTable($tableName)
return (bool)$this->preparedQuery( {
"SELECT table_name FROM information_schema.tables WHERE table_name = ?", return (bool)$this->preparedQuery(
array($tableName) "SELECT table_name FROM information_schema.tables WHERE table_name = ?",
)->value(); array($tableName)
} )->value();
}
/** /**
* 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);
} }
return $classes; return $classes;
} }
/** /**
* This is a lookup table for data types. * This is a lookup table for data types.
* *
* 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( {
'unsigned integer'=>'BIGINT' $values = array(
); 'unsigned integer'=>'BIGINT'
if(isset($values[$type])) { );
return $values[$type]; if (isset($values[$type])) {
} else { return $values[$type];
return ''; } else {
} return '';
} }
}
protected function indexKey($table, $index, $spec) { protected function indexKey($table, $index, $spec)
return $index; {
} return $index;
}
} }

View File

@ -5,188 +5,208 @@
* *
* @package mssql * @package mssql
*/ */
class SQLServerConnector extends DBConnector { class SQLServerConnector extends DBConnector
{
/** /**
* Connection to the DBMS. * Connection to the DBMS.
* *
* @var resource * @var resource
*/ */
protected $dbConn = null; protected $dbConn = null;
/** /**
* Stores the affected rows of the last query. * Stores the affected rows of the last query.
* Used by sqlsrv functions only, as sqlsrv_rows_affected * Used by sqlsrv functions only, as sqlsrv_rows_affected
* accepts a result instead of a database handle. * accepts a result instead of a database handle.
* *
* @var integer * @var integer
*/ */
protected $lastAffectedRows; protected $lastAffectedRows;
/** /**
* Name of the currently selected database * Name of the currently selected database
* *
* @var string * @var string
*/ */
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 {
if(ini_get('sqlsrv.WarningsReturnAsErrors')) { // Disable default warnings as errors behaviour for sqlsrv to keep it in line with mssql functions
ini_set('sqlsrv.WarningsReturnAsErrors', 'Off'); if (ini_get('sqlsrv.WarningsReturnAsErrors')) {
} ini_set('sqlsrv.WarningsReturnAsErrors', 'Off');
}
$charset = isset($parameters['charset']) ? $parameters : 'UTF-8'; $charset = isset($parameters['charset']) ? $parameters : 'UTF-8';
$multiResultSets = isset($parameters['multipleactiveresultsets']) $multiResultSets = isset($parameters['multipleactiveresultsets'])
? $parameters['multipleactiveresultsets'] ? $parameters['multipleactiveresultsets']
: true; : true;
$options = array( $options = array(
'CharacterSet' => $charset, 'CharacterSet' => $charset,
'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'];
$options['PWD'] = $parameters['password']; $options['PWD'] = $parameters['password'];
} }
// 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'];
} }
} }
/** /**
* Start transaction. READ ONLY not supported. * Start transaction. READ ONLY not supported.
*/ */
public function transactionStart(){ public function transactionStart()
$result = sqlsrv_begin_transaction($this->dbConn); {
if (!$result) { $result = sqlsrv_begin_transaction($this->dbConn);
$this->databaseError("Couldn't start the transaction."); if (!$result) {
} $this->databaseError("Couldn't start the transaction.");
} }
}
/** /**
* 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); {
if (!$result) { $result = sqlsrv_commit($this->dbConn);
$this->databaseError("Couldn't commit the transaction."); if (!$result) {
} $this->databaseError("Couldn't commit the transaction.");
} }
}
/** /**
* Rollback or revert to a savepoint if your queries encounter problems * Rollback or revert to a savepoint if your queries encounter problems
* 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); {
if (!$result) { $result = sqlsrv_rollback($this->dbConn);
$this->databaseError("Couldn't rollback the transaction."); if (!$result) {
} $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(); {
$errors = sqlsrv_errors(); $errorMessages = array();
if($errors) foreach($errors as $info) { $errors = sqlsrv_errors();
$errorMessages[] = implode(', ', array($info['SQLSTATE'], $info['code'], $info['message'])); if ($errors) {
} foreach ($errors as $info) {
return implode('; ', $errorMessages); $errorMessages[] = implode(', ', array($info['SQLSTATE'], $info['code'], $info['message']));
} }
}
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 {
$this->lastAffectedRows = 0; // Reset state
$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;
} }
// Report result // Report result
$this->lastAffectedRows = sqlsrv_rows_affected($handle); $this->lastAffectedRows = sqlsrv_rows_affected($handle);
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->selectedDatabase = $name; $this->query("USE \"$name\"");
return true; $this->selectedDatabase = $name;
} return true;
}
public function __destruct() { public function __destruct()
if(is_resource($this->dbConn)) { {
sqlsrv_close($this->dbConn); if (is_resource($this->dbConn)) {
} sqlsrv_close($this->dbConn);
} }
}
public function getVersion() { public function getVersion()
// @todo - use sqlsrv_server_info? {
return trim($this->query("SELECT CONVERT(char(15), SERVERPROPERTY('ProductVersion'))")->value()); // @todo - use sqlsrv_server_info?
} 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->selectedDatabase = null; $this->selectDatabase('Master');
} $this->selectedDatabase = null;
}
/** /**
* Quotes a string, including the "N" prefix so unicode * Quotes a string, including the "N" prefix so unicode
* strings are saved to the database correctly. * strings are saved to the database correctly.
* *
* @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("\0", "[NULL]", $value); $value = str_replace("'", "''", $value);
return $value; $value = str_replace("\0", "[NULL]", $value);
} return $value;
}
} }

View File

@ -5,72 +5,85 @@
* *
* @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.
* *
* @var SQLServerConnector * @var SQLServerConnector
*/ */
private $connector; private $connector;
/** /**
* The internal MSSQL handle that points to the result set. * The internal MSSQL handle that points to the result set.
* *
* @var resource * @var resource
*/ */
private $handle; private $handle;
/** /**
* Hook the result-set given into a Query class, suitable for use by sapphire. * Hook the result-set given into a Query class, suitable for use by sapphire.
* @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->handle = $handle; $this->connector = $connector;
} $this->handle = $handle;
}
public function __destruct() { public function __destruct()
if(is_resource($this->handle)) { {
sqlsrv_free_stmt($this->handle); if (is_resource($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; }
} else { }
// Free the handle if there are no more results - sqlsrv crashes if there are too many handles return $data;
sqlsrv_free_stmt($this->handle); } else {
$this->handle = null; // Free the handle if there are no more results - sqlsrv crashes if there are too many handles
} sqlsrv_free_stmt($this->handle);
$this->handle = null;
return false; }
}
return false;
}
} }

View File

@ -1,28 +1,30 @@
<?php <?php
class MSSQLDatabaseQueryTest extends SapphireTest { class MSSQLDatabaseQueryTest extends SapphireTest
{
public static $fixture_file = 'MSSQLDatabaseQueryTest.yml'; public static $fixture_file = 'MSSQLDatabaseQueryTest.yml';
protected $extraDataObjects = array( protected $extraDataObjects = array(
'MSSQLDatabaseQueryTestDataObject' 'MSSQLDatabaseQueryTestDataObject'
); );
public function testDateValueFormatting() { public function testDateValueFormatting()
$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)'); $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)');
}
public function testDatetimeValueFormatting() {
$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)');
}
public function testDatetimeValueFormatting()
{
$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)');
}
} }
class MSSQLDatabaseQueryTestDataObject extends DataObject implements TestOnly { class MSSQLDatabaseQueryTestDataObject extends DataObject implements TestOnly
{
public static $db = array(
'TestDate' => 'Date',
'TestDatetime' => 'SS_Datetime'
);
public static $db = array(
'TestDate' => 'Date',
'TestDatetime' => 'SS_Datetime'
);
} }