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
{
31 var $mInsertId = null;
32 var $mLastResult = null;
33 var $mAffectedRows = null;
37 function cascadingDeletes() {
40 function cleanupTriggers() {
43 function strictIPs() {
46 function realTimestamps() {
49 function implicitGroupby() {
52 function implicitOrderby() {
55 function functionalIndexes() {
58 function unionSupportsOrderAndLimit() {
63 * Usually aborts on failure
64 * @param string $server
66 * @param string $password
67 * @param string $dbName
68 * @throws DBConnectionError
69 * @return bool|DatabaseBase|null
71 function open( $server, $user, $password, $dbName ) {
72 # Test for driver support, to avoid suppressed fatal error
73 if ( !function_exists( 'sqlsrv_connect' ) ) {
74 throw new DBConnectionError( $this, "MS Sql Server Native (sqlsrv) functions missing. You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n" );
79 if ( !strlen( $user ) ) { # e.g. the class is being loaded
84 $this->mServer
= $server;
85 $this->mPort
= $wgDBport;
87 $this->mPassword
= $password;
88 $this->mDBname
= $dbName;
90 $connectionInfo = array();
93 $connectionInfo['Database'] = $dbName;
97 // Quick and dirty work around to provide NT Auth designation support.
98 // Current solution requires installer to know to input 'ntauth' for both username and password
99 // to trigger connection via NT Auth. - ugly, ugly, ugly
100 // TO-DO: Make this better and add NT Auth choice to MW installer when SQL Server option is chosen.
101 $ntAuthUserTest = strtolower( $user );
102 $ntAuthPassTest = strtolower( $password );
104 // Decide which auth scenerio to use
105 if( $ntAuthPassTest == 'ntauth' && $ntAuthUserTest == 'ntauth' ) {
106 // Don't add credentials to $connectionInfo
108 $connectionInfo['UID'] = $user;
109 $connectionInfo['PWD'] = $password;
113 wfSuppressWarnings();
114 $this->mConn
= sqlsrv_connect( $server, $connectionInfo );
117 if ( $this->mConn
=== false ) {
118 wfDebug( "DB connection error\n" );
119 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
120 wfDebug( $this->lastError() . "\n" );
124 $this->mOpened
= true;
129 * Closes a database connection, if it is open
130 * Returns success, true if already closed
133 protected function closeConnection() {
134 return sqlsrv_close( $this->mConn
);
137 protected function doQuery( $sql ) {
138 wfDebug( "SQL: [$sql]\n" );
141 // several extensions seem to think that all databases support limits via LIMIT N after the WHERE clause
142 // well, MSSQL uses SELECT TOP N, so to catch any of those extensions we'll do a quick check for a LIMIT
143 // clause and pass $sql through $this->LimitToTopN() which parses the limit clause and passes the result to
144 // $this->limitResult();
145 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
146 // massage LIMIT -> TopN
147 $sql = $this->LimitToTopN( $sql );
150 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
151 if ( preg_match('#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
152 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
153 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
157 $stmt = sqlsrv_query( $this->mConn
, $sql );
158 if ( $stmt == false ) {
159 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
160 "Query: " . htmlentities( $sql ) . "\n" .
161 "Function: " . __METHOD__
. "\n";
162 // process each error (our driver will give us an array of errors unlike other providers)
163 foreach ( sqlsrv_errors() as $error ) {
164 $message .= $message . "ERROR[" . $error['code'] . "] " . $error['message'] . "\n";
167 throw new DBUnexpectedError( $this, $message );
169 // remember number of rows affected
170 $this->mAffectedRows
= sqlsrv_rows_affected( $stmt );
172 // if it is a SELECT statement, or an insert with a request to output something we want to return a row.
173 if ( ( preg_match( '#\bSELECT\s#i', $sql ) ) ||
174 ( preg_match( '#\bINSERT\s#i', $sql ) && preg_match( '#\bOUTPUT\s+INSERTED\b#i', $sql ) ) ) {
175 // this is essentially a rowset, but Mediawiki calls these 'result'
176 // the rowset owns freeing the statement
177 $res = new MssqlResult( $stmt );
179 // otherwise we simply return it was successful, failure throws an exception
185 function freeResult( $res ) {
186 if ( $res instanceof ResultWrapper
) {
192 function fetchObject( $res ) {
193 if ( $res instanceof ResultWrapper
) {
196 $row = $res->fetch( 'OBJECT' );
200 function getErrors() {
202 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
203 if ( $retErrors != null ) {
204 foreach ( $retErrors as $arrError ) {
205 $strRet .= "SQLState: " . $arrError[ 'SQLSTATE'] . "\n";
206 $strRet .= "Error Code: " . $arrError[ 'code'] . "\n";
207 $strRet .= "Message: " . $arrError[ 'message'] . "\n";
210 $strRet = "No errors found";
215 function fetchRow( $res ) {
216 if ( $res instanceof ResultWrapper
) {
219 $row = $res->fetch( SQLSRV_FETCH_BOTH
);
223 function numRows( $res ) {
224 if ( $res instanceof ResultWrapper
) {
227 return ( $res ) ?
$res->numrows() : 0;
230 function numFields( $res ) {
231 if ( $res instanceof ResultWrapper
) {
234 return ( $res ) ?
$res->numfields() : 0;
237 function fieldName( $res, $n ) {
238 if ( $res instanceof ResultWrapper
) {
241 return ( $res ) ?
$res->fieldname( $n ) : 0;
245 * This must be called after nextSequenceVal
248 function insertId() {
249 return $this->mInsertId
;
252 function dataSeek( $res, $row ) {
253 if ( $res instanceof ResultWrapper
) {
256 return ( $res ) ?
$res->seek( $row ) : false;
259 function lastError() {
260 if ( $this->mConn
) {
261 return $this->getErrors();
263 return "No database connection";
267 function lastErrno() {
268 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
270 return $err[0]['code'];
276 function affectedRows() {
277 return $this->mAffectedRows
;
283 * @param $table Mixed: array or string, table name(s) (prefix auto-added)
284 * @param $vars Mixed: array or string, field name(s) to be retrieved
285 * @param $conds Mixed: array or string, condition(s) for WHERE
286 * @param $fname String: calling function name (use __METHOD__) for logs/profiling
287 * @param array $options associative array of options (e.g. array('GROUP BY' => 'page_title')),
288 * see Database::makeSelectOptions code for list of supported stuff
289 * @param $join_conds Array: Associative array of table join conditions (optional)
290 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
291 * @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
293 function select( $table, $vars, $conds = '', $fname = 'DatabaseMssql::select', $options = array(), $join_conds = array() )
295 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
296 if ( isset( $options['EXPLAIN'] ) ) {
297 sqlsrv_query( $this->mConn
, "SET SHOWPLAN_ALL ON;" );
298 $ret = $this->query( $sql, $fname );
299 sqlsrv_query( $this->mConn
, "SET SHOWPLAN_ALL OFF;" );
302 return $this->query( $sql, $fname );
308 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
309 * @param $vars Mixed: Array or string, field name(s) to be retrieved
310 * @param $conds Mixed: Array or string, condition(s) for WHERE
311 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
312 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
313 * see Database::makeSelectOptions code for list of supported stuff
314 * @param $join_conds Array: Associative array of table join conditions (optional)
315 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
316 * @return string, the SQL text
318 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseMssql::select', $options = array(), $join_conds = array() ) {
319 if ( isset( $options['EXPLAIN'] ) ) {
320 unset( $options['EXPLAIN'] );
322 return parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
326 * Estimate rows in dataset
327 * Returns estimated count, based on SHOWPLAN_ALL output
328 * This is not necessarily an accurate estimate, so use sparingly
329 * Returns -1 if count cannot be found
330 * Takes same arguments as Database::select()
333 function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseMssql::estimateRowCount', $options = array() ) {
334 $options['EXPLAIN'] = true;// http://msdn2.microsoft.com/en-us/library/aa259203.aspx
335 $res = $this->select( $table, $vars, $conds, $fname, $options );
339 $row = $this->fetchRow( $res );
340 if ( isset( $row['EstimateRows'] ) ) $rows = $row['EstimateRows'];
346 * Returns information about an index
347 * If errors are explicitly ignored, returns NULL on failure
348 * @return array|bool|null
350 function indexInfo( $table, $index, $fname = 'DatabaseMssql::indexExists' ) {
351 # This does not return the same info as MYSQL would, but that's OK because MediaWiki never uses the
352 # returned value except to check for the existance of indexes.
353 $sql = "sp_helpindex '" . $table . "'";
354 $res = $this->query( $sql, $fname );
360 foreach ( $res as $row ) {
361 if ( $row->index_name
== $index ) {
362 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
363 $cols = explode( ", ", $row->index_keys
);
364 foreach ( $cols as $col ) {
365 $row->Column_name
= trim( $col );
366 $result[] = clone $row;
368 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
369 $row->Non_unique
= 0;
370 $cols = explode( ", ", $row->index_keys
);
371 foreach ( $cols as $col ) {
372 $row->Column_name
= trim( $col );
373 $result[] = clone $row;
377 return empty( $result ) ?
false : $result;
381 * INSERT wrapper, inserts an array into a table
383 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
386 * Usually aborts on failure
387 * If errors are explicitly ignored, returns success
388 * @param string $table
389 * @param array $arrToInsert
390 * @param string $fname
391 * @param array $options
392 * @throws DBQueryError
395 function insert( $table, $arrToInsert, $fname = 'DatabaseMssql::insert', $options = array() ) {
396 # No rows to insert, easy just return now
397 if ( !count( $arrToInsert ) ) {
401 if ( !is_array( $options ) ) {
402 $options = array( $options );
405 $table = $this->tableName( $table );
407 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) {// Not multi row
408 $arrToInsert = array( 0 => $arrToInsert );// make everything multi row compatible
413 // We know the table we're inserting into, get its identity column
415 $tableRaw = preg_replace( '#\[([^\]]*)\]#', '$1', $table ); // strip matching square brackets from table name
416 $res = $this->doQuery( "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'" );
417 if( $res && $res->numrows() ) {
418 // There is an identity for this table.
419 $identity = array_pop( $res->fetch( SQLSRV_FETCH_ASSOC
) );
423 foreach ( $arrToInsert as $a ) {
424 // start out with empty identity column, this is so we can return it as a result of the insert logic
427 $identityClause = '';
429 // if we have an identity column
432 foreach ($a as $k => $v ) {
433 if ( $k == $identity ) {
435 // there is a value being passed to us, we need to turn on and off inserted identity
436 $sqlPre = "SET IDENTITY_INSERT $table ON;";
437 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
440 // we can't insert NULL into an identity column, so remove the column from the insert.
445 $identityClause = "OUTPUT INSERTED.$identity "; // we want to output an identity column as result
448 $keys = array_keys( $a );
450 // INSERT IGNORE is not supported by SQL Server
451 // remove IGNORE from options list and set ignore flag to true
452 $ignoreClause = false;
453 foreach ( $options as $k => $v ) {
454 if ( strtoupper( $v ) == "IGNORE" ) {
455 unset( $options[$k] );
456 $ignoreClause = true;
460 // translate MySQL INSERT IGNORE to something SQL Server can use
462 // MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
463 // MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '1') INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
464 if ( $ignoreClause ) {
465 $prival = $a[$keys[0]];
466 $sqlPre .= "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival')";
469 // Build the actual query
470 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
471 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
474 foreach ( $a as $value ) {
480 if ( is_string( $value ) ) {
481 $sql .= $this->addQuotes( $value );
482 } elseif ( is_null( $value ) ) {
484 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
485 if ( is_object( $value ) && strtolower( get_class( $value ) ) == 'blob' ) {
486 $sql .= $this->addQuotes( $value );
488 $sql .= $this->addQuotes( serialize( $value ) );
494 $sql .= ')' . $sqlPost;
497 $ret = sqlsrv_query( $this->mConn
, $sql );
499 if ( $ret === false ) {
500 throw new DBQueryError( $this, $this->getErrors(), $this->lastErrno(), $sql, $fname );
501 } elseif ( $ret != null ) {
502 // remember number of rows affected
503 $this->mAffectedRows
= sqlsrv_rows_affected( $ret );
504 if ( !is_null($identity) ) {
505 // then we want to get the identity column value we were assigned and save it off
506 $row = sqlsrv_fetch_object( $ret );
507 $this->mInsertId
= $row->$identity;
509 sqlsrv_free_stmt( $ret );
518 * INSERT SELECT wrapper
519 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
520 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
521 * $conds may be "*" to copy the whole table
522 * srcTable may be an array of tables.
523 * @param string $destTable
524 * @param array|string $srcTable
525 * @param array $varMap
526 * @param array $conds
527 * @param string $fname
528 * @param array $insertOptions
529 * @param array $selectOptions
530 * @throws DBQueryError
531 * @return null|ResultWrapper
533 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseMssql::insertSelect',
534 $insertOptions = array(), $selectOptions = array() ) {
535 $ret = parent
::insertSelect( $destTable, $srcTable, $varMap, $conds, $fname, $insertOptions, $selectOptions );
537 if ( $ret === false ) {
538 throw new DBQueryError( $this, $this->getErrors(), $this->lastErrno(), /*$sql*/ '', $fname );
539 } elseif ( $ret != null ) {
540 // remember number of rows affected
541 $this->mAffectedRows
= sqlsrv_rows_affected( $ret );
548 * Return the next in a sequence, save the value for retrieval via insertId()
551 function nextSequenceValue( $seqName ) {
552 if ( !$this->tableExists( 'sequence_' . $seqName ) ) {
553 sqlsrv_query( $this->mConn
, "CREATE TABLE [sequence_$seqName] (id INT NOT NULL IDENTITY PRIMARY KEY, junk varchar(10) NULL)" );
555 sqlsrv_query( $this->mConn
, "INSERT INTO [sequence_$seqName] (junk) VALUES ('')" );
556 $ret = sqlsrv_query( $this->mConn
, "SELECT TOP 1 id FROM [sequence_$seqName] ORDER BY id DESC" );
557 $row = sqlsrv_fetch_array( $ret, SQLSRV_FETCH_ASSOC
);// KEEP ASSOC THERE, weird weird bug dealing with the return value if you don't
559 sqlsrv_free_stmt( $ret );
560 $this->mInsertId
= $row['id'];
565 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
568 function currentSequenceValue( $seqName ) {
569 $ret = sqlsrv_query( $this->mConn
, "SELECT TOP 1 id FROM [sequence_$seqName] ORDER BY id DESC" );
570 if ( $ret !== false ) {
571 $row = sqlsrv_fetch_array( $ret );
572 sqlsrv_free_stmt( $ret );
575 return $this->nextSequenceValue( $seqName );
579 # Returns the size of a text field, or -1 for "unlimited"
580 function textFieldSize( $table, $field ) {
581 $table = $this->tableName( $table );
582 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
583 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
584 $res = $this->query( $sql );
585 $row = $this->fetchRow( $res );
587 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
588 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
594 * Construct a LIMIT query with optional offset
595 * This is used for query pages
596 * $sql string SQL query we will append the limit too
597 * $limit integer the SQL limit
598 * $offset integer the SQL offset (default false)
599 * @return mixed|string
601 function limitResult( $sql, $limit, $offset = false ) {
602 if ( $offset === false ||
$offset == 0 ) {
603 if ( strpos( $sql, "SELECT" ) === false ) {
604 return "TOP {$limit} " . $sql;
606 return preg_replace( '/\bSELECT(\s*DISTINCT)?\b/Dsi', 'SELECT$1 TOP ' . $limit, $sql, 1 );
611 SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3 FROM (
612 SELECT 1 AS line2, sub1.* FROM (' . $sql . ') AS sub1
615 WHERE line3 BETWEEN ' . ( $offset +
1 ) . ' AND ' . ( $offset +
$limit );
620 // If there is a limit clause, parse it, strip it, and pass the remaining sql through limitResult()
621 // with the appropriate parameters. Not the prettiest solution, but better than building a whole new parser.
622 // This exists becase there are still too many extensions that don't use dynamic sql generation.
623 function LimitToTopN( $sql ) {
624 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
625 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
626 if ( preg_match( $pattern, $sql, $matches ) ) {
627 // row_count = $matches[4]
628 $row_count = $matches[4];
629 // offset = $matches[3] OR $matches[6]
630 $offset = $matches[3] or
631 $offset = $matches[6] or
634 // strip the matching LIMIT clause out
635 $sql = str_replace( $matches[0], '', $sql );
636 return $this->limitResult( $sql, $row_count, $offset );
641 function timestamp( $ts = 0 ) {
642 return wfTimestamp( TS_ISO_8601
, $ts );
646 * @return string wikitext of a link to the server software's web site
648 public static function getSoftwareLink() {
649 return "[http://www.microsoft.com/sql/ MS SQL Server]";
653 * @return string Version information from the database
655 function getServerVersion() {
656 $server_info = sqlsrv_server_info( $this->mConn
);
658 if ( isset( $server_info['SQLServerVersion'] ) ) {
659 $version = $server_info['SQLServerVersion'];
664 function tableExists( $table, $fname = __METHOD__
, $schema = false ) {
665 $res = sqlsrv_query( $this->mConn
, "SELECT * FROM information_schema.tables
666 WHERE table_type='BASE TABLE' AND table_name = '$table'" );
667 if ( $res === false ) {
668 print( "Error in tableExists query: " . $this->getErrors() );
671 if ( sqlsrv_fetch( $res ) ) {
679 * Query whether a given column exists in the mediawiki schema
682 function fieldExists( $table, $field, $fname = 'DatabaseMssql::fieldExists' ) {
683 $table = $this->tableName( $table );
684 $res = sqlsrv_query( $this->mConn
, "SELECT DATA_TYPE FROM INFORMATION_SCHEMA.Columns
685 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
686 if ( $res === false ) {
687 print( "Error in fieldExists query: " . $this->getErrors() );
690 if ( sqlsrv_fetch( $res ) ) {
697 function fieldInfo( $table, $field ) {
698 $table = $this->tableName( $table );
699 $res = sqlsrv_query( $this->mConn
, "SELECT * FROM INFORMATION_SCHEMA.Columns
700 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
701 if ( $res === false ) {
702 print( "Error in fieldInfo query: " . $this->getErrors() );
705 $meta = $this->fetchRow( $res );
707 return new MssqlField( $meta );
713 * Begin a transaction, committing any previously open transaction
715 protected function doBegin( $fname = 'DatabaseMssql::begin' ) {
716 sqlsrv_begin_transaction( $this->mConn
);
717 $this->mTrxLevel
= 1;
723 protected function doCommit( $fname = 'DatabaseMssql::commit' ) {
724 sqlsrv_commit( $this->mConn
);
725 $this->mTrxLevel
= 0;
729 * Rollback a transaction.
730 * No-op on non-transactional databases.
732 protected function doRollback( $fname = 'DatabaseMssql::rollback' ) {
733 sqlsrv_rollback( $this->mConn
);
734 $this->mTrxLevel
= 0;
738 * Escapes a identifier for use inm SQL.
739 * Throws an exception if it is invalid.
740 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
742 * @throws MWException
745 private function escapeIdentifier( $identifier ) {
746 if ( strlen( $identifier ) == 0 ) {
747 throw new MWException( "An identifier must not be empty" );
749 if ( strlen( $identifier ) > 128 ) {
750 throw new MWException( "The identifier '$identifier' is too long (max. 128)" );
752 if ( ( strpos( $identifier, '[' ) !== false ) ||
( strpos( $identifier, ']' ) !== false ) ) {
753 // It may be allowed if you quoted with double quotation marks, but that would break if QUOTED_IDENTIFIER is OFF
754 throw new MWException( "You can't use square brackers in the identifier '$identifier'" );
756 return "[$identifier]";
761 * Precondition: This object is connected as the superuser.
762 * Creates the database, schema, user and login.
764 function initial_setup( $dbName, $newUser, $loginPassword ) {
765 $dbName = $this->escapeIdentifier( $dbName );
767 // It is not clear what can be used as a login,
768 // From http://msdn.microsoft.com/en-us/library/ms173463.aspx
769 // a sysname may be the same as an identifier.
770 $newUser = $this->escapeIdentifier( $newUser );
771 $loginPassword = $this->addQuotes( $loginPassword );
773 $this->doQuery( "CREATE DATABASE $dbName;" );
774 $this->doQuery( "USE $dbName;" );
775 $this->doQuery( "CREATE SCHEMA $dbName;" );
780 PASSWORD=$loginPassword
789 DEFAULT_SCHEMA=$dbName
802 CREATE FULLTEXT CATALOG
818 function encodeBlob( $b ) {
819 // we can't have zero's and such, this is a simple encoding to make sure we don't barf
820 return base64_encode( $b );
823 function decodeBlob( $b ) {
824 // we can't have zero's and such, this is a simple encoding to make sure we don't barf
825 return base64_decode( $b );
832 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
835 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
836 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
837 foreach ( $tables as $table ) {
838 // Is there a JOIN and INDEX clause for this table?
839 if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
840 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
841 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
842 $tableClause .= ' ON (' . $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
) . ')';
843 $retJOIN[] = $tableClause;
844 // Is there an INDEX clause?
845 } elseif ( isset( $use_index_safe[$table] ) ) {
846 $tableClause = $this->tableName( $table );
847 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
848 $ret[] = $tableClause;
849 // Is there a JOIN clause?
850 } elseif ( isset( $join_conds_safe[$table] ) ) {
851 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
852 $tableClause .= ' ON (' . $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
) . ')';
853 $retJOIN[] = $tableClause;
855 $tableClause = $this->tableName( $table );
856 $ret[] = $tableClause;
859 // We can't separate explicit JOIN clauses with ',', use ' ' for those
860 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
861 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
862 // Compile our final table clause
863 return implode( ' ', array( $straightJoins, $otherJoins ) );
866 function strencode( $s ) { # Should not be called by us
867 return str_replace( "'", "''", $s );
870 function addQuotes( $s ) {
871 if ( $s instanceof Blob
) {
872 return "'" . $s->fetch( $s ) . "'";
874 return parent
::addQuotes( $s );
878 public function addIdentifierQuotes( $s ) {
879 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
880 return '[' . $s . ']';
883 public function isQuotedIdentifier( $name ) {
884 return $name[0] == '[' && substr( $name, -1, 1 ) == ']';
887 function selectDB( $db ) {
888 return ( $this->query( "SET DATABASE $db" ) !== false );
894 * @param array $options an associative array of options to be turned into
895 * an SQL query, valid keys are listed in the function.
898 function makeSelectOptions( $options ) {
902 $noKeyOptions = array();
903 foreach ( $options as $key => $option ) {
904 if ( is_numeric( $key ) ) {
905 $noKeyOptions[$option] = true;
909 $tailOpts .= $this->makeGroupByWithHaving( $options );
911 $tailOpts .= $this->makeOrderBy( $options );
913 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) {
914 $startOpts .= 'DISTINCT';
917 // we want this to be compatible with the output of parent::makeSelectOptions()
918 return array( $startOpts, '', $tailOpts, '' );
922 * Get the type of the DBMS, as it appears in $wgDBtype.
929 function buildConcat( $stringList ) {
930 return implode( ' + ', $stringList );
933 public function getSearchEngine() {
934 return "SearchMssql";
938 * Since MSSQL doesn't recognize the infinity keyword, set date manually.
939 * @todo Remove magic date
942 public function getInfinity() {
943 return '3000-01-31 00:00:00.000';
946 } // end DatabaseMssql class
953 class MssqlField
implements Field
{
954 private $name, $tablename, $default, $max_length, $nullable, $type;
955 function __construct( $info ) {
956 $this->name
= $info['COLUMN_NAME'];
957 $this->tablename
= $info['TABLE_NAME'];
958 $this->default = $info['COLUMN_DEFAULT'];
959 $this->max_length
= $info['CHARACTER_MAXIMUM_LENGTH'];
960 $this->nullable
= !( strtolower( $info['IS_NULLABLE'] ) == 'no' );
961 $this->type
= $info['DATA_TYPE'];
968 function tableName() {
969 return $this->tableName
;
972 function defaultValue() {
973 return $this->default;
976 function maxLength() {
977 return $this->max_length
;
980 function isNullable() {
981 return $this->nullable
;
990 * The MSSQL PHP driver doesn't support sqlsrv_num_rows, so we recall all rows into an array and maintain our
991 * own cursor index into that array...This is similar to the way the Oracle driver handles this same issue
997 public function __construct( $queryresult = false ) {
999 $this->mRows
= array();
1000 $this->mNumFields
= sqlsrv_num_fields( $queryresult );
1001 $this->mFieldMeta
= sqlsrv_field_metadata( $queryresult );
1003 $rows = sqlsrv_fetch_array( $queryresult, SQLSRV_FETCH_ASSOC
);
1005 foreach( $rows as $row ) {
1006 if ( $row !== null ) {
1007 foreach ( $row as $k => $v ) {
1008 if ( is_object( $v ) && method_exists( $v, 'format' ) ) {// DateTime Object
1009 $row[$k] = $v->format( "Y-m-d\TH:i:s\Z" );
1012 $this->mRows
[] = $row;// read results into memory, cursors are not supported
1015 $this->mRowCount
= count( $this->mRows
);
1016 sqlsrv_free_stmt( $queryresult );
1019 private function array_to_obj( $array, &$obj ) {
1020 foreach ( $array as $key => $value ) {
1021 if ( is_array( $value ) ) {
1022 $obj->$key = new stdClass();
1023 $this->array_to_obj( $value, $obj->$key );
1025 if ( !empty( $key ) ) {
1026 $obj->$key = $value;
1033 public function fetch( $mode = SQLSRV_FETCH_BOTH
, $object_class = 'stdClass' ) {
1034 if ( $this->mCursor
>= $this->mRowCount ||
$this->mRowCount
== 0 ) {
1038 if ( $mode == SQLSRV_FETCH_NUMERIC ||
$mode == SQLSRV_FETCH_BOTH
) {
1039 foreach ( $this->mRows
[$this->mCursor
] as $value ) {
1044 case SQLSRV_FETCH_ASSOC
:
1045 $ret = $this->mRows
[$this->mCursor
];
1047 case SQLSRV_FETCH_NUMERIC
:
1051 $o = new $object_class;
1052 $ret = $this->array_to_obj( $this->mRows
[$this->mCursor
], $o );
1054 case SQLSRV_FETCH_BOTH
:
1056 $ret = $this->mRows
[$this->mCursor
] +
$arrNum;
1064 public function get( $pos, $fld ) {
1065 return $this->mRows
[$pos][$fld];
1068 public function numrows() {
1069 return $this->mRowCount
;
1072 public function seek( $iRow ) {
1073 $this->mCursor
= min( $iRow, $this->mRowCount
);
1076 public function numfields() {
1077 return $this->mNumFields
;
1080 public function fieldname( $nr ) {
1081 $arrKeys = array_keys( $this->mRows
[0] );
1082 return $arrKeys[$nr];
1085 public function fieldtype( $nr ) {
1088 foreach ( $this->mFieldMeta
as $meta ) {
1090 $intType = $meta['Type'];
1095 // http://msdn.microsoft.com/en-us/library/cc296183.aspx contains type table
1096 switch( $intType ) {
1097 case SQLSRV_SQLTYPE_BIGINT
: $strType = 'bigint'; break;
1098 case SQLSRV_SQLTYPE_BINARY
: $strType = 'binary'; break;
1099 case SQLSRV_SQLTYPE_BIT
: $strType = 'bit'; break;
1100 case SQLSRV_SQLTYPE_CHAR
: $strType = 'char'; break;
1101 case SQLSRV_SQLTYPE_DATETIME
: $strType = 'datetime'; break;
1102 case SQLSRV_SQLTYPE_DECIMAL
/*($precision, $scale)*/: $strType = 'decimal'; break;
1103 case SQLSRV_SQLTYPE_FLOAT
: $strType = 'float'; break;
1104 case SQLSRV_SQLTYPE_IMAGE
: $strType = 'image'; break;
1105 case SQLSRV_SQLTYPE_INT
: $strType = 'int'; break;
1106 case SQLSRV_SQLTYPE_MONEY
: $strType = 'money'; break;
1107 case SQLSRV_SQLTYPE_NCHAR
/*($charCount)*/: $strType = 'nchar'; break;
1108 case SQLSRV_SQLTYPE_NUMERIC
/*($precision, $scale)*/: $strType = 'numeric'; break;
1109 case SQLSRV_SQLTYPE_NVARCHAR
/*($charCount)*/: $strType = 'nvarchar'; break;
1110 // case SQLSRV_SQLTYPE_NVARCHAR('max'): $strType = 'nvarchar(MAX)'; break;
1111 case SQLSRV_SQLTYPE_NTEXT
: $strType = 'ntext'; break;
1112 case SQLSRV_SQLTYPE_REAL
: $strType = 'real'; break;
1113 case SQLSRV_SQLTYPE_SMALLDATETIME
: $strType = 'smalldatetime'; break;
1114 case SQLSRV_SQLTYPE_SMALLINT
: $strType = 'smallint'; break;
1115 case SQLSRV_SQLTYPE_SMALLMONEY
: $strType = 'smallmoney'; break;
1116 case SQLSRV_SQLTYPE_TEXT
: $strType = 'text'; break;
1117 case SQLSRV_SQLTYPE_TIMESTAMP
: $strType = 'timestamp'; break;
1118 case SQLSRV_SQLTYPE_TINYINT
: $strType = 'tinyint'; break;
1119 case SQLSRV_SQLTYPE_UNIQUEIDENTIFIER
: $strType = 'uniqueidentifier'; break;
1120 case SQLSRV_SQLTYPE_UDT
: $strType = 'UDT'; break;
1121 case SQLSRV_SQLTYPE_VARBINARY
/*($byteCount)*/: $strType = 'varbinary'; break;
1122 // case SQLSRV_SQLTYPE_VARBINARY('max'): $strType = 'varbinary(MAX)'; break;
1123 case SQLSRV_SQLTYPE_VARCHAR
/*($charCount)*/: $strType = 'varchar'; break;
1124 // case SQLSRV_SQLTYPE_VARCHAR('max'): $strType = 'varchar(MAX)'; break;
1125 case SQLSRV_SQLTYPE_XML
: $strType = 'xml'; break;
1126 default: $strType = $intType;
1131 public function free() {
1132 unset( $this->mRows
);