MediaWiki  1.32.0
DatabaseMssql.php
Go to the documentation of this file.
1 <?php
28 namespace Wikimedia\Rdbms;
29 
31 use Exception;
32 use stdClass;
33 
37 class DatabaseMssql extends Database {
39  protected $serverPort;
41  protected $useWindowsAuth = false;
43  protected $lastInsertId = null;
45  protected $lastAffectedRowCount = null;
47  protected $subqueryId = 0;
49  protected $scrollableCursor = true;
51  protected $prepareStatements = true;
53  protected $binaryColumnCache = null;
55  protected $bitColumnCache = null;
57  protected $ignoreDupKeyErrors = false;
59  protected $ignoreErrors = [];
60 
61  public function implicitGroupby() {
62  return false;
63  }
64 
65  public function implicitOrderby() {
66  return false;
67  }
68 
69  public function unionSupportsOrderAndLimit() {
70  return false;
71  }
72 
73  public function __construct( array $params ) {
74  $this->serverPort = $params['port'];
75  $this->useWindowsAuth = $params['UseWindowsAuth'];
76 
77  parent::__construct( $params );
78  }
79 
80  protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
81  # Test for driver support, to avoid suppressed fatal error
82  if ( !function_exists( 'sqlsrv_connect' ) ) {
83  throw new DBConnectionError(
84  $this,
85  "Microsoft SQL Server Native (sqlsrv) functions missing.
86  You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
87  );
88  }
89 
90  # e.g. the class is being loaded
91  if ( !strlen( $user ) ) {
92  return null;
93  }
94 
95  $this->close();
96  $this->server = $server;
97  $this->user = $user;
98  $this->password = $password;
99 
100  $connectionInfo = [];
101 
102  if ( $dbName != '' ) {
103  $connectionInfo['Database'] = $dbName;
104  }
105 
106  // Decide which auth scenerio to use
107  // if we are using Windows auth, then don't add credentials to $connectionInfo
108  if ( !$this->useWindowsAuth ) {
109  $connectionInfo['UID'] = $user;
110  $connectionInfo['PWD'] = $password;
111  }
112 
113  Wikimedia\suppressWarnings();
114  $this->conn = sqlsrv_connect( $server, $connectionInfo );
115  Wikimedia\restoreWarnings();
116 
117  if ( $this->conn === false ) {
118  throw new DBConnectionError( $this, $this->lastError() );
119  }
120 
121  $this->opened = true;
122  $this->currentDomain = new DatabaseDomain(
123  ( $dbName != '' ) ? $dbName : null,
124  null,
125  $tablePrefix
126  );
127 
128  return (bool)$this->conn;
129  }
130 
136  protected function closeConnection() {
137  return sqlsrv_close( $this->conn );
138  }
139 
144  protected function resultObject( $result ) {
145  if ( !$result ) {
146  return false;
147  } elseif ( $result instanceof MssqlResultWrapper ) {
148  return $result;
149  } elseif ( $result === true ) {
150  // Successful write query
151  return $result;
152  } else {
153  return new MssqlResultWrapper( $this, $result );
154  }
155  }
156 
162  protected function doQuery( $sql ) {
163  // several extensions seem to think that all databases support limits
164  // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
165  // so to catch any of those extensions we'll do a quick check for a
166  // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
167  // the LIMIT clause and passes the result to $this->limitResult();
168  if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
169  // massage LIMIT -> TopN
170  $sql = $this->LimitToTopN( $sql );
171  }
172 
173  // MSSQL doesn't have EXTRACT(epoch FROM XXX)
174  if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
175  // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
176  $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
177  }
178 
179  // perform query
180 
181  // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
182  // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
183  // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
184  // strings make php throw a fatal error "Severe error translating Unicode"
185  if ( $this->scrollableCursor ) {
186  $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC ];
187  } else {
188  $scrollArr = [];
189  }
190 
191  if ( $this->prepareStatements ) {
192  // we do prepare + execute so we can get its field metadata for later usage if desired
193  $stmt = sqlsrv_prepare( $this->conn, $sql, [], $scrollArr );
194  $success = sqlsrv_execute( $stmt );
195  } else {
196  $stmt = sqlsrv_query( $this->conn, $sql, [], $scrollArr );
197  $success = (bool)$stmt;
198  }
199 
200  // Make a copy to ensure what we add below does not get reflected in future queries
202 
203  if ( $this->ignoreDupKeyErrors ) {
204  // ignore duplicate key errors
205  // this emulates INSERT IGNORE in MySQL
206  $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
207  $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
208  $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
209  }
210 
211  if ( $success === false ) {
212  $errors = sqlsrv_errors();
213  $success = true;
214 
215  foreach ( $errors as $err ) {
216  if ( !in_array( $err['code'], $ignoreErrors ) ) {
217  $success = false;
218  break;
219  }
220  }
221 
222  if ( $success === false ) {
223  return false;
224  }
225  }
226  // remember number of rows affected
227  $this->lastAffectedRowCount = sqlsrv_rows_affected( $stmt );
228 
229  return $stmt;
230  }
231 
232  public function freeResult( $res ) {
233  if ( $res instanceof ResultWrapper ) {
234  $res = $res->result;
235  }
236 
237  sqlsrv_free_stmt( $res );
238  }
239 
244  public function fetchObject( $res ) {
245  // $res is expected to be an instance of MssqlResultWrapper here
246  return $res->fetchObject();
247  }
248 
253  public function fetchRow( $res ) {
254  return $res->fetchRow();
255  }
256 
261  public function numRows( $res ) {
262  if ( $res instanceof ResultWrapper ) {
263  $res = $res->result;
264  }
265 
266  $ret = sqlsrv_num_rows( $res );
267 
268  if ( $ret === false ) {
269  // we cannot get an amount of rows from this cursor type
270  // has_rows returns bool true/false if the result has rows
271  $ret = (int)sqlsrv_has_rows( $res );
272  }
273 
274  return $ret;
275  }
276 
281  public function numFields( $res ) {
282  if ( $res instanceof ResultWrapper ) {
283  $res = $res->result;
284  }
285 
286  return sqlsrv_num_fields( $res );
287  }
288 
294  public function fieldName( $res, $n ) {
295  if ( $res instanceof ResultWrapper ) {
296  $res = $res->result;
297  }
298 
299  return sqlsrv_field_metadata( $res )[$n]['Name'];
300  }
301 
306  public function insertId() {
307  return $this->lastInsertId;
308  }
309 
315  public function dataSeek( $res, $row ) {
316  return $res->seek( $row );
317  }
318 
322  public function lastError() {
323  $strRet = '';
324  $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL );
325  if ( $retErrors != null ) {
326  foreach ( $retErrors as $arrError ) {
327  $strRet .= $this->formatError( $arrError ) . "\n";
328  }
329  } else {
330  $strRet = "No errors found";
331  }
332 
333  return $strRet;
334  }
335 
340  private function formatError( $err ) {
341  return '[SQLSTATE ' .
342  $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
343  }
344 
348  public function lastErrno() {
349  $err = sqlsrv_errors( SQLSRV_ERR_ALL );
350  if ( $err !== null && isset( $err[0] ) ) {
351  return $err[0]['code'];
352  } else {
353  return 0;
354  }
355  }
356 
357  protected function wasKnownStatementRollbackError() {
358  $errors = sqlsrv_errors( SQLSRV_ERR_ALL );
359  if ( !$errors ) {
360  return false;
361  }
362  // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
363  // that the "statement has been terminated" error (3621) is specifically present.
364  // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
365  $statementOnly = false;
366  $codeWhitelist = [ '2601', '2627', '547' ];
367  foreach ( $errors as $error ) {
368  if ( $error['code'] == '3621' ) {
369  $statementOnly = true;
370  } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
371  $statementOnly = false;
372  break;
373  }
374  }
375 
376  return $statementOnly;
377  }
378 
382  protected function fetchAffectedRowCount() {
384  }
385 
404  public function select( $table, $vars, $conds = '', $fname = __METHOD__,
405  $options = [], $join_conds = []
406  ) {
407  $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
408  if ( isset( $options['EXPLAIN'] ) ) {
409  try {
410  $this->scrollableCursor = false;
411  $this->prepareStatements = false;
412  $this->query( "SET SHOWPLAN_ALL ON" );
413  $ret = $this->query( $sql, $fname );
414  $this->query( "SET SHOWPLAN_ALL OFF" );
415  } catch ( DBQueryError $dqe ) {
416  if ( isset( $options['FOR COUNT'] ) ) {
417  // likely don't have privs for SHOWPLAN, so run a select count instead
418  $this->query( "SET SHOWPLAN_ALL OFF" );
419  unset( $options['EXPLAIN'] );
420  $ret = $this->select(
421  $table,
422  'COUNT(*) AS EstimateRows',
423  $conds,
424  $fname,
425  $options,
426  $join_conds
427  );
428  } else {
429  // someone actually wanted the query plan instead of an est row count
430  // let them know of the error
431  $this->scrollableCursor = true;
432  $this->prepareStatements = true;
433  throw $dqe;
434  }
435  }
436  $this->scrollableCursor = true;
437  $this->prepareStatements = true;
438  return $ret;
439  }
440  return $this->query( $sql, $fname );
441  }
442 
456  public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
457  $options = [], $join_conds = []
458  ) {
459  if ( isset( $options['EXPLAIN'] ) ) {
460  unset( $options['EXPLAIN'] );
461  }
462 
463  $sql = parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
464 
465  // try to rewrite aggregations of bit columns (currently MAX and MIN)
466  if ( strpos( $sql, 'MAX(' ) !== false || strpos( $sql, 'MIN(' ) !== false ) {
467  $bitColumns = [];
468  if ( is_array( $table ) ) {
469  $tables = $table;
470  while ( $tables ) {
471  $t = array_pop( $tables );
472  if ( is_array( $t ) ) {
473  $tables = array_merge( $tables, $t );
474  } else {
475  $bitColumns += $this->getBitColumns( $this->tableName( $t ) );
476  }
477  }
478  } else {
479  $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
480  }
481 
482  foreach ( $bitColumns as $col => $info ) {
483  $replace = [
484  "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
485  "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
486  ];
487  $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
488  }
489  }
490 
491  return $sql;
492  }
493 
494  public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
495  $fname = __METHOD__
496  ) {
497  $this->scrollableCursor = false;
498  try {
499  parent::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
500  } catch ( Exception $e ) {
501  $this->scrollableCursor = true;
502  throw $e;
503  }
504  $this->scrollableCursor = true;
505  }
506 
507  public function delete( $table, $conds, $fname = __METHOD__ ) {
508  $this->scrollableCursor = false;
509  try {
510  parent::delete( $table, $conds, $fname );
511  } catch ( Exception $e ) {
512  $this->scrollableCursor = true;
513  throw $e;
514  }
515  $this->scrollableCursor = true;
516  }
517 
532  public function estimateRowCount( $table, $var = '*', $conds = '',
533  $fname = __METHOD__, $options = [], $join_conds = []
534  ) {
535  $conds = $this->normalizeConditions( $conds, $fname );
536  $column = $this->extractSingleFieldFromList( $var );
537  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
538  $conds[] = "$column IS NOT NULL";
539  }
540 
541  // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
542  $options['EXPLAIN'] = true;
543  $options['FOR COUNT'] = true;
544  $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
545 
546  $rows = -1;
547  if ( $res ) {
548  $row = $this->fetchRow( $res );
549 
550  if ( isset( $row['EstimateRows'] ) ) {
551  $rows = (int)$row['EstimateRows'];
552  }
553  }
554 
555  return $rows;
556  }
557 
566  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
567  # This does not return the same info as MYSQL would, but that's OK
568  # because MediaWiki never uses the returned value except to check for
569  # the existence of indexes.
570  $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
571  $res = $this->query( $sql, $fname );
572 
573  if ( !$res ) {
574  return null;
575  }
576 
577  $result = [];
578  foreach ( $res as $row ) {
579  if ( $row->index_name == $index ) {
580  $row->Non_unique = !stristr( $row->index_description, "unique" );
581  $cols = explode( ", ", $row->index_keys );
582  foreach ( $cols as $col ) {
583  $row->Column_name = trim( $col );
584  $result[] = clone $row;
585  }
586  } elseif ( $index == 'PRIMARY' && stristr( $row->index_description, 'PRIMARY' ) ) {
587  $row->Non_unique = 0;
588  $cols = explode( ", ", $row->index_keys );
589  foreach ( $cols as $col ) {
590  $row->Column_name = trim( $col );
591  $result[] = clone $row;
592  }
593  }
594  }
595 
596  return $result ?: false;
597  }
598 
614  public function insert( $table, $arrToInsert, $fname = __METHOD__, $options = [] ) {
615  # No rows to insert, easy just return now
616  if ( !count( $arrToInsert ) ) {
617  return true;
618  }
619 
620  if ( !is_array( $options ) ) {
621  $options = [ $options ];
622  }
623 
624  $table = $this->tableName( $table );
625 
626  if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
627  $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
628  }
629 
630  // We know the table we're inserting into, get its identity column
631  $identity = null;
632  // strip matching square brackets and the db/schema from table name
633  $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
634  $tableRaw = array_pop( $tableRawArr );
635  $res = $this->doQuery(
636  "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
637  "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
638  );
639  if ( $res && sqlsrv_has_rows( $res ) ) {
640  // There is an identity for this table.
641  $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC );
642  $identity = array_pop( $identityArr );
643  }
644  sqlsrv_free_stmt( $res );
645 
646  // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
647  $binaryColumns = $this->getBinaryColumns( $table );
648 
649  // INSERT IGNORE is not supported by SQL Server
650  // remove IGNORE from options list and set ignore flag to true
651  if ( in_array( 'IGNORE', $options ) ) {
652  $options = array_diff( $options, [ 'IGNORE' ] );
653  $this->ignoreDupKeyErrors = true;
654  }
655 
656  $ret = null;
657  foreach ( $arrToInsert as $a ) {
658  // start out with empty identity column, this is so we can return
659  // it as a result of the INSERT logic
660  $sqlPre = '';
661  $sqlPost = '';
662  $identityClause = '';
663 
664  // if we have an identity column
665  if ( $identity ) {
666  // iterate through
667  foreach ( $a as $k => $v ) {
668  if ( $k == $identity ) {
669  if ( !is_null( $v ) ) {
670  // there is a value being passed to us,
671  // we need to turn on and off inserted identity
672  $sqlPre = "SET IDENTITY_INSERT $table ON;";
673  $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
674  } else {
675  // we can't insert NULL into an identity column,
676  // so remove the column from the insert.
677  unset( $a[$k] );
678  }
679  }
680  }
681 
682  // we want to output an identity column as result
683  $identityClause = "OUTPUT INSERTED.$identity ";
684  }
685 
686  $keys = array_keys( $a );
687 
688  // Build the actual query
689  $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
690  " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
691 
692  $first = true;
693  foreach ( $a as $key => $value ) {
694  if ( isset( $binaryColumns[$key] ) ) {
695  $value = new MssqlBlob( $value );
696  }
697  if ( $first ) {
698  $first = false;
699  } else {
700  $sql .= ',';
701  }
702  if ( is_null( $value ) ) {
703  $sql .= 'null';
704  } elseif ( is_array( $value ) || is_object( $value ) ) {
705  if ( is_object( $value ) && $value instanceof Blob ) {
706  $sql .= $this->addQuotes( $value );
707  } else {
708  $sql .= $this->addQuotes( serialize( $value ) );
709  }
710  } else {
711  $sql .= $this->addQuotes( $value );
712  }
713  }
714  $sql .= ')' . $sqlPost;
715 
716  // Run the query
717  $this->scrollableCursor = false;
718  try {
719  $ret = $this->query( $sql );
720  } catch ( Exception $e ) {
721  $this->scrollableCursor = true;
722  $this->ignoreDupKeyErrors = false;
723  throw $e;
724  }
725  $this->scrollableCursor = true;
726 
727  if ( $ret instanceof ResultWrapper && !is_null( $identity ) ) {
728  // Then we want to get the identity column value we were assigned and save it off
729  $row = $ret->fetchObject();
730  if ( is_object( $row ) ) {
731  $this->lastInsertId = $row->$identity;
732  // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
733  // used if we got an identity back, we know for sure a row was affected, so
734  // adjust that here
735  if ( $this->lastAffectedRowCount == -1 ) {
736  $this->lastAffectedRowCount = 1;
737  }
738  }
739  }
740  }
741 
742  $this->ignoreDupKeyErrors = false;
743 
744  return $ret;
745  }
746 
763  public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
764  $insertOptions = [], $selectOptions = [], $selectJoinConds = []
765  ) {
766  $this->scrollableCursor = false;
767  try {
768  $ret = parent::nativeInsertSelect(
769  $destTable,
770  $srcTable,
771  $varMap,
772  $conds,
773  $fname,
774  $insertOptions,
775  $selectOptions,
776  $selectJoinConds
777  );
778  } catch ( Exception $e ) {
779  $this->scrollableCursor = true;
780  throw $e;
781  }
782  $this->scrollableCursor = true;
783 
784  return $ret;
785  }
786 
812  function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
813  $table = $this->tableName( $table );
814  $binaryColumns = $this->getBinaryColumns( $table );
815 
816  $opts = $this->makeUpdateOptions( $options );
817  $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET, $binaryColumns );
818 
819  if ( $conds !== [] && $conds !== '*' ) {
820  $sql .= " WHERE " . $this->makeList( $conds, LIST_AND, $binaryColumns );
821  }
822 
823  $this->scrollableCursor = false;
824  try {
825  $this->query( $sql );
826  } catch ( Exception $e ) {
827  $this->scrollableCursor = true;
828  throw $e;
829  }
830  $this->scrollableCursor = true;
831  return true;
832  }
833 
850  public function makeList( $a, $mode = LIST_COMMA, $binaryColumns = [] ) {
851  if ( !is_array( $a ) ) {
852  throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
853  }
854 
855  if ( $mode != LIST_NAMES ) {
856  // In MS SQL, values need to be specially encoded when they are
857  // inserted into binary fields. Perform this necessary encoding
858  // for the specified set of columns.
859  foreach ( array_keys( $a ) as $field ) {
860  if ( !isset( $binaryColumns[$field] ) ) {
861  continue;
862  }
863 
864  if ( is_array( $a[$field] ) ) {
865  foreach ( $a[$field] as &$v ) {
866  $v = new MssqlBlob( $v );
867  }
868  unset( $v );
869  } else {
870  $a[$field] = new MssqlBlob( $a[$field] );
871  }
872  }
873  }
874 
875  return parent::makeList( $a, $mode );
876  }
877 
883  public function textFieldSize( $table, $field ) {
884  $table = $this->tableName( $table );
885  $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
886  WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
887  $res = $this->query( $sql );
888  $row = $this->fetchRow( $res );
889  $size = -1;
890  if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
891  $size = $row['CHARACTER_MAXIMUM_LENGTH'];
892  }
893 
894  return $size;
895  }
896 
907  public function limitResult( $sql, $limit, $offset = false ) {
908  if ( $offset === false || $offset == 0 ) {
909  if ( strpos( $sql, "SELECT" ) === false ) {
910  return "TOP {$limit} " . $sql;
911  } else {
912  return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
913  'SELECT$1 TOP ' . $limit, $sql, 1 );
914  }
915  } else {
916  // This one is fun, we need to pull out the select list as well as any ORDER BY clause
917  $select = $orderby = [];
918  $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
919  $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
920  $postOrder = '';
921  $first = $offset + 1;
922  $last = $offset + $limit;
923  $sub1 = 'sub_' . $this->subqueryId;
924  $sub2 = 'sub_' . ( $this->subqueryId + 1 );
925  $this->subqueryId += 2;
926  if ( !$s1 ) {
927  // wat
928  throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
929  }
930  if ( !$s2 ) {
931  // no ORDER BY
932  $overOrder = 'ORDER BY (SELECT 1)';
933  } else {
934  if ( !isset( $orderby[2] ) || !$orderby[2] ) {
935  // don't need to strip it out if we're using a FOR XML clause
936  $sql = str_replace( $orderby[1], '', $sql );
937  }
938  $overOrder = $orderby[1];
939  $postOrder = ' ' . $overOrder;
940  }
941  $sql = "SELECT {$select[1]}
942  FROM (
943  SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
944  FROM ({$sql}) {$sub1}
945  ) {$sub2}
946  WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
947 
948  return $sql;
949  }
950  }
951 
962  public function LimitToTopN( $sql ) {
963  // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
964  $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
965  if ( preg_match( $pattern, $sql, $matches ) ) {
966  $row_count = $matches[4];
967  $offset = $matches[3] ?: $matches[6] ?: false;
968 
969  // strip the matching LIMIT clause out
970  $sql = str_replace( $matches[0], '', $sql );
971 
972  return $this->limitResult( $sql, $row_count, $offset );
973  }
974 
975  return $sql;
976  }
977 
981  public function getSoftwareLink() {
982  return "[{{int:version-db-mssql-url}} MS SQL Server]";
983  }
984 
988  public function getServerVersion() {
989  $server_info = sqlsrv_server_info( $this->conn );
990  $version = 'Error';
991  if ( isset( $server_info['SQLServerVersion'] ) ) {
992  $version = $server_info['SQLServerVersion'];
993  }
994 
995  return $version;
996  }
997 
1003  public function tableExists( $table, $fname = __METHOD__ ) {
1004  list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1005 
1006  if ( $db !== false ) {
1007  // remote database
1008  $this->queryLogger->error( "Attempting to call tableExists on a remote table" );
1009  return false;
1010  }
1011 
1012  if ( $schema === false ) {
1013  $schema = $this->dbSchema();
1014  }
1015 
1016  $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1017  WHERE TABLE_TYPE = 'BASE TABLE'
1018  AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1019 
1020  if ( $res->numRows() ) {
1021  return true;
1022  } else {
1023  return false;
1024  }
1025  }
1026 
1034  public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1035  list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1036 
1037  if ( $db !== false ) {
1038  // remote database
1039  $this->queryLogger->error( "Attempting to call fieldExists on a remote table" );
1040  return false;
1041  }
1042 
1043  $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1044  WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1045 
1046  if ( $res->numRows() ) {
1047  return true;
1048  } else {
1049  return false;
1050  }
1051  }
1052 
1053  public function fieldInfo( $table, $field ) {
1054  list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1055 
1056  if ( $db !== false ) {
1057  // remote database
1058  $this->queryLogger->error( "Attempting to call fieldInfo on a remote table" );
1059  return false;
1060  }
1061 
1062  $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1063  WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1064 
1065  $meta = $res->fetchRow();
1066  if ( $meta ) {
1067  return new MssqlField( $meta );
1068  }
1069 
1070  return false;
1071  }
1072 
1073  protected function doSavepoint( $identifier, $fname ) {
1074  $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1075  }
1076 
1077  protected function doReleaseSavepoint( $identifier, $fname ) {
1078  // Not supported. Also not really needed, a new doSavepoint() for the
1079  // same identifier will overwrite the old.
1080  }
1081 
1082  protected function doRollbackToSavepoint( $identifier, $fname ) {
1083  $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1084  }
1085 
1090  protected function doBegin( $fname = __METHOD__ ) {
1091  sqlsrv_begin_transaction( $this->conn );
1092  $this->trxLevel = 1;
1093  }
1094 
1099  protected function doCommit( $fname = __METHOD__ ) {
1100  sqlsrv_commit( $this->conn );
1101  $this->trxLevel = 0;
1102  }
1103 
1109  protected function doRollback( $fname = __METHOD__ ) {
1110  sqlsrv_rollback( $this->conn );
1111  $this->trxLevel = 0;
1112  }
1113 
1118  public function strencode( $s ) {
1119  // Should not be called by us
1120  return str_replace( "'", "''", $s );
1121  }
1122 
1127  public function addQuotes( $s ) {
1128  if ( $s instanceof MssqlBlob ) {
1129  return $s->fetch();
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();
1135  } else {
1136  if ( is_bool( $s ) ) {
1137  $s = $s ? 1 : 0;
1138  }
1139  return parent::addQuotes( $s );
1140  }
1141  }
1142 
1147  public function addIdentifierQuotes( $s ) {
1148  // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1149  return '[' . $s . ']';
1150  }
1151 
1156  public function isQuotedIdentifier( $name ) {
1157  return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1158  }
1159 
1167  protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1168  return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1169  [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1170  "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1171  $s );
1172  }
1173 
1174  protected function doSelectDomain( DatabaseDomain $domain ) {
1175  $encDatabase = $this->addIdentifierQuotes( $domain->getDatabase() );
1176  $this->query( "USE $encDatabase" );
1177  // Update that domain fields on success (no exception thrown)
1178  $this->currentDomain = $domain;
1179 
1180  return true;
1181  }
1182 
1188  public function makeSelectOptions( $options ) {
1189  $tailOpts = '';
1190  $startOpts = '';
1191 
1192  $noKeyOptions = [];
1193  foreach ( $options as $key => $option ) {
1194  if ( is_numeric( $key ) ) {
1195  $noKeyOptions[$option] = true;
1196  }
1197  }
1198 
1199  $tailOpts .= $this->makeGroupByWithHaving( $options );
1200 
1201  $tailOpts .= $this->makeOrderBy( $options );
1202 
1203  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1204  $startOpts .= 'DISTINCT';
1205  }
1206 
1207  if ( isset( $noKeyOptions['FOR XML'] ) ) {
1208  // used in group concat field emulation
1209  $tailOpts .= " FOR XML PATH('')";
1210  }
1211 
1212  // we want this to be compatible with the output of parent::makeSelectOptions()
1213  return [ $startOpts, '', $tailOpts, '', '' ];
1214  }
1215 
1216  public function getType() {
1217  return 'mssql';
1218  }
1219 
1224  public function buildConcat( $stringList ) {
1225  return implode( ' + ', $stringList );
1226  }
1227 
1245  public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1246  $join_conds = []
1247  ) {
1248  $gcsq = 'gcsq_' . $this->subqueryId;
1249  $this->subqueryId++;
1250 
1251  $delimLen = strlen( $delim );
1252  $fld = "{$field} + {$this->addQuotes( $delim )}";
1253  $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1254  . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1255  . ") {$gcsq} ({$field}))";
1256 
1257  return $sql;
1258  }
1259 
1260  public function buildSubstring( $input, $startPosition, $length = null ) {
1261  $this->assertBuildSubstringParams( $startPosition, $length );
1262  if ( $length === null ) {
1268  $length = 2147483647;
1269  }
1270  return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1271  }
1272 
1279  private function getBinaryColumns( $table ) {
1280  $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1281  $tableRaw = array_pop( $tableRawArr );
1282 
1283  if ( $this->binaryColumnCache === null ) {
1284  $this->populateColumnCaches();
1285  }
1286 
1287  return $this->binaryColumnCache[$tableRaw] ?? [];
1288  }
1289 
1294  private function getBitColumns( $table ) {
1295  $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1296  $tableRaw = array_pop( $tableRawArr );
1297 
1298  if ( $this->bitColumnCache === null ) {
1299  $this->populateColumnCaches();
1300  }
1301 
1302  return $this->bitColumnCache[$tableRaw] ?? [];
1303  }
1304 
1305  private function populateColumnCaches() {
1306  $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1307  [
1308  'TABLE_CATALOG' => $this->getDBname(),
1309  'TABLE_SCHEMA' => $this->dbSchema(),
1310  'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1311  ] );
1312 
1313  $this->binaryColumnCache = [];
1314  $this->bitColumnCache = [];
1315  foreach ( $res as $row ) {
1316  if ( $row->DATA_TYPE == 'bit' ) {
1317  $this->bitColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1318  } else {
1319  $this->binaryColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1320  }
1321  }
1322  }
1323 
1329  function tableName( $name, $format = 'quoted' ) {
1330  # Replace reserved words with better ones
1331  switch ( $name ) {
1332  case 'user':
1333  return $this->realTableName( 'mwuser', $format );
1334  default:
1335  return $this->realTableName( $name, $format );
1336  }
1337  }
1338 
1345  function realTableName( $name, $format = 'quoted' ) {
1346  $table = parent::tableName( $name, $format );
1347  if ( $format == 'split' ) {
1348  // Used internally, we want the schema split off from the table name and returned
1349  // as a list with 3 elements (database, schema, table)
1350  $table = explode( '.', $table );
1351  while ( count( $table ) < 3 ) {
1352  array_unshift( $table, false );
1353  }
1354  }
1355  return $table;
1356  }
1357 
1365  public function dropTable( $tableName, $fName = __METHOD__ ) {
1366  if ( !$this->tableExists( $tableName, $fName ) ) {
1367  return false;
1368  }
1369 
1370  // parent function incorrectly appends CASCADE, which we don't want
1371  $sql = "DROP TABLE " . $this->tableName( $tableName );
1372 
1373  return $this->query( $sql, $fName );
1374  }
1375 
1382  public function prepareStatements( $value = null ) {
1383  $old = $this->prepareStatements;
1384  if ( $value !== null ) {
1385  $this->prepareStatements = $value;
1386  }
1387 
1388  return $old;
1389  }
1390 
1397  public function scrollableCursor( $value = null ) {
1398  $old = $this->scrollableCursor;
1399  if ( $value !== null ) {
1400  $this->scrollableCursor = $value;
1401  }
1402 
1403  return $old;
1404  }
1405 }
1406 
1410 class_alias( DatabaseMssql::class, 'DatabaseMssql' );
Wikimedia\Rdbms\DatabaseMssql\indexInfo
indexInfo( $table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure.
Definition: DatabaseMssql.php:566
Wikimedia\Rdbms\DatabaseMssql\update
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
Definition: DatabaseMssql.php:812
Wikimedia\Rdbms\DatabaseMssql\buildGroupConcatField
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
Definition: DatabaseMssql.php:1245
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
Wikimedia\Rdbms\DatabaseMssql\$ignoreDupKeyErrors
bool $ignoreDupKeyErrors
Definition: DatabaseMssql.php:57
Wikimedia\Rdbms\DatabaseMssql\limitResult
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset This is used for query pages.
Definition: DatabaseMssql.php:907
Wikimedia\Rdbms\DatabaseMssql\resultObject
resultObject( $result)
Definition: DatabaseMssql.php:144
Wikimedia\Rdbms\DatabaseMssql\realTableName
realTableName( $name, $format='quoted')
call this instead of tableName() in the updater when renaming tables
Definition: DatabaseMssql.php:1345
Wikimedia\Rdbms\DatabaseMssql\freeResult
freeResult( $res)
Free a result object returned by query() or select().
Definition: DatabaseMssql.php:232
Wikimedia\Rdbms\DatabaseMssql\deleteJoin
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
Definition: DatabaseMssql.php:494
Wikimedia\Rdbms\DatabaseMssql\__construct
__construct(array $params)
Definition: DatabaseMssql.php:73
captcha-old.count
count
Definition: captcha-old.py:249
$last
$last
Definition: profileinfo.php:419
Wikimedia\Rdbms\DatabaseMssql\$useWindowsAuth
bool $useWindowsAuth
Definition: DatabaseMssql.php:41
Wikimedia\Rdbms\Database\$password
string $password
Password used to establish the current connection.
Definition: Database.php:83
Wikimedia\Rdbms\DatabaseMssql\insert
insert( $table, $arrToInsert, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
Definition: DatabaseMssql.php:614
Wikimedia\Rdbms\DatabaseMssql\implicitOrderby
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
Definition: DatabaseMssql.php:65
Wikimedia\Rdbms\DatabaseMssql\$prepareStatements
bool $prepareStatements
Definition: DatabaseMssql.php:51
$result
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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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 since 1.16! 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:Array with elements of the form "language:title" in the order that they will be output. & $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 since 1.28! 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:2034
Wikimedia\Rdbms\DatabaseMssql\getServerVersion
getServerVersion()
Definition: DatabaseMssql.php:988
Wikimedia\Rdbms\DatabaseMssql\lastErrno
lastErrno()
Definition: DatabaseMssql.php:348
$tables
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:1018
Wikimedia\Rdbms\DatabaseMssql\buildConcat
buildConcat( $stringList)
Definition: DatabaseMssql.php:1224
Wikimedia\Rdbms\DatabaseMssql\$bitColumnCache
stdClass[][] null $bitColumnCache
Definition: DatabaseMssql.php:55
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\Database\normalizeConditions
normalizeConditions( $conds, $fname)
Definition: Database.php:1893
$params
$params
Definition: styleTest.css.php:44
Wikimedia\Rdbms\DatabaseMssql\$binaryColumnCache
stdClass[][] null $binaryColumnCache
Definition: DatabaseMssql.php:53
$s
$s
Definition: mergeMessageFileList.php:187
Wikimedia\Rdbms\Database\extractSingleFieldFromList
extractSingleFieldFromList( $var)
Definition: Database.php:1916
Wikimedia\Rdbms\DatabaseMssql\implicitGroupby
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
Definition: DatabaseMssql.php:61
Wikimedia\Rdbms\DatabaseDomain\getDatabase
getDatabase()
Definition: DatabaseDomain.php:158
$res
$res
Definition: database.txt:21
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:24
Wikimedia\Rdbms\DatabaseMssql\dropTable
dropTable( $tableName, $fName=__METHOD__)
Delete a table.
Definition: DatabaseMssql.php:1365
$success
$success
Definition: NoLocalSettings.php:42
serialize
serialize()
Definition: ApiMessageTrait.php:131
Wikimedia\Rdbms\DatabaseMssql\populateColumnCaches
populateColumnCaches()
Definition: DatabaseMssql.php:1305
Wikimedia\Rdbms\DatabaseMssql\dataSeek
dataSeek( $res, $row)
Definition: DatabaseMssql.php:315
Wikimedia\Rdbms\DatabaseMssql\makeList
makeList( $a, $mode=LIST_COMMA, $binaryColumns=[])
Makes an encoded list of strings from an array.
Definition: DatabaseMssql.php:850
Wikimedia\Rdbms\DatabaseMssql\getType
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
Definition: DatabaseMssql.php:1216
Wikimedia\Rdbms\DatabaseMssql\isQuotedIdentifier
isQuotedIdentifier( $name)
Definition: DatabaseMssql.php:1156
Wikimedia\Rdbms\DatabaseMssql\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Definition: DatabaseMssql.php:357
php
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:35
LIST_AND
const LIST_AND
Definition: Defines.php:43
Wikimedia\Rdbms\DatabaseMssql\tableExists
tableExists( $table, $fname=__METHOD__)
Definition: DatabaseMssql.php:1003
Wikimedia\Rdbms\DatabaseMssql\nativeInsertSelect
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper $varMap must be an associative array of the form [ 'dest1' => 'source1',...
Definition: DatabaseMssql.php:763
Wikimedia\Rdbms\Database\assertBuildSubstringParams
assertBuildSubstringParams( $startPosition, $length)
Check type and bounds for parameters to self::buildSubstring()
Definition: Database.php:2263
user
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Definition: distributors.txt:9
Wikimedia\Rdbms\DatabaseMssql\unionSupportsOrderAndLimit
unionSupportsOrderAndLimit()
Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries within th...
Definition: DatabaseMssql.php:69
Wikimedia\Rdbms\DatabaseMssql\doCommit
doCommit( $fname=__METHOD__)
End a transaction.
Definition: DatabaseMssql.php:1099
$blob
$blob
Definition: testCompression.php:65
Wikimedia\Rdbms\DatabaseMssql\closeConnection
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
Definition: DatabaseMssql.php:136
tableName
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
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:579
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:141
Wikimedia\Rdbms\DatabaseMssql\$lastInsertId
int null $lastInsertId
Definition: DatabaseMssql.php:43
$matches
$matches
Definition: NoLocalSettings.php:24
Wikimedia\Rdbms\DatabaseMssql\open
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
Definition: DatabaseMssql.php:80
Wikimedia\Rdbms\DatabaseMssql\fieldInfo
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
Definition: DatabaseMssql.php:1053
Wikimedia\Rdbms\DatabaseMssql\estimateRowCount
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate rows in dataset Returns estimated count, based on SHOWPLAN_ALL output This is not necessaril...
Definition: DatabaseMssql.php:532
LIST_SET
const LIST_SET
Definition: Defines.php:44
Wikimedia\Rdbms\DatabaseMssql\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
MS SQL supports more pattern operators than other databases (ex: [,],^)
Definition: DatabaseMssql.php:1167
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
Wikimedia\Rdbms\Database\$user
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:81
Wikimedia\Rdbms\MssqlBlob
Definition: MssqlBlob.php:5
Wikimedia\Rdbms\DatabaseMssql\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
SELECT wrapper.
Definition: DatabaseMssql.php:404
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2270
Wikimedia\Rdbms\DatabaseMssql\fetchRow
fetchRow( $res)
Definition: DatabaseMssql.php:253
Wikimedia\Rdbms\DatabaseMssql\prepareStatements
prepareStatements( $value=null)
Called in the installer and updater.
Definition: DatabaseMssql.php:1382
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
Wikimedia\Rdbms\MssqlField
Definition: MssqlField.php:5
list
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
Wikimedia\Rdbms\DatabaseMssql\fetchAffectedRowCount
fetchAffectedRowCount()
Definition: DatabaseMssql.php:382
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
Wikimedia\Rdbms\DatabaseMssql\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Definition: DatabaseMssql.php:1174
Wikimedia\Rdbms\Database\makeUpdateOptions
makeUpdateOptions( $options)
Make UPDATE options for the Database::update function.
Definition: Database.php:2097
LIST_COMMA
const LIST_COMMA
Definition: Defines.php:42
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:121
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
Wikimedia\Rdbms\DatabaseMssql\strencode
strencode( $s)
Definition: DatabaseMssql.php:1118
Wikimedia\Rdbms\DatabaseMssql\numRows
numRows( $res)
Definition: DatabaseMssql.php:261
Wikimedia\Rdbms\DatabaseMssql\doRollback
doRollback( $fname=__METHOD__)
Rollback a transaction.
Definition: DatabaseMssql.php:1109
Wikimedia\Rdbms\DatabaseMssql\selectSQLText
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
SELECT wrapper.
Definition: DatabaseMssql.php:456
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2213
$value
$value
Definition: styleTest.css.php:49
Wikimedia\Rdbms\DatabaseMssql\$ignoreErrors
string[] $ignoreErrors
Definition: DatabaseMssql.php:59
Wikimedia\Rdbms\DatabaseMssql\lastError
lastError()
Definition: DatabaseMssql.php:322
Wikimedia\Rdbms\DatabaseMssql\fetchObject
fetchObject( $res)
Definition: DatabaseMssql.php:244
Wikimedia\Rdbms\DatabaseMssql\addQuotes
addQuotes( $s)
Definition: DatabaseMssql.php:1127
Wikimedia\Rdbms\DatabaseMssql\doBegin
doBegin( $fname=__METHOD__)
Begin a transaction, committing any previously open transaction.
Definition: DatabaseMssql.php:1090
Wikimedia\Rdbms\DatabaseMssql\insertId
insertId()
This must be called after nextSequenceVal.
Definition: DatabaseMssql.php:306
Wikimedia\Rdbms\DatabaseMssql\textFieldSize
textFieldSize( $table, $field)
Definition: DatabaseMssql.php:883
Wikimedia\Rdbms\DatabaseMssql\doRollbackToSavepoint
doRollbackToSavepoint( $identifier, $fname)
Rollback to a savepoint.
Definition: DatabaseMssql.php:1082
Wikimedia\Rdbms\DatabaseMssql\getBinaryColumns
getBinaryColumns( $table)
Returns an associative array for fields that are of type varbinary, binary, or image $table can be ei...
Definition: DatabaseMssql.php:1279
$ret
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:2036
Wikimedia\Rdbms\DatabaseMssql\formatError
formatError( $err)
Definition: DatabaseMssql.php:340
Wikimedia\Rdbms\Database\$conn
resource null $conn
Database connection.
Definition: Database.php:106
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition: Database.php:1126
Wikimedia\Rdbms\DatabaseMssql\makeSelectOptions
makeSelectOptions( $options)
Definition: DatabaseMssql.php:1188
Wikimedia\Rdbms\DatabaseMssql\$lastAffectedRowCount
int null $lastAffectedRowCount
Definition: DatabaseMssql.php:45
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:27
Wikimedia\Rdbms\MssqlResultWrapper
Definition: MssqlResultWrapper.php:7
Wikimedia\Rdbms\DatabaseMssql\doQuery
doQuery( $sql)
Definition: DatabaseMssql.php:162
Wikimedia\Rdbms\Database\dbSchema
dbSchema( $schema=null)
Get/set the db schema.
Definition: Database.php:608
Wikimedia\Rdbms\Database\close
close()
Close the database connection.
Definition: Database.php:917
Wikimedia\Rdbms\DatabaseMssql\fieldName
fieldName( $res, $n)
Definition: DatabaseMssql.php:294
$rows
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2675
Wikimedia\Rdbms\DatabaseMssql\getBitColumns
getBitColumns( $table)
Definition: DatabaseMssql.php:1294
$options
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 & $options
Definition: hooks.txt:2036
Wikimedia\Rdbms\DatabaseMssql\$subqueryId
int $subqueryId
Definition: DatabaseMssql.php:47
Wikimedia\Rdbms\Database\makeGroupByWithHaving
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1650
as
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
Definition: distributors.txt:9
Wikimedia\Rdbms\DatabaseMssql
Definition: DatabaseMssql.php:37
Wikimedia\Rdbms\DatabaseMssql\LimitToTopN
LimitToTopN( $sql)
If there is a limit clause, parse it, strip it, and pass the remaining SQL through limitResult() with...
Definition: DatabaseMssql.php:962
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
Wikimedia
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:79
$keys
$keys
Definition: testCompression.php:67
Wikimedia\Rdbms\Database\makeOrderBy
makeOrderBy( $options)
Returns an optional ORDER BY.
Definition: Database.php:1676
Wikimedia\Rdbms\DatabaseMssql\buildSubstring
buildSubstring( $input, $startPosition, $length=null)
Definition: DatabaseMssql.php:1260
Wikimedia\Rdbms\DatabaseMssql\$scrollableCursor
bool $scrollableCursor
Definition: DatabaseMssql.php:49
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
$t
$t
Definition: testCompression.php:69
Wikimedia\Rdbms\DatabaseMssql\doReleaseSavepoint
doReleaseSavepoint( $identifier, $fname)
Release a savepoint.
Definition: DatabaseMssql.php:1077
Wikimedia\Rdbms\DatabaseMssql\tableName
tableName( $name, $format='quoted')
Definition: DatabaseMssql.php:1329
LIST_NAMES
const LIST_NAMES
Definition: Defines.php:45
Wikimedia\Rdbms\DatabaseMssql\doSavepoint
doSavepoint( $identifier, $fname)
Create a savepoint.
Definition: DatabaseMssql.php:1073
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/prefix specification for IDatabase domains.
Definition: DatabaseDomain.php:28
server
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break but it is *strongly *advised not to try any more intrusive changes to get MediaWiki to conform more closely to your filesystem hierarchy Any such attempt will almost certainly result in unnecessary bugs The standard recommended location to install relative to the web is it should be possible to enable the appropriate rewrite rules by if you can reconfigure the web server
Definition: distributors.txt:53
Wikimedia\Rdbms\DatabaseMssql\getSoftwareLink
getSoftwareLink()
Definition: DatabaseMssql.php:981
Wikimedia\Rdbms\DatabaseMssql\scrollableCursor
scrollableCursor( $value=null)
Called in the installer and updater.
Definition: DatabaseMssql.php:1397
Wikimedia\Rdbms\DatabaseMssql\numFields
numFields( $res)
Definition: DatabaseMssql.php:281
Wikimedia\Rdbms\DatabaseMssql\addIdentifierQuotes
addIdentifierQuotes( $s)
Definition: DatabaseMssql.php:1147
Wikimedia\Rdbms\DatabaseMssql\$serverPort
int $serverPort
Definition: DatabaseMssql.php:39
Wikimedia\Rdbms\DatabaseMssql\fieldExists
fieldExists( $table, $field, $fname=__METHOD__)
Query whether a given column exists in the mediawiki schema.
Definition: DatabaseMssql.php:1034
Wikimedia\Rdbms\Database\getDBname
getDBname()
Get the current DB name.
Definition: Database.php:2315
Wikimedia\Rdbms\Blob
Definition: Blob.php:5