3 * This is the MS SQL Server Native database abstraction layer.
7 * @author Joel Penner <a-joelpe at microsoft dot com>
8 * @author Chris Pucci <a-cpucci at microsoft dot com>
9 * @author Ryan Biesemeyer <v-ryanbi at microsoft dot com>
15 class DatabaseMssql
extends DatabaseBase
{
16 var $mInsertId = NULL;
17 var $mLastResult = NULL;
18 var $mAffectedRows = NULL;
20 function __construct( $server = false, $user = false, $password = false, $dbName = false,
21 $failFunction = false, $flags = 0 )
23 $this->mFailFunction
= $failFunction;
24 $this->mFlags
= $flags;
25 $this->open( $server, $user, $password, $dbName );
29 function cascadingDeletes() {
32 function cleanupTriggers() {
35 function strictIPs() {
38 function realTimestamps() {
41 function implicitGroupby() {
44 function implicitOrderby() {
47 function functionalIndexes() {
50 function unionSupportsOrderAndLimit() {
54 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
56 return new DatabaseMssql( $server, $user, $password, $dbName, $failFunction, $flags );
60 * Usually aborts on failure
61 * If the failFunction is set to a non-zero integer, returns success
63 function open( $server, $user, $password, $dbName ) {
64 # Test for driver support, to avoid suppressed fatal error
65 if ( !function_exists( 'sqlsrv_connect' ) ) {
66 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" );
71 if ( !strlen( $user ) ) { # # e.g. the class is being loaded
76 $this->mServer
= $server;
77 $this->mPort
= $wgDBport;
79 $this->mPassword
= $password;
80 $this->mDBname
= $dbName;
82 $connectionInfo = array();
85 $connectionInfo['Database'] = $dbName;
89 // Quick and dirty work around to provide NT Auth designation support.
90 // Current solution requires installer to know to input 'ntauth' for both username and password
91 // to trigger connection via NT Auth. - ugly, ugly, ugly
92 // TO-DO: Make this better and add NT Auth choice to MW installer when SQL Server option is chosen.
93 $ntAuthUserTest = strtolower( $user );
94 $ntAuthPassTest = strtolower( $password );
96 // Decide which auth scenerio to use
97 if( ( $ntAuthPassTest == 'ntauth' && $ntAuthUserTest == 'ntauth' ) ){
98 // Don't add credentials to $connectionInfo
100 $connectionInfo['UID'] = $user;
101 $connectionInfo['PWD'] = $password;
105 $this->mConn
= @sqlsrv_connect
( $server, $connectionInfo );
107 if ( $this->mConn
=== false ) {
108 wfDebug( "DB connection error\n" );
109 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
110 wfDebug( $this->lastError() . "\n" );
114 $this->mOpened
= true;
119 * Closes a database connection, if it is open
120 * Returns success, true if already closed
123 $this->mOpened
= false;
124 if ( $this->mConn
) {
125 return sqlsrv_close( $this->mConn
);
131 function doQuery( $sql ) {
132 wfDebug( "SQL: [$sql]\n" );
135 // several extensions seem to think that all databases support limits via LIMIT N after the WHERE clause
136 // well, MSSQL uses SELECT TOP N, so to catch any of those extensions we'll do a quick check for a LIMIT
137 // clause and pass $sql through $this->LimitToTopN() which parses the limit clause and passes the result to
138 // $this->limitResult();
139 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
140 // massage LIMIT -> TopN
141 $sql = $this->LimitToTopN( $sql ) ;
144 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
145 if ( preg_match('#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
146 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
147 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
151 $stmt = sqlsrv_query( $this->mConn
, $sql );
152 if ( $stmt == false ) {
153 $message = "A database error has occurred\n" .
154 "Query: " . htmlentities( $sql ) . "\n" .
155 "Function: " . __FUNCTION__
. "\n";
156 // process each error (our driver will give us an array of errors unlike other providers)
157 foreach ( sqlsrv_errors() as $error ) {
158 $message .= $message . "ERROR[" . $error['code'] . "] " . $error['message'] . "\n";
161 throw new DBUnexpectedError( $this, $message );
163 // remember number of rows affected
164 $this->mAffectedRows
= sqlsrv_rows_affected( $stmt );
166 // if it is a SELECT statement, or an insert with a request to output something we want to return a row.
167 if ( ( preg_match( '#\bSELECT\s#i', $sql ) ) ||
168 ( preg_match( '#\bINSERT\s#i', $sql ) && preg_match( '#\bOUTPUT\s+INSERTED\b#i', $sql ) ) ) {
169 // this is essentially a rowset, but Mediawiki calls these 'result'
170 // the rowset owns freeing the statement
171 $res = new MssqlResult( $stmt );
173 // otherwise we simply return it was successful, failure throws an exception
179 function freeResult( $res ) {
180 if ( $res instanceof ResultWrapper
) {
186 function fetchObject( $res ) {
187 if ( $res instanceof ResultWrapper
) {
190 $row = $res->fetch( 'OBJECT' );
194 function getErrors() {
196 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
197 if ( $retErrors != null ) {
198 foreach ( $retErrors as $arrError ) {
199 $strRet .= "SQLState: " . $arrError[ 'SQLSTATE'] . "\n";
200 $strRet .= "Error Code: " . $arrError[ 'code'] . "\n";
201 $strRet .= "Message: " . $arrError[ 'message'] . "\n";
204 $strRet = "No errors found";
209 function fetchRow( $res ) {
210 if ( $res instanceof ResultWrapper
) {
213 $row = $res->fetch( SQLSRV_FETCH_BOTH
);
217 function numRows( $res ) {
218 if ( $res instanceof ResultWrapper
) {
221 return ( $res ) ?
$res->numrows() : 0;
224 function numFields( $res ) {
225 if ( $res instanceof ResultWrapper
) {
228 return ( $res ) ?
$res->numfields() : 0;
231 function fieldName( $res, $n ) {
232 if ( $res instanceof ResultWrapper
) {
235 return ( $res ) ?
$res->fieldname( $n ) : 0;
239 * This must be called after nextSequenceVal
241 function insertId() {
242 return $this->mInsertId
;
245 function dataSeek( $res, $row ) {
246 if ( $res instanceof ResultWrapper
) {
249 return ( $res ) ?
$res->seek( $row ) : false;
252 function lastError() {
253 if ( $this->mConn
) {
254 return $this->getErrors();
257 return "No database connection";
261 function lastErrno() {
262 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
263 if ( $err[0] ) return $err[0]['code'];
267 function affectedRows() {
268 return $this->mAffectedRows
;
274 * @param mixed $table Array or string, table name(s) (prefix auto-added)
275 * @param mixed $vars Array or string, field name(s) to be retrieved
276 * @param mixed $conds Array or string, condition(s) for WHERE
277 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
278 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
279 * see Database::makeSelectOptions code for list of supported stuff
280 * @param $join_conds Array: Associative array of table join conditions (optional)
281 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
282 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
284 function select( $table, $vars, $conds = '', $fname = 'Database::select', $options = array(), $join_conds = array() )
286 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
287 if ( isset( $options['EXPLAIN'] ) ) {
288 sqlsrv_query( $this->mConn
, "SET SHOWPLAN_ALL ON;" );
289 return $this->query( $sql, $fname );
290 sqlsrv_query( $this->mConn
, "SET SHOWPLAN_ALL OFF;" );
292 return $this->query( $sql, $fname );
298 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
299 * @param $vars Mixed: Array or string, field name(s) to be retrieved
300 * @param $conds Mixed: Array or string, condition(s) for WHERE
301 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
302 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
303 * see Database::makeSelectOptions code for list of supported stuff
304 * @param $join_conds Array: Associative array of table join conditions (optional)
305 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
306 * @return string, the SQL text
308 function selectSQLText( $table, $vars, $conds = '', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
309 if ( isset( $options['EXPLAIN'] ) ) {
310 unset( $options['EXPLAIN'] );
312 return parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
316 * Estimate rows in dataset
317 * Returns estimated count, based on SHOWPLAN_ALL output
318 * This is not necessarily an accurate estimate, so use sparingly
319 * Returns -1 if count cannot be found
320 * Takes same arguments as Database::select()
322 function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'Database::estimateRowCount', $options = array() ) {
323 $options['EXPLAIN'] = true;// http://msdn2.microsoft.com/en-us/library/aa259203.aspx
324 $res = $this->select( $table, $vars, $conds, $fname, $options );
328 $row = $this->fetchRow( $res );
329 if ( isset( $row['EstimateRows'] ) ) $rows = $row['EstimateRows'];
336 * Returns information about an index
337 * If errors are explicitly ignored, returns NULL on failure
339 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
340 # This does not return the same info as MYSQL would, but that's OK because MediaWiki never uses the
341 # returned value except to check for the existance of indexes.
342 $sql = "sp_helpindex '" . $table . "'";
343 $res = $this->query( $sql, $fname );
349 while ( $row = $res->FetchNextObj() ) {
350 if ( $row->index_name
== $index ) {
351 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
352 $cols = explode( ", ", $row->index_keys
);
353 foreach ( $cols as $col ) {
354 $row->Column_name
= trim( $col );
355 $result[] = clone $row;
357 } else if ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
358 $row->Non_unique
= 0;
359 $cols = explode( ", ", $row->index_keys
);
360 foreach ( $cols as $col ) {
361 $row->Column_name
= trim( $col );
362 $result[] = clone $row;
366 return empty( $result ) ?
false : $result;
370 * INSERT wrapper, inserts an array into a table
372 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
375 * Usually aborts on failure
376 * If errors are explicitly ignored, returns success
378 function insert( $table, $arrToInsert, $fname = 'Database::insert', $options = array() ) {
379 # No rows to insert, easy just return now
380 if ( !count( $arrToInsert ) ) {
384 if ( !is_array( $options ) ) {
385 $options = array( $options );
388 $table = $this->tableName( $table );
390 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) {// Not multi row
391 $arrToInsert = array( 0 => $arrToInsert );// make everything multi row compatible
397 // We know the table we're inserting into, get its identity column
399 $tableRaw = preg_replace( '#\[([^\]]*)\]#', '$1', $table ); // strip matching square brackets from table name
400 $res = $this->doQuery( "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'" );
401 if( $res && $res->numrows() ){
402 // There is an identity for this table.
403 $identity = array_pop( $res->fetch( SQLSRV_FETCH_ASSOC
) );
407 foreach ( $arrToInsert as $blah => $a ) {
408 // start out with empty identity column, this is so we can return it as a result of the insert logic
411 $identityClause = '';
413 // if we have an identity column
416 foreach ($a as $k => $v ) {
417 if ( $k == $identity ) {
419 // there is a value being passed to us, we need to turn on and off inserted identity
420 $sqlPre = "SET IDENTITY_INSERT $table ON;" ;
421 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
424 // we can't insert NULL into an identity column, so remove the column from the insert.
429 $identityClause = "OUTPUT INSERTED.$identity "; // we want to output an identity column as result
432 $keys = array_keys( $a );
435 // INSERT IGNORE is not supported by SQL Server
436 // remove IGNORE from options list and set ignore flag to true
437 $ignoreClause = false;
438 foreach ( $options as $k => $v ) {
439 if ( strtoupper( $v ) == "IGNORE" ) {
440 unset( $options[$k] );
441 $ignoreClause = true;
445 // translate MySQL INSERT IGNORE to something SQL Server can use
447 // MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
448 // MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '1') INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
449 if ( $ignoreClause == true ) {
450 $prival = $a[$keys[0]];
451 $sqlPre .= "IF NOT EXISTS (SELECT * FROM $table WHERE $keys[0] = '$prival')";
454 // Build the actual query
455 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
456 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
459 foreach ( $a as $key => $value ) {
465 if ( is_string( $value ) ) {
466 $sql .= $this->quote_ident( $value );
467 } elseif ( is_null( $value ) ) {
469 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
470 if ( is_object( $value ) && strtolower( get_class( $value ) ) == 'blob' ) {
471 $sql .= $this->quote_ident( $value->fetch() );
473 $sql .= $this->quote_ident( serialize( $value ) );
479 $sql .= ')' . $sqlPost;
482 $ret = sqlsrv_query( $this->mConn
, $sql );
484 if ( $ret === false ) {
485 throw new DBQueryError( $this, $this->getErrors(), $this->lastErrno(), $sql, $fname );
486 } elseif ( $ret != NULL ) {
487 // remember number of rows affected
488 $this->mAffectedRows
= sqlsrv_rows_affected( $ret );
489 if ( !is_null($identity) ) {
490 // then we want to get the identity column value we were assigned and save it off
491 $row = sqlsrv_fetch_object( $ret );
492 $this->mInsertId
= $row->$identity;
494 sqlsrv_free_stmt( $ret );
503 * INSERT SELECT wrapper
504 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
505 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
506 * $conds may be "*" to copy the whole table
507 * srcTable may be an array of tables.
509 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
510 $insertOptions = array(), $selectOptions = array() )
512 $ret = parent
::insertSelect( $destTable, $srcTable, $varMap, $conds, $fname, $insertOptions, $selectOptions );
514 if ( $ret === false ) {
515 throw new DBQueryError( $this, $this->getErrors(), $this->lastErrno(), $sql, $fname );
516 } elseif ( $ret != NULL ) {
517 // remember number of rows affected
518 $this->mAffectedRows
= sqlsrv_rows_affected( $ret );
525 * Format a table name ready for use in constructing an SQL query
527 * This does two important things: it brackets table names which as necessary,
528 * and it adds a table prefix if there is one.
530 * All functions of this object which require a table name call this function
531 * themselves. Pass the canonical name to such functions. This is only needed
532 * when calling query() directly.
534 * @param string $name database table name
536 function tableName( $name ) {
538 # Skip quoted literals
539 if ( $name != '' && $name { 0 } != '[' ) {
540 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
541 $name = "{$this->mTablePrefix}$name";
543 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
544 $name = "[$wgSharedDB].[$name]";
547 if ( $name != '' ) $name = "[$name]";
554 * Return the next in a sequence, save the value for retrieval via insertId()
556 function nextSequenceValue( $seqName ) {
557 if ( !$this->tableExists( 'sequence_' . $seqName ) ) {
558 $ret = sqlsrv_query( $this->mConn
, "CREATE TABLE [sequence_$seqName] (id INT NOT NULL IDENTITY PRIMARY KEY, junk varchar(10) NULL)" );
560 $ret = sqlsrv_query( $this->mConn
, "INSERT INTO [sequence_$seqName] (junk) VALUES ('')" );
561 $ret = sqlsrv_query( $this->mConn
, "SELECT TOP 1 id FROM [sequence_$seqName] ORDER BY id DESC" );
562 $row = sqlsrv_fetch_array( $ret, SQLSRV_FETCH_ASSOC
);// KEEP ASSOC THERE, weird weird bug dealing with the return value if you don't
564 sqlsrv_free_stmt( $ret );
565 $this->mInsertId
= $row['id'];
570 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
572 function currentSequenceValue( $seqName ) {
573 $ret = sqlsrv_query( $this->mConn
, "SELECT TOP 1 id FROM [sequence_$seqName] ORDER BY id DESC" );
574 if ( $ret !== false ) {
575 $row = sqlsrv_fetch_array( $ret );
576 sqlsrv_free_stmt( $ret );
579 return $this->nextSequenceValue( $seqName );
584 # REPLACE query wrapper
585 # MSSQL simulates this with a DELETE followed by INSERT
586 # $row is the row to insert, an associative array
587 # $uniqueIndexes is an array of indexes. Each element may be either a
588 # field name or an array of field names
590 # It may be more efficient to leave off unique indexes which are unlikely to collide.
591 # However if you do this, you run the risk of encountering errors which wouldn't have
593 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
594 $table = $this->tableName( $table );
596 if ( count( $rows ) == 0 ) {
601 if ( !is_array( reset( $rows ) ) ) {
602 $rows = array( $rows );
605 foreach ( $rows as $row ) {
606 # Delete rows which collide
607 if ( $uniqueIndexes ) {
608 $sql = "DELETE FROM $table WHERE ";
610 foreach ( $uniqueIndexes as $index ) {
617 if ( is_array( $index ) ) {
619 foreach ( $index as $col ) {
625 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
628 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
632 $this->query( $sql, $fname );
636 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) . ') VALUES (' .
637 $this->makeList( $row, LIST_COMMA
) . ')';
638 $this->query( $sql, $fname );
642 # DELETE where the condition is a join
643 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
645 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
648 $delTable = $this->tableName( $delTable );
649 $joinTable = $this->tableName( $joinTable );
650 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
651 if ( $conds != '*' ) {
652 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
656 $this->query( $sql, $fname );
659 # Returns the size of a text field, or -1 for "unlimited"
660 function textFieldSize( $table, $field ) {
661 $table = $this->tableName( $table );
662 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
663 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
664 $res = $this->query( $sql );
665 $row = $this->fetchRow( $res );
667 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) $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)
678 function limitResult( $sql, $limit, $offset = false ) {
679 if ( $offset === false ||
$offset == 0 ) {
680 if ( strpos( $sql, "SELECT" ) === false ) {
681 return "TOP {$limit} " . $sql;
683 return preg_replace( '/\bSELECT(\s*DISTINCT)?\b/Dsi', 'SELECT$1 TOP ' . $limit, $sql, 1 );
688 SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3 FROM (
689 SELECT 1 AS line2, sub1.* FROM (' . $sql . ') AS sub1
692 WHERE line3 BETWEEN ' . ( $offset +
1 ) . ' AND ' . ( $offset +
$limit );
697 // If there is a limit clause, parse it, strip it, and pass the remaining sql through limitResult()
698 // with the appropriate parameters. Not the prettiest solution, but better than building a whole new parser.
699 // This exists becase there are still too many extensions that don't use dynamic sql generation.
700 function LimitToTopN( $sql ) {
701 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
702 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
703 if ( preg_match( $pattern, $sql, $matches ) ) {
704 // row_count = $matches[4]
705 $row_count = $matches[4];
706 // offset = $matches[3] OR $matches[6]
707 $offset = $matches[3] or
708 $offset = $matches[6] or
711 // strip the matching LIMIT clause out
712 $sql = str_replace( $matches[0], '', $sql );
713 return $this->limitResult( $sql, $row_count, $offset );
718 // MSSQL does support this, but documentation is too thin to make a generalized
719 // function for this. Apparently UPDATE TOP (N) works, but the sort order
720 // may not be what we're expecting so the top n results may be a random selection.
721 // TODO: Implement properly.
722 function limitResultForUpdate( $sql, $num ) {
727 function timestamp( $ts = 0 ) {
728 return wfTimestamp( TS_ISO_8601
, $ts );
732 * @return string wikitext of a link to the server software's web site
734 function getSoftwareLink() {
735 return "[http://www.microsoft.com/sql/ MS SQL Server]";
739 * @return string Version information from the database
741 function getServerVersion() {
742 $server_info = sqlsrv_server_info( $this->mConn
);
744 if ( isset( $server_info['SQLServerVersion'] ) ) $version = $server_info['SQLServerVersion'];
748 function tableExists ( $table, $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() );
755 if ( sqlsrv_fetch( $res ) )
762 * Query whether a given column exists in the mediawiki schema
764 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
765 $table = $this->tableName( $table );
766 $res = sqlsrv_query( $this->mConn
, "SELECT DATA_TYPE FROM INFORMATION_SCHEMA.Columns
767 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
768 if ( $res === false ) {
769 print( "Error in fieldExists query: " . $this->getErrors() );
772 if ( sqlsrv_fetch( $res ) )
778 function fieldInfo( $table, $field ) {
779 $table = $this->tableName( $table );
780 $res = sqlsrv_query( $this->mConn
, "SELECT * FROM INFORMATION_SCHEMA.Columns
781 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
782 if ( $res === false ) {
783 print( "Error in fieldInfo query: " . $this->getErrors() );
786 if ( $meta = $this->fetchRow( $res ) )
787 return new MssqlField( $meta );
792 * Begin a transaction, committing any previously open transaction
794 function begin( $fname = 'Database::begin' ) {
795 sqlsrv_begin_transaction( $this->mConn
);
796 $this->mTrxLevel
= 1;
802 function commit( $fname = 'Database::commit' ) {
803 sqlsrv_commit( $this->mConn
);
804 $this->mTrxLevel
= 0;
808 * Rollback a transaction.
809 * No-op on non-transactional databases.
811 function rollback( $fname = 'Database::rollback' ) {
812 sqlsrv_rollback( $this->mConn
);
813 $this->mTrxLevel
= 0;
816 function setup_database() {
817 global $wgVersion, $wgDBport, $wgDBuser;
819 // Make sure that we can write to the correct schema
820 $ctest = "mediawiki_test_table";
821 if ( $this->tableExists( $ctest ) ) {
822 $this->doQuery( "DROP TABLE $ctest" );
824 $SQL = "CREATE TABLE $ctest (a int)";
825 $res = $this->doQuery( $SQL );
827 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the database</li>\n";
830 $this->doQuery( "DROP TABLE $ctest" );
832 $res = dbsource( "../maintenance/mssql/tables.sql", $this );
834 # # Update version information
835 $mwv = $this->addQuotes( $wgVersion );
836 $pgv = $this->addQuotes( $this->getServerVersion() );
837 $pgu = $this->addQuotes( $this->mUser
);
838 $pgp = $this->addQuotes( $wgDBport );
839 $dbn = $this->addQuotes( $this->mDBname
);
841 # # Avoid the non-standard "REPLACE INTO" syntax
842 $f = fopen( "../maintenance/interwiki.sql", 'r' );
844 dieout( "<li>Could not find the interwiki.sql file" );
846 # # We simply assume it is already empty as we have just created it
847 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
848 while ( ! feof( $f ) ) {
849 $line = fgets( $f, 1024 );
851 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
854 $this->query( "$SQL $matches[1],$matches[2])" );
856 print " (table interwiki successfully populated)...\n";
862 * Escapes a identifier for use inm SQL.
863 * Throws an exception if it is invalid.
864 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
866 private function escapeIdentifier( $identifier ) {
867 if ( strlen( $identifier ) == 0 ) {
868 throw new MWException( "An identifier must not be empty" );
870 if ( strlen( $identifier ) > 128 ) {
871 throw new MWException( "The identifier '$identifier' is too long (max. 128)" );
873 if ( ( strpos( $identifier, '[' ) !== false ) ||
( strpos( $identifier, ']' ) !== false ) ) {
874 // It may be allowed if you quoted with double quotation marks, but that would break if QUOTED_IDENTIFIER is OFF
875 throw new MWException( "You can't use square brackers in the identifier '$identifier'" );
877 return "[$identifier]";
882 * Precondition: This object is connected as the superuser.
883 * Creates the database, schema, user and login.
885 function initial_setup( $dbName, $newUser, $loginPassword ) {
886 $dbName = $this->escapeIdentifier( $dbName );
888 // It is not clear what can be used as a login,
889 // From http://msdn.microsoft.com/en-us/library/ms173463.aspx
890 // a sysname may be the same as an identifier.
891 $newUser = $this->escapeIdentifier( $newUser );
892 $loginPassword = $this->addQuotes( $loginPassword );
894 $this->doQuery("CREATE DATABASE $dbName;");
895 $this->doQuery("USE $dbName;");
896 $this->doQuery("CREATE SCHEMA $dbName;");
901 PASSWORD=$loginPassword
910 DEFAULT_SCHEMA=$dbName
923 CREATE FULLTEXT CATALOG
941 function encodeBlob( $b ) {
942 // we can't have zero's and such, this is a simple encoding to make sure we don't barf
943 return base64_encode( $b );
946 function decodeBlob( $b ) {
947 // we can't have zero's and such, this is a simple encoding to make sure we don't barf
948 return base64_decode( $b );
954 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
957 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
958 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
959 foreach ( $tables as $table ) {
960 // Is there a JOIN and INDEX clause for this table?
961 if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
962 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
963 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
964 $tableClause .= ' ON (' . $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
) . ')';
965 $retJOIN[] = $tableClause;
966 // Is there an INDEX clause?
967 } else if ( isset( $use_index_safe[$table] ) ) {
968 $tableClause = $this->tableName( $table );
969 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
970 $ret[] = $tableClause;
971 // Is there a JOIN clause?
972 } else if ( isset( $join_conds_safe[$table] ) ) {
973 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
974 $tableClause .= ' ON (' . $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
) . ')';
975 $retJOIN[] = $tableClause;
977 $tableClause = $this->tableName( $table );
978 $ret[] = $tableClause;
981 // We can't separate explicit JOIN clauses with ',', use ' ' for those
982 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
983 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
984 // Compile our final table clause
985 return implode( ' ', array( $straightJoins, $otherJoins ) );
988 function strencode( $s ) { # # Should not be called by us
989 return str_replace( "'", "''", $s );
992 function addQuotes( $s ) {
993 if ( $s instanceof Blob
) {
994 return "'" . $s->fetch( $s ) . "'";
996 return parent
::addQuotes( $s );
1000 function quote_ident( $s ) {
1001 return "'" . str_replace( "'", "''", $s ) . "'";
1004 function selectDB( $db ) {
1005 return ( $this->query( "SET DATABASE $db" ) !== false );
1011 * @param array $options an associative array of options to be turned into
1012 * an SQL query, valid keys are listed in the function.
1015 function makeSelectOptions( $options ) {
1019 $noKeyOptions = array();
1020 foreach ( $options as $key => $option ) {
1021 if ( is_numeric( $key ) ) {
1022 $noKeyOptions[$option] = true;
1026 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
1027 if ( isset( $options['HAVING'] ) ) $tailOpts .= " HAVING {$options['GROUP BY']}";
1028 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
1030 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1032 // we want this to be compatible with the output of parent::makeSelectOptions()
1033 return array( $startOpts, '' , $tailOpts, '' );
1037 * Get the type of the DBMS, as it appears in $wgDBtype.
1043 function buildConcat( $stringList ) {
1044 return implode( ' + ', $stringList );
1047 public function getSearchEngine() {
1048 return "SearchMssql";
1051 } // end DatabaseMssql class
1059 private $name, $tablename, $default, $max_length, $nullable, $type;
1060 function __construct ( $info ) {
1061 $this->name
= $info['COLUMN_NAME'];
1062 $this->tablename
= $info['TABLE_NAME'];
1063 $this->default = $info['COLUMN_DEFAULT'];
1064 $this->max_length
= $info['CHARACTER_MAXIMUM_LENGTH'];
1065 $this->nullable
= ( strtolower( $info['IS_NULLABLE'] ) == 'no' ) ?
false:true;
1066 $this->type
= $info['DATA_TYPE'];
1072 function tableName() {
1073 return $this->tableName
;
1076 function defaultValue() {
1077 return $this->default;
1080 function maxLength() {
1081 return $this->max_length
;
1084 function nullable() {
1085 return $this->nullable
;
1094 * The MSSQL PHP driver doesn't support sqlsrv_num_rows, so we recall all rows into an array and maintain our
1095 * own cursor index into that array...This is similar to the way the Oracle driver handles this same issue
1101 public function __construct( $queryresult = false ) {
1103 $this->mRows
= array();
1104 $this->mNumFields
= sqlsrv_num_fields( $queryresult );
1105 $this->mFieldMeta
= sqlsrv_field_metadata( $queryresult );
1106 while ( $row = sqlsrv_fetch_array( $queryresult, SQLSRV_FETCH_ASSOC
) ) {
1107 if ( $row !== null ) {
1108 foreach ( $row as $k => $v ) {
1109 if ( is_object( $v ) && method_exists( $v, 'format' ) ) {// DateTime Object
1110 $row[$k] = $v->format( "Y-m-d\TH:i:s\Z" );
1113 $this->mRows
[] = $row;// read results into memory, cursors are not supported
1116 $this->mRowCount
= count( $this->mRows
);
1117 sqlsrv_free_stmt( $queryresult );
1120 private function array_to_obj( $array, &$obj ) {
1121 foreach ( $array as $key => $value ) {
1122 if ( is_array( $value ) ) {
1123 $obj->$key = new stdClass();
1124 array_to_obj( $value, $obj->$key );
1126 if ( !empty( $key ) ) {
1127 $obj->$key = $value;
1134 public function fetch( $mode = SQLSRV_FETCH_BOTH
, $object_class = 'stdClass' ) {
1135 if ( $this->mCursor
>= $this->mRowCount ||
$this->mRowCount
== 0 ) return false;
1138 if ( $mode == SQLSRV_FETCH_NUMERIC ||
$mode == SQLSRV_FETCH_BOTH
) {
1139 foreach ( $this->mRows
[$this->mCursor
] as $key => $value ) {
1144 case SQLSRV_FETCH_ASSOC
:
1145 $ret = $this->mRows
[$this->mCursor
];
1147 case SQLSRV_FETCH_NUMERIC
:
1151 $o = new $object_class;
1152 $ret = $this->array_to_obj( $this->mRows
[$this->mCursor
], $o );
1154 case SQLSRV_FETCH_BOTH
:
1156 $ret = $this->mRows
[$this->mCursor
] +
$arrNum;
1164 public function get( $pos, $fld ) {
1165 return $this->mRows
[$pos][$fld];
1168 public function numrows() {
1169 return $this->mRowCount
;
1172 public function seek( $iRow ) {
1173 $this->mCursor
= min( $iRow, $this->mRowCount
);
1176 public function numfields() {
1177 return $this->mNumFields
;
1180 public function fieldname( $nr ) {
1181 $arrKeys = array_keys( $this->mRows
[0] );
1182 return $arrKeys[$nr];
1185 public function fieldtype( $nr ) {
1189 foreach ( $this->mFieldMeta
as $meta ) {
1191 $intType = $meta['Type'];
1196 // http://msdn.microsoft.com/en-us/library/cc296183.aspx contains type table
1197 switch( $intType ) {
1198 case SQLSRV_SQLTYPE_BIGINT
: $strType = 'bigint'; break;
1199 case SQLSRV_SQLTYPE_BINARY
: $strType = 'binary'; break;
1200 case SQLSRV_SQLTYPE_BIT
: $strType = 'bit'; break;
1201 case SQLSRV_SQLTYPE_CHAR
: $strType = 'char'; break;
1202 case SQLSRV_SQLTYPE_DATETIME
: $strType = 'datetime'; break;
1203 case SQLSRV_SQLTYPE_DECIMAL
/*($precision, $scale)*/: $strType = 'decimal'; break;
1204 case SQLSRV_SQLTYPE_FLOAT
: $strType = 'float'; break;
1205 case SQLSRV_SQLTYPE_IMAGE
: $strType = 'image'; break;
1206 case SQLSRV_SQLTYPE_INT
: $strType = 'int'; break;
1207 case SQLSRV_SQLTYPE_MONEY
: $strType = 'money'; break;
1208 case SQLSRV_SQLTYPE_NCHAR
/*($charCount)*/: $strType = 'nchar'; break;
1209 case SQLSRV_SQLTYPE_NUMERIC
/*($precision, $scale)*/: $strType = 'numeric'; break;
1210 case SQLSRV_SQLTYPE_NVARCHAR
/*($charCount)*/: $strType = 'nvarchar'; break;
1211 // case SQLSRV_SQLTYPE_NVARCHAR('max'): $strType = 'nvarchar(MAX)'; break;
1212 case SQLSRV_SQLTYPE_NTEXT
: $strType = 'ntext'; break;
1213 case SQLSRV_SQLTYPE_REAL
: $strType = 'real'; break;
1214 case SQLSRV_SQLTYPE_SMALLDATETIME
: $strType = 'smalldatetime'; break;
1215 case SQLSRV_SQLTYPE_SMALLINT
: $strType = 'smallint'; break;
1216 case SQLSRV_SQLTYPE_SMALLMONEY
: $strType = 'smallmoney'; break;
1217 case SQLSRV_SQLTYPE_TEXT
: $strType = 'text'; break;
1218 case SQLSRV_SQLTYPE_TIMESTAMP
: $strType = 'timestamp'; break;
1219 case SQLSRV_SQLTYPE_TINYINT
: $strType = 'tinyint'; break;
1220 case SQLSRV_SQLTYPE_UNIQUEIDENTIFIER
: $strType = 'uniqueidentifier'; break;
1221 case SQLSRV_SQLTYPE_UDT
: $strType = 'UDT'; break;
1222 case SQLSRV_SQLTYPE_VARBINARY
/*($byteCount)*/: $strType = 'varbinary'; break;
1223 // case SQLSRV_SQLTYPE_VARBINARY('max'): $strType = 'varbinary(MAX)'; break;
1224 case SQLSRV_SQLTYPE_VARCHAR
/*($charCount)*/: $strType = 'varchar'; break;
1225 // case SQLSRV_SQLTYPE_VARCHAR('max'): $strType = 'varchar(MAX)'; break;
1226 case SQLSRV_SQLTYPE_XML
: $strType = 'xml'; break;
1227 default: $strType = $intType;
1232 public function free() {
1233 unset( $this->mRows
);