28use Psr\Log\LoggerAwareInterface;
29use Psr\Log\LoggerInterface;
30use Psr\Log\NullLogger;
31use Wikimedia\ScopedCallback;
32use Wikimedia\Timestamp\ConvertibleTimestamp;
37use InvalidArgumentException;
38use UnexpectedValueException;
66 const ATTR_DB_LEVEL_LOCKING =
'db-level-locking';
68 const ATTR_SCHEMAS_AS_TABLE_GROUPS =
'supports-schemas';
71 const NEW_UNCONNECTED = 0;
73 const NEW_CONNECTED = 1;
282 const STATUS_TRX_ERROR = 1;
284 const STATUS_TRX_OK = 2;
286 const STATUS_TRX_NONE = 3;
289 const TEMP_NORMAL = 1;
291 const TEMP_PSEUDO_PERMANENT = 2;
298 foreach ( [
'host',
'user',
'password',
'dbname',
'schema',
'tablePrefix' ]
as $name ) {
302 $this->cliMode =
$params[
'cliMode'];
304 $this->agent = str_replace(
'/',
'-',
$params[
'agent'] );
306 $this->flags =
$params[
'flags'];
307 if ( $this->flags & self::DBO_DEFAULT ) {
308 if ( $this->cliMode ) {
317 $this->sessionVars =
$params[
'variables'];
321 $this->profiler = is_callable(
$params[
'profiler'] ) ?
$params[
'profiler'] :
null;
322 $this->trxProfiler =
$params[
'trxProfiler'];
323 $this->connLogger =
$params[
'connLogger'];
324 $this->queryLogger =
$params[
'queryLogger'];
325 $this->errorLogger =
$params[
'errorLogger'];
326 $this->deprecationLogger =
$params[
'deprecationLogger'];
328 if ( isset(
$params[
'nonNativeInsertSelectBatchSize'] ) ) {
329 $this->nonNativeInsertSelectBatchSize =
$params[
'nonNativeInsertSelectBatchSize'];
350 throw new LogicException( __METHOD__ .
': already connected.' );
364 if ( strlen( $this->connectionParams[
'user'] ) ) {
366 $this->connectionParams[
'host'],
367 $this->connectionParams[
'user'],
368 $this->connectionParams[
'password'],
369 $this->connectionParams[
'dbname'],
370 $this->connectionParams[
'schema'],
371 $this->connectionParams[
'tablePrefix']
374 throw new InvalidArgumentException(
"No database user provided." );
437 final public static function factory( $dbType, $p = [], $connect = self::NEW_CONNECTED ) {
440 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
442 $p[
'host'] = $p[
'host'] ??
false;
443 $p[
'user'] = $p[
'user'] ??
false;
444 $p[
'password'] = $p[
'password'] ??
false;
445 $p[
'dbname'] = $p[
'dbname'] ??
false;
446 $p[
'flags'] = $p[
'flags'] ?? 0;
447 $p[
'variables'] = $p[
'variables'] ?? [];
448 $p[
'tablePrefix'] = $p[
'tablePrefix'] ??
'';
449 $p[
'schema'] = $p[
'schema'] ??
null;
450 $p[
'cliMode'] = $p[
'cliMode'] ?? ( PHP_SAPI ===
'cli' || PHP_SAPI ===
'phpdbg' );
451 $p[
'agent'] = $p[
'agent'] ??
'';
452 if ( !isset( $p[
'connLogger'] ) ) {
453 $p[
'connLogger'] =
new NullLogger();
455 if ( !isset( $p[
'queryLogger'] ) ) {
456 $p[
'queryLogger'] =
new NullLogger();
458 $p[
'profiler'] = $p[
'profiler'] ??
null;
459 if ( !isset( $p[
'trxProfiler'] ) ) {
462 if ( !isset( $p[
'errorLogger'] ) ) {
463 $p[
'errorLogger'] =
function ( Exception
$e ) {
464 trigger_error( get_class(
$e ) .
': ' .
$e->getMessage(), E_USER_WARNING );
467 if ( !isset( $p[
'deprecationLogger'] ) ) {
468 $p[
'deprecationLogger'] =
function ( $msg ) {
469 trigger_error( $msg, E_USER_DEPRECATED );
474 $conn =
new $class( $p );
475 if ( $connect == self::NEW_CONNECTED ) {
476 $conn->initConnection();
494 self::ATTR_DB_LEVEL_LOCKING =>
false,
495 self::ATTR_SCHEMAS_AS_TABLE_GROUPS =>
false
500 return call_user_func( [ $class,
'getAttributes' ] ) + $defaults;
509 private static function getClass( $dbType, $driver =
null ) {
516 static $builtinTypes = [
517 'mssql' => DatabaseMssql::class,
518 'mysql' => [
'mysqli' => DatabaseMysqli::class ],
519 'sqlite' => DatabaseSqlite::class,
520 'postgres' => DatabasePostgres::class,
523 $dbType = strtolower( $dbType );
526 if ( isset( $builtinTypes[$dbType] ) ) {
527 $possibleDrivers = $builtinTypes[$dbType];
528 if ( is_string( $possibleDrivers ) ) {
529 $class = $possibleDrivers;
530 } elseif ( (
string)$driver !==
'' ) {
531 if ( !isset( $possibleDrivers[$driver] ) ) {
532 throw new InvalidArgumentException( __METHOD__ .
533 " type '$dbType' does not support driver '{$driver}'" );
536 $class = $possibleDrivers[$driver];
538 foreach ( $possibleDrivers
as $posDriver => $possibleClass ) {
539 if ( extension_loaded( $posDriver ) ) {
540 $class = $possibleClass;
546 $class =
'Database' . ucfirst( $dbType );
549 if ( $class ===
false ) {
550 throw new InvalidArgumentException( __METHOD__ .
551 " no viable database extension found for type '$dbType'" );
573 $this->queryLogger = $logger;
585 : $this->
setFlag( self::DBO_NOBUFFER );
608 $old = $this->currentDomain->getTablePrefix();
609 if ( $prefix !==
null ) {
611 $this->currentDomain->getDatabase(),
612 $this->currentDomain->getSchema(),
621 if ( strlen( $schema ) && $this->
getDBname() ===
null ) {
622 throw new DBUnexpectedError( $this,
"Cannot set schema to '$schema'; no database set." );
625 $old = $this->currentDomain->getSchema();
626 if ( $schema !==
null ) {
628 $this->currentDomain->getDatabase(),
630 strlen( $schema ) ? $schema :
null,
631 $this->currentDomain->getTablePrefix()
646 if ( is_null(
$name ) ) {
650 if ( array_key_exists(
$name, $this->lbInfo ) ) {
651 return $this->lbInfo[
$name];
658 if ( is_null(
$value ) ) {
659 $this->lbInfo =
$name;
666 $this->lazyMasterHandle =
$conn;
695 return $this->lastWriteTime ?:
false;
704 $this->trxDoneWrites ||
705 $this->trxIdleCallbacks ||
706 $this->trxPreCommitCallbacks ||
707 $this->trxEndCallbacks ||
721 if ( $this->
getFlag( self::DBO_TRX ) ) {
724 return is_string( $id ) ? $id :
null;
733 } elseif ( !$this->trxDoneWrites ) {
738 case self::ESTIMATE_DB_APPLY:
751 $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
752 $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
755 $applyTime += self::TINY_WRITE_SEC * $omitted;
761 return $this->
trxLevel ? $this->trxWriteCallers : [];
779 $this->trxIdleCallbacks,
780 $this->trxPreCommitCallbacks,
781 $this->trxEndCallbacks,
782 $this->trxSectionCancelCallbacks
784 foreach ( $callbacks
as $callback ) {
785 $fnames[] = $callback[1];
796 return array_reduce( $this->trxAtomicLevels,
function ( $accum, $v ) {
797 return $accum ===
null ? $v[0] :
"$accum, " . $v[0];
805 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
806 if ( ( $flag & self::DBO_IGNORE ) ) {
807 throw new UnexpectedValueException(
"Modifying DBO_IGNORE is not allowed." );
810 if ( $remember === self::REMEMBER_PRIOR ) {
811 array_push( $this->priorFlags, $this->flags );
813 $this->flags |= $flag;
816 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
817 if ( ( $flag & self::DBO_IGNORE ) ) {
818 throw new UnexpectedValueException(
"Modifying DBO_IGNORE is not allowed." );
821 if ( $remember === self::REMEMBER_PRIOR ) {
822 array_push( $this->priorFlags, $this->flags );
824 $this->flags &= ~$flag;
828 if ( !$this->priorFlags ) {
832 if ( $state === self::RESTORE_INITIAL ) {
833 $this->flags = reset( $this->priorFlags );
834 $this->priorFlags = [];
836 $this->flags = array_pop( $this->priorFlags );
841 return (
bool)( $this->flags & $flag );
854 return $this->currentDomain->getId();
882 $this->phpError =
false;
883 $this->htmlErrors = ini_set(
'html_errors',
'0' );
884 set_error_handler( [ $this,
'connectionErrorLogger' ] );
893 restore_error_handler();
894 if ( $this->htmlErrors !==
false ) {
895 ini_set(
'html_errors', $this->htmlErrors );
905 if ( $this->phpError ) {
906 $error = preg_replace(
'!\[<a.*</a>\]!',
'', $this->phpError );
907 $error = preg_replace(
'!^.*?:\s?(.*)$!',
'$1', $error );
923 $this->phpError = $errstr;
935 'db_server' => $this->
server,
937 'db_user' => $this->
user,
951 if ( $this->trxAtomicLevels ) {
956 __METHOD__ .
": atomic sections $levels are still open."
958 } elseif ( $this->trxAutomatic ) {
965 ": mass commit/rollback of peer transaction required (DBO_TRX set)."
973 __METHOD__ .
": transaction is still open (from {$this->trxFname})."
977 if ( $this->trxEndCallbacksSuppressed ) {
980 __METHOD__ .
': callbacks are suppressed; cannot properly commit.'
985 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
995 $this->opened =
false;
998 if ( $exception instanceof Exception ) {
1010 throw new RuntimeException(
1011 "Transaction callbacks are still pending:\n" . implode(
', ', $fnames )
1028 if ( !$this->
isOpen() ) {
1039 if ( $this->
getLBInfo(
'replica' ) ===
true ) {
1042 'Write operations are not allowed on replica database connections.'
1046 if ( $reason !==
false ) {
1064 call_user_func( $this->deprecationLogger,
'Use of ' . __METHOD__ .
' is deprecated.' );
1119 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|\(SELECT)\b/i',
1129 return preg_match(
'/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) :
null;
1148 [
'BEGIN',
'ROLLBACK',
'COMMIT',
'SET',
'SHOW',
'CREATE',
'ALTER' ],
1159 static $qt =
'[`"\']?(\w+)[`"\']?';
1162 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt .
'/i',
1166 $type = $pseudoPermanent ? self::TEMP_PSEUDO_PERMANENT : self::TEMP_NORMAL;
1170 } elseif ( preg_match(
1171 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt .
'/i',
1176 unset( $this->sessionTempTables[
$matches[1]] );
1179 } elseif ( preg_match(
1180 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt .
'/i',
1184 return $this->sessionTempTables[
$matches[1]] ??
null;
1185 } elseif ( preg_match(
1186 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt .
'/i',
1190 return $this->sessionTempTables[
$matches[1]] ??
null;
1201 $ignoreErrors = $this->
hasFlags(
$flags, self::QUERY_SILENCE_ERRORS );
1208 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1211 # Do not treat temporary table writes as "meaningful writes" that need committing.
1212 # Profile them as reads. Integration tests can override this behavior via $flags.
1213 $pseudoPermanent = $this->
hasFlags(
$flags, self::QUERY_PSEUDO_PERMANENT );
1215 $isEffectiveWrite = ( $tableType !== self::TEMP_NORMAL );
1216 # DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1217 if ( $isEffectiveWrite && $this->
hasFlags(
$flags, self::QUERY_REPLICA_ROLE ) ) {
1221 $isEffectiveWrite =
false;
1224 # Add trace comment to the begin of the sql string, right after the operator.
1225 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1226 $commentedSql = preg_replace( '/\s|$/', " ", $sql, 1 );
1228 # Send the query to the server and fetch any corresponding errors
1229 $ret = $this->attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname );
1230 $lastError = $this->lastError();
1231 $lastErrno = $this->lastErrno();
1233 $recoverableSR = false; // recoverable statement rollback?
1234 $recoverableCL = false; // recoverable connection loss?
1236 if ( $ret === false && $this->wasConnectionLoss() ) {
1237 # Check if no meaningful session state was lost
1238 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1239 # Update session state tracking and try to restore the connection
1240 $reconnected = $this->replaceLostConnection( __METHOD__ );
1241 # Silently resend the query to the server if it is safe and possible
1242 if ( $recoverableCL && $reconnected ) {
1243 $ret = $this->attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname );
1244 $lastError = $this->lastError();
1245 $lastErrno = $this->lastErrno();
1247 if ( $ret === false && $this->wasConnectionLoss() ) {
1248 # Query probably causes disconnects; reconnect and do not re-run it
1249 $this->replaceLostConnection( __METHOD__ );
1251 $recoverableCL = false; // connection does not need recovering
1252 $recoverableSR = $this->wasKnownStatementRollbackError();
1256 $recoverableSR = $this->wasKnownStatementRollbackError();
1259 if ( $ret === false ) {
1260 if ( $priorTransaction ) {
1261 if ( $recoverableSR ) {
1262 # We're ignoring an error that caused just the current query to be aborted.
1263 # But log the cause so we can log a deprecation notice if a caller actually
1265 $this->trxStatusIgnoredCause = [ $lastError, $lastErrno, $fname ];
1266 } elseif ( !$recoverableCL ) {
1267 # Either the query was aborted or all queries after BEGIN where aborted.
1268 # In the first case, the only options going forward are (a) ROLLBACK, or
1269 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1270 # option is ROLLBACK, since the snapshots would have been released.
1271 $this->trxStatus = self::STATUS_TRX_ERROR;
1272 $this->trxStatusCause =
1273 $this->getQueryExceptionAndLog( $lastError, $lastErrno, $sql, $fname );
1274 $ignoreErrors = false; // cannot recover
1275 $this->trxStatusIgnoredCause = null;
1279 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $ignoreErrors );
1282 return $this->resultObject( $ret );
1295 private function attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname ) {
1296 $this->beginIfImplied( $sql, $fname );
1298 # Keep track of whether the transaction has write queries pending
1299 if ( $isEffectiveWrite ) {
1300 $this->lastWriteTime = microtime( true );
1301 if ( $this->trxLevel && !$this->trxDoneWrites ) {
1302 $this->trxDoneWrites = true;
1303 $this->trxProfiler->transactionWritingIn(
1304 $this->server, $this->getDomainID(), $this->trxShortId );
1308 if ( $this->getFlag( self::DBO_DEBUG ) ) {
1309 $this->queryLogger->debug( "{$this->getDomainID()} {$commentedSql}" );
1312 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1313 # generalizeSQL() will probably cut down the query to reasonable
1314 # logging size most of the time. The substr is really just a sanity check.
1316 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1318 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1321 # Include query transaction state
1322 $queryProf .= $this->trxShortId ? " [TRX#{$this->trxShortId}]" : "";
1324 $startTime = microtime( true );
1325 $ps = $this->profiler ? ( $this->profiler )( $queryProf ) : null;
1326 $this->affectedRowCount = null;
1327 $ret = $this->doQuery( $commentedSql );
1328 $this->affectedRowCount = $this->affectedRows();
1329 unset( $ps ); // profile out (if set)
1330 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1332 if ( $ret !== false ) {
1333 $this->lastPing = $startTime;
1334 if ( $isEffectiveWrite && $this->trxLevel ) {
1335 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1336 $this->trxWriteCallers[] = $fname;
1340 if ( $sql === self::PING_QUERY ) {
1341 $this->rttEstimate = $queryRuntime;
1344 $this->trxProfiler->recordQueryCompletion(
1348 $isEffectiveWrite ? $this->affectedRows() : $this->numRows( $ret )
1350 $this->queryLogger->debug( $sql, [
1352 'master' => $isMaster,
1353 'runtime' => $queryRuntime,
1365 private function beginIfImplied( $sql, $fname ) {
1368 $this->getFlag( self::DBO_TRX ) &&
1369 $this->isTransactableQuery( $sql )
1371 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1372 $this->trxAutomatic = true;
1388 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1389 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1390 $indicativeOfReplicaRuntime = true;
1391 if ( $runtime > self::SLOW_WRITE_SEC ) {
1392 $verb = $this->getQueryVerb( $sql );
1393 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1394 if ( $verb === 'INSERT' ) {
1395 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1396 } elseif ( $verb === 'REPLACE' ) {
1397 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1401 $this->trxWriteDuration += $runtime;
1402 $this->trxWriteQueryCount += 1;
1403 $this->trxWriteAffectedRows += $affected;
1404 if ( $indicativeOfReplicaRuntime ) {
1405 $this->trxWriteAdjDuration += $runtime;
1406 $this->trxWriteAdjQueryCount += 1;
1417 private function assertTransactionStatus( $sql, $fname ) {
1418 $verb = $this->getQueryVerb( $sql );
1419 if ( $verb === 'USE' ) {
1420 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead." );
1423 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1427 if ( $this->trxStatus < self::STATUS_TRX_OK ) {
1428 throw new DBTransactionStateError(
1430 "Cannot execute query from $fname while transaction status is ERROR.",
1432 $this->trxStatusCause
1434 } elseif ( $this->trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1435 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause;
1436 call_user_func( $this->deprecationLogger,
1437 "Caller from $fname ignored an error originally raised from $iFname: " .
1438 "[$iLastErrno] $iLastError"
1440 $this->trxStatusIgnoredCause = null;
1444 public function assertNoOpenTransactions() {
1445 if ( $this->explicitTrxActive() ) {
1446 throw new DBTransactionError(
1448 "Explicit transaction still active. A caller may have caught an error. "
1449 . "Open transactions: " . $this->flatAtomicSectionList()
1463 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1464 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1465 # Dropped connections also mean that named locks are automatically released.
1466 # Only allow error suppression in autocommit mode or when the lost transaction
1467 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1468 if ( $this->namedLocksHeld ) {
1469 return false; // possible critical section violation
1470 } elseif ( $this->sessionTempTables ) {
1471 return false; // tables might be queried latter
1472 } elseif ( $sql === 'COMMIT' ) {
1473 return !$priorWritesPending; // nothing written anyway? (T127428)
1474 } elseif ( $sql === 'ROLLBACK' ) {
1475 return true; // transaction lost...which is also what was requested :)
1476 } elseif ( $this->explicitTrxActive() ) {
1477 return false; // don't drop atomocity and explicit snapshots
1478 } elseif ( $priorWritesPending ) {
1479 return false; // prior writes lost from implicit transaction
1488 private function handleSessionLossPreconnect() {
1489 // Clean up tracking of session-level things...
1490 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1491 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1492 $this->sessionTempTables = [];
1493 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1494 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1495 $this->namedLocksHeld = [];
1496 // Session loss implies transaction loss
1497 $this->trxLevel = 0;
1498 $this->trxAtomicCounter = 0;
1499 $this->trxIdleCallbacks = []; // T67263; transaction already lost
1500 $this->trxPreCommitCallbacks = []; // T67263; transaction already lost
1501 // @note: leave trxRecurringCallbacks in place
1502 if ( $this->trxDoneWrites ) {
1503 $this->trxProfiler->transactionWritingOut(
1505 $this->getDomainID(),
1507 $this->pendingWriteQueryDuration( self::ESTIMATE_TOTAL ),
1508 $this->trxWriteAffectedRows
1516 private function handleSessionLossPostconnect() {
1518 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1519 // If callback suppression is set then the array will remain unhandled.
1520 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1521 } catch ( Exception $ex ) {
1522 // Already logged; move on...
1525 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1526 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1527 } catch ( Exception $ex ) {
1528 // Already logged; move on...
1542 protected function wasQueryTimeout( $error, $errno ) {
1557 public function reportQueryError( $error, $errno, $sql, $fname, $ignoreErrors = false ) {
1558 if ( $ignoreErrors ) {
1559 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1561 $exception = $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1574 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1575 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1576 $this->queryLogger->error(
1577 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1578 $this->getLogContext( [
1579 'method' => __METHOD__,
1582 'sql1line' => $sql1line,
1584 'exception' => new RuntimeException()
1587 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1588 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1589 if ( $wasQueryTimeout ) {
1590 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1592 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1598 public function freeResult( $res ) {
1601 public function selectField(
1602 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1604 if ( $var === '*' ) { // sanity
1605 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1608 if ( !is_array( $options ) ) {
1609 $options = [ $options ];
1612 $options['LIMIT'] = 1;
1614 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1615 if ( $res === false || !$this->numRows( $res ) ) {
1619 $row = $this->fetchRow( $res );
1621 if ( $row !== false ) {
1622 return reset( $row );
1628 public function selectFieldValues(
1629 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1631 if ( $var === '*' ) { // sanity
1632 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1633 } elseif ( !is_string( $var ) ) { // sanity
1634 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1637 if ( !is_array( $options ) ) {
1638 $options = [ $options ];
1641 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1642 if ( $res === false ) {
1647 foreach ( $res as $row ) {
1648 $values[] = $row->value;
1663 protected function makeSelectOptions( $options ) {
1664 $preLimitTail = $postLimitTail = '';
1669 foreach ( $options as $key => $option ) {
1670 if ( is_numeric( $key ) ) {
1671 $noKeyOptions[$option] = true;
1675 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1677 $preLimitTail .= $this->makeOrderBy( $options );
1679 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1680 $postLimitTail .= ' FOR UPDATE';
1683 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1684 $postLimitTail .= ' LOCK IN SHARE MODE';
1687 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1688 $startOpts .= 'DISTINCT';
1691 # Various MySQL extensions
1692 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1693 $startOpts .= ' /*! STRAIGHT_JOIN */';
1696 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1697 $startOpts .= ' HIGH_PRIORITY';
1700 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1701 $startOpts .= ' SQL_BIG_RESULT';
1704 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1705 $startOpts .= ' SQL_BUFFER_RESULT';
1708 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1709 $startOpts .= ' SQL_SMALL_RESULT';
1712 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1713 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1716 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1717 $startOpts .= ' SQL_CACHE';
1720 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1721 $startOpts .= ' SQL_NO_CACHE';
1724 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1725 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1729 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1730 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1735 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1746 protected function makeGroupByWithHaving( $options ) {
1748 if ( isset( $options['GROUP BY'] ) ) {
1749 $gb = is_array( $options['GROUP BY'] )
1750 ? implode( ',', $options['GROUP BY'] )
1751 : $options['GROUP BY'];
1752 $sql .= ' GROUP BY ' . $gb;
1754 if ( isset( $options['HAVING'] ) ) {
1755 $having = is_array( $options['HAVING'] )
1756 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1757 : $options['HAVING'];
1758 $sql .= ' HAVING ' . $having;
1772 protected function makeOrderBy( $options ) {
1773 if ( isset( $options['ORDER BY'] ) ) {
1774 $ob = is_array( $options['ORDER BY'] )
1775 ? implode( ',', $options['ORDER BY'] )
1776 : $options['ORDER BY'];
1778 return ' ORDER BY ' . $ob;
1784 public function select(
1785 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1787 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1789 return $this->query( $sql, $fname );
1792 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1793 $options = [], $join_conds = []
1795 if ( is_array( $vars ) ) {
1796 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1801 $options = (array)$options;
1802 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1803 ? $options['USE INDEX']
1806 isset( $options['IGNORE INDEX'] ) &&
1807 is_array( $options['IGNORE INDEX'] )
1809 ? $options['IGNORE INDEX']
1813 $this->selectOptionsIncludeLocking( $options ) &&
1814 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1816 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1817 // functions. Discourage use of such queries to encourage compatibility.
1819 $this->deprecationLogger,
1820 __METHOD__ . ": aggregation used with a locking SELECT ($fname)."
1824 if ( is_array( $table ) ) {
1826 $this->tableNamesWithIndexClauseOrJOIN(
1827 $table, $useIndexes, $ignoreIndexes, $join_conds );
1828 } elseif ( $table != '' ) {
1830 $this->tableNamesWithIndexClauseOrJOIN(
1831 [ $table ], $useIndexes, $ignoreIndexes, [] );
1836 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1837 $this->makeSelectOptions( $options );
1839 if ( is_array( $conds ) ) {
1840 $conds = $this->makeList( $conds, self::LIST_AND );
1843 if ( $conds === null || $conds === false ) {
1844 $this->queryLogger->warning(
1848 . ' with incorrect parameters: $conds must be a string or an array'
1853 if ( $conds === '' || $conds === '*' ) {
1854 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1855 } elseif ( is_string( $conds ) ) {
1856 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1857 "WHERE $conds $preLimitTail";
1859 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1862 if ( isset( $options['LIMIT'] ) ) {
1863 $sql = $this->limitResult( $sql, $options['LIMIT'],
1864 $options['OFFSET'] ?? false );
1866 $sql = "$sql $postLimitTail";
1868 if ( isset( $options['EXPLAIN'] ) ) {
1869 $sql = 'EXPLAIN ' . $sql;
1875 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1876 $options = [], $join_conds = []
1878 $options = (array)$options;
1879 $options['LIMIT'] = 1;
1880 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1882 if ( $res === false ) {
1886 if ( !$this->numRows( $res ) ) {
1890 $obj = $this->fetchObject( $res );
1895 public function estimateRowCount(
1896 $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1898 $conds = $this->normalizeConditions( $conds, $fname );
1899 $column = $this->extractSingleFieldFromList( $var );
1900 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1901 $conds[] = "$column IS NOT NULL";
1904 $res = $this->select(
1905 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1907 $row = $res ? $this->fetchRow( $res ) : [];
1909 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1912 public function selectRowCount(
1913 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1915 $conds = $this->normalizeConditions( $conds, $fname );
1916 $column = $this->extractSingleFieldFromList( $var );
1917 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1918 $conds[] = "$column IS NOT NULL";
1921 $res = $this->select(
1923 'tmp_count' => $this->buildSelectSubquery(
1932 [ 'rowcount' => 'COUNT(*)' ],
1936 $row = $res ? $this->fetchRow( $res ) : [];
1938 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1945 private function selectOptionsIncludeLocking( $options ) {
1946 $options = (array)$options;
1947 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1948 if ( in_array( $lock, $options, true ) ) {
1961 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1962 foreach ( (array)$options as $key => $value ) {
1963 if ( is_string( $key ) ) {
1964 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1967 } elseif ( is_string( $value ) ) {
1968 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1974 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1975 foreach ( (array)$fields as $field ) {
1976 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1989 final protected function normalizeConditions( $conds, $fname ) {
1990 if ( $conds === null || $conds === false ) {
1991 $this->queryLogger->warning(
1995 . ' with incorrect parameters: $conds must be a string or an array'
2000 if ( !is_array( $conds ) ) {
2001 $conds = ( $conds === '' ) ? [] : [ $conds ];
2012 final protected function extractSingleFieldFromList( $var ) {
2013 if ( is_array( $var ) ) {
2016 } elseif ( count( $var ) == 1 ) {
2017 $column = $var[0] ?? reset( $var );
2019 throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns.' );
2028 public function lockForUpdate(
2029 $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2031 if ( !$this->trxLevel && !$this->getFlag( self::DBO_TRX ) ) {
2032 throw new DBUnexpectedError(
2034 __METHOD__ . ': no transaction is active nor is DBO_TRX set'
2038 $options = (array)$options;
2039 $options[] = 'FOR UPDATE';
2041 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2052 protected static function generalizeSQL( $sql ) {
2053 # This does the same as the regexp below would do, but in such a way
2054 # as to avoid crashing php on some large strings.
2055 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
2057 $sql = str_replace(
"\\\\",
'', $sql );
2058 $sql = str_replace(
"\\'",
'', $sql );
2059 $sql = str_replace(
"\\\"",
'', $sql );
2060 $sql = preg_replace(
"/'.*'/s",
"'X'", $sql );
2061 $sql = preg_replace(
'/".*"/s',
"'X'", $sql );
2063 # All newlines, tabs, etc replaced by single space
2064 $sql = preg_replace(
'/\s+/',
' ', $sql );
2067 # except the ones surrounded by characters, e.g. l10n
2068 $sql = preg_replace(
'/-?\d+(,-?\d+)+/s',
'N,...,N', $sql );
2069 $sql = preg_replace(
'/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s',
'N', $sql );
2075 $info = $this->
fieldInfo( $table, $field );
2086 if ( is_null( $info ) ) {
2089 return $info !==
false;
2096 $indexInfo = $this->
indexInfo( $table, $index );
2098 if ( !$indexInfo ) {
2102 return !$indexInfo[0]->Non_unique;
2116 # No rows to insert, easy just return now
2117 if ( !count( $a ) ) {
2129 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2131 $keys = array_keys( $a[0] );
2134 $keys = array_keys( $a );
2138 " INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
2142 foreach ( $a
as $row ) {
2148 $sql .=
'(' . $this->
makeList( $row ) .
')';
2151 $sql .=
'(' . $this->
makeList( $a ) .
')';
2172 if ( in_array(
'IGNORE',
$options ) ) {
2188 return implode(
' ', $opts );
2194 $sql =
"UPDATE $opts $table SET " . $this->
makeList( $values, self::LIST_SET );
2196 if ( $conds !== [] && $conds !==
'*' ) {
2197 $sql .=
" WHERE " . $this->
makeList( $conds, self::LIST_AND );
2205 public function makeList( $a, $mode = self::LIST_COMMA ) {
2206 if ( !is_array( $a ) ) {
2207 throw new DBUnexpectedError( $this, __METHOD__ .
' called with incorrect parameters' );
2213 foreach ( $a
as $field =>
$value ) {
2215 if ( $mode == self::LIST_AND ) {
2217 } elseif ( $mode == self::LIST_OR ) {
2226 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
2227 $list .=
"($value)";
2228 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
2231 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array(
$value )
2234 $includeNull =
false;
2235 foreach ( array_keys(
$value,
null,
true )
as $nullKey ) {
2236 $includeNull =
true;
2237 unset(
$value[$nullKey] );
2239 if ( count(
$value ) == 0 && !$includeNull ) {
2240 throw new InvalidArgumentException(
2241 __METHOD__ .
": empty input for field $field" );
2242 } elseif ( count(
$value ) == 0 ) {
2244 $list .=
"$field IS NULL";
2247 if ( $includeNull ) {
2251 if ( count(
$value ) == 1 ) {
2261 if ( $includeNull ) {
2262 $list .=
" OR $field IS NULL)";
2265 } elseif (
$value ===
null ) {
2266 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2267 $list .=
"$field IS ";
2268 } elseif ( $mode == self::LIST_SET ) {
2269 $list .=
"$field = ";
2274 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2276 $list .=
"$field = ";
2289 if ( count( $sub ) ) {
2291 [ $baseKey =>
$base, $subKey => array_keys( $sub ) ],
2297 return $this->
makeList( $conds, self::LIST_OR );
2312 public function bitAnd( $fieldLeft, $fieldRight ) {
2313 return "($fieldLeft & $fieldRight)";
2316 public function bitOr( $fieldLeft, $fieldRight ) {
2317 return "($fieldLeft | $fieldRight)";
2321 return 'CONCAT(' . implode(
',', $stringList ) .
')';
2325 $delim, $table, $field, $conds =
'', $join_conds = []
2327 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->
addQuotes( $delim ) .
')';
2329 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
2334 $functionBody =
"$input FROM $startPosition";
2335 if ( $length !==
null ) {
2336 $functionBody .=
" FOR $length";
2338 return 'SUBSTRING(' . $functionBody .
')';
2354 if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2355 throw new InvalidArgumentException(
2356 '$startPosition must be a positive integer'
2359 if ( !( is_int( $length ) && $length >= 0 || $length ===
null ) ) {
2360 throw new InvalidArgumentException(
2361 '$length must be null or an integer greater than or equal to 0'
2369 return "CAST( $field AS CHARACTER )";
2373 return 'CAST( ' . $field .
' AS INTEGER )';
2392 $this->currentDomain->getSchema(),
2393 $this->currentDomain->getTablePrefix()
2404 $this->currentDomain = $domain;
2408 return $this->currentDomain->getDatabase();
2419 __METHOD__ .
': got Subquery instance when expecting a string.'
2423 # Skip the entire process when we have a string quoted on both ends.
2424 # Note that we check the end so that we will still quote any use of
2425 # use of `database`.table. But won't break things if someone wants
2426 # to query a database table with a dot in the name.
2431 # Lets test for any bits of text that should never show up in a table
2432 # name. Basically anything like JOIN or ON which are actually part of
2433 # SQL queries, but may end up inside of the table value to combine
2434 # sql. Such as how the API is doing.
2435 # Note that we use a whitespace test rather than a \b test to avoid
2436 # any remote case where a word like on may be inside of a table name
2437 # surrounded by symbols which may be considered word breaks.
2438 if ( preg_match(
'/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i',
$name ) !== 0 ) {
2439 $this->queryLogger->warning(
2440 __METHOD__ .
": use of subqueries is not supported this way.",
2441 [
'exception' =>
new RuntimeException() ]
2447 # Split database and table into proper variables.
2450 # Quote $table and apply the prefix if not quoted.
2451 # $tableName might be empty if this is called from Database::replaceVars()
2452 $tableName =
"{$prefix}{$table}";
2453 if ( $format ===
'quoted'
2455 && $tableName !==
''
2460 # Quote $schema and $database and merge them with the table name if needed
2474 # We reverse the explode so that database.table and table both output the correct table.
2475 $dbDetails = explode(
'.',
$name, 3 );
2476 if ( count( $dbDetails ) == 3 ) {
2477 list( $database, $schema, $table ) = $dbDetails;
2478 # We don't want any prefix added in this case
2480 } elseif ( count( $dbDetails ) == 2 ) {
2481 list( $database, $table ) = $dbDetails;
2482 # We don't want any prefix added in this case
2484 # In dbs that support it, $database may actually be the schema
2485 # but that doesn't affect any of the functionality here
2488 list( $table ) = $dbDetails;
2489 if ( isset( $this->tableAliases[$table] ) ) {
2490 $database = $this->tableAliases[$table][
'dbname'];
2491 $schema = is_string( $this->tableAliases[$table][
'schema'] )
2492 ? $this->tableAliases[$table][
'schema']
2494 $prefix = is_string( $this->tableAliases[$table][
'prefix'] )
2495 ? $this->tableAliases[$table][
'prefix']
2504 return [ $database, $schema, $prefix, $table ];
2514 if ( strlen( $namespace ) ) {
2518 $relation = $namespace .
'.' . $relation;
2525 $inArray = func_get_args();
2528 foreach ( $inArray
as $name ) {
2536 $inArray = func_get_args();
2539 foreach ( $inArray
as $name ) {
2558 if ( is_string( $table ) ) {
2559 $quotedTable = $this->
tableName( $table );
2560 } elseif ( $table instanceof
Subquery ) {
2561 $quotedTable = (
string)$table;
2563 throw new InvalidArgumentException(
"Table must be a string or Subquery." );
2566 if ( $alias ===
false || $alias === $table ) {
2567 if ( $table instanceof
Subquery ) {
2568 throw new InvalidArgumentException(
"Subquery table missing alias." );
2571 return $quotedTable;
2585 foreach (
$tables as $alias => $table ) {
2586 if ( is_numeric( $alias ) ) {
2604 if ( !$alias || (
string)$alias === (
string)
$name ) {
2619 foreach ( $fields
as $alias => $field ) {
2620 if ( is_numeric( $alias ) ) {
2640 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2644 $use_index = (
array)$use_index;
2645 $ignore_index = (
array)$ignore_index;
2646 $join_conds = (
array)$join_conds;
2648 foreach (
$tables as $alias => $table ) {
2649 if ( !is_string( $alias ) ) {
2654 if ( is_array( $table ) ) {
2656 if ( count( $table ) > 1 ) {
2657 $joinedTable =
'(' .
2659 $table, $use_index, $ignore_index, $join_conds ) .
')';
2662 $innerTable = reset( $table );
2663 $innerAlias =
key( $table );
2666 is_string( $innerAlias ) ? $innerAlias : $innerTable
2674 if ( isset( $join_conds[$alias] ) ) {
2675 list( $joinType, $conds ) = $join_conds[$alias];
2676 $tableClause = $joinType;
2677 $tableClause .=
' ' . $joinedTable;
2678 if ( isset( $use_index[$alias] ) ) {
2681 $tableClause .=
' ' . $use;
2684 if ( isset( $ignore_index[$alias] ) ) {
2686 implode(
',', (
array)$ignore_index[$alias] ) );
2687 if ( $ignore !=
'' ) {
2688 $tableClause .=
' ' . $ignore;
2693 $tableClause .=
' ON (' . $on .
')';
2696 $retJOIN[] = $tableClause;
2697 } elseif ( isset( $use_index[$alias] ) ) {
2699 $tableClause = $joinedTable;
2701 implode(
',', (
array)$use_index[$alias] )
2704 $ret[] = $tableClause;
2705 } elseif ( isset( $ignore_index[$alias] ) ) {
2707 $tableClause = $joinedTable;
2709 implode(
',', (
array)$ignore_index[$alias] )
2712 $ret[] = $tableClause;
2714 $tableClause = $joinedTable;
2716 $ret[] = $tableClause;
2721 $implicitJoins =
$ret ? implode(
',',
$ret ) :
"";
2722 $explicitJoins = $retJOIN ? implode(
' ', $retJOIN ) :
"";
2725 return implode(
' ', [ $implicitJoins, $explicitJoins ] );
2735 return $this->indexAliases[$index] ?? $index;
2739 if (
$s instanceof
Blob ) {
2742 if (
$s ===
null ) {
2744 } elseif ( is_bool(
$s ) ) {
2747 # This will also quote numeric values. This should be harmless,
2748 # and protects against weird problems that occur when they really
2749 # _are_ strings such as article titles and string->number->string
2750 # conversion is not 1:1.
2756 return '"' . str_replace(
'"',
'""',
$s ) .
'"';
2769 return $name[0] ==
'"' && substr(
$name, -1, 1 ) ==
'"';
2778 return str_replace( [ $escapeChar,
'%',
'_' ],
2779 [
"{$escapeChar}{$escapeChar}",
"{$escapeChar}%",
"{$escapeChar}_" ],
2851 if ( count(
$rows ) == 0 ) {
2855 $uniqueIndexes = (
array)$uniqueIndexes;
2857 if ( !is_array( reset(
$rows ) ) ) {
2866 $indexWhereClauses = [];
2867 foreach ( $uniqueIndexes
as $index ) {
2868 $indexColumns = (
array)$index;
2869 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2870 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2873 'New record does not provide all values for unique key (' .
2874 implode(
', ', $indexColumns ) .
')'
2876 } elseif ( in_array(
null, $indexRowValues,
true ) ) {
2879 'New record has a null value for unique key (' .
2880 implode(
', ', $indexColumns ) .
')'
2886 if ( $indexWhereClauses ) {
2897 }
catch ( Exception
$e ) {
2915 if ( !is_array( reset(
$rows ) ) ) {
2919 $sql =
"REPLACE INTO $table (" . implode(
',', array_keys(
$rows[0] ) ) .
') VALUES ';
2929 $sql .=
'(' . $this->
makeList( $row ) .
')';
2938 if (
$rows === [] ) {
2942 $uniqueIndexes = (
array)$uniqueIndexes;
2943 if ( !is_array( reset(
$rows ) ) ) {
2947 if ( count( $uniqueIndexes ) ) {
2950 foreach ( $uniqueIndexes
as $index ) {
2951 $index = is_array( $index ) ? $index : [ $index ];
2953 foreach ( $index
as $column ) {
2954 $rowKey[$column] = $row[$column];
2956 $clauses[] = $this->
makeList( $rowKey, self::LIST_AND );
2959 $where = [ $this->
makeList( $clauses, self::LIST_OR ) ];
2967 # Update any existing conflicting row(s)
2968 if ( $where !==
false ) {
2972 # Now insert any non-conflicting row(s)
2977 }
catch ( Exception
$e ) {
2985 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2992 $delTable = $this->
tableName( $delTable );
2993 $joinTable = $this->
tableName( $joinTable );
2994 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2995 if ( $conds !=
'*' ) {
2996 $sql .=
'WHERE ' . $this->
makeList( $conds, self::LIST_AND );
3005 $sql =
"SHOW COLUMNS FROM $table LIKE \"$field\";";
3006 $res = $this->
query( $sql, __METHOD__ );
3011 if ( preg_match(
'/\((.*)\)/', $row->Type, $m ) ) {
3020 public function delete( $table, $conds,
$fname = __METHOD__ ) {
3022 throw new DBUnexpectedError( $this, __METHOD__ .
' called with no conditions' );
3026 $sql =
"DELETE FROM $table";
3028 if ( $conds !=
'*' ) {
3029 if ( is_array( $conds ) ) {
3030 $conds = $this->
makeList( $conds, self::LIST_AND );
3032 $sql .=
' WHERE ' . $conds;
3041 $destTable, $srcTable, $varMap, $conds,
3042 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3044 static $hints = [
'NO_AUTO_COLUMNS' ];
3046 $insertOptions = (
array)$insertOptions;
3047 $selectOptions = (
array)$selectOptions;
3049 if ( $this->cliMode && $this->
isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3058 array_diff( $insertOptions, $hints ),
3069 array_diff( $insertOptions, $hints ),
3104 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3110 foreach ( $varMap
as $dstColumn => $sourceColumnOrSql ) {
3113 $selectOptions[] =
'FOR UPDATE';
3115 $srcTable, implode(
',', $fields ), $conds,
$fname, $selectOptions, $selectJoinConds
3126 foreach (
$res as $row ) {
3139 if (
$rows && $ok ) {
3151 }
catch ( Exception
$e ) {
3173 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3175 $destTable = $this->
tableName( $destTable );
3177 if ( !is_array( $insertOptions ) ) {
3178 $insertOptions = [ $insertOptions ];
3185 array_values( $varMap ),
3192 $sql =
"INSERT $insertOptions" .
3193 " INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
') ' .
3219 if ( !is_numeric( $limit ) ) {
3221 "Invalid non-numeric limit passed to limitResult()\n" );
3224 return "$sql LIMIT "
3225 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," :
"" )
3234 $glue = $all ?
') UNION ALL (' :
') UNION (';
3236 return '(' . implode( $glue, $sqls ) .
')';
3240 $table,
$vars,
array $permute_conds, $extra_conds =
'',
$fname = __METHOD__,
3245 foreach ( $permute_conds
as $field => $values ) {
3250 $values = array_unique( $values );
3252 foreach ( $conds
as $cond ) {
3255 $newConds[] = $cond;
3261 $extra_conds = $extra_conds ===
'' ? [] : (
array)$extra_conds;
3265 if ( count( $conds ) === 1 &&
3278 $limit =
$options[
'LIMIT'] ??
null;
3279 $offset =
$options[
'OFFSET'] ??
false;
3284 if ( array_key_exists(
'INNER ORDER BY',
$options ) ) {
3287 if ( $limit !==
null && is_numeric( $offset ) && $offset != 0 ) {
3291 $options[
'LIMIT'] = $limit + $offset;
3297 foreach ( $conds
as $cond ) {
3303 if ( $limit !==
null ) {
3304 $sql = $this->
limitResult( $sql, $limit, $offset );
3311 if ( is_array( $cond ) ) {
3312 $cond = $this->
makeList( $cond, self::LIST_AND );
3315 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3319 return "REPLACE({$orig}, {$old}, {$new})";
3371 $args = func_get_args();
3372 $function = array_shift(
$args );
3375 $this->
begin( __METHOD__ );
3382 $retVal = $function( ...
$args );
3387 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3393 }
while ( --$tries > 0 );
3395 if ( $tries <= 0 ) {
3400 $this->
commit( __METHOD__ );
3407 # Real waits are implemented in the subclass.
3435 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
3436 $this->trxAutomatic =
true;
3452 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
3453 $this->trxAutomatic =
true;
3460 $this->
startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3464 }
catch ( Exception
$e ) {
3472 if ( !$this->
trxLevel || !$this->trxAtomicLevels ) {
3473 throw new DBUnexpectedError( $this,
"No atomic section is open (got $fname)." );
3482 if ( $this->
trxLevel && $this->trxAtomicLevels ) {
3483 $levelInfo = end( $this->trxAtomicLevels );
3485 return $levelInfo[1];
3500 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3501 if ( $info[2] === $old ) {
3502 $this->trxPreCommitCallbacks[$key][2] = $new;
3505 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3506 if ( $info[2] === $old ) {
3507 $this->trxIdleCallbacks[$key][2] = $new;
3510 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3511 if ( $info[2] === $old ) {
3512 $this->trxEndCallbacks[$key][2] = $new;
3515 foreach ( $this->trxSectionCancelCallbacks
as $key => $info ) {
3516 if ( $info[2] === $old ) {
3517 $this->trxSectionCancelCallbacks[$key][2] = $new;
3545 $this->trxIdleCallbacks = array_filter(
3546 $this->trxIdleCallbacks,
3547 function ( $entry )
use ( $sectionIds ) {
3548 return !in_array( $entry[2], $sectionIds,
true );
3551 $this->trxPreCommitCallbacks = array_filter(
3552 $this->trxPreCommitCallbacks,
3553 function ( $entry )
use ( $sectionIds ) {
3554 return !in_array( $entry[2], $sectionIds,
true );
3558 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3559 if ( in_array( $entry[2], $sectionIds,
true ) ) {
3560 $callback = $entry[0];
3561 $this->trxEndCallbacks[$key][0] =
function ()
use ( $callback ) {
3563 return $callback( self::TRIGGER_ROLLBACK, $this );
3566 $this->trxEndCallbacks[$key][2] =
null;
3570 foreach ( $this->trxSectionCancelCallbacks
as $key => $entry ) {
3571 if ( in_array( $entry[2], $sectionIds,
true ) ) {
3572 $this->trxSectionCancelCallbacks[$key][2] = $newSectionId;
3579 $this->trxRecurringCallbacks[
$name] = $callback;
3581 unset( $this->trxRecurringCallbacks[
$name] );
3594 $this->trxEndCallbacksSuppressed = $suppress;
3609 throw new DBUnexpectedError( $this, __METHOD__ .
': a transaction is still open.' );
3612 if ( $this->trxEndCallbacksSuppressed ) {
3617 $autoTrx = $this->
getFlag( self::DBO_TRX );
3621 $callbacks = array_merge(
3622 $this->trxIdleCallbacks,
3623 $this->trxEndCallbacks
3625 $this->trxIdleCallbacks = [];
3626 $this->trxEndCallbacks = [];
3630 if ( $trigger === self::TRIGGER_ROLLBACK ) {
3631 $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks );
3633 $this->trxSectionCancelCallbacks = [];
3635 foreach ( $callbacks
as $callback ) {
3637 list( $phpCallback ) = $callback;
3641 call_user_func( $phpCallback, $trigger, $this );
3642 }
catch ( Exception $ex ) {
3643 call_user_func( $this->errorLogger, $ex );
3648 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
3652 $this->
setFlag( self::DBO_TRX );
3658 }
while ( count( $this->trxIdleCallbacks ) );
3660 if (
$e instanceof Exception ) {
3682 $this->trxPreCommitCallbacks = [];
3683 foreach ( $callbacks
as $callback ) {
3686 list( $phpCallback ) = $callback;
3687 $phpCallback( $this );
3688 }
catch ( Exception $ex ) {
3693 }
while ( count( $this->trxPreCommitCallbacks ) );
3695 if (
$e instanceof Exception ) {
3710 $trigger,
array $sectionIds =
null
3718 $this->trxSectionCancelCallbacks = [];
3719 foreach ( $callbacks
as $entry ) {
3720 if ( $sectionIds ===
null || in_array( $entry[2], $sectionIds,
true ) ) {
3722 $entry[0]( $trigger, $this );
3723 }
catch ( Exception $ex ) {
3726 }
catch ( Throwable $ex ) {
3731 $notCancelled[] = $entry;
3734 }
while ( count( $this->trxSectionCancelCallbacks ) );
3735 $this->trxSectionCancelCallbacks = $notCancelled;
3737 if (
$e !==
null ) {
3752 if ( $this->trxEndCallbacksSuppressed ) {
3759 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3761 $phpCallback( $trigger, $this );
3762 }
catch ( Exception $ex ) {
3768 if (
$e instanceof Exception ) {
3821 if ( strlen( $savepointId ) > 30 ) {
3826 'There have been an excessively large number of atomic sections in a transaction'
3827 .
" started by $this->trxFname (at $fname)"
3831 return $savepointId;
3835 $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE
3840 $this->
begin(
$fname, self::TRANSACTION_INTERNAL );
3843 if ( $this->
getFlag( self::DBO_TRX ) ) {
3849 $this->trxAutomaticAtomic =
true;
3851 } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
3857 $this->trxAtomicLevels[] = [
$fname, $sectionId, $savepointId ];
3858 $this->queryLogger->debug(
'startAtomic: entering level ' .
3859 ( count( $this->trxAtomicLevels ) - 1 ) .
" ($fname)" );
3865 if ( !$this->
trxLevel || !$this->trxAtomicLevels ) {
3866 throw new DBUnexpectedError( $this,
"No atomic section is open (got $fname)." );
3870 $pos = count( $this->trxAtomicLevels ) - 1;
3871 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3872 $this->queryLogger->debug(
"endAtomic: leaving level $pos ($fname)" );
3874 if ( $savedFname !==
$fname ) {
3877 "Invalid atomic section ended (got $fname but expected $savedFname)."
3882 array_pop( $this->trxAtomicLevels );
3884 if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3886 } elseif ( $savepointId !==
null && $savepointId !== self::$NOT_APPLICABLE ) {
3893 if ( $currentSectionId ) {
3901 if ( !$this->
trxLevel || !$this->trxAtomicLevels ) {
3902 throw new DBUnexpectedError( $this,
"No atomic section is open (got $fname)." );
3908 $excisedFnames = [];
3909 if ( $sectionId !==
null ) {
3912 foreach ( $this->trxAtomicLevels
as $i =>
list( $asFname, $asId, $spId ) ) {
3913 if ( $asId === $sectionId ) {
3921 $len = count( $this->trxAtomicLevels );
3922 for ( $i = $pos + 1; $i < $len; ++$i ) {
3923 $excisedFnames[] = $this->trxAtomicLevels[$i][0];
3924 $excisedIds[] = $this->trxAtomicLevels[$i][1];
3926 $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
3931 $pos = count( $this->trxAtomicLevels ) - 1;
3932 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3934 if ( $excisedFnames ) {
3935 $this->queryLogger->debug(
"cancelAtomic: canceling level $pos ($savedFname) " .
3936 "and descendants " . implode(
', ', $excisedFnames ) );
3938 $this->queryLogger->debug(
"cancelAtomic: canceling level $pos ($savedFname)" );
3941 if ( $savedFname !==
$fname ) {
3944 "Invalid atomic section ended (got $fname but expected $savedFname)."
3949 array_pop( $this->trxAtomicLevels );
3950 $excisedIds[] = $savedSectionId;
3953 if ( $savepointId !==
null ) {
3955 if ( $savepointId === self::$NOT_APPLICABLE ) {
3961 $this->trxStatusIgnoredCause =
null;
3966 } elseif ( $this->
trxStatus > self::STATUS_TRX_ERROR ) {
3968 $this->
trxStatus = self::STATUS_TRX_ERROR;
3971 "Uncancelable atomic section canceled (got $fname)."
3980 $this->affectedRowCount = 0;
3984 $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
3989 }
catch ( Exception
$e ) {
3999 final public function begin(
$fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
4000 static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
4001 if ( !in_array( $mode, $modes,
true ) ) {
4002 throw new DBUnexpectedError( $this,
"$fname: invalid mode parameter '$mode'." );
4007 if ( $this->trxAtomicLevels ) {
4009 $msg =
"$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
4011 } elseif ( !$this->trxAutomatic ) {
4012 $msg =
"$fname: Explicit transaction already active (from {$this->trxFname}).";
4015 $msg =
"$fname: Implicit transaction already active (from {$this->trxFname}).";
4018 } elseif ( $this->
getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
4019 $msg =
"$fname: Implicit transaction expected (DBO_TRX set).";
4027 $this->trxStatusIgnoredCause =
null;
4028 $this->trxAtomicCounter = 0;
4030 $this->trxFname =
$fname;
4031 $this->trxDoneWrites =
false;
4032 $this->trxAutomaticAtomic =
false;
4033 $this->trxAtomicLevels = [];
4034 $this->trxShortId = sprintf(
'%06x', mt_rand( 0, 0xffffff ) );
4035 $this->trxWriteDuration = 0.0;
4036 $this->trxWriteQueryCount = 0;
4037 $this->trxWriteAffectedRows = 0;
4038 $this->trxWriteAdjDuration = 0.0;
4039 $this->trxWriteAdjQueryCount = 0;
4040 $this->trxWriteCallers = [];
4043 $this->trxReplicaLag =
null;
4048 $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
4062 final public function commit(
$fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4063 static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
4064 if ( !in_array( $flush, $modes,
true ) ) {
4065 throw new DBUnexpectedError( $this,
"$fname: invalid flush parameter '$flush'." );
4068 if ( $this->
trxLevel && $this->trxAtomicLevels ) {
4073 "$fname: Got COMMIT while atomic sections $levels are still open."
4077 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
4080 } elseif ( !$this->trxAutomatic ) {
4083 "$fname: Flushing an explicit transaction, getting out of sync."
4087 $this->queryLogger->error(
4088 "$fname: No transaction to commit, something got out of sync." );
4090 } elseif ( $this->trxAutomatic ) {
4093 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
4103 $this->
trxStatus = self::STATUS_TRX_NONE;
4105 if ( $this->trxDoneWrites ) {
4106 $this->lastWriteTime = microtime(
true );
4107 $this->trxProfiler->transactionWritingOut(
4112 $this->trxWriteAffectedRows
4117 if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4139 if ( $flush !== self::FLUSHING_INTERNAL
4140 && $flush !== self::FLUSHING_ALL_PEERS
4141 && $this->
getFlag( self::DBO_TRX )
4145 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
4153 $this->
trxStatus = self::STATUS_TRX_NONE;
4154 $this->trxAtomicLevels = [];
4158 if ( $this->trxDoneWrites ) {
4159 $this->trxProfiler->transactionWritingOut(
4164 $this->trxWriteAffectedRows
4171 $this->trxIdleCallbacks = [];
4172 $this->trxPreCommitCallbacks = [];
4175 if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4178 }
catch ( Exception
$e ) {
4183 }
catch ( Exception
$e ) {
4187 $this->affectedRowCount = 0;
4199 # Disconnects cause rollback anyway, so ignore those errors
4200 $ignoreErrors =
true;
4201 $this->
query(
'ROLLBACK',
$fname, $ignoreErrors );
4212 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
4224 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
4226 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
4230 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
4234 throw new RuntimeException( __METHOD__ .
' is not implemented in descendant class' );
4238 $t =
new ConvertibleTimestamp( $ts );
4240 return $t->getTimestamp( TS_MW );
4244 if ( is_null( $ts ) ) {
4252 return ( $this->affectedRowCount ===
null )
4280 } elseif (
$result ===
true ) {
4288 public function ping( &$rtt =
null ) {
4290 if ( $this->
isOpen() && ( microtime(
true ) - $this->lastPing ) < self::PING_TTL ) {
4291 if ( !func_num_args() || $this->rttEstimate > 0 ) {
4298 $this->
clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
4299 $ok = ( $this->
query( self::PING_QUERY, __METHOD__,
true ) !==
false );
4317 $this->opened =
false;
4318 $this->conn =
false;
4331 $this->lastPing = microtime(
true );
4334 $this->connLogger->warning(
4335 $fname .
': lost connection to {dbserver}; reconnected',
4338 'exception' =>
new RuntimeException()
4344 $this->connLogger->error(
4345 $fname .
': lost connection to {dbserver} permanently',
4373 return ( $this->
trxLevel && $this->trxReplicaLag !==
null )
4387 'since' => microtime(
true )
4411 $res = [
'lag' => 0,
'since' => INF,
'pending' =>
false ];
4412 foreach ( func_get_args()
as $db ) {
4414 $status = $db->getSessionLagStatus();
4415 if (
$status[
'lag'] ===
false ) {
4416 $res[
'lag'] =
false;
4417 } elseif (
$res[
'lag'] !==
false ) {
4421 $res[
'pending'] =
$res[
'pending'] ?: $db->writesPending();
4440 if ( $b instanceof
Blob ) {
4451 callable $lineCallback =
null,
4452 callable $resultCallback =
null,
4454 callable $inputCallback =
null
4456 Wikimedia\suppressWarnings();
4457 $fp = fopen( $filename,
'r' );
4458 Wikimedia\restoreWarnings();
4460 if ( $fp ===
false ) {
4461 throw new RuntimeException(
"Could not open \"{$filename}\".\n" );
4465 $fname = __METHOD__ .
"( $filename )";
4470 $fp, $lineCallback, $resultCallback,
$fname, $inputCallback );
4471 }
catch ( Exception
$e ) {
4482 $this->schemaVars =
$vars;
4487 callable $lineCallback =
null,
4488 callable $resultCallback =
null,
4490 callable $inputCallback =
null
4492 $delimiterReset =
new ScopedCallback(
4500 while ( !feof( $fp ) ) {
4501 if ( $lineCallback ) {
4502 call_user_func( $lineCallback );
4505 $line = trim( fgets( $fp ) );
4507 if (
$line ==
'' ) {
4523 if ( $done || feof( $fp ) ) {
4526 if ( $inputCallback ) {
4527 $callbackResult = $inputCallback( $cmd );
4529 if ( is_string( $callbackResult ) || !$callbackResult ) {
4530 $cmd = $callbackResult;
4537 if ( $resultCallback ) {
4538 $resultCallback(
$res, $this );
4541 if (
$res ===
false ) {
4544 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4551 ScopedCallback::consume( $delimiterReset );
4563 if ( $this->delimiter ) {
4565 $newLine = preg_replace(
4566 '/' . preg_quote( $this->delimiter,
'/' ) .
'$/',
'', $newLine );
4567 if ( $newLine != $prev ) {
4597 return preg_replace_callback(
4599 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4600 \'\{\$ (\w+) }\' | # 3. addQuotes
4601 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4602 /\*\$ (\w+) \*/ # 5. leave unencoded
4607 if ( isset( $m[1] ) && $m[1] !==
'' ) {
4608 if ( $m[1] ===
'i' ) {
4613 } elseif ( isset( $m[3] ) && $m[3] !==
'' && array_key_exists( $m[3],
$vars ) ) {
4615 } elseif ( isset( $m[4] ) && $m[4] !==
'' && array_key_exists( $m[4],
$vars ) ) {
4617 } elseif ( isset( $m[5] ) && $m[5] !==
'' && array_key_exists( $m[5],
$vars ) ) {
4618 return $vars[$m[5]];
4634 if ( $this->schemaVars ) {
4657 return !isset( $this->namedLocksHeld[$lockName] );
4660 public function lock( $lockName, $method, $timeout = 5 ) {
4661 $this->namedLocksHeld[$lockName] = 1;
4666 public function unlock( $lockName, $method ) {
4667 unset( $this->namedLocksHeld[$lockName] );
4678 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4682 if ( !$this->
lock( $lockKey,
$fname, $timeout ) ) {
4686 $unlocker =
new ScopedCallback(
function ()
use ( $lockKey,
$fname ) {
4717 throw new DBUnexpectedError( $this,
"Transaction writes or callbacks still pending." );
4766 public function dropTable( $tableName, $fName = __METHOD__ ) {
4767 if ( !$this->
tableExists( $tableName, $fName ) ) {
4770 $sql =
"DROP TABLE " . $this->
tableName( $tableName ) .
" CASCADE";
4772 return $this->
query( $sql, $fName );
4780 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() )
4786 if ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() ) {
4790 return ConvertibleTimestamp::convert( $format, $expiry );
4805 $reason = $this->
getLBInfo(
'readOnlyReason' );
4807 return is_string( $reason ) ? $reason :
false;
4811 $this->tableAliases = $aliases;
4815 $this->indexAliases = $aliases;
4839 if ( !$this->conn ) {
4842 'DB connection was already closed or the connection dropped.'
4862 $this->connLogger->warning(
4863 "Cloning " . static::class .
" is not recommended; forking connection",
4864 [
'exception' =>
new RuntimeException() ]
4869 $this->opened =
false;
4870 $this->conn =
false;
4871 $this->trxEndCallbacks = [];
4872 $this->trxSectionCancelCallbacks = [];
4882 $this->lastPing = microtime(
true );
4892 throw new RuntimeException(
'Database serialization may cause problems, since ' .
4893 'the connection is not restored on wakeup.' );
4900 if ( $this->
trxLevel && $this->trxDoneWrites ) {
4901 trigger_error(
"Uncommitted DB writes (transaction from {$this->trxFname})." );
4905 if ( $danglingWriters ) {
4906 $fnames = implode(
', ', $danglingWriters );
4907 trigger_error(
"DB transaction writes or callbacks still pending ($fnames)." );
4910 if ( $this->conn ) {
4913 Wikimedia\suppressWarnings();
4915 Wikimedia\restoreWarnings();
4916 $this->conn =
false;
4917 $this->opened =
false;
4925class_alias( Database::class,
'DatabaseBase' );
4930class_alias( Database::class,
'Database' );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Class representing a cache/ephemeral data store.
Simple store for keeping values in an associative array for the current process.
Class to handle database/prefix specification for IDatabase domains.
static newFromId( $domain)
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like select() and insert() are usually more convenient. They take care of things like table prefixes and escaping for you. If you really need to make your own SQL
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
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
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
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
Wikitext formatted, in the key only.
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
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
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. '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 '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
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
presenting them properly to the user as errors is done by the caller return true use this to change the list i e rollback
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, 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. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
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
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 use $formDescriptor instead 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 set this to the key of the message First element is the message key
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
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
Allows to change the fields on the form that will be generated $name
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and insert
processing should stop and the error should be shown to the user * false
returning false will NOT prevent logging $e
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
Advanced database interface for IDatabase handles that include maintenance methods.
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
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))
if(is_array($mode)) switch( $mode) $input