MediaWiki  1.28.1
DatabaseOracle.php
Go to the documentation of this file.
1 <?php
30 class ORAResult {
31  private $rows;
32  private $cursor;
33  private $nrows;
34 
35  private $columns = [];
36 
37  private function array_unique_md( $array_in ) {
38  $array_out = [];
39  $array_hashes = [];
40 
41  foreach ( $array_in as $item ) {
42  $hash = md5( serialize( $item ) );
43  if ( !isset( $array_hashes[$hash] ) ) {
44  $array_hashes[$hash] = $hash;
45  $array_out[] = $item;
46  }
47  }
48 
49  return $array_out;
50  }
51 
57  function __construct( &$db, $stmt, $unique = false ) {
58  $this->db =& $db;
59 
60  $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM );
61  if ( $this->nrows === false ) {
62  $e = oci_error( $stmt );
63  $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
64  $this->free();
65 
66  return;
67  }
68 
69  if ( $unique ) {
70  $this->rows = $this->array_unique_md( $this->rows );
71  $this->nrows = count( $this->rows );
72  }
73 
74  if ( $this->nrows > 0 ) {
75  foreach ( $this->rows[0] as $k => $v ) {
76  $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
77  }
78  }
79 
80  $this->cursor = 0;
81  oci_free_statement( $stmt );
82  }
83 
84  public function free() {
85  unset( $this->db );
86  }
87 
88  public function seek( $row ) {
89  $this->cursor = min( $row, $this->nrows );
90  }
91 
92  public function numRows() {
93  return $this->nrows;
94  }
95 
96  public function numFields() {
97  return count( $this->columns );
98  }
99 
100  public function fetchObject() {
101  if ( $this->cursor >= $this->nrows ) {
102  return false;
103  }
104  $row = $this->rows[$this->cursor++];
105  $ret = new stdClass();
106  foreach ( $row as $k => $v ) {
107  $lc = $this->columns[$k];
108  $ret->$lc = $v;
109  }
110 
111  return $ret;
112  }
113 
114  public function fetchRow() {
115  if ( $this->cursor >= $this->nrows ) {
116  return false;
117  }
118 
119  $row = $this->rows[$this->cursor++];
120  $ret = [];
121  foreach ( $row as $k => $v ) {
122  $lc = $this->columns[$k];
123  $ret[$lc] = $v;
124  $ret[$k] = $v;
125  }
126 
127  return $ret;
128  }
129 }
130 
134 class DatabaseOracle extends DatabaseBase {
136  protected $mLastResult = null;
137 
139  protected $mAffectedRows;
140 
142  private $mInsertId = null;
143 
145  private $ignoreDupValOnIndex = false;
146 
148  private $sequenceData = null;
149 
151  private $defaultCharset = 'AL32UTF8';
152 
154  private $mFieldInfoCache = [];
155 
156  function __construct( array $p ) {
158 
159  if ( $p['tablePrefix'] == 'get from global' ) {
160  $p['tablePrefix'] = $wgDBprefix;
161  }
162  $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
163  parent::__construct( $p );
164  Hooks::run( 'DatabaseOraclePostInit', [ $this ] );
165  }
166 
167  function __destruct() {
168  if ( $this->mOpened ) {
169  MediaWiki\suppressWarnings();
170  $this->close();
171  MediaWiki\restoreWarnings();
172  }
173  }
174 
175  function getType() {
176  return 'oracle';
177  }
178 
179  function implicitGroupby() {
180  return false;
181  }
182 
183  function implicitOrderby() {
184  return false;
185  }
186 
196  function open( $server, $user, $password, $dbName ) {
198  if ( !function_exists( 'oci_connect' ) ) {
199  throw new DBConnectionError(
200  $this,
201  "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
202  "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
203  "and database)\n" );
204  }
205 
206  $this->close();
207  $this->mUser = $user;
208  $this->mPassword = $password;
209  // changed internal variables functions
210  // mServer now holds the TNS endpoint
211  // mDBname is schema name if different from username
212  if ( !$server ) {
213  // backward compatibillity (server used to be null and TNS was supplied in dbname)
214  $this->mServer = $dbName;
215  $this->mDBname = $user;
216  } else {
217  $this->mServer = $server;
218  if ( !$dbName ) {
219  $this->mDBname = $user;
220  } else {
221  $this->mDBname = $dbName;
222  }
223  }
224 
225  if ( !strlen( $user ) ) { # e.g. the class is being loaded
226  return null;
227  }
228 
229  if ( $wgDBOracleDRCP ) {
230  $this->setFlag( DBO_PERSISTENT );
231  }
232 
233  $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
234 
235  MediaWiki\suppressWarnings();
236  if ( $this->mFlags & DBO_PERSISTENT ) {
237  $this->mConn = oci_pconnect(
238  $this->mUser,
239  $this->mPassword,
240  $this->mServer,
241  $this->defaultCharset,
242  $session_mode
243  );
244  } elseif ( $this->mFlags & DBO_DEFAULT ) {
245  $this->mConn = oci_new_connect(
246  $this->mUser,
247  $this->mPassword,
248  $this->mServer,
249  $this->defaultCharset,
250  $session_mode
251  );
252  } else {
253  $this->mConn = oci_connect(
254  $this->mUser,
255  $this->mPassword,
256  $this->mServer,
257  $this->defaultCharset,
258  $session_mode
259  );
260  }
261  MediaWiki\restoreWarnings();
262 
263  if ( $this->mUser != $this->mDBname ) {
264  // change current schema in session
265  $this->selectDB( $this->mDBname );
266  }
267 
268  if ( !$this->mConn ) {
269  throw new DBConnectionError( $this, $this->lastError() );
270  }
271 
272  $this->mOpened = true;
273 
274  # removed putenv calls because they interfere with the system globaly
275  $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
276  $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
277  $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
278 
279  return $this->mConn;
280  }
281 
287  protected function closeConnection() {
288  return oci_close( $this->mConn );
289  }
290 
291  function execFlags() {
292  return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
293  }
294 
295  protected function doQuery( $sql ) {
296  wfDebug( "SQL: [$sql]\n" );
297  if ( !StringUtils::isUtf8( $sql ) ) {
298  throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
299  }
300 
301  // handle some oracle specifics
302  // remove AS column/table/subquery namings
303  if ( !$this->getFlag( DBO_DDLMODE ) ) {
304  $sql = preg_replace( '/ as /i', ' ', $sql );
305  }
306 
307  // Oracle has issues with UNION clause if the statement includes LOB fields
308  // So we do a UNION ALL and then filter the results array with array_unique
309  $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
310  // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
311  // you have to select data from plan table after explain
312  $explain_id = MWTimestamp::getLocalInstance()->format( 'dmYHis' );
313 
314  $sql = preg_replace(
315  '/^EXPLAIN /',
316  'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
317  $sql,
318  1,
319  $explain_count
320  );
321 
322  MediaWiki\suppressWarnings();
323 
324  $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql );
325  if ( $stmt === false ) {
326  $e = oci_error( $this->mConn );
327  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
328 
329  return false;
330  }
331 
332  if ( !oci_execute( $stmt, $this->execFlags() ) ) {
333  $e = oci_error( $stmt );
334  if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
335  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
336 
337  return false;
338  }
339  }
340 
341  MediaWiki\restoreWarnings();
342 
343  if ( $explain_count > 0 ) {
344  return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
345  'WHERE statement_id = \'' . $explain_id . '\'' );
346  } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
347  return new ORAResult( $this, $stmt, $union_unique );
348  } else {
349  $this->mAffectedRows = oci_num_rows( $stmt );
350 
351  return true;
352  }
353  }
354 
355  function queryIgnore( $sql, $fname = '' ) {
356  return $this->query( $sql, $fname, true );
357  }
358 
363  function freeResult( $res ) {
364  if ( $res instanceof ResultWrapper ) {
365  $res = $res->result;
366  }
367 
368  $res->free();
369  }
370 
375  function fetchObject( $res ) {
376  if ( $res instanceof ResultWrapper ) {
377  $res = $res->result;
378  }
379 
380  return $res->fetchObject();
381  }
382 
387  function fetchRow( $res ) {
388  if ( $res instanceof ResultWrapper ) {
389  $res = $res->result;
390  }
391 
392  return $res->fetchRow();
393  }
394 
399  function numRows( $res ) {
400  if ( $res instanceof ResultWrapper ) {
401  $res = $res->result;
402  }
403 
404  return $res->numRows();
405  }
406 
411  function numFields( $res ) {
412  if ( $res instanceof ResultWrapper ) {
413  $res = $res->result;
414  }
415 
416  return $res->numFields();
417  }
418 
419  function fieldName( $stmt, $n ) {
420  return oci_field_name( $stmt, $n );
421  }
422 
427  function insertId() {
428  return $this->mInsertId;
429  }
430 
435  function dataSeek( $res, $row ) {
436  if ( $res instanceof ORAResult ) {
437  $res->seek( $row );
438  } else {
439  $res->result->seek( $row );
440  }
441  }
442 
443  function lastError() {
444  if ( $this->mConn === false ) {
445  $e = oci_error();
446  } else {
447  $e = oci_error( $this->mConn );
448  }
449 
450  return $e['message'];
451  }
452 
453  function lastErrno() {
454  if ( $this->mConn === false ) {
455  $e = oci_error();
456  } else {
457  $e = oci_error( $this->mConn );
458  }
459 
460  return $e['code'];
461  }
462 
463  function affectedRows() {
464  return $this->mAffectedRows;
465  }
466 
475  function indexInfo( $table, $index, $fname = __METHOD__ ) {
476  return false;
477  }
478 
479  function indexUnique( $table, $index, $fname = __METHOD__ ) {
480  return false;
481  }
482 
483  function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
484  if ( !count( $a ) ) {
485  return true;
486  }
487 
488  if ( !is_array( $options ) ) {
489  $options = [ $options ];
490  }
491 
492  if ( in_array( 'IGNORE', $options ) ) {
493  $this->ignoreDupValOnIndex = true;
494  }
495 
496  if ( !is_array( reset( $a ) ) ) {
497  $a = [ $a ];
498  }
499 
500  foreach ( $a as &$row ) {
501  $this->insertOneRow( $table, $row, $fname );
502  }
503  $retVal = true;
504 
505  if ( in_array( 'IGNORE', $options ) ) {
506  $this->ignoreDupValOnIndex = false;
507  }
508 
509  return $retVal;
510  }
511 
512  private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
513  $col_info = $this->fieldInfoMulti( $table, $col );
514  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
515 
516  $bind = '';
517  if ( is_numeric( $col ) ) {
518  $bind = $val;
519  $val = null;
520 
521  return $bind;
522  } elseif ( $includeCol ) {
523  $bind = "$col = ";
524  }
525 
526  if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
527  $val = null;
528  }
529 
530  if ( $val === 'NULL' ) {
531  $val = null;
532  }
533 
534  if ( $val === null ) {
535  if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
536  $bind .= 'DEFAULT';
537  } else {
538  $bind .= 'NULL';
539  }
540  } else {
541  $bind .= ':' . $col;
542  }
543 
544  return $bind;
545  }
546 
554  private function insertOneRow( $table, $row, $fname ) {
556 
557  $table = $this->tableName( $table );
558  // "INSERT INTO tables (a, b, c)"
559  $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
560  $sql .= " VALUES (";
561 
562  // for each value, append ":key"
563  $first = true;
564  foreach ( $row as $col => &$val ) {
565  if ( !$first ) {
566  $sql .= ', ';
567  } else {
568  $first = false;
569  }
570  if ( $this->isQuotedIdentifier( $val ) ) {
571  $sql .= $this->removeIdentifierQuotes( $val );
572  unset( $row[$col] );
573  } else {
574  $sql .= $this->fieldBindStatement( $table, $col, $val );
575  }
576  }
577  $sql .= ')';
578 
579  $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql );
580  if ( $stmt === false ) {
581  $e = oci_error( $this->mConn );
582  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
583 
584  return false;
585  }
586  foreach ( $row as $col => &$val ) {
587  $col_info = $this->fieldInfoMulti( $table, $col );
588  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
589 
590  if ( $val === null ) {
591  // do nothing ... null was inserted in statement creation
592  } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
593  if ( is_object( $val ) ) {
594  $val = $val->fetch();
595  }
596 
597  // backward compatibility
598  if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
599  $val = $this->getInfinity();
600  }
601 
602  $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
603  if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
604  $e = oci_error( $stmt );
605  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
606 
607  return false;
608  }
609  } else {
611  $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB );
612  if ( $lob[$col] === false ) {
613  $e = oci_error( $stmt );
614  throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
615  }
616 
617  if ( is_object( $val ) ) {
618  $val = $val->fetch();
619  }
620 
621  if ( $col_type == 'BLOB' ) {
622  $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
623  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB );
624  } else {
625  $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
626  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
627  }
628  }
629  }
630 
631  MediaWiki\suppressWarnings();
632 
633  if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
634  $e = oci_error( $stmt );
635  if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
636  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
637 
638  return false;
639  } else {
640  $this->mAffectedRows = oci_num_rows( $stmt );
641  }
642  } else {
643  $this->mAffectedRows = oci_num_rows( $stmt );
644  }
645 
646  MediaWiki\restoreWarnings();
647 
648  if ( isset( $lob ) ) {
649  foreach ( $lob as $lob_v ) {
650  $lob_v->free();
651  }
652  }
653 
654  if ( !$this->mTrxLevel ) {
655  oci_commit( $this->mConn );
656  }
657 
658  return oci_free_statement( $stmt );
659  }
660 
661  function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
662  $insertOptions = [], $selectOptions = []
663  ) {
664  $destTable = $this->tableName( $destTable );
665  if ( !is_array( $selectOptions ) ) {
666  $selectOptions = [ $selectOptions ];
667  }
668  list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
669  $this->makeSelectOptions( $selectOptions );
670  if ( is_array( $srcTable ) ) {
671  $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
672  } else {
673  $srcTable = $this->tableName( $srcTable );
674  }
675 
676  $sequenceData = $this->getSequenceData( $destTable );
677  if ( $sequenceData !== false &&
678  !isset( $varMap[$sequenceData['column']] )
679  ) {
680  $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
681  }
682 
683  // count-alias subselect fields to avoid abigious definition errors
684  $i = 0;
685  foreach ( $varMap as &$val ) {
686  $val = $val . ' field' . ( $i++ );
687  }
688 
689  $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
690  " SELECT $startOpts " . implode( ',', $varMap ) .
691  " FROM $srcTable $useIndex $ignoreIndex ";
692  if ( $conds != '*' ) {
693  $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
694  }
695  $sql .= " $tailOpts";
696 
697  if ( in_array( 'IGNORE', $insertOptions ) ) {
698  $this->ignoreDupValOnIndex = true;
699  }
700 
701  $retval = $this->query( $sql, $fname );
702 
703  if ( in_array( 'IGNORE', $insertOptions ) ) {
704  $this->ignoreDupValOnIndex = false;
705  }
706 
707  return $retval;
708  }
709 
710  public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
711  $fname = __METHOD__
712  ) {
713  if ( !count( $rows ) ) {
714  return true; // nothing to do
715  }
716 
717  if ( !is_array( reset( $rows ) ) ) {
718  $rows = [ $rows ];
719  }
720 
721  $sequenceData = $this->getSequenceData( $table );
722  if ( $sequenceData !== false ) {
723  // add sequence column to each list of columns, when not set
724  foreach ( $rows as &$row ) {
725  if ( !isset( $row[$sequenceData['column']] ) ) {
726  $row[$sequenceData['column']] =
727  $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
728  $sequenceData['sequence'] . '\')' );
729  }
730  }
731  }
732 
733  return parent::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
734  }
735 
736  function tableName( $name, $format = 'quoted' ) {
737  /*
738  Replace reserved words with better ones
739  Using uppercase because that's the only way Oracle can handle
740  quoted tablenames
741  */
742  switch ( $name ) {
743  case 'user':
744  $name = 'MWUSER';
745  break;
746  case 'text':
747  $name = 'PAGECONTENT';
748  break;
749  }
750 
751  return strtoupper( parent::tableName( $name, $format ) );
752  }
753 
754  function tableNameInternal( $name ) {
755  $name = $this->tableName( $name );
756 
757  return preg_replace( '/.*\.(.*)/', '$1', $name );
758  }
759 
766  function nextSequenceValue( $seqName ) {
767  $res = $this->query( "SELECT $seqName.nextval FROM dual" );
768  $row = $this->fetchRow( $res );
769  $this->mInsertId = $row[0];
770 
771  return $this->mInsertId;
772  }
773 
780  private function getSequenceData( $table ) {
781  if ( $this->sequenceData == null ) {
782  $result = $this->doQuery( "SELECT lower(asq.sequence_name),
783  lower(atc.table_name),
784  lower(atc.column_name)
785  FROM all_sequences asq, all_tab_columns atc
786  WHERE decode(
787  atc.table_name,
788  '{$this->mTablePrefix}MWUSER',
789  '{$this->mTablePrefix}USER',
790  atc.table_name
791  ) || '_' ||
792  atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
793  AND asq.sequence_owner = upper('{$this->mDBname}')
794  AND atc.owner = upper('{$this->mDBname}')" );
795 
796  while ( ( $row = $result->fetchRow() ) !== false ) {
797  $this->sequenceData[$row[1]] = [
798  'sequence' => $row[0],
799  'column' => $row[2]
800  ];
801  }
802  }
803  $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
804 
805  return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
806  }
807 
815  function textFieldSize( $table, $field ) {
816  $fieldInfoData = $this->fieldInfo( $table, $field );
817 
818  return $fieldInfoData->maxLength();
819  }
820 
821  function limitResult( $sql, $limit, $offset = false ) {
822  if ( $offset === false ) {
823  $offset = 0;
824  }
825 
826  return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
827  }
828 
829  function encodeBlob( $b ) {
830  return new Blob( $b );
831  }
832 
833  function decodeBlob( $b ) {
834  if ( $b instanceof Blob ) {
835  $b = $b->fetch();
836  }
837 
838  return $b;
839  }
840 
841  function unionQueries( $sqls, $all ) {
842  $glue = ' UNION ALL ';
843 
844  return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) .
845  'FROM (' . implode( $glue, $sqls ) . ')';
846  }
847 
848  function wasDeadlock() {
849  return $this->lastErrno() == 'OCI-00060';
850  }
851 
852  function duplicateTableStructure( $oldName, $newName, $temporary = false,
853  $fname = __METHOD__
854  ) {
855  $temporary = $temporary ? 'TRUE' : 'FALSE';
856 
857  $newName = strtoupper( $newName );
858  $oldName = strtoupper( $oldName );
859 
860  $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
861  $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
862  $newPrefix = strtoupper( $this->mTablePrefix );
863 
864  return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
865  "'$oldPrefix', '$newPrefix', $temporary ); END;" );
866  }
867 
868  function listTables( $prefix = null, $fname = __METHOD__ ) {
869  $listWhere = '';
870  if ( !empty( $prefix ) ) {
871  $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
872  }
873 
874  $owner = strtoupper( $this->mDBname );
875  $result = $this->doQuery( "SELECT table_name FROM all_tables " .
876  "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
877 
878  // dirty code ... i know
879  $endArray = [];
880  $endArray[] = strtoupper( $prefix . 'MWUSER' );
881  $endArray[] = strtoupper( $prefix . 'PAGE' );
882  $endArray[] = strtoupper( $prefix . 'IMAGE' );
883  $fixedOrderTabs = $endArray;
884  while ( ( $row = $result->fetchRow() ) !== false ) {
885  if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
886  $endArray[] = $row['table_name'];
887  }
888  }
889 
890  return $endArray;
891  }
892 
893  public function dropTable( $tableName, $fName = __METHOD__ ) {
894  $tableName = $this->tableName( $tableName );
895  if ( !$this->tableExists( $tableName ) ) {
896  return false;
897  }
898 
899  return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
900  }
901 
902  function timestamp( $ts = 0 ) {
903  return wfTimestamp( TS_ORACLE, $ts );
904  }
905 
913  public function aggregateValue( $valuedata, $valuename = 'value' ) {
914  return $valuedata;
915  }
916 
920  public function getSoftwareLink() {
921  return '[{{int:version-db-oracle-url}} Oracle]';
922  }
923 
927  function getServerVersion() {
928  // better version number, fallback on driver
929  $rset = $this->doQuery(
930  'SELECT version FROM product_component_version ' .
931  'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
932  );
933  $row = $rset->fetchRow();
934  if ( !$row ) {
935  return oci_server_version( $this->mConn );
936  }
937 
938  return $row['version'];
939  }
940 
948  function indexExists( $table, $index, $fname = __METHOD__ ) {
949  $table = $this->tableName( $table );
950  $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
951  $index = strtoupper( $index );
952  $owner = strtoupper( $this->mDBname );
953  $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
954  $res = $this->doQuery( $sql );
955  if ( $res ) {
956  $count = $res->numRows();
957  $res->free();
958  } else {
959  $count = 0;
960  }
961 
962  return $count != 0;
963  }
964 
971  function tableExists( $table, $fname = __METHOD__ ) {
972  $table = $this->tableName( $table );
973  $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
974  $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
975  $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
976  $res = $this->doQuery( $sql );
977  if ( $res && $res->numRows() > 0 ) {
978  $exists = true;
979  } else {
980  $exists = false;
981  }
982 
983  $res->free();
984 
985  return $exists;
986  }
987 
998  private function fieldInfoMulti( $table, $field ) {
999  $field = strtoupper( $field );
1000  if ( is_array( $table ) ) {
1001  $table = array_map( [ &$this, 'tableNameInternal' ], $table );
1002  $tableWhere = 'IN (';
1003  foreach ( $table as &$singleTable ) {
1004  $singleTable = $this->removeIdentifierQuotes( $singleTable );
1005  if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
1006  return $this->mFieldInfoCache["$singleTable.$field"];
1007  }
1008  $tableWhere .= '\'' . $singleTable . '\',';
1009  }
1010  $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1011  } else {
1012  $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1013  if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
1014  return $this->mFieldInfoCache["$table.$field"];
1015  }
1016  $tableWhere = '= \'' . $table . '\'';
1017  }
1018 
1019  $fieldInfoStmt = oci_parse(
1020  $this->mConn,
1021  'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1022  $tableWhere . ' and column_name = \'' . $field . '\''
1023  );
1024  if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1025  $e = oci_error( $fieldInfoStmt );
1026  $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
1027 
1028  return false;
1029  }
1030  $res = new ORAResult( $this, $fieldInfoStmt );
1031  if ( $res->numRows() == 0 ) {
1032  if ( is_array( $table ) ) {
1033  foreach ( $table as &$singleTable ) {
1034  $this->mFieldInfoCache["$singleTable.$field"] = false;
1035  }
1036  } else {
1037  $this->mFieldInfoCache["$table.$field"] = false;
1038  }
1039  $fieldInfoTemp = null;
1040  } else {
1041  $fieldInfoTemp = new ORAField( $res->fetchRow() );
1042  $table = $fieldInfoTemp->tableName();
1043  $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
1044  }
1045  $res->free();
1046 
1047  return $fieldInfoTemp;
1048  }
1049 
1056  function fieldInfo( $table, $field ) {
1057  if ( is_array( $table ) ) {
1058  throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1059  }
1060 
1061  return $this->fieldInfoMulti( $table, $field );
1062  }
1063 
1064  protected function doBegin( $fname = __METHOD__ ) {
1065  $this->mTrxLevel = 1;
1066  $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1067  }
1068 
1069  protected function doCommit( $fname = __METHOD__ ) {
1070  if ( $this->mTrxLevel ) {
1071  $ret = oci_commit( $this->mConn );
1072  if ( !$ret ) {
1073  throw new DBUnexpectedError( $this, $this->lastError() );
1074  }
1075  $this->mTrxLevel = 0;
1076  $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1077  }
1078  }
1079 
1080  protected function doRollback( $fname = __METHOD__ ) {
1081  if ( $this->mTrxLevel ) {
1082  oci_rollback( $this->mConn );
1083  $this->mTrxLevel = 0;
1084  $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1085  }
1086  }
1087 
1098  function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
1099  $fname = __METHOD__, $inputCallback = false ) {
1100  $cmd = '';
1101  $done = false;
1102  $dollarquote = false;
1103 
1104  $replacements = [];
1105 
1106  while ( !feof( $fp ) ) {
1107  if ( $lineCallback ) {
1108  call_user_func( $lineCallback );
1109  }
1110  $line = trim( fgets( $fp, 1024 ) );
1111  $sl = strlen( $line ) - 1;
1112 
1113  if ( $sl < 0 ) {
1114  continue;
1115  }
1116  if ( '-' == $line[0] && '-' == $line[1] ) {
1117  continue;
1118  }
1119 
1120  // Allow dollar quoting for function declarations
1121  if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1122  if ( $dollarquote ) {
1123  $dollarquote = false;
1124  $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1125  $done = true;
1126  } else {
1127  $dollarquote = true;
1128  }
1129  } elseif ( !$dollarquote ) {
1130  if ( ';' == $line[$sl] && ( $sl < 2 || ';' != $line[$sl - 1] ) ) {
1131  $done = true;
1132  $line = substr( $line, 0, $sl );
1133  }
1134  }
1135 
1136  if ( $cmd != '' ) {
1137  $cmd .= ' ';
1138  }
1139  $cmd .= "$line\n";
1140 
1141  if ( $done ) {
1142  $cmd = str_replace( ';;', ";", $cmd );
1143  if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1144  if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1145  $replacements[$defines[2]] = $defines[1];
1146  }
1147  } else {
1148  foreach ( $replacements as $mwVar => $scVar ) {
1149  $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1150  }
1151 
1152  $cmd = $this->replaceVars( $cmd );
1153  if ( $inputCallback ) {
1154  call_user_func( $inputCallback, $cmd );
1155  }
1156  $res = $this->doQuery( $cmd );
1157  if ( $resultCallback ) {
1158  call_user_func( $resultCallback, $res, $this );
1159  }
1160 
1161  if ( false === $res ) {
1162  $err = $this->lastError();
1163 
1164  return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1165  }
1166  }
1167 
1168  $cmd = '';
1169  $done = false;
1170  }
1171  }
1172 
1173  return true;
1174  }
1175 
1176  function selectDB( $db ) {
1177  $this->mDBname = $db;
1178  if ( $db == null || $db == $this->mUser ) {
1179  return true;
1180  }
1181  $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1182  $stmt = oci_parse( $this->mConn, $sql );
1183  MediaWiki\suppressWarnings();
1184  $success = oci_execute( $stmt );
1185  MediaWiki\restoreWarnings();
1186  if ( !$success ) {
1187  $e = oci_error( $stmt );
1188  if ( $e['code'] != '1435' ) {
1189  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1190  }
1191 
1192  return false;
1193  }
1194 
1195  return true;
1196  }
1197 
1198  function strencode( $s ) {
1199  return str_replace( "'", "''", $s );
1200  }
1201 
1202  function addQuotes( $s ) {
1204  if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1205  $s = $wgContLang->checkTitleEncoding( $s );
1206  }
1207 
1208  return "'" . $this->strencode( $s ) . "'";
1209  }
1210 
1211  public function addIdentifierQuotes( $s ) {
1212  if ( !$this->getFlag( DBO_DDLMODE ) ) {
1213  $s = '/*Q*/' . $s;
1214  }
1215 
1216  return $s;
1217  }
1218 
1219  public function removeIdentifierQuotes( $s ) {
1220  return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1221  }
1222 
1223  public function isQuotedIdentifier( $s ) {
1224  return strpos( $s, '/*Q*/' ) !== false;
1225  }
1226 
1227  private function wrapFieldForWhere( $table, &$col, &$val ) {
1229 
1230  $col_info = $this->fieldInfoMulti( $table, $col );
1231  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1232  if ( $col_type == 'CLOB' ) {
1233  $col = 'TO_CHAR(' . $col . ')';
1234  $val = $wgContLang->checkTitleEncoding( $val );
1235  } elseif ( $col_type == 'VARCHAR2' ) {
1236  $val = $wgContLang->checkTitleEncoding( $val );
1237  }
1238  }
1239 
1240  private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1241  $conds2 = [];
1242  foreach ( $conds as $col => $val ) {
1243  if ( is_array( $val ) ) {
1244  $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1245  } else {
1246  if ( is_numeric( $col ) && $parentCol != null ) {
1247  $this->wrapFieldForWhere( $table, $parentCol, $val );
1248  } else {
1249  $this->wrapFieldForWhere( $table, $col, $val );
1250  }
1251  $conds2[$col] = $val;
1252  }
1253  }
1254 
1255  return $conds2;
1256  }
1257 
1258  function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1259  $options = [], $join_conds = []
1260  ) {
1261  if ( is_array( $conds ) ) {
1262  $conds = $this->wrapConditionsForWhere( $table, $conds );
1263  }
1264 
1265  return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1266  }
1267 
1277  $preLimitTail = $postLimitTail = '';
1278  $startOpts = '';
1279 
1280  $noKeyOptions = [];
1281  foreach ( $options as $key => $option ) {
1282  if ( is_numeric( $key ) ) {
1283  $noKeyOptions[$option] = true;
1284  }
1285  }
1286 
1287  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1288 
1289  $preLimitTail .= $this->makeOrderBy( $options );
1290 
1291  if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1292  $postLimitTail .= ' FOR UPDATE';
1293  }
1294 
1295  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1296  $startOpts .= 'DISTINCT';
1297  }
1298 
1299  if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1300  $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1301  } else {
1302  $useIndex = '';
1303  }
1304 
1305  if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1306  $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1307  } else {
1308  $ignoreIndex = '';
1309  }
1310 
1311  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1312  }
1313 
1314  public function delete( $table, $conds, $fname = __METHOD__ ) {
1315  if ( is_array( $conds ) ) {
1316  $conds = $this->wrapConditionsForWhere( $table, $conds );
1317  }
1318  // a hack for deleting pages, users and images (which have non-nullable FKs)
1319  // all deletions on these tables have transactions so final failure rollbacks these updates
1320  $table = $this->tableName( $table );
1321  if ( $table == $this->tableName( 'user' ) ) {
1322  $this->update( 'archive', [ 'ar_user' => 0 ],
1323  [ 'ar_user' => $conds['user_id'] ], $fname );
1324  $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1325  [ 'ipb_user' => $conds['user_id'] ], $fname );
1326  $this->update( 'image', [ 'img_user' => 0 ],
1327  [ 'img_user' => $conds['user_id'] ], $fname );
1328  $this->update( 'oldimage', [ 'oi_user' => 0 ],
1329  [ 'oi_user' => $conds['user_id'] ], $fname );
1330  $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1331  [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1332  $this->update( 'filearchive', [ 'fa_user' => 0 ],
1333  [ 'fa_user' => $conds['user_id'] ], $fname );
1334  $this->update( 'uploadstash', [ 'us_user' => 0 ],
1335  [ 'us_user' => $conds['user_id'] ], $fname );
1336  $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1337  [ 'rc_user' => $conds['user_id'] ], $fname );
1338  $this->update( 'logging', [ 'log_user' => 0 ],
1339  [ 'log_user' => $conds['user_id'] ], $fname );
1340  } elseif ( $table == $this->tableName( 'image' ) ) {
1341  $this->update( 'oldimage', [ 'oi_name' => 0 ],
1342  [ 'oi_name' => $conds['img_name'] ], $fname );
1343  }
1344 
1345  return parent::delete( $table, $conds, $fname );
1346  }
1347 
1357  function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1359 
1360  $table = $this->tableName( $table );
1361  $opts = $this->makeUpdateOptions( $options );
1362  $sql = "UPDATE $opts $table SET ";
1363 
1364  $first = true;
1365  foreach ( $values as $col => &$val ) {
1366  $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1367 
1368  if ( !$first ) {
1369  $sqlSet = ', ' . $sqlSet;
1370  } else {
1371  $first = false;
1372  }
1373  $sql .= $sqlSet;
1374  }
1375 
1376  if ( $conds !== [] && $conds !== '*' ) {
1377  $conds = $this->wrapConditionsForWhere( $table, $conds );
1378  $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1379  }
1380 
1381  $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql );
1382  if ( $stmt === false ) {
1383  $e = oci_error( $this->mConn );
1384  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1385 
1386  return false;
1387  }
1388  foreach ( $values as $col => &$val ) {
1389  $col_info = $this->fieldInfoMulti( $table, $col );
1390  $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1391 
1392  if ( $val === null ) {
1393  // do nothing ... null was inserted in statement creation
1394  } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1395  if ( is_object( $val ) ) {
1396  $val = $val->getData();
1397  }
1398 
1399  if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1400  $val = '31-12-2030 12:00:00.000000';
1401  }
1402 
1403  $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1404  if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1405  $e = oci_error( $stmt );
1406  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1407 
1408  return false;
1409  }
1410  } else {
1412  $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB );
1413  if ( $lob[$col] === false ) {
1414  $e = oci_error( $stmt );
1415  throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1416  }
1417 
1418  if ( is_object( $val ) ) {
1419  $val = $val->getData();
1420  }
1421 
1422  if ( $col_type == 'BLOB' ) {
1423  $lob[$col]->writeTemporary( $val );
1424  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
1425  } else {
1426  $lob[$col]->writeTemporary( $val );
1427  oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
1428  }
1429  }
1430  }
1431 
1432  MediaWiki\suppressWarnings();
1433 
1434  if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1435  $e = oci_error( $stmt );
1436  if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
1437  $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1438 
1439  return false;
1440  } else {
1441  $this->mAffectedRows = oci_num_rows( $stmt );
1442  }
1443  } else {
1444  $this->mAffectedRows = oci_num_rows( $stmt );
1445  }
1446 
1447  MediaWiki\restoreWarnings();
1448 
1449  if ( isset( $lob ) ) {
1450  foreach ( $lob as $lob_v ) {
1451  $lob_v->free();
1452  }
1453  }
1454 
1455  if ( !$this->mTrxLevel ) {
1456  oci_commit( $this->mConn );
1457  }
1458 
1459  return oci_free_statement( $stmt );
1460  }
1461 
1462  function bitNot( $field ) {
1463  // expecting bit-fields smaller than 4bytes
1464  return 'BITNOT(' . $field . ')';
1465  }
1466 
1467  function bitAnd( $fieldLeft, $fieldRight ) {
1468  return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1469  }
1470 
1471  function bitOr( $fieldLeft, $fieldRight ) {
1472  return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1473  }
1474 
1475  function getDBname() {
1476  return $this->mDBname;
1477  }
1478 
1479  function getServer() {
1480  return $this->mServer;
1481  }
1482 
1483  public function buildGroupConcatField(
1484  $delim, $table, $field, $conds = '', $join_conds = []
1485  ) {
1486  $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1487 
1488  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1489  }
1490 
1496  public function buildStringCast( $field ) {
1497  return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1498  }
1499 
1500  public function getInfinity() {
1501  return '31-12-2030 12:00:00.000000';
1502  }
1503 }
doRollback($fname=__METHOD__)
#define the
table suitable for use with IDatabase::select()
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
the array() calling protocol came about after MediaWiki 1.4rc1.
Utility classThis allows us to distinguish a blob from a normal string and an array of strings...
Definition: Blob.php:8
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 and or sell copies of the and to permit persons to whom the Software is furnished to do subject to the following WITHOUT WARRANTY OF ANY EXPRESS OR INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER WHETHER IN AN ACTION OF TORT OR ARISING FROM
Definition: LICENSE.txt:10
$success
queryIgnore($sql, $fname= '')
fieldBindStatement($table, $col, &$val, $includeCol=false)
sourceStream($fp, $lineCallback=false, $resultCallback=false, $fname=__METHOD__, $inputCallback=false)
defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
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:1936
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:2102
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 except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server.Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use.Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves.The master writes thequery to the binlog when the transaction is committed.The slaves pollthe binlog and start executing the query as soon as it appears.They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes.Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load.MediaWiki's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database.All edits and other write operations will berefused, with an error returned to the user.This gives the slaves achance to catch up.Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order.A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests.This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it.Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in"lagged slave mode".Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode().The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time.Multi-row INSERT...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it's not practical to guarantee a low-lagenvironment.Lag will usually be less than one second, but mayoccasionally be up to 30 seconds.For scalability, it's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer.So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum.In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks.By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent.Locks willbe held from the time when the query is done until the commit.So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction.Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
insert($table, $a, $fname=__METHOD__, $options=[])
insertId()
This must be called after nextSequenceVal.
getSequenceData($table)
Return sequence_name if table has a sequence.
indexUnique($table, $index, $fname=__METHOD__)
freeResult($res)
Frees resources associated with the LOB descriptor.
__construct(array $p)
open($server, $user, $password, $dbName)
Usually aborts on failure.
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
array_unique_md($array_in)
fieldInfoMulti($table, $field)
Function translates mysql_fetch_field() functionality on ORACLE.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
duplicateTableStructure($oldName, $newName, $temporary=false, $fname=__METHOD__)
in this case you re responsible for computing and outputting the entire conflict i e
Definition: hooks.txt:1376
textFieldSize($table, $field)
Returns the size of a text field, or -1 for "unlimited".
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
const DBO_DDLMODE
Definition: defines.php:13
__construct(&$db, $stmt, $unique=false)
static isUtf8($value)
Test whether a string is valid UTF-8.
Definition: StringUtils.php:41
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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:1934
const DBO_PERSISTENT
Definition: defines.php:11
static getLocalInstance($ts=false)
Get a timestamp instance in the server local timezone ($wgLocaltimezone)
insertOneRow($table, $row, $fname)
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wrapConditionsForWhere($table, $conds, $parentCol=null)
bitOr($fieldLeft, $fieldRight)
fieldName($stmt, $n)
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a message
Definition: hooks.txt:2094
int $mAffectedRows
The number of rows affected as an integer.
const LIST_AND
Definition: Defines.php:35
wrapFieldForWhere($table, &$col, &$val)
tableNameInternal($name)
update($table, $values, $conds, $fname=__METHOD__, $options=[])
const DBO_SYSDBA
Definition: defines.php:12
dataSeek($res, $row)
makeSelectOptions($options)
Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the quer...
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:1046
$res
Definition: database.txt:21
doCommit($fname=__METHOD__)
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
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
limitResult($sql, $limit, $offset=false)
fieldInfo($table, $field)
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:242
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
const DBO_DEFAULT
Definition: defines.php:10
tableExists($table, $fname=__METHOD__)
Query whether a given table exists (in the given schema, or the default mw one if not given) ...
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of or an object and a method hook function The function part of a third party developers and local administrators to define code that will be run at certain points in the mainline code
Definition: hooks.txt:23
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:36
listTables($prefix=null, $fname=__METHOD__)
nativeInsertSelect($destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[])
unionQueries($sqls, $all)
$line
Definition: cdb.php:59
$wgDBprefix
Table name prefix.
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:1046
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
nextSequenceValue($seqName)
Return the next in a sequence, save the value for retrieval via insertId()
aggregateValue($valuedata, $valuename= 'value')
Return aggregated value function call.
$count
doBegin($fname=__METHOD__)
Result wrapper for grabbing data queried from an IDatabase object.
serialize()
Definition: ApiMessage.php:94
The oci8 extension is fairly weak and doesn't support oci_num_rows, among other things.
buildGroupConcatField($delim, $table, $field, $conds= '', $join_conds=[])
$wgDBOracleDRCP
Set true to enable Oracle DCRP (supported from 11gR1 onward)
selectRow($table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
const TS_ORACLE
Oracle format time.
Definition: defines.php:42
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2159
For a write query
Definition: database.txt:26
indexInfo($table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure...
indexExists($table, $index, $fname=__METHOD__)
Query whether a given index exists.
bitAnd($fieldLeft, $fieldRight)
dropTable($tableName, $fName=__METHOD__)
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300
tableName()
Name of table this field belongs to.
Definition: ORAField.php:23