3 * This is the MS SQL Server Native database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Joel Penner <a-joelpe at microsoft dot com>
23 * @author Chris Pucci <a-cpucci at microsoft dot com>
24 * @author Ryan Biesemeyer <v-ryanbi at microsoft dot com>
30 class DatabaseMssql
extends DatabaseBase
{
32 protected $mLastResult = null;
34 /** @var int The number of rows affected as an integer */
35 protected $mAffectedRows = null;
38 * @var int Post number for database
39 * @todo Unused and can be removed?
44 private $mInsertId = null;
46 function cascadingDeletes() {
50 function cleanupTriggers() {
54 function strictIPs() {
58 function realTimestamps() {
62 function implicitGroupby() {
66 function implicitOrderby() {
70 function functionalIndexes() {
74 function unionSupportsOrderAndLimit() {
79 * Usually aborts on failure
80 * @param string $server
82 * @param string $password
83 * @param string $dbName
84 * @throws DBConnectionError
85 * @return bool|DatabaseBase|null
87 function open( $server, $user, $password, $dbName ) {
88 # Test for driver support, to avoid suppressed fatal error
89 if ( !function_exists( 'sqlsrv_connect' ) ) {
90 throw new DBConnectionError(
92 "MS Sql Server Native (sqlsrv) functions missing. You can download " .
93 "the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n" );
98 # e.g. the class is being loaded
99 if ( !strlen( $user ) ) {
104 $this->mServer
= $server;
105 $this->mPort
= $wgDBport;
106 $this->mUser
= $user;
107 $this->mPassword
= $password;
108 $this->mDBname
= $dbName;
110 $connectionInfo = array();
113 $connectionInfo['Database'] = $dbName;
116 // Start NT Auth Hack
117 // Quick and dirty work around to provide NT Auth designation support.
118 // Current solution requires installer to know to input 'ntauth' for
119 // both username and password to trigger connection via NT Auth. Ugly,
121 // @todo Make this better and add NT Auth choice to MW installer when
122 // SQL Server option is chosen.
123 $ntAuthUserTest = strtolower( $user );
124 $ntAuthPassTest = strtolower( $password );
126 // Decide which auth scenerio to use
127 if ( $ntAuthPassTest == 'ntauth' && $ntAuthUserTest == 'ntauth' ) {
128 // Don't add credentials to $connectionInfo
130 $connectionInfo['UID'] = $user;
131 $connectionInfo['PWD'] = $password;
135 wfSuppressWarnings();
136 $this->mConn
= sqlsrv_connect( $server, $connectionInfo );
139 if ( $this->mConn
=== false ) {
140 wfDebug( "DB connection error\n" );
141 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " .
142 substr( $password, 0, 3 ) . "...\n" );
143 wfDebug( $this->lastError() . "\n" );
148 $this->mOpened
= true;
154 * Closes a database connection, if it is open
155 * Returns success, true if already closed
158 protected function closeConnection() {
159 return sqlsrv_close( $this->mConn
);
162 protected function doQuery( $sql ) {
163 wfDebug( "SQL: [$sql]\n" );
166 // several extensions seem to think that all databases support limits
167 // via LIMIT N after the WHERE clause well, MSSQL uses SELECT TOP N,
168 // so to catch any of those extensions we'll do a quick check for a
169 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
170 // the limit clause and passes the result to $this->limitResult();
171 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
172 // massage LIMIT -> TopN
173 $sql = $this->LimitToTopN( $sql );
176 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
177 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
178 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
179 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
183 $stmt = sqlsrv_query( $this->mConn
, $sql );
184 if ( $stmt == false ) {
185 $message = "A database error has occurred. Did you forget " .
186 "to run maintenance/update.php after upgrading? See: " .
187 "http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
188 "Query: " . htmlentities( $sql ) . "\n" .
189 "Function: " . __METHOD__
. "\n";
190 // process each error (our driver will give us an array of errors unlike other providers)
191 foreach ( sqlsrv_errors() as $error ) {
192 $message .= $message . "ERROR[" . $error['code'] . "] " . $error['message'] . "\n";
195 throw new DBUnexpectedError( $this, $message );
197 // remember number of rows affected
198 $this->mAffectedRows
= sqlsrv_rows_affected( $stmt );
200 // if it is a SELECT statement, or an insert with a request to output
201 // something we want to return a row.
202 if ( ( preg_match( '#\bSELECT\s#i', $sql ) ) ||
203 ( preg_match( '#\bINSERT\s#i', $sql ) && preg_match( '#\bOUTPUT\s+INSERTED\b#i', $sql ) )
205 // this is essentially a rowset, but Mediawiki calls these 'result'
206 // the rowset owns freeing the statement
207 $res = new MssqlResult( $stmt );
209 // otherwise we simply return it was successful, failure throws an exception
216 function freeResult( $res ) {
217 if ( $res instanceof ResultWrapper
) {
223 function fetchObject( $res ) {
224 if ( $res instanceof ResultWrapper
) {
227 $row = $res->fetch( 'OBJECT' );
232 function getErrors() {
234 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
235 if ( $retErrors != null ) {
236 foreach ( $retErrors as $arrError ) {
237 $strRet .= "SQLState: " . $arrError['SQLSTATE'] . "\n";
238 $strRet .= "Error Code: " . $arrError['code'] . "\n";
239 $strRet .= "Message: " . $arrError['message'] . "\n";
242 $strRet = "No errors found";
248 function fetchRow( $res ) {
249 if ( $res instanceof ResultWrapper
) {
252 $row = $res->fetch( SQLSRV_FETCH_BOTH
);
257 function numRows( $res ) {
258 if ( $res instanceof ResultWrapper
) {
262 return ( $res ) ?
$res->numrows() : 0;
265 function numFields( $res ) {
266 if ( $res instanceof ResultWrapper
) {
270 return ( $res ) ?
$res->numfields() : 0;
273 function fieldName( $res, $n ) {
274 if ( $res instanceof ResultWrapper
) {
278 return ( $res ) ?
$res->fieldname( $n ) : 0;
282 * This must be called after nextSequenceVal
285 function insertId() {
286 return $this->mInsertId
;
289 function dataSeek( $res, $row ) {
290 if ( $res instanceof ResultWrapper
) {
294 return ( $res ) ?
$res->seek( $row ) : false;
297 function lastError() {
298 if ( $this->mConn
) {
299 return $this->getErrors();
301 return "No database connection";
305 function lastErrno() {
306 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
308 return $err[0]['code'];
314 function affectedRows() {
315 return $this->mAffectedRows
;
321 * @param $table Mixed: array or string, table name(s) (prefix auto-added)
322 * @param $vars Mixed: array or string, field name(s) to be retrieved
323 * @param $conds Mixed: array or string, condition(s) for WHERE
324 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
325 * @param array $options associative array of options (e.g.
326 * array('GROUP BY' => 'page_title')), see Database::makeSelectOptions
327 * code for list of supported stuff
328 * @param $join_conds Array: Associative array of table join conditions
329 * (optional) (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
330 * @return Mixed: database result resource (feed to Database::fetchObject
331 * or whatever), or false on failure
333 function select( $table, $vars, $conds = '', $fname = __METHOD__
,
334 $options = array(), $join_conds = array()
336 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
337 if ( isset( $options['EXPLAIN'] ) ) {
338 sqlsrv_query( $this->mConn
, "SET SHOWPLAN_ALL ON;" );
339 $ret = $this->query( $sql, $fname );
340 sqlsrv_query( $this->mConn
, "SET SHOWPLAN_ALL OFF;" );
345 return $this->query( $sql, $fname );
351 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
352 * @param $vars Mixed: Array or string, field name(s) to be retrieved
353 * @param $conds Mixed: Array or string, condition(s) for WHERE
354 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
355 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
356 * see Database::makeSelectOptions code for list of supported stuff
357 * @param $join_conds Array: Associative array of table join conditions (optional)
358 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
359 * @return string, the SQL text
361 function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
362 $options = array(), $join_conds = array()
364 if ( isset( $options['EXPLAIN'] ) ) {
365 unset( $options['EXPLAIN'] );
368 return parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
372 * Estimate rows in dataset
373 * Returns estimated count, based on SHOWPLAN_ALL output
374 * This is not necessarily an accurate estimate, so use sparingly
375 * Returns -1 if count cannot be found
376 * Takes same arguments as Database::select()
379 function estimateRowCount( $table, $vars = '*', $conds = '',
380 $fname = __METHOD__
, $options = array()
382 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
383 $options['EXPLAIN'] = true;
384 $res = $this->select( $table, $vars, $conds, $fname, $options );
388 $row = $this->fetchRow( $res );
389 if ( isset( $row['EstimateRows'] ) ) {
390 $rows = $row['EstimateRows'];
398 * Returns information about an index
399 * If errors are explicitly ignored, returns NULL on failure
400 * @return array|bool|null
402 function indexInfo( $table, $index, $fname = __METHOD__
) {
403 # This does not return the same info as MYSQL would, but that's OK
404 # because MediaWiki never uses the returned value except to check for
405 # the existance of indexes.
406 $sql = "sp_helpindex '" . $table . "'";
407 $res = $this->query( $sql, $fname );
413 foreach ( $res as $row ) {
414 if ( $row->index_name
== $index ) {
415 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
416 $cols = explode( ", ", $row->index_keys
);
417 foreach ( $cols as $col ) {
418 $row->Column_name
= trim( $col );
419 $result[] = clone $row;
421 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
422 $row->Non_unique
= 0;
423 $cols = explode( ", ", $row->index_keys
);
424 foreach ( $cols as $col ) {
425 $row->Column_name
= trim( $col );
426 $result[] = clone $row;
431 return empty( $result ) ?
false : $result;
435 * INSERT wrapper, inserts an array into a table
437 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
440 * Usually aborts on failure
441 * If errors are explicitly ignored, returns success
442 * @param string $table
443 * @param array $arrToInsert
444 * @param string $fname
445 * @param array $options
446 * @throws DBQueryError
449 function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = array() ) {
450 # No rows to insert, easy just return now
451 if ( !count( $arrToInsert ) ) {
455 if ( !is_array( $options ) ) {
456 $options = array( $options );
459 $table = $this->tableName( $table );
461 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
462 $arrToInsert = array( 0 => $arrToInsert ); // make everything multi row compatible
467 // We know the table we're inserting into, get its identity column
469 // strip matching square brackets from table name
470 $tableRaw = preg_replace( '#\[([^\]]*)\]#', '$1', $table );
471 $res = $this->doQuery(
472 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
473 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
475 if ( $res && $res->numrows() ) {
476 // There is an identity for this table.
477 $identity = array_pop( $res->fetch( SQLSRV_FETCH_ASSOC
) );
481 foreach ( $arrToInsert as $a ) {
482 // start out with empty identity column, this is so we can return
483 // it as a result of the insert logic
486 $identityClause = '';
488 // if we have an identity column
491 foreach ( $a as $k => $v ) {
492 if ( $k == $identity ) {
493 if ( !is_null( $v ) ) {
494 // there is a value being passed to us, we need to turn on and off inserted identity
495 $sqlPre = "SET IDENTITY_INSERT $table ON;";
496 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
498 // we can't insert NULL into an identity column, so remove the column from the insert.
504 // we want to output an identity column as result
505 $identityClause = "OUTPUT INSERTED.$identity ";
508 $keys = array_keys( $a );
510 // INSERT IGNORE is not supported by SQL Server
511 // remove IGNORE from options list and set ignore flag to true
512 $ignoreClause = false;
513 foreach ( $options as $k => $v ) {
514 if ( strtoupper( $v ) == "IGNORE" ) {
515 unset( $options[$k] );
516 $ignoreClause = true;
520 // translate MySQL INSERT IGNORE to something SQL Server can use
522 // MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
523 // MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '1')
524 // INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
525 if ( $ignoreClause ) {
526 $prival = $a[$keys[0]];
527 $sqlPre .= "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival')";
530 // Build the actual query
531 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
532 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
535 foreach ( $a as $value ) {
541 if ( is_string( $value ) ) {
542 $sql .= $this->addQuotes( $value );
543 } elseif ( is_null( $value ) ) {
545 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
546 if ( is_object( $value ) && strtolower( get_class( $value ) ) == 'blob' ) {
547 $sql .= $this->addQuotes( $value );
549 $sql .= $this->addQuotes( serialize( $value ) );
555 $sql .= ')' . $sqlPost;
558 $ret = sqlsrv_query( $this->mConn
, $sql );
560 if ( $ret === false ) {
561 throw new DBQueryError( $this, $this->getErrors(), $this->lastErrno(), $sql, $fname );
562 } elseif ( $ret != null ) {
563 // remember number of rows affected
564 $this->mAffectedRows
= sqlsrv_rows_affected( $ret );
565 if ( !is_null( $identity ) ) {
566 // then we want to get the identity column value we were assigned and save it off
567 $row = sqlsrv_fetch_object( $ret );
568 $this->mInsertId
= $row->$identity;
570 sqlsrv_free_stmt( $ret );
580 * INSERT SELECT wrapper
581 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
582 * Source items may be literals rather than field names, but strings should
583 * be quoted with Database::addQuotes().
584 * @param string $destTable
585 * @param array|string $srcTable May be an array of tables.
586 * @param array $varMap
587 * @param array $conds May be "*" to copy the whole table.
588 * @param string $fname
589 * @param array $insertOptions
590 * @param array $selectOptions
591 * @throws DBQueryError
592 * @return null|ResultWrapper
594 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
595 $insertOptions = array(), $selectOptions = array() ) {
596 $ret = parent
::insertSelect(
606 if ( $ret === false ) {
607 throw new DBQueryError( $this, $this->getErrors(), $this->lastErrno(), /*$sql*/ '', $fname );
608 } elseif ( $ret != null ) {
609 // remember number of rows affected
610 $this->mAffectedRows
= sqlsrv_rows_affected( $ret );
619 * Return the next in a sequence, save the value for retrieval via insertId()
622 function nextSequenceValue( $seqName ) {
623 if ( !$this->tableExists( 'sequence_' . $seqName ) ) {
626 "CREATE TABLE [sequence_$seqName] (id INT NOT NULL IDENTITY PRIMARY KEY, junk varchar(10) NULL)"
629 sqlsrv_query( $this->mConn
, "INSERT INTO [sequence_$seqName] (junk) VALUES ('')" );
630 $ret = sqlsrv_query( $this->mConn
, "SELECT TOP 1 id FROM [sequence_$seqName] ORDER BY id DESC" );
631 // KEEP ASSOC THERE, weird weird bug dealing with the return value if you don't
632 $row = sqlsrv_fetch_array( $ret, SQLSRV_FETCH_ASSOC
);
634 sqlsrv_free_stmt( $ret );
635 $this->mInsertId
= $row['id'];
641 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
644 function currentSequenceValue( $seqName ) {
645 $ret = sqlsrv_query( $this->mConn
, "SELECT TOP 1 id FROM [sequence_$seqName] ORDER BY id DESC" );
646 if ( $ret !== false ) {
647 $row = sqlsrv_fetch_array( $ret );
648 sqlsrv_free_stmt( $ret );
652 return $this->nextSequenceValue( $seqName );
656 # Returns the size of a text field, or -1 for "unlimited"
657 function textFieldSize( $table, $field ) {
658 $table = $this->tableName( $table );
659 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
660 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
661 $res = $this->query( $sql );
662 $row = $this->fetchRow( $res );
664 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
665 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
672 * Construct a LIMIT query with optional offset
673 * This is used for query pages
674 * $sql string SQL query we will append the limit too
675 * $limit integer the SQL limit
676 * $offset integer the SQL offset (default false)
677 * @return mixed|string
679 function limitResult( $sql, $limit, $offset = false ) {
680 if ( $offset === false ||
$offset == 0 ) {
681 if ( strpos( $sql, "SELECT" ) === false ) {
682 return "TOP {$limit} " . $sql;
684 return preg_replace( '/\bSELECT(\s*DISTINCT)?\b/Dsi', 'SELECT$1 TOP ' . $limit, $sql, 1 );
689 SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3 FROM (
690 SELECT 1 AS line2, sub1.* FROM (' . $sql . ') AS sub1
693 WHERE line3 BETWEEN ' . ( $offset +
1 ) . ' AND ' . ( $offset +
$limit );
699 // If there is a limit clause, parse it, strip it, and pass the remaining
700 // SQL through limitResult() with the appropriate parameters. Not the
701 // prettiest solution, but better than building a whole new parser. This
702 // exists becase there are still too many extensions that don't use dynamic
704 function LimitToTopN( $sql ) {
705 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
706 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
707 if ( preg_match( $pattern, $sql, $matches ) ) {
708 // row_count = $matches[4]
709 $row_count = $matches[4];
710 // offset = $matches[3] OR $matches[6]
711 $offset = $matches[3] or
712 $offset = $matches[6] or
715 // strip the matching LIMIT clause out
716 $sql = str_replace( $matches[0], '', $sql );
718 return $this->limitResult( $sql, $row_count, $offset );
724 function timestamp( $ts = 0 ) {
725 return wfTimestamp( TS_ISO_8601
, $ts );
729 * @return string wikitext of a link to the server software's web site
731 public function getSoftwareLink() {
732 return "[http://www.microsoft.com/sql/ MS SQL Server]";
736 * @return string Version information from the database
738 function getServerVersion() {
739 $server_info = sqlsrv_server_info( $this->mConn
);
741 if ( isset( $server_info['SQLServerVersion'] ) ) {
742 $version = $server_info['SQLServerVersion'];
748 function tableExists( $table, $fname = __METHOD__
, $schema = false ) {
749 $res = sqlsrv_query( $this->mConn
, "SELECT * FROM information_schema.tables
750 WHERE table_type='BASE TABLE' AND table_name = '$table'" );
751 if ( $res === false ) {
752 print "Error in tableExists query: " . $this->getErrors();
756 if ( sqlsrv_fetch( $res ) ) {
764 * Query whether a given column exists in the mediawiki schema
767 function fieldExists( $table, $field, $fname = __METHOD__
) {
768 $table = $this->tableName( $table );
769 $res = sqlsrv_query( $this->mConn
, "SELECT DATA_TYPE FROM INFORMATION_SCHEMA.Columns
770 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
771 if ( $res === false ) {
772 print "Error in fieldExists query: " . $this->getErrors();
776 if ( sqlsrv_fetch( $res ) ) {
783 function fieldInfo( $table, $field ) {
784 $table = $this->tableName( $table );
785 $res = sqlsrv_query( $this->mConn
, "SELECT * FROM INFORMATION_SCHEMA.Columns
786 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
787 if ( $res === false ) {
788 print "Error in fieldInfo query: " . $this->getErrors();
792 $meta = $this->fetchRow( $res );
794 return new MssqlField( $meta );
801 * Begin a transaction, committing any previously open transaction
803 protected function doBegin( $fname = __METHOD__
) {
804 sqlsrv_begin_transaction( $this->mConn
);
805 $this->mTrxLevel
= 1;
811 protected function doCommit( $fname = __METHOD__
) {
812 sqlsrv_commit( $this->mConn
);
813 $this->mTrxLevel
= 0;
817 * Rollback a transaction.
818 * No-op on non-transactional databases.
820 protected function doRollback( $fname = __METHOD__
) {
821 sqlsrv_rollback( $this->mConn
);
822 $this->mTrxLevel
= 0;
826 * Escapes a identifier for use inm SQL.
827 * Throws an exception if it is invalid.
828 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
830 * @throws MWException
833 private function escapeIdentifier( $identifier ) {
834 if ( strlen( $identifier ) == 0 ) {
835 throw new MWException( "An identifier must not be empty" );
837 if ( strlen( $identifier ) > 128 ) {
838 throw new MWException( "The identifier '$identifier' is too long (max. 128)" );
840 if ( ( strpos( $identifier, '[' ) !== false ) ||
( strpos( $identifier, ']' ) !== false ) ) {
841 // It may be allowed if you quoted with double quotation marks, but
842 // that would break if QUOTED_IDENTIFIER is OFF
843 throw new MWException( "You can't use square brackers in the identifier '$identifier'" );
846 return "[$identifier]";
851 * Precondition: This object is connected as the superuser.
852 * Creates the database, schema, user and login.
854 function initial_setup( $dbName, $newUser, $loginPassword ) {
855 $dbName = $this->escapeIdentifier( $dbName );
857 // It is not clear what can be used as a login,
858 // From http://msdn.microsoft.com/en-us/library/ms173463.aspx
859 // a sysname may be the same as an identifier.
860 $newUser = $this->escapeIdentifier( $newUser );
861 $loginPassword = $this->addQuotes( $loginPassword );
863 $this->doQuery( "CREATE DATABASE $dbName;" );
864 $this->doQuery( "USE $dbName;" );
865 $this->doQuery( "CREATE SCHEMA $dbName;" );
870 PASSWORD=$loginPassword
879 DEFAULT_SCHEMA=$dbName
892 CREATE FULLTEXT CATALOG
908 function encodeBlob( $b ) {
909 // we can't have zero's and such, this is a simple encoding to make sure we don't barf
910 return base64_encode( $b );
913 function decodeBlob( $b ) {
914 // we can't have zero's and such, this is a simple encoding to make sure we don't barf
915 return base64_decode( $b );
922 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
925 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
926 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
927 foreach ( $tables as $table ) {
928 // Is there a JOIN and INDEX clause for this table?
929 if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
930 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
931 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
932 $tableClause .= ' ON (' . $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
) . ')';
933 $retJOIN[] = $tableClause;
934 // Is there an INDEX clause?
935 } elseif ( isset( $use_index_safe[$table] ) ) {
936 $tableClause = $this->tableName( $table );
937 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
938 $ret[] = $tableClause;
939 // Is there a JOIN clause?
940 } elseif ( isset( $join_conds_safe[$table] ) ) {
941 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
942 $tableClause .= ' ON (' . $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
) . ')';
943 $retJOIN[] = $tableClause;
945 $tableClause = $this->tableName( $table );
946 $ret[] = $tableClause;
949 // We can't separate explicit JOIN clauses with ',', use ' ' for those
950 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
951 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
953 // Compile our final table clause
954 return implode( ' ', array( $straightJoins, $otherJoins ) );
957 function strencode( $s ) { # Should not be called by us
958 return str_replace( "'", "''", $s );
961 function addQuotes( $s ) {
962 if ( $s instanceof Blob
) {
963 return "'" . $s->fetch( $s ) . "'";
965 return parent
::addQuotes( $s );
969 public function addIdentifierQuotes( $s ) {
970 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
971 return '[' . $s . ']';
974 public function isQuotedIdentifier( $name ) {
975 return $name[0] == '[' && substr( $name, -1, 1 ) == ']';
978 function selectDB( $db ) {
979 return ( $this->query( "SET DATABASE $db" ) !== false );
985 * @param array $options an associative array of options to be turned into
986 * an SQL query, valid keys are listed in the function.
989 function makeSelectOptions( $options ) {
993 $noKeyOptions = array();
994 foreach ( $options as $key => $option ) {
995 if ( is_numeric( $key ) ) {
996 $noKeyOptions[$option] = true;
1000 $tailOpts .= $this->makeGroupByWithHaving( $options );
1002 $tailOpts .= $this->makeOrderBy( $options );
1004 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) {
1005 $startOpts .= 'DISTINCT';
1008 // we want this to be compatible with the output of parent::makeSelectOptions()
1009 return array( $startOpts, '', $tailOpts, '' );
1013 * Get the type of the DBMS, as it appears in $wgDBtype.
1016 function getType() {
1020 function buildConcat( $stringList ) {
1021 return implode( ' + ', $stringList );
1024 public function getSearchEngine() {
1025 return "SearchMssql";
1029 * Since MSSQL doesn't recognize the infinity keyword, set date manually.
1030 * @todo Remove magic date
1033 public function getInfinity() {
1034 return '3000-01-31 00:00:00.000';
1036 } // end DatabaseMssql class
1043 class MssqlField
implements Field
{
1044 private $name, $tablename, $default, $max_length, $nullable, $type;
1046 function __construct( $info ) {
1047 $this->name
= $info['COLUMN_NAME'];
1048 $this->tablename
= $info['TABLE_NAME'];
1049 $this->default = $info['COLUMN_DEFAULT'];
1050 $this->max_length
= $info['CHARACTER_MAXIMUM_LENGTH'];
1051 $this->nullable
= !( strtolower( $info['IS_NULLABLE'] ) == 'no' );
1052 $this->type
= $info['DATA_TYPE'];
1059 function tableName() {
1060 return $this->tableName
;
1063 function defaultValue() {
1064 return $this->default;
1067 function maxLength() {
1068 return $this->max_length
;
1071 function isNullable() {
1072 return $this->nullable
;
1081 * The MSSQL PHP driver doesn't support sqlsrv_num_rows, so we recall all rows
1082 * into an array and maintain our own cursor index into that array... This is
1083 * similar to the way the Oracle driver handles this same issue
1089 public function __construct( $queryresult = false ) {
1091 $this->mRows
= array();
1092 $this->mNumFields
= sqlsrv_num_fields( $queryresult );
1093 $this->mFieldMeta
= sqlsrv_field_metadata( $queryresult );
1095 $rows = sqlsrv_fetch_array( $queryresult, SQLSRV_FETCH_ASSOC
);
1097 foreach ( $rows as $row ) {
1098 if ( $row !== null ) {
1099 foreach ( $row as $k => $v ) {
1100 if ( is_object( $v ) && method_exists( $v, 'format' ) ) { // DateTime Object
1101 $row[$k] = $v->format( "Y-m-d\TH:i:s\Z" );
1104 $this->mRows
[] = $row; // read results into memory, cursors are not supported
1107 $this->mRowCount
= count( $this->mRows
);
1108 sqlsrv_free_stmt( $queryresult );
1111 private function array_to_obj( $array, &$obj ) {
1112 foreach ( $array as $key => $value ) {
1113 if ( is_array( $value ) ) {
1114 $obj->$key = new stdClass();
1115 $this->array_to_obj( $value, $obj->$key );
1117 if ( !empty( $key ) ) {
1118 $obj->$key = $value;
1126 public function fetch( $mode = SQLSRV_FETCH_BOTH
, $object_class = 'stdClass' ) {
1127 if ( $this->mCursor
>= $this->mRowCount ||
$this->mRowCount
== 0 ) {
1131 if ( $mode == SQLSRV_FETCH_NUMERIC ||
$mode == SQLSRV_FETCH_BOTH
) {
1132 foreach ( $this->mRows
[$this->mCursor
] as $value ) {
1137 case SQLSRV_FETCH_ASSOC
:
1138 $ret = $this->mRows
[$this->mCursor
];
1140 case SQLSRV_FETCH_NUMERIC
:
1144 $o = new $object_class;
1145 $ret = $this->array_to_obj( $this->mRows
[$this->mCursor
], $o );
1147 case SQLSRV_FETCH_BOTH
:
1149 $ret = $this->mRows
[$this->mCursor
] +
$arrNum;
1158 public function get( $pos, $fld ) {
1159 return $this->mRows
[$pos][$fld];
1162 public function numrows() {
1163 return $this->mRowCount
;
1166 public function seek( $iRow ) {
1167 $this->mCursor
= min( $iRow, $this->mRowCount
);
1170 public function numfields() {
1171 return $this->mNumFields
;
1174 public function fieldname( $nr ) {
1175 $arrKeys = array_keys( $this->mRows
[0] );
1177 return $arrKeys[$nr];
1180 public function fieldtype( $nr ) {
1183 foreach ( $this->mFieldMeta
as $meta ) {
1185 $intType = $meta['Type'];
1190 // http://msdn.microsoft.com/en-us/library/cc296183.aspx contains type table
1191 switch ( $intType ) {
1192 case SQLSRV_SQLTYPE_BIGINT
:
1193 $strType = 'bigint';
1195 case SQLSRV_SQLTYPE_BINARY
:
1196 $strType = 'binary';
1198 case SQLSRV_SQLTYPE_BIT
:
1201 case SQLSRV_SQLTYPE_CHAR
:
1204 case SQLSRV_SQLTYPE_DATETIME
:
1205 $strType = 'datetime';
1207 case SQLSRV_SQLTYPE_DECIMAL
: // ($precision, $scale)
1208 $strType = 'decimal';
1210 case SQLSRV_SQLTYPE_FLOAT
:
1213 case SQLSRV_SQLTYPE_IMAGE
:
1216 case SQLSRV_SQLTYPE_INT
:
1219 case SQLSRV_SQLTYPE_MONEY
:
1222 case SQLSRV_SQLTYPE_NCHAR
: // ($charCount):
1225 case SQLSRV_SQLTYPE_NUMERIC
: // ($precision, $scale):
1226 $strType = 'numeric';
1228 case SQLSRV_SQLTYPE_NVARCHAR
: // ($charCount)
1229 $strType = 'nvarchar';
1231 // case SQLSRV_SQLTYPE_NVARCHAR('max'):
1232 // $strType = 'nvarchar(MAX)';
1234 case SQLSRV_SQLTYPE_NTEXT
:
1237 case SQLSRV_SQLTYPE_REAL
:
1240 case SQLSRV_SQLTYPE_SMALLDATETIME
:
1241 $strType = 'smalldatetime';
1243 case SQLSRV_SQLTYPE_SMALLINT
:
1244 $strType = 'smallint';
1246 case SQLSRV_SQLTYPE_SMALLMONEY
:
1247 $strType = 'smallmoney';
1249 case SQLSRV_SQLTYPE_TEXT
:
1252 case SQLSRV_SQLTYPE_TIMESTAMP
:
1253 $strType = 'timestamp';
1255 case SQLSRV_SQLTYPE_TINYINT
:
1256 $strType = 'tinyint';
1258 case SQLSRV_SQLTYPE_UNIQUEIDENTIFIER
:
1259 $strType = 'uniqueidentifier';
1261 case SQLSRV_SQLTYPE_UDT
:
1264 case SQLSRV_SQLTYPE_VARBINARY
: // ($byteCount)
1265 $strType = 'varbinary';
1267 // case SQLSRV_SQLTYPE_VARBINARY('max'):
1268 // $strType = 'varbinary(MAX)';
1270 case SQLSRV_SQLTYPE_VARCHAR
: // ($charCount)
1271 $strType = 'varchar';
1273 // case SQLSRV_SQLTYPE_VARCHAR('max'):
1274 // $strType = 'varchar(MAX)';
1276 case SQLSRV_SQLTYPE_XML
:
1280 $strType = $intType;
1286 public function free() {
1287 unset( $this->mRows
);