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>
25 * @author Ryan Schmidt <skizzerz at gmail dot com>
31 class DatabaseMssql
extends DatabaseBase
{
32 protected $mInsertId = null;
33 protected $mLastResult = null;
34 protected $mAffectedRows = null;
35 protected $mSubqueryId = 0;
36 protected $mScrollableCursor = true;
37 protected $mPrepareStatements = true;
38 protected $mBinaryColumnCache = null;
39 protected $mBitColumnCache = null;
40 protected $mIgnoreDupKeyErrors = false;
44 public function cascadingDeletes() {
48 public function cleanupTriggers() {
52 public function strictIPs() {
56 public function realTimestamps() {
60 public function implicitGroupby() {
64 public function implicitOrderby() {
68 public function functionalIndexes() {
72 public function unionSupportsOrderAndLimit() {
77 * Usually aborts on failure
78 * @param string $server
80 * @param string $password
81 * @param string $dbName
82 * @throws DBConnectionError
83 * @return bool|DatabaseBase|null
85 public function open( $server, $user, $password, $dbName ) {
86 # Test for driver support, to avoid suppressed fatal error
87 if ( !function_exists( 'sqlsrv_connect' ) ) {
88 throw new DBConnectionError(
90 "Microsoft SQL Server Native (sqlsrv) functions missing.
91 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
95 global $wgDBport, $wgDBWindowsAuthentication;
97 # e.g. the class is being loaded
98 if ( !strlen( $user ) ) {
103 $this->mServer
= $server;
104 $this->mPort
= $wgDBport;
105 $this->mUser
= $user;
106 $this->mPassword
= $password;
107 $this->mDBname
= $dbName;
109 $connectionInfo = array();
112 $connectionInfo['Database'] = $dbName;
115 // Decide which auth scenerio to use
116 // if we are using Windows auth, don't add credentials to $connectionInfo
117 if ( !$wgDBWindowsAuthentication ) {
118 $connectionInfo['UID'] = $user;
119 $connectionInfo['PWD'] = $password;
122 wfSuppressWarnings();
123 $this->mConn
= sqlsrv_connect( $server, $connectionInfo );
126 if ( $this->mConn
=== false ) {
127 throw new DBConnectionError( $this, $this->lastError() );
130 $this->mOpened
= true;
136 * Closes a database connection, if it is open
137 * Returns success, true if already closed
140 protected function closeConnection() {
141 return sqlsrv_close( $this->mConn
);
145 * @param bool|MssqlResultWrapper|resource $result
146 * @return bool|MssqlResultWrapper
148 public function resultObject( $result ) {
149 if ( empty( $result ) ) {
151 } elseif ( $result instanceof MssqlResultWrapper
) {
153 } elseif ( $result === true ) {
154 // Successful write query
157 return new MssqlResultWrapper( $this, $result );
163 * @return bool|MssqlResult
164 * @throws DBUnexpectedError
166 protected function doQuery( $sql ) {
167 if ( $this->debug() ) {
168 wfDebug( "SQL: [$sql]\n" );
172 // several extensions seem to think that all databases support limits
173 // via LIMIT N after the WHERE clause well, MSSQL uses SELECT TOP N,
174 // so to catch any of those extensions we'll do a quick check for a
175 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
176 // the limit clause and passes the result to $this->limitResult();
177 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
178 // massage LIMIT -> TopN
179 $sql = $this->LimitToTopN( $sql );
182 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
183 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
184 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
185 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
190 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
191 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
192 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
193 // strings make php throw a fatal error "Severe error translating Unicode"
194 if ( $this->mScrollableCursor
) {
195 $scrollArr = array( 'Scrollable' => SQLSRV_CURSOR_STATIC
);
197 $scrollArr = array();
200 if ( $this->mPrepareStatements
) {
201 // we do prepare + execute so we can get its field metadata for later usage if desired
202 $stmt = sqlsrv_prepare( $this->mConn
, $sql, array(), $scrollArr );
203 $success = sqlsrv_execute( $stmt );
205 $stmt = sqlsrv_query( $this->mConn
, $sql, array(), $scrollArr );
206 $success = (bool)$stmt;
209 if ( $this->mIgnoreDupKeyErrors
) {
210 // ignore duplicate key errors, but nothing else
211 // this emulates INSERT IGNORE in MySQL
212 if ( $success === false ) {
213 $errors = sqlsrv_errors( SQLSRV_ERR_ERRORS
);
216 foreach ( $errors as $err ) {
217 if ( $err['SQLSTATE'] == '23000' && $err['code'] == '2601' ) {
218 continue; // duplicate key error caused by unique index
219 } elseif ( $err['SQLSTATE'] == '23000' && $err['code'] == '2627' ) {
220 continue; // duplicate key error caused by primary key
221 } elseif ( $err['SQLSTATE'] == '01000' && $err['code'] == '3621' ) {
222 continue; // generic "the statement has been terminated" error
225 $success = false; // getting here means we got an error we weren't expecting
230 $this->mAffectedRows
= 0;
236 if ( $success === false ) {
239 // remember number of rows affected
240 $this->mAffectedRows
= sqlsrv_rows_affected( $stmt );
245 public function freeResult( $res ) {
246 if ( $res instanceof ResultWrapper
) {
250 sqlsrv_free_stmt( $res );
254 * @param MssqlResultWrapper $res
257 public function fetchObject( $res ) {
258 // $res is expected to be an instance of MssqlResultWrapper here
259 return $res->fetchObject();
263 * @param MssqlResultWrapper $res
266 public function fetchRow( $res ) {
267 return $res->fetchRow();
274 public function numRows( $res ) {
275 if ( $res instanceof ResultWrapper
) {
279 return sqlsrv_num_rows( $res );
286 public function numFields( $res ) {
287 if ( $res instanceof ResultWrapper
) {
291 return sqlsrv_num_fields( $res );
299 public function fieldName( $res, $n ) {
300 if ( $res instanceof ResultWrapper
) {
304 $metadata = sqlsrv_field_metadata( $res );
305 return $metadata[$n]['Name'];
309 * This must be called after nextSequenceVal
312 public function insertId() {
313 return $this->mInsertId
;
317 * @param MssqlResultWrapper $res
321 public function dataSeek( $res, $row ) {
322 return $res->seek( $row );
328 public function lastError() {
330 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
331 if ( $retErrors != null ) {
332 foreach ( $retErrors as $arrError ) {
333 $strRet .= $this->formatError( $arrError ) . "\n";
336 $strRet = "No errors found";
345 private function formatError( $err ) {
346 return '[SQLSTATE ' . $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
352 public function lastErrno() {
353 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
354 if ( $err !== null && isset( $err[0] ) ) {
355 return $err[0]['code'];
364 public function affectedRows() {
365 return $this->mAffectedRows
;
371 * @param mixed $table Array or string, table name(s) (prefix auto-added)
372 * @param mixed $vars Array or string, field name(s) to be retrieved
373 * @param mixed $conds Array or string, condition(s) for WHERE
374 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
375 * @param array $options Associative array of options (e.g.
376 * array('GROUP BY' => 'page_title')), see Database::makeSelectOptions
377 * code for list of supported stuff
378 * @param array $join_conds Associative array of table join conditions
379 * (optional) (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
380 * @return mixed Database result resource (feed to Database::fetchObject
381 * or whatever), or false on failure
383 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
384 $options = array(), $join_conds = array()
386 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
387 if ( isset( $options['EXPLAIN'] ) ) {
389 $this->mScrollableCursor
= false;
390 $this->mPrepareStatements
= false;
391 $this->query( "SET SHOWPLAN_ALL ON" );
392 $ret = $this->query( $sql, $fname );
393 $this->query( "SET SHOWPLAN_ALL OFF" );
394 } catch ( DBQueryError
$dqe ) {
395 if ( isset( $options['FOR COUNT'] ) ) {
396 // likely don't have privs for SHOWPLAN, so run a select count instead
397 $this->query( "SET SHOWPLAN_ALL OFF" );
398 unset( $options['EXPLAIN'] );
399 $ret = $this->select(
401 'COUNT(*) AS EstimateRows',
408 // someone actually wanted the query plan instead of an est row count
409 // let them know of the error
410 $this->mScrollableCursor
= true;
411 $this->mPrepareStatements
= true;
415 $this->mScrollableCursor
= true;
416 $this->mPrepareStatements
= true;
421 return $this->query( $sql, $fname );
427 * @param mixed $table Array or string, table name(s) (prefix auto-added)
428 * @param mixed $vars Array or string, field name(s) to be retrieved
429 * @param mixed $conds Array or string, condition(s) for WHERE
430 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
431 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
432 * see Database::makeSelectOptions code for list of supported stuff
433 * @param array $join_conds Associative array of table join conditions (optional)
434 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
435 * @return string The SQL text
437 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
438 $options = array(), $join_conds = array()
440 if ( isset( $options['EXPLAIN'] ) ) {
441 unset( $options['EXPLAIN'] );
444 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
446 // try to rewrite aggregations of bit columns (currently MAX and MIN)
447 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
448 $bitColumns = array();
449 if ( is_array( $table ) ) {
450 foreach ( $table as $t ) {
451 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
454 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
457 foreach ( $bitColumns as $col => $info ) {
459 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
460 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
462 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
469 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
472 $this->mScrollableCursor
= false;
474 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
475 } catch ( Exception
$e ) {
476 $this->mScrollableCursor
= true;
479 $this->mScrollableCursor
= true;
482 public function delete( $table, $conds, $fname = __METHOD__
) {
483 $this->mScrollableCursor
= false;
485 parent
::delete( $table, $conds, $fname );
486 } catch ( Exception
$e ) {
487 $this->mScrollableCursor
= true;
490 $this->mScrollableCursor
= true;
494 * Estimate rows in dataset
495 * Returns estimated count, based on SHOWPLAN_ALL output
496 * This is not necessarily an accurate estimate, so use sparingly
497 * Returns -1 if count cannot be found
498 * Takes same arguments as Database::select()
499 * @param string $table
500 * @param string $vars
501 * @param string $conds
502 * @param string $fname
503 * @param array $options
506 public function estimateRowCount( $table, $vars = '*', $conds = '',
507 $fname = __METHOD__
, $options = array()
509 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
510 $options['EXPLAIN'] = true;
511 $options['FOR COUNT'] = true;
512 $res = $this->select( $table, $vars, $conds, $fname, $options );
516 $row = $this->fetchRow( $res );
518 if ( isset( $row['EstimateRows'] ) ) {
519 $rows = $row['EstimateRows'];
527 * Returns information about an index
528 * If errors are explicitly ignored, returns NULL on failure
529 * @param string $table
530 * @param string $index
531 * @param string $fname
532 * @return array|bool|null
534 public function indexInfo( $table, $index, $fname = __METHOD__
) {
535 # This does not return the same info as MYSQL would, but that's OK
536 # because MediaWiki never uses the returned value except to check for
537 # the existance of indexes.
538 $sql = "sp_helpindex '" . $table . "'";
539 $res = $this->query( $sql, $fname );
545 foreach ( $res as $row ) {
546 if ( $row->index_name
== $index ) {
547 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
548 $cols = explode( ", ", $row->index_keys
);
549 foreach ( $cols as $col ) {
550 $row->Column_name
= trim( $col );
551 $result[] = clone $row;
553 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
554 $row->Non_unique
= 0;
555 $cols = explode( ", ", $row->index_keys
);
556 foreach ( $cols as $col ) {
557 $row->Column_name
= trim( $col );
558 $result[] = clone $row;
563 return empty( $result ) ?
false : $result;
567 * INSERT wrapper, inserts an array into a table
569 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
572 * Usually aborts on failure
573 * If errors are explicitly ignored, returns success
574 * @param string $table
575 * @param array $arrToInsert
576 * @param string $fname
577 * @param array $options
578 * @throws DBQueryError
581 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = array() ) {
582 # No rows to insert, easy just return now
583 if ( !count( $arrToInsert ) ) {
587 if ( !is_array( $options ) ) {
588 $options = array( $options );
591 $table = $this->tableName( $table );
593 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
594 $arrToInsert = array( 0 => $arrToInsert ); // make everything multi row compatible
597 // We know the table we're inserting into, get its identity column
599 // strip matching square brackets and the db/schema from table name
600 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
601 $tableRaw = array_pop( $tableRawArr );
602 $res = $this->doQuery(
603 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
604 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
606 if ( $res && sqlsrv_has_rows( $res ) ) {
607 // There is an identity for this table.
608 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
609 $identity = array_pop( $identityArr );
611 sqlsrv_free_stmt( $res );
613 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
614 $binaryColumns = $this->getBinaryColumns( $table );
616 foreach ( $arrToInsert as $a ) {
617 // start out with empty identity column, this is so we can return
618 // it as a result of the insert logic
621 $identityClause = '';
623 // if we have an identity column
626 foreach ( $a as $k => $v ) {
627 if ( $k == $identity ) {
628 if ( !is_null( $v ) ) {
629 // there is a value being passed to us,
630 // we need to turn on and off inserted identity
631 $sqlPre = "SET IDENTITY_INSERT $table ON;";
632 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
634 // we can't insert NULL into an identity column,
635 // so remove the column from the insert.
641 // we want to output an identity column as result
642 $identityClause = "OUTPUT INSERTED.$identity ";
645 $keys = array_keys( $a );
647 // INSERT IGNORE is not supported by SQL Server
648 // remove IGNORE from options list and set ignore flag to true
649 $ignoreClause = false;
650 if ( in_array( 'IGNORE', $options ) ) {
651 $options = array_diff( $options, array( 'IGNORE' ) );
652 $this->mIgnoreDupKeyErrors
= true;
655 // Build the actual query
656 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
657 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
660 foreach ( $a as $key => $value ) {
661 if ( isset( $binaryColumns[$key] ) ) {
662 $value = new MssqlBlob( $value );
669 if ( is_null( $value ) ) {
671 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
672 if ( is_object( $value ) && $value instanceof Blob
) {
673 $sql .= $this->addQuotes( $value );
675 $sql .= $this->addQuotes( serialize( $value ) );
678 $sql .= $this->addQuotes( $value );
681 $sql .= ')' . $sqlPost;
684 $this->mScrollableCursor
= false;
686 $ret = $this->query( $sql );
687 } catch ( Exception
$e ) {
688 $this->mScrollableCursor
= true;
689 $this->mIgnoreDupKeyErrors
= false;
692 $this->mScrollableCursor
= true;
693 $this->mIgnoreDupKeyErrors
= false;
695 if ( !is_null( $identity ) ) {
696 // then we want to get the identity column value we were assigned and save it off
697 $row = $ret->fetchObject();
698 $this->mInsertId
= $row->$identity;
706 * INSERT SELECT wrapper
707 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
708 * Source items may be literals rather than field names, but strings should
709 * be quoted with Database::addQuotes().
710 * @param string $destTable
711 * @param array|string $srcTable May be an array of tables.
712 * @param array $varMap
713 * @param array $conds May be "*" to copy the whole table.
714 * @param string $fname
715 * @param array $insertOptions
716 * @param array $selectOptions
717 * @throws DBQueryError
718 * @return null|ResultWrapper
720 public function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
721 $insertOptions = array(), $selectOptions = array()
723 $this->mScrollableCursor
= false;
725 $ret = parent
::insertSelect(
734 } catch ( Exception
$e ) {
735 $this->mScrollableCursor
= true;
738 $this->mScrollableCursor
= true;
744 * UPDATE wrapper. Takes a condition array and a SET array.
746 * @param string $table name of the table to UPDATE. This will be passed through
747 * DatabaseBase::tableName().
749 * @param array $values An array of values to SET. For each array element,
750 * the key gives the field name, and the value gives the data
751 * to set that field to. The data will be quoted by
752 * DatabaseBase::addQuotes().
754 * @param array $conds An array of conditions (WHERE). See
755 * DatabaseBase::select() for the details of the format of
756 * condition arrays. Use '*' to update all rows.
758 * @param string $fname The function name of the caller (from __METHOD__),
759 * for logging and profiling.
761 * @param array $options An array of UPDATE options, can be:
762 * - IGNORE: Ignore unique key conflicts
763 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
766 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
767 $table = $this->tableName( $table );
768 $binaryColumns = $this->getBinaryColumns( $table );
770 $opts = $this->makeUpdateOptions( $options );
771 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
773 if ( $conds !== array() && $conds !== '*' ) {
774 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
777 $this->mScrollableCursor
= false;
779 $ret = $this->query( $sql );
780 } catch ( Exception
$e ) {
781 $this->mScrollableCursor
= true;
784 $this->mScrollableCursor
= true;
789 * Makes an encoded list of strings from an array
790 * @param array $a containing the data
791 * @param int $mode Constant
792 * - LIST_COMMA: comma separated, no field names
793 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
794 * the documentation for $conds in DatabaseBase::select().
795 * - LIST_OR: ORed WHERE clause (without the WHERE)
796 * - LIST_SET: comma separated with field names, like a SET clause
797 * - LIST_NAMES: comma separated field names
798 * @param array $binaryColumns Contains a list of column names that are binary types
799 * This is a custom parameter only present for MS SQL.
801 * @throws MWException|DBUnexpectedError
804 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = array() ) {
805 if ( !is_array( $a ) ) {
806 throw new DBUnexpectedError( $this,
807 'DatabaseBase::makeList called with incorrect parameters' );
813 foreach ( $a as $field => $value ) {
814 if ( $mode != LIST_NAMES
&& isset( $binaryColumns[$field] ) ) {
815 if ( is_array( $value ) ) {
816 foreach ( $value as &$v ) {
817 $v = new MssqlBlob( $v );
820 $value = new MssqlBlob( $value );
825 if ( $mode == LIST_AND
) {
827 } elseif ( $mode == LIST_OR
) {
836 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
838 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
840 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
841 if ( count( $value ) == 0 ) {
842 throw new MWException( __METHOD__
. ": empty input for field $field" );
843 } elseif ( count( $value ) == 1 ) {
844 // Special-case single values, as IN isn't terribly efficient
845 // Don't necessarily assume the single key is 0; we don't
846 // enforce linear numeric ordering on other arrays here.
847 $value = array_values( $value );
848 $list .= $field . " = " . $this->addQuotes( $value[0] );
850 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
852 } elseif ( $value === null ) {
853 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
854 $list .= "$field IS ";
855 } elseif ( $mode == LIST_SET
) {
856 $list .= "$field = ";
860 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
861 $list .= "$field = ";
863 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
871 * @param string $table
872 * @param string $field
873 * @return int Returns the size of a text field, or -1 for "unlimited"
875 public function textFieldSize( $table, $field ) {
876 $table = $this->tableName( $table );
877 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
878 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
879 $res = $this->query( $sql );
880 $row = $this->fetchRow( $res );
882 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
883 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
890 * Construct a LIMIT query with optional offset
891 * This is used for query pages
893 * @param string $sql SQL query we will append the limit too
894 * @param int $limit The SQL limit
895 * @param bool|int $offset The SQL offset (default false)
896 * @return array|string
898 public function limitResult( $sql, $limit, $offset = false ) {
899 if ( $offset === false ||
$offset == 0 ) {
900 if ( strpos( $sql, "SELECT" ) === false ) {
901 return "TOP {$limit} " . $sql;
903 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
904 'SELECT$1 TOP ' . $limit, $sql, 1 );
907 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
908 $select = $orderby = array();
909 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
910 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
911 $overOrder = $postOrder = '';
912 $first = $offset +
1;
913 $last = $offset +
$limit;
914 $sub1 = 'sub_' . $this->mSubqueryId
;
915 $sub2 = 'sub_' . ( $this->mSubqueryId +
1 );
916 $this->mSubqueryId +
= 2;
919 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
923 $overOrder = 'ORDER BY 1';
925 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
926 // don't need to strip it out if we're using a FOR XML clause
927 $sql = str_replace( $orderby[1], '', $sql );
929 $overOrder = $orderby[1];
930 $postOrder = ' ' . $overOrder;
932 $sql = "SELECT {$select[1]}
934 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
935 FROM ({$sql}) {$sub1}
937 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
944 * If there is a limit clause, parse it, strip it, and pass the remaining
945 * SQL through limitResult() with the appropriate parameters. Not the
946 * prettiest solution, but better than building a whole new parser. This
947 * exists becase there are still too many extensions that don't use dynamic
951 * @return array|mixed|string
953 public function LimitToTopN( $sql ) {
954 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
955 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
956 if ( preg_match( $pattern, $sql, $matches ) ) {
957 // row_count = $matches[4]
958 $row_count = $matches[4];
959 // offset = $matches[3] OR $matches[6]
960 $offset = $matches[3] or
961 $offset = $matches[6] or
964 // strip the matching LIMIT clause out
965 $sql = str_replace( $matches[0], '', $sql );
967 return $this->limitResult( $sql, $row_count, $offset );
974 * @return string Wikitext of a link to the server software's web site
976 public function getSoftwareLink() {
977 return "[{{int:version-db-mssql-url}} MS SQL Server]";
981 * @return string Version information from the database
983 public function getServerVersion() {
984 $server_info = sqlsrv_server_info( $this->mConn
);
986 if ( isset( $server_info['SQLServerVersion'] ) ) {
987 $version = $server_info['SQLServerVersion'];
994 * @param string $table
995 * @param string $fname
998 public function tableExists( $table, $fname = __METHOD__
) {
999 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1001 if ( $db !== false ) {
1003 wfDebug( "Attempting to call tableExists on a remote table" );
1007 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1008 WHERE TABLE_TYPE = 'BASE TABLE'
1009 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1011 if ( $res->numRows() ) {
1019 * Query whether a given column exists in the mediawiki schema
1020 * @param string $table
1021 * @param string $field
1022 * @param string $fname
1025 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1026 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1028 if ( $db !== false ) {
1030 wfDebug( "Attempting to call fieldExists on a remote table" );
1034 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1035 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1037 if ( $res->numRows() ) {
1044 public function fieldInfo( $table, $field ) {
1045 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1047 if ( $db !== false ) {
1049 wfDebug( "Attempting to call fieldInfo on a remote table" );
1053 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1054 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1056 $meta = $res->fetchRow();
1058 return new MssqlField( $meta );
1065 * Begin a transaction, committing any previously open transaction
1067 protected function doBegin( $fname = __METHOD__
) {
1068 sqlsrv_begin_transaction( $this->mConn
);
1069 $this->mTrxLevel
= 1;
1075 protected function doCommit( $fname = __METHOD__
) {
1076 sqlsrv_commit( $this->mConn
);
1077 $this->mTrxLevel
= 0;
1081 * Rollback a transaction.
1082 * No-op on non-transactional databases.
1084 protected function doRollback( $fname = __METHOD__
) {
1085 sqlsrv_rollback( $this->mConn
);
1086 $this->mTrxLevel
= 0;
1090 * Escapes a identifier for use inm SQL.
1091 * Throws an exception if it is invalid.
1092 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
1093 * @param string $identifier
1094 * @throws MWException
1097 private function escapeIdentifier( $identifier ) {
1098 if ( strlen( $identifier ) == 0 ) {
1099 throw new MWException( "An identifier must not be empty" );
1101 if ( strlen( $identifier ) > 128 ) {
1102 throw new MWException( "The identifier '$identifier' is too long (max. 128)" );
1104 if ( ( strpos( $identifier, '[' ) !== false )
1105 ||
( strpos( $identifier, ']' ) !== false )
1107 // It may be allowed if you quoted with double quotation marks, but
1108 // that would break if QUOTED_IDENTIFIER is OFF
1109 throw new MWException( "Square brackets are not allowed in '$identifier'" );
1112 return "[$identifier]";
1119 public function strencode( $s ) { # Should not be called by us
1120 return str_replace( "'", "''", $s );
1127 public function addQuotes( $s ) {
1128 if ( $s instanceof MssqlBlob
) {
1130 } elseif ( $s instanceof Blob
) {
1131 // this shouldn't really ever be called, but it's here if needed
1132 // (and will quite possibly make the SQL error out)
1133 $blob = new MssqlBlob( $s->fetch() );
1134 return $blob->fetch();
1136 if ( is_bool( $s ) ) {
1139 return parent
::addQuotes( $s );
1147 public function addIdentifierQuotes( $s ) {
1148 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1149 return '[' . $s . ']';
1153 * @param string $name
1156 public function isQuotedIdentifier( $name ) {
1157 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1164 public function selectDB( $db ) {
1166 $this->mDBname
= $db;
1167 $this->query( "USE $db" );
1169 } catch ( Exception
$e ) {
1175 * @param array $options an associative array of options to be turned into
1176 * an SQL query, valid keys are listed in the function.
1179 public function makeSelectOptions( $options ) {
1183 $noKeyOptions = array();
1184 foreach ( $options as $key => $option ) {
1185 if ( is_numeric( $key ) ) {
1186 $noKeyOptions[$option] = true;
1190 $tailOpts .= $this->makeGroupByWithHaving( $options );
1192 $tailOpts .= $this->makeOrderBy( $options );
1194 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1195 $startOpts .= 'DISTINCT';
1198 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1199 // used in group concat field emulation
1200 $tailOpts .= " FOR XML PATH('')";
1203 // we want this to be compatible with the output of parent::makeSelectOptions()
1204 return array( $startOpts, '', $tailOpts, '' );
1208 * Get the type of the DBMS, as it appears in $wgDBtype.
1211 public function getType() {
1216 * @param array $stringList
1219 public function buildConcat( $stringList ) {
1220 return implode( ' + ', $stringList );
1224 * Build a GROUP_CONCAT or equivalent statement for a query.
1225 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1227 * This is useful for combining a field for several rows into a single string.
1228 * NULL values will not appear in the output, duplicated values will appear,
1229 * and the resulting delimiter-separated values have no defined sort order.
1230 * Code using the results may need to use the PHP unique() or sort() methods.
1232 * @param string $delim Glue to bind the results together
1233 * @param string|array $table Table name
1234 * @param string $field Field name
1235 * @param string|array $conds Conditions
1236 * @param string|array $join_conds Join conditions
1237 * @return string SQL text
1240 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1241 $join_conds = array()
1243 $gcsq = 'gcsq_' . $this->mSubqueryId
;
1244 $this->mSubqueryId++
;
1246 $delimLen = strlen( $delim );
1247 $fld = "{$field} + {$this->addQuotes( $delim )}";
1248 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1249 . $this->selectSQLText( $table, $fld, $conds, null, array( 'FOR XML' ), $join_conds )
1250 . ") {$gcsq} ({$field}))";
1258 public function getSearchEngine() {
1259 return "SearchMssql";
1263 * Returns an associative array for fields that are of type varbinary, binary, or image
1264 * $table can be either a raw table name or passed through tableName() first
1265 * @param string $table
1268 private function getBinaryColumns( $table ) {
1269 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1270 $tableRaw = array_pop( $tableRawArr );
1272 if ( $this->mBinaryColumnCache
=== null ) {
1273 $this->populateColumnCaches();
1276 return isset( $this->mBinaryColumnCache
[$tableRaw] )
1277 ?
$this->mBinaryColumnCache
[$tableRaw]
1282 * @param string $table
1285 private function getBitColumns( $table ) {
1286 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1287 $tableRaw = array_pop( $tableRawArr );
1289 if ( $this->mBitColumnCache
=== null ) {
1290 $this->populateColumnCaches();
1293 return isset( $this->mBitColumnCache
[$tableRaw] )
1294 ?
$this->mBitColumnCache
[$tableRaw]
1301 private function populateColumnCaches() {
1302 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1304 'TABLE_CATALOG' => $this->mDBname
,
1305 'TABLE_SCHEMA' => $this->mSchema
,
1306 'DATA_TYPE' => array( 'varbinary', 'binary', 'image', 'bit' )
1309 $this->mBinaryColumnCache
= array();
1310 $this->mBitColumnCache
= array();
1311 foreach ( $res as $row ) {
1312 if ( $row->DATA_TYPE
== 'bit' ) {
1313 $this->mBitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1315 $this->mBinaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1321 * @param string $name
1322 * @param string $format
1325 function tableName( $name, $format = 'quoted' ) {
1326 # Replace reserved words with better ones
1329 return $this->realTableName( 'mwuser', $format );
1331 return $this->realTableName( $name, $format );
1336 * call this instead of tableName() in the updater when renaming tables
1337 * @param string $name
1338 * @param string $format One of quoted, raw, or split
1341 function realTableName( $name, $format = 'quoted' ) {
1342 $table = parent
::tableName( $name, $format );
1343 if ( $format == 'split' ) {
1344 // Used internally, we want the schema split off from the table name and returned
1345 // as a list with 3 elements (database, schema, table)
1346 $table = explode( '.', $table );
1347 if ( count( $table ) == 2 ) {
1348 array_unshift( $table, false );
1355 * Called in the installer and updater.
1356 * Probably doesn't need to be called anywhere else in the codebase.
1357 * @param bool|null $value
1360 public function prepareStatements( $value = null ) {
1361 return wfSetVar( $this->mPrepareStatements
, $value );
1365 * Called in the installer and updater.
1366 * Probably doesn't need to be called anywhere else in the codebase.
1367 * @param bool|null $value
1370 public function scrollableCursor( $value = null ) {
1371 return wfSetVar( $this->mScrollableCursor
, $value );
1373 } // end DatabaseMssql class
1380 class MssqlField
implements Field
{
1381 private $name, $tableName, $default, $max_length, $nullable, $type;
1383 function __construct( $info ) {
1384 $this->name
= $info['COLUMN_NAME'];
1385 $this->tableName
= $info['TABLE_NAME'];
1386 $this->default = $info['COLUMN_DEFAULT'];
1387 $this->max_length
= $info['CHARACTER_MAXIMUM_LENGTH'];
1388 $this->nullable
= !( strtolower( $info['IS_NULLABLE'] ) == 'no' );
1389 $this->type
= $info['DATA_TYPE'];
1396 function tableName() {
1397 return $this->tableName
;
1400 function defaultValue() {
1401 return $this->default;
1404 function maxLength() {
1405 return $this->max_length
;
1408 function isNullable() {
1409 return $this->nullable
;
1417 class MssqlBlob
extends Blob
{
1418 public function __construct( $data ) {
1419 if ( $data instanceof MssqlBlob
) {
1421 } elseif ( $data instanceof Blob
) {
1422 $this->mData
= $data->fetch();
1423 } elseif ( is_array( $data ) && is_object( $data ) ) {
1424 $this->mData
= serialize( $data );
1426 $this->mData
= $data;
1431 * Returns an unquoted hex representation of a binary string
1432 * for insertion into varbinary-type fields
1435 public function fetch() {
1436 if ( $this->mData
=== null ) {
1441 $dataLength = strlen( $this->mData
);
1442 for ( $i = 0; $i < $dataLength; $i++
) {
1443 $ret .= bin2hex( pack( 'C', ord( $this->mData
[$i] ) ) );
1450 class MssqlResultWrapper
extends ResultWrapper
{
1451 private $mSeekTo = null;
1454 * @return stdClass|bool
1456 public function fetchObject() {
1457 $res = $this->result
;
1459 if ( $this->mSeekTo
!== null ) {
1460 $result = sqlsrv_fetch_object( $res, 'stdClass', array(),
1461 SQLSRV_SCROLL_ABSOLUTE
, $this->mSeekTo
);
1462 $this->mSeekTo
= null;
1464 $result = sqlsrv_fetch_object( $res );
1467 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1468 if ( $result === null ) {
1476 * @return array|bool
1478 public function fetchRow() {
1479 $res = $this->result
;
1481 if ( $this->mSeekTo
!== null ) {
1482 $result = sqlsrv_fetch_array( $res, SQLSRV_FETCH_BOTH
,
1483 SQLSRV_SCROLL_ABSOLUTE
, $this->mSeekTo
);
1484 $this->mSeekTo
= null;
1486 $result = sqlsrv_fetch_array( $res );
1489 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1490 if ( $result === null ) {
1501 public function seek( $row ) {
1502 $res = $this->result
;
1505 $numRows = $this->db
->numRows( $res );
1506 $row = intval( $row );
1508 if ( $numRows === 0 ) {
1510 } elseif ( $row < 0 ||
$row > $numRows - 1 ) {
1514 // Unlike MySQL, the seek actually happens on the next access
1515 $this->mSeekTo
= $row;