MediaWiki REL1_28
DatabaseMssql.php
Go to the documentation of this file.
1<?php
31class 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;
41 protected $mIgnoreErrors = [];
42
43 protected $mPort;
44
45 public function implicitGroupby() {
46 return false;
47 }
48
49 public function implicitOrderby() {
50 return false;
51 }
52
53 public function unionSupportsOrderAndLimit() {
54 return false;
55 }
56
66 public function open( $server, $user, $password, $dbName ) {
67 # Test for driver support, to avoid suppressed fatal error
68 if ( !function_exists( 'sqlsrv_connect' ) ) {
69 throw new DBConnectionError(
70 $this,
71 "Microsoft SQL Server Native (sqlsrv) functions missing.
72 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
73 );
74 }
75
77
78 # e.g. the class is being loaded
79 if ( !strlen( $user ) ) {
80 return null;
81 }
82
83 $this->close();
84 $this->mServer = $server;
85 $this->mPort = $wgDBport;
86 $this->mUser = $user;
87 $this->mPassword = $password;
88 $this->mDBname = $dbName;
89
90 $connectionInfo = [];
91
92 if ( $dbName ) {
93 $connectionInfo['Database'] = $dbName;
94 }
95
96 // Decide which auth scenerio to use
97 // if we are using Windows auth, don't add credentials to $connectionInfo
99 $connectionInfo['UID'] = $user;
100 $connectionInfo['PWD'] = $password;
101 }
102
103 MediaWiki\suppressWarnings();
104 $this->mConn = sqlsrv_connect( $server, $connectionInfo );
105 MediaWiki\restoreWarnings();
106
107 if ( $this->mConn === false ) {
108 throw new DBConnectionError( $this, $this->lastError() );
109 }
110
111 $this->mOpened = true;
112
113 return $this->mConn;
114 }
115
121 protected function closeConnection() {
122 return sqlsrv_close( $this->mConn );
123 }
124
129 protected function resultObject( $result ) {
130 if ( !$result ) {
131 return false;
132 } elseif ( $result instanceof MssqlResultWrapper ) {
133 return $result;
134 } elseif ( $result === true ) {
135 // Successful write query
136 return $result;
137 } else {
138 return new MssqlResultWrapper( $this, $result );
139 }
140 }
141
147 protected function doQuery( $sql ) {
148 if ( $this->getFlag( DBO_DEBUG ) ) {
149 wfDebug( "SQL: [$sql]\n" );
150 }
151 $this->offset = 0;
152
153 // several extensions seem to think that all databases support limits
154 // via LIMIT N after the WHERE clause well, MSSQL uses SELECT TOP N,
155 // so to catch any of those extensions we'll do a quick check for a
156 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
157 // the limit clause and passes the result to $this->limitResult();
158 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
159 // massage LIMIT -> TopN
160 $sql = $this->LimitToTopN( $sql );
161 }
162
163 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
164 if ( preg_match( '#\bEXTRACT\s*?\‍(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
165 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
166 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
167 }
168
169 // perform query
170
171 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
172 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
173 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
174 // strings make php throw a fatal error "Severe error translating Unicode"
175 if ( $this->mScrollableCursor ) {
176 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC ];
177 } else {
178 $scrollArr = [];
179 }
180
181 if ( $this->mPrepareStatements ) {
182 // we do prepare + execute so we can get its field metadata for later usage if desired
183 $stmt = sqlsrv_prepare( $this->mConn, $sql, [], $scrollArr );
184 $success = sqlsrv_execute( $stmt );
185 } else {
186 $stmt = sqlsrv_query( $this->mConn, $sql, [], $scrollArr );
187 $success = (bool)$stmt;
188 }
189
190 // make a copy so that anything we add below does not get reflected in future queries
191 $ignoreErrors = $this->mIgnoreErrors;
192
193 if ( $this->mIgnoreDupKeyErrors ) {
194 // ignore duplicate key errors
195 // this emulates INSERT IGNORE in MySQL
196 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
197 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
198 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
199 }
200
201 if ( $success === false ) {
202 $errors = sqlsrv_errors();
203 $success = true;
204
205 foreach ( $errors as $err ) {
206 if ( !in_array( $err['code'], $ignoreErrors ) ) {
207 $success = false;
208 break;
209 }
210 }
211
212 if ( $success === false ) {
213 return false;
214 }
215 }
216 // remember number of rows affected
217 $this->mAffectedRows = sqlsrv_rows_affected( $stmt );
218
219 return $stmt;
220 }
221
222 public function freeResult( $res ) {
223 if ( $res instanceof ResultWrapper ) {
224 $res = $res->result;
225 }
226
227 sqlsrv_free_stmt( $res );
228 }
229
234 public function fetchObject( $res ) {
235 // $res is expected to be an instance of MssqlResultWrapper here
236 return $res->fetchObject();
237 }
238
243 public function fetchRow( $res ) {
244 return $res->fetchRow();
245 }
246
251 public function numRows( $res ) {
252 if ( $res instanceof ResultWrapper ) {
253 $res = $res->result;
254 }
255
256 $ret = sqlsrv_num_rows( $res );
257
258 if ( $ret === false ) {
259 // we cannot get an amount of rows from this cursor type
260 // has_rows returns bool true/false if the result has rows
261 $ret = (int)sqlsrv_has_rows( $res );
262 }
263
264 return $ret;
265 }
266
271 public function numFields( $res ) {
272 if ( $res instanceof ResultWrapper ) {
273 $res = $res->result;
274 }
275
276 return sqlsrv_num_fields( $res );
277 }
278
284 public function fieldName( $res, $n ) {
285 if ( $res instanceof ResultWrapper ) {
286 $res = $res->result;
287 }
288
289 return sqlsrv_field_metadata( $res )[$n]['Name'];
290 }
291
296 public function insertId() {
297 return $this->mInsertId;
298 }
299
305 public function dataSeek( $res, $row ) {
306 return $res->seek( $row );
307 }
308
312 public function lastError() {
313 $strRet = '';
314 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL );
315 if ( $retErrors != null ) {
316 foreach ( $retErrors as $arrError ) {
317 $strRet .= $this->formatError( $arrError ) . "\n";
318 }
319 } else {
320 $strRet = "No errors found";
321 }
322
323 return $strRet;
324 }
325
330 private function formatError( $err ) {
331 return '[SQLSTATE ' . $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
332 }
333
337 public function lastErrno() {
338 $err = sqlsrv_errors( SQLSRV_ERR_ALL );
339 if ( $err !== null && isset( $err[0] ) ) {
340 return $err[0]['code'];
341 } else {
342 return 0;
343 }
344 }
345
349 public function affectedRows() {
351 }
352
371 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
372 $options = [], $join_conds = []
373 ) {
374 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
375 if ( isset( $options['EXPLAIN'] ) ) {
376 try {
377 $this->mScrollableCursor = false;
378 $this->mPrepareStatements = false;
379 $this->query( "SET SHOWPLAN_ALL ON" );
380 $ret = $this->query( $sql, $fname );
381 $this->query( "SET SHOWPLAN_ALL OFF" );
382 } catch ( DBQueryError $dqe ) {
383 if ( isset( $options['FOR COUNT'] ) ) {
384 // likely don't have privs for SHOWPLAN, so run a select count instead
385 $this->query( "SET SHOWPLAN_ALL OFF" );
386 unset( $options['EXPLAIN'] );
387 $ret = $this->select(
388 $table,
389 'COUNT(*) AS EstimateRows',
390 $conds,
391 $fname,
392 $options,
393 $join_conds
394 );
395 } else {
396 // someone actually wanted the query plan instead of an est row count
397 // let them know of the error
398 $this->mScrollableCursor = true;
399 $this->mPrepareStatements = true;
400 throw $dqe;
401 }
402 }
403 $this->mScrollableCursor = true;
404 $this->mPrepareStatements = true;
405 return $ret;
406 }
407 return $this->query( $sql, $fname );
408 }
409
423 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
424 $options = [], $join_conds = []
425 ) {
426 if ( isset( $options['EXPLAIN'] ) ) {
427 unset( $options['EXPLAIN'] );
428 }
429
430 $sql = parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
431
432 // try to rewrite aggregations of bit columns (currently MAX and MIN)
433 if ( strpos( $sql, 'MAX(' ) !== false || strpos( $sql, 'MIN(' ) !== false ) {
434 $bitColumns = [];
435 if ( is_array( $table ) ) {
436 foreach ( $table as $t ) {
437 $bitColumns += $this->getBitColumns( $this->tableName( $t ) );
438 }
439 } else {
440 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
441 }
442
443 foreach ( $bitColumns as $col => $info ) {
444 $replace = [
445 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
446 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
447 ];
448 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
449 }
450 }
451
452 return $sql;
453 }
454
455 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
456 $fname = __METHOD__
457 ) {
458 $this->mScrollableCursor = false;
459 try {
460 parent::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
461 } catch ( Exception $e ) {
462 $this->mScrollableCursor = true;
463 throw $e;
464 }
465 $this->mScrollableCursor = true;
466 }
467
468 public function delete( $table, $conds, $fname = __METHOD__ ) {
469 $this->mScrollableCursor = false;
470 try {
471 parent::delete( $table, $conds, $fname );
472 } catch ( Exception $e ) {
473 $this->mScrollableCursor = true;
474 throw $e;
475 }
476 $this->mScrollableCursor = true;
477 }
478
492 public function estimateRowCount( $table, $vars = '*', $conds = '',
493 $fname = __METHOD__, $options = []
494 ) {
495 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
496 $options['EXPLAIN'] = true;
497 $options['FOR COUNT'] = true;
498 $res = $this->select( $table, $vars, $conds, $fname, $options );
499
500 $rows = -1;
501 if ( $res ) {
502 $row = $this->fetchRow( $res );
503
504 if ( isset( $row['EstimateRows'] ) ) {
505 $rows = (int)$row['EstimateRows'];
506 }
507 }
508
509 return $rows;
510 }
511
520 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
521 # This does not return the same info as MYSQL would, but that's OK
522 # because MediaWiki never uses the returned value except to check for
523 # the existance of indexes.
524 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
525 $res = $this->query( $sql, $fname );
526
527 if ( !$res ) {
528 return null;
529 }
530
531 $result = [];
532 foreach ( $res as $row ) {
533 if ( $row->index_name == $index ) {
534 $row->Non_unique = !stristr( $row->index_description, "unique" );
535 $cols = explode( ", ", $row->index_keys );
536 foreach ( $cols as $col ) {
537 $row->Column_name = trim( $col );
538 $result[] = clone $row;
539 }
540 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description, 'PRIMARY' ) ) {
541 $row->Non_unique = 0;
542 $cols = explode( ", ", $row->index_keys );
543 foreach ( $cols as $col ) {
544 $row->Column_name = trim( $col );
545 $result[] = clone $row;
546 }
547 }
548 }
549
550 return empty( $result ) ? false : $result;
551 }
552
568 public function insert( $table, $arrToInsert, $fname = __METHOD__, $options = [] ) {
569 # No rows to insert, easy just return now
570 if ( !count( $arrToInsert ) ) {
571 return true;
572 }
573
574 if ( !is_array( $options ) ) {
575 $options = [ $options ];
576 }
577
578 $table = $this->tableName( $table );
579
580 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
581 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
582 }
583
584 // We know the table we're inserting into, get its identity column
585 $identity = null;
586 // strip matching square brackets and the db/schema from table name
587 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
588 $tableRaw = array_pop( $tableRawArr );
589 $res = $this->doQuery(
590 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
591 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
592 );
593 if ( $res && sqlsrv_has_rows( $res ) ) {
594 // There is an identity for this table.
595 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC );
596 $identity = array_pop( $identityArr );
597 }
598 sqlsrv_free_stmt( $res );
599
600 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
601 $binaryColumns = $this->getBinaryColumns( $table );
602
603 // INSERT IGNORE is not supported by SQL Server
604 // remove IGNORE from options list and set ignore flag to true
605 if ( in_array( 'IGNORE', $options ) ) {
606 $options = array_diff( $options, [ 'IGNORE' ] );
607 $this->mIgnoreDupKeyErrors = true;
608 }
609
610 foreach ( $arrToInsert as $a ) {
611 // start out with empty identity column, this is so we can return
612 // it as a result of the insert logic
613 $sqlPre = '';
614 $sqlPost = '';
615 $identityClause = '';
616
617 // if we have an identity column
618 if ( $identity ) {
619 // iterate through
620 foreach ( $a as $k => $v ) {
621 if ( $k == $identity ) {
622 if ( !is_null( $v ) ) {
623 // there is a value being passed to us,
624 // we need to turn on and off inserted identity
625 $sqlPre = "SET IDENTITY_INSERT $table ON;";
626 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
627 } else {
628 // we can't insert NULL into an identity column,
629 // so remove the column from the insert.
630 unset( $a[$k] );
631 }
632 }
633 }
634
635 // we want to output an identity column as result
636 $identityClause = "OUTPUT INSERTED.$identity ";
637 }
638
639 $keys = array_keys( $a );
640
641 // Build the actual query
642 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
643 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
644
645 $first = true;
646 foreach ( $a as $key => $value ) {
647 if ( isset( $binaryColumns[$key] ) ) {
648 $value = new MssqlBlob( $value );
649 }
650 if ( $first ) {
651 $first = false;
652 } else {
653 $sql .= ',';
654 }
655 if ( is_null( $value ) ) {
656 $sql .= 'null';
657 } elseif ( is_array( $value ) || is_object( $value ) ) {
658 if ( is_object( $value ) && $value instanceof Blob ) {
659 $sql .= $this->addQuotes( $value );
660 } else {
661 $sql .= $this->addQuotes( serialize( $value ) );
662 }
663 } else {
664 $sql .= $this->addQuotes( $value );
665 }
666 }
667 $sql .= ')' . $sqlPost;
668
669 // Run the query
670 $this->mScrollableCursor = false;
671 try {
672 $ret = $this->query( $sql );
673 } catch ( Exception $e ) {
674 $this->mScrollableCursor = true;
675 $this->mIgnoreDupKeyErrors = false;
676 throw $e;
677 }
678 $this->mScrollableCursor = true;
679
680 if ( !is_null( $identity ) ) {
681 // then we want to get the identity column value we were assigned and save it off
682 $row = $ret->fetchObject();
683 if ( is_object( $row ) ) {
684 $this->mInsertId = $row->$identity;
685
686 // it seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is used
687 // if we got an identity back, we know for sure a row was affected, so adjust that here
688 if ( $this->mAffectedRows == -1 ) {
689 $this->mAffectedRows = 1;
690 }
691 }
692 }
693 }
694 $this->mIgnoreDupKeyErrors = false;
695 return $ret;
696 }
697
713 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
714 $insertOptions = [], $selectOptions = []
715 ) {
716 $this->mScrollableCursor = false;
717 try {
718 $ret = parent::nativeInsertSelect(
719 $destTable,
720 $srcTable,
721 $varMap,
722 $conds,
723 $fname,
724 $insertOptions,
725 $selectOptions
726 );
727 } catch ( Exception $e ) {
728 $this->mScrollableCursor = true;
729 throw $e;
730 }
731 $this->mScrollableCursor = true;
732
733 return $ret;
734 }
735
761 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
762 $table = $this->tableName( $table );
763 $binaryColumns = $this->getBinaryColumns( $table );
764
765 $opts = $this->makeUpdateOptions( $options );
766 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET, $binaryColumns );
767
768 if ( $conds !== [] && $conds !== '*' ) {
769 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND, $binaryColumns );
770 }
771
772 $this->mScrollableCursor = false;
773 try {
774 $this->query( $sql );
775 } catch ( Exception $e ) {
776 $this->mScrollableCursor = true;
777 throw $e;
778 }
779 $this->mScrollableCursor = true;
780 return true;
781 }
782
799 public function makeList( $a, $mode = LIST_COMMA, $binaryColumns = [] ) {
800 if ( !is_array( $a ) ) {
801 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
802 }
803
804 if ( $mode != LIST_NAMES ) {
805 // In MS SQL, values need to be specially encoded when they are
806 // inserted into binary fields. Perform this necessary encoding
807 // for the specified set of columns.
808 foreach ( array_keys( $a ) as $field ) {
809 if ( !isset( $binaryColumns[$field] ) ) {
810 continue;
811 }
812
813 if ( is_array( $a[$field] ) ) {
814 foreach ( $a[$field] as &$v ) {
815 $v = new MssqlBlob( $v );
816 }
817 unset( $v );
818 } else {
819 $a[$field] = new MssqlBlob( $a[$field] );
820 }
821 }
822 }
823
824 return parent::makeList( $a, $mode );
825 }
826
832 public function textFieldSize( $table, $field ) {
833 $table = $this->tableName( $table );
834 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
835 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
836 $res = $this->query( $sql );
837 $row = $this->fetchRow( $res );
838 $size = -1;
839 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
840 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
841 }
842
843 return $size;
844 }
845
856 public function limitResult( $sql, $limit, $offset = false ) {
857 if ( $offset === false || $offset == 0 ) {
858 if ( strpos( $sql, "SELECT" ) === false ) {
859 return "TOP {$limit} " . $sql;
860 } else {
861 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
862 'SELECT$1 TOP ' . $limit, $sql, 1 );
863 }
864 } else {
865 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
866 $select = $orderby = [];
867 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
868 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
869 $overOrder = $postOrder = '';
870 $first = $offset + 1;
871 $last = $offset + $limit;
872 $sub1 = 'sub_' . $this->mSubqueryId;
873 $sub2 = 'sub_' . ( $this->mSubqueryId + 1 );
874 $this->mSubqueryId += 2;
875 if ( !$s1 ) {
876 // wat
877 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
878 }
879 if ( !$s2 ) {
880 // no ORDER BY
881 $overOrder = 'ORDER BY (SELECT 1)';
882 } else {
883 if ( !isset( $orderby[2] ) || !$orderby[2] ) {
884 // don't need to strip it out if we're using a FOR XML clause
885 $sql = str_replace( $orderby[1], '', $sql );
886 }
887 $overOrder = $orderby[1];
888 $postOrder = ' ' . $overOrder;
889 }
890 $sql = "SELECT {$select[1]}
891 FROM (
892 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
893 FROM ({$sql}) {$sub1}
894 ) {$sub2}
895 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
896
897 return $sql;
898 }
899 }
900
911 public function LimitToTopN( $sql ) {
912 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
913 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
914 if ( preg_match( $pattern, $sql, $matches ) ) {
915 $row_count = $matches[4];
916 $offset = $matches[3] ?: $matches[6] ?: false;
917
918 // strip the matching LIMIT clause out
919 $sql = str_replace( $matches[0], '', $sql );
920
921 return $this->limitResult( $sql, $row_count, $offset );
922 }
923
924 return $sql;
925 }
926
930 public function getSoftwareLink() {
931 return "[{{int:version-db-mssql-url}} MS SQL Server]";
932 }
933
937 public function getServerVersion() {
938 $server_info = sqlsrv_server_info( $this->mConn );
939 $version = 'Error';
940 if ( isset( $server_info['SQLServerVersion'] ) ) {
941 $version = $server_info['SQLServerVersion'];
942 }
943
944 return $version;
945 }
946
952 public function tableExists( $table, $fname = __METHOD__ ) {
953 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
954
955 if ( $db !== false ) {
956 // remote database
957 wfDebug( "Attempting to call tableExists on a remote table" );
958 return false;
959 }
960
961 if ( $schema === false ) {
963 $schema = $wgDBmwschema;
964 }
965
966 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
967 WHERE TABLE_TYPE = 'BASE TABLE'
968 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
969
970 if ( $res->numRows() ) {
971 return true;
972 } else {
973 return false;
974 }
975 }
976
984 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
985 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
986
987 if ( $db !== false ) {
988 // remote database
989 wfDebug( "Attempting to call fieldExists on a remote table" );
990 return false;
991 }
992
993 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
994 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
995
996 if ( $res->numRows() ) {
997 return true;
998 } else {
999 return false;
1000 }
1001 }
1002
1003 public function fieldInfo( $table, $field ) {
1004 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1005
1006 if ( $db !== false ) {
1007 // remote database
1008 wfDebug( "Attempting to call fieldInfo on a remote table" );
1009 return false;
1010 }
1011
1012 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1013 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1014
1015 $meta = $res->fetchRow();
1016 if ( $meta ) {
1017 return new MssqlField( $meta );
1018 }
1019
1020 return false;
1021 }
1022
1027 protected function doBegin( $fname = __METHOD__ ) {
1028 sqlsrv_begin_transaction( $this->mConn );
1029 $this->mTrxLevel = 1;
1030 }
1031
1036 protected function doCommit( $fname = __METHOD__ ) {
1037 sqlsrv_commit( $this->mConn );
1038 $this->mTrxLevel = 0;
1039 }
1040
1046 protected function doRollback( $fname = __METHOD__ ) {
1047 sqlsrv_rollback( $this->mConn );
1048 $this->mTrxLevel = 0;
1049 }
1050
1059 private function escapeIdentifier( $identifier ) {
1060 if ( strlen( $identifier ) == 0 ) {
1061 throw new InvalidArgumentException( "An identifier must not be empty" );
1062 }
1063 if ( strlen( $identifier ) > 128 ) {
1064 throw new InvalidArgumentException( "The identifier '$identifier' is too long (max. 128)" );
1065 }
1066 if ( ( strpos( $identifier, '[' ) !== false )
1067 || ( strpos( $identifier, ']' ) !== false )
1068 ) {
1069 // It may be allowed if you quoted with double quotation marks, but
1070 // that would break if QUOTED_IDENTIFIER is OFF
1071 throw new InvalidArgumentException( "Square brackets are not allowed in '$identifier'" );
1072 }
1073
1074 return "[$identifier]";
1075 }
1076
1081 public function strencode( $s ) {
1082 // Should not be called by us
1083
1084 return str_replace( "'", "''", $s );
1085 }
1086
1091 public function addQuotes( $s ) {
1092 if ( $s instanceof MssqlBlob ) {
1093 return $s->fetch();
1094 } elseif ( $s instanceof Blob ) {
1095 // this shouldn't really ever be called, but it's here if needed
1096 // (and will quite possibly make the SQL error out)
1097 $blob = new MssqlBlob( $s->fetch() );
1098 return $blob->fetch();
1099 } else {
1100 if ( is_bool( $s ) ) {
1101 $s = $s ? 1 : 0;
1102 }
1103 return parent::addQuotes( $s );
1104 }
1105 }
1106
1111 public function addIdentifierQuotes( $s ) {
1112 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1113 return '[' . $s . ']';
1114 }
1115
1120 public function isQuotedIdentifier( $name ) {
1121 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1122 }
1123
1130 protected function escapeLikeInternal( $s ) {
1131 return addcslashes( $s, '\%_[]^' );
1132 }
1133
1144 public function buildLike() {
1145 $params = func_get_args();
1146 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1147 $params = $params[0];
1148 }
1149
1150 return parent::buildLike( $params ) . " ESCAPE '\' ";
1151 }
1152
1157 public function selectDB( $db ) {
1158 try {
1159 $this->mDBname = $db;
1160 $this->query( "USE $db" );
1161 return true;
1162 } catch ( Exception $e ) {
1163 return false;
1164 }
1165 }
1166
1172 public function makeSelectOptions( $options ) {
1173 $tailOpts = '';
1174 $startOpts = '';
1175
1176 $noKeyOptions = [];
1177 foreach ( $options as $key => $option ) {
1178 if ( is_numeric( $key ) ) {
1179 $noKeyOptions[$option] = true;
1180 }
1181 }
1182
1183 $tailOpts .= $this->makeGroupByWithHaving( $options );
1184
1185 $tailOpts .= $this->makeOrderBy( $options );
1186
1187 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1188 $startOpts .= 'DISTINCT';
1189 }
1190
1191 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1192 // used in group concat field emulation
1193 $tailOpts .= " FOR XML PATH('')";
1194 }
1195
1196 // we want this to be compatible with the output of parent::makeSelectOptions()
1197 return [ $startOpts, '', $tailOpts, '', '' ];
1198 }
1199
1204 public function getType() {
1205 return 'mssql';
1206 }
1207
1212 public function buildConcat( $stringList ) {
1213 return implode( ' + ', $stringList );
1214 }
1215
1233 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1234 $join_conds = []
1235 ) {
1236 $gcsq = 'gcsq_' . $this->mSubqueryId;
1237 $this->mSubqueryId++;
1238
1239 $delimLen = strlen( $delim );
1240 $fld = "{$field} + {$this->addQuotes( $delim )}";
1241 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1242 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1243 . ") {$gcsq} ({$field}))";
1244
1245 return $sql;
1246 }
1247
1254 private function getBinaryColumns( $table ) {
1255 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1256 $tableRaw = array_pop( $tableRawArr );
1257
1258 if ( $this->mBinaryColumnCache === null ) {
1259 $this->populateColumnCaches();
1260 }
1261
1262 return isset( $this->mBinaryColumnCache[$tableRaw] )
1263 ? $this->mBinaryColumnCache[$tableRaw]
1264 : [];
1265 }
1266
1271 private function getBitColumns( $table ) {
1272 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1273 $tableRaw = array_pop( $tableRawArr );
1274
1275 if ( $this->mBitColumnCache === null ) {
1276 $this->populateColumnCaches();
1277 }
1278
1279 return isset( $this->mBitColumnCache[$tableRaw] )
1280 ? $this->mBitColumnCache[$tableRaw]
1281 : [];
1282 }
1283
1284 private function populateColumnCaches() {
1285 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1286 [
1287 'TABLE_CATALOG' => $this->mDBname,
1288 'TABLE_SCHEMA' => $this->mSchema,
1289 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1290 ] );
1291
1292 $this->mBinaryColumnCache = [];
1293 $this->mBitColumnCache = [];
1294 foreach ( $res as $row ) {
1295 if ( $row->DATA_TYPE == 'bit' ) {
1296 $this->mBitColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1297 } else {
1298 $this->mBinaryColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1299 }
1300 }
1301 }
1302
1308 function tableName( $name, $format = 'quoted' ) {
1309 # Replace reserved words with better ones
1310 switch ( $name ) {
1311 case 'user':
1312 return $this->realTableName( 'mwuser', $format );
1313 default:
1314 return $this->realTableName( $name, $format );
1315 }
1316 }
1317
1324 function realTableName( $name, $format = 'quoted' ) {
1325 $table = parent::tableName( $name, $format );
1326 if ( $format == 'split' ) {
1327 // Used internally, we want the schema split off from the table name and returned
1328 // as a list with 3 elements (database, schema, table)
1329 $table = explode( '.', $table );
1330 while ( count( $table ) < 3 ) {
1331 array_unshift( $table, false );
1332 }
1333 }
1334 return $table;
1335 }
1336
1344 public function dropTable( $tableName, $fName = __METHOD__ ) {
1345 if ( !$this->tableExists( $tableName, $fName ) ) {
1346 return false;
1347 }
1348
1349 // parent function incorrectly appends CASCADE, which we don't want
1350 $sql = "DROP TABLE " . $this->tableName( $tableName );
1351
1352 return $this->query( $sql, $fName );
1353 }
1354
1361 public function prepareStatements( $value = null ) {
1362 return wfSetVar( $this->mPrepareStatements, $value );
1363 }
1364
1371 public function scrollableCursor( $value = null ) {
1372 return wfSetVar( $this->mScrollableCursor, $value );
1373 }
1374
1381 public function ignoreErrors( array $value = null ) {
1382 return wfSetVar( $this->mIgnoreErrors, $value );
1383 }
1384} // end DatabaseMssql class
serialize()
$wgDBmwschema
Mediawiki schema.
$wgDBport
Database port number (for PostgreSQL and Microsoft SQL Server).
$wgDBWindowsAuthentication
Use Windows Authentication instead of $wgDBuser / $wgDBpassword for MS SQL Server.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition Setup.php:36
Utility class.
Definition Blob.php:8
makeList( $a, $mode=LIST_COMMA, $binaryColumns=[])
Makes an encoded list of strings from an array.
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[])
INSERT SELECT wrapper $varMap must be an associative array of the form [ 'dest1' => 'source1',...
indexInfo( $table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure.
fieldInfo( $table, $field)
buildConcat( $stringList)
buildLike()
MS SQL requires specifying the escape character used in a LIKE query or using Square brackets to surr...
getBitColumns( $table)
LimitToTopN( $sql)
If there is a limit clause, parse it, strip it, and pass the remaining SQL through limitResult() with...
isQuotedIdentifier( $name)
escapeIdentifier( $identifier)
Escapes a identifier for use inm SQL.
fieldExists( $table, $field, $fname=__METHOD__)
Query whether a given column exists in the mediawiki schema.
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
realTableName( $name, $format='quoted')
call this instead of tableName() in the updater when renaming tables
doBegin( $fname=__METHOD__)
Begin a transaction, committing any previously open transaction.
escapeLikeInternal( $s)
MS SQL supports more pattern operators than other databases (ex: [,],^)
insertId()
This must be called after nextSequenceVal.
insert( $table, $arrToInsert, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
scrollableCursor( $value=null)
Called in the installer and updater.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
SELECT wrapper.
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
SELECT wrapper.
ignoreErrors(array $value=null)
Called in the installer and updater.
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
resultObject( $result)
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset This is used for query pages.
tableExists( $table, $fname=__METHOD__)
doCommit( $fname=__METHOD__)
End a transaction.
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on SHOWPLAN_ALL output This is not necessaril...
getBinaryColumns( $table)
Returns an associative array for fields that are of type varbinary, binary, or image $table can be ei...
dataSeek( $res, $row)
textFieldSize( $table, $field)
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
tableName( $name, $format='quoted')
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
fieldName( $res, $n)
makeSelectOptions( $options)
open( $server, $user, $password, $dbName)
Usually aborts on failure.
dropTable( $tableName, $fName=__METHOD__)
Delete a table.
doRollback( $fname=__METHOD__)
Rollback a transaction.
prepareStatements( $value=null)
Called in the installer and updater.
Result wrapper for grabbing data queried from an IDatabase object.
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like select() and insert() are usually more convenient. They take care of things like table prefixes and escaping for you. If you really need to make your own SQL
$res
Definition database.txt:21
For a write query
Definition database.txt:26
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const LIST_NAMES
Definition Defines.php:37
const LIST_COMMA
Definition Defines.php:34
const LIST_SET
Definition Defines.php:36
const LIST_AND
Definition Defines.php:35
the array() calling protocol came about after MediaWiki 1.4rc1.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition hooks.txt:2162
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:249
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1937
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition hooks.txt:1096
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition hooks.txt:1135
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:1949
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
returning false will NOT prevent logging $e
Definition hooks.txt:2110
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
$last
const DBO_DEBUG
Definition defines.php:6
$params