MediaWiki  master
Database.php
Go to the documentation of this file.
1 <?php
26 namespace Wikimedia\Rdbms;
27 
28 use BagOStuff;
29 use Exception;
30 use HashBagOStuff;
31 use InvalidArgumentException;
32 use LogicException;
33 use Psr\Log\LoggerAwareInterface;
34 use Psr\Log\LoggerInterface;
35 use Psr\Log\NullLogger;
36 use RuntimeException;
37 use Throwable;
38 use UnexpectedValueException;
39 use Wikimedia\AtEase\AtEase;
40 use Wikimedia\ScopedCallback;
41 use Wikimedia\Timestamp\ConvertibleTimestamp;
42 
50 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
52  protected $srvCache;
54  protected $connLogger;
56  protected $queryLogger;
58  protected $replLogger;
60  protected $errorLogger;
62  protected $deprecationLogger;
64  protected $profiler;
66  protected $trxProfiler;
67 
69  protected $currentDomain;
70 
72  protected $conn;
73 
76 
78  protected $server;
80  protected $user;
82  protected $password;
84  protected $cliMode;
86  protected $agent;
88  protected $topologyRole;
92  protected $connectionParams;
97 
99  protected $flags;
101  protected $lbInfo = [];
103  protected $delimiter = ';';
105  protected $tableAliases = [];
107  protected $indexAliases = [];
109  protected $schemaVars;
110 
112  private $htmlErrors;
114  private $priorFlags = [];
115 
117  protected $sessionNamedLocks = [];
119  protected $sessionTempTables = [];
121  protected $sessionDirtyTempTables = [];
122 
124  private $trxShortId = '';
126  private $trxStatus = self::STATUS_TRX_NONE;
132  private $trxTimestamp = null;
134  private $trxReplicaLag = null;
136  private $trxFname = null;
138  private $trxDoneWrites = false;
140  private $trxAutomatic = false;
142  private $trxAtomicCounter = 0;
144  private $trxAtomicLevels = [];
146  private $trxAutomaticAtomic = false;
148  private $trxWriteCallers = [];
150  private $trxWriteDuration = 0.0;
152  private $trxWriteQueryCount = 0;
156  private $trxWriteAdjDuration = 0.0;
160  private $trxIdleCallbacks = [];
167  private $trxEndCallbacks = [];
173  private $trxEndCallbacksSuppressed = false;
174 
176  protected $affectedRowCount;
177 
179  private $lastPing = 0.0;
181  private $lastQuery = '';
183  private $lastWriteTime = false;
185  private $lastPhpError = false;
187  private $lastRoundTripEstimate = 0.0;
188 
190  private $ownerId;
191 
193  public const ATTR_DB_IS_FILE = 'db-is-file';
195  public const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
197  public const ATTR_SCHEMAS_AS_TABLE_GROUPS = 'supports-schemas';
198 
200  public const NEW_UNCONNECTED = 0;
202  public const NEW_CONNECTED = 1;
203 
205  public const STATUS_TRX_ERROR = 1;
207  public const STATUS_TRX_OK = 2;
209  public const STATUS_TRX_NONE = 3;
210 
212  private static $NOT_APPLICABLE = 'n/a';
214  private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
215 
217  private static $TEMP_NORMAL = 1;
219  private static $TEMP_PSEUDO_PERMANENT = 2;
220 
222  private static $DEADLOCK_TRIES = 4;
224  private static $DEADLOCK_DELAY_MIN = 500000;
226  private static $DEADLOCK_DELAY_MAX = 1500000;
227 
229  private static $PING_TTL = 1.0;
231  private static $PING_QUERY = 'SELECT 1 AS ping';
232 
234  private static $TINY_WRITE_SEC = 0.010;
236  private static $SLOW_WRITE_SEC = 0.500;
238  private static $SMALL_WRITE_ROWS = 100;
239 
241  protected static $MUTABLE_FLAGS = [
242  'DBO_DEBUG',
243  'DBO_NOBUFFER',
244  'DBO_TRX',
245  'DBO_DDLMODE',
246  ];
248  protected static $DBO_MUTABLE = (
250  );
251 
257  public function __construct( array $params ) {
258  $this->connectionParams = [
259  'host' => strlen( $params['host'] ) ? $params['host'] : null,
260  'user' => strlen( $params['user'] ) ? $params['user'] : null,
261  'dbname' => strlen( $params['dbname'] ) ? $params['dbname'] : null,
262  'schema' => strlen( $params['schema'] ) ? $params['schema'] : null,
263  'password' => is_string( $params['password'] ) ? $params['password'] : null,
264  'tablePrefix' => (string)$params['tablePrefix']
265  ];
266 
267  $this->lbInfo = $params['lbInfo'] ?? [];
268  $this->lazyMasterHandle = $params['lazyMasterHandle'] ?? null;
269  $this->connectionVariables = $params['variables'] ?? [];
270 
271  $this->flags = (int)$params['flags'];
272  $this->cliMode = (bool)$params['cliMode'];
273  $this->agent = (string)$params['agent'];
274  $this->topologyRole = (string)$params['topologyRole'];
275  $this->topologyRootMaster = (string)$params['topologicalMaster'];
276  $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'] ?? 10000;
277 
278  $this->srvCache = $params['srvCache'];
279  $this->profiler = is_callable( $params['profiler'] ) ? $params['profiler'] : null;
280  $this->trxProfiler = $params['trxProfiler'];
281  $this->connLogger = $params['connLogger'];
282  $this->queryLogger = $params['queryLogger'];
283  $this->replLogger = $params['replLogger'];
284  $this->errorLogger = $params['errorLogger'];
285  $this->deprecationLogger = $params['deprecationLogger'];
286 
287  // Set initial dummy domain until open() sets the final DB/prefix
288  $this->currentDomain = new DatabaseDomain(
289  $params['dbname'] != '' ? $params['dbname'] : null,
290  $params['schema'] != '' ? $params['schema'] : null,
291  $params['tablePrefix']
292  );
293 
294  $this->ownerId = $params['ownerId'] ?? null;
295  }
296 
305  final public function initConnection() {
306  if ( $this->isOpen() ) {
307  throw new LogicException( __METHOD__ . ': already connected' );
308  }
309  // Establish the connection
310  $this->doInitConnection();
311  }
312 
319  protected function doInitConnection() {
320  $this->open(
321  $this->connectionParams['host'],
322  $this->connectionParams['user'],
323  $this->connectionParams['password'],
324  $this->connectionParams['dbname'],
325  $this->connectionParams['schema'],
326  $this->connectionParams['tablePrefix']
327  );
328  }
329 
341  abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
342 
396  final public static function factory( $type, $params = [], $connect = self::NEW_CONNECTED ) {
397  $class = self::getClass( $type, $params['driver'] ?? null );
398 
399  if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
400  $params += [
401  // Default configuration
402  'host' => null,
403  'user' => null,
404  'password' => null,
405  'dbname' => null,
406  'schema' => null,
407  'tablePrefix' => '',
408  'flags' => 0,
409  'variables' => [],
410  'lbInfo' => [],
411  'cliMode' => ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ),
412  'agent' => '',
413  'ownerId' => null,
414  'topologyRole' => null,
415  'topologicalMaster' => null,
416  // Objects and callbacks
417  'lazyMasterHandle' => $params['lazyMasterHandle'] ?? null,
418  'srvCache' => $params['srvCache'] ?? new HashBagOStuff(),
419  'profiler' => $params['profiler'] ?? null,
420  'trxProfiler' => $params['trxProfiler'] ?? new TransactionProfiler(),
421  'connLogger' => $params['connLogger'] ?? new NullLogger(),
422  'queryLogger' => $params['queryLogger'] ?? new NullLogger(),
423  'replLogger' => $params['replLogger'] ?? new NullLogger(),
424  'errorLogger' => $params['errorLogger'] ?? function ( Throwable $e ) {
425  trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
426  },
427  'deprecationLogger' => $params['deprecationLogger'] ?? function ( $msg ) {
428  trigger_error( $msg, E_USER_DEPRECATED );
429  }
430  ];
431 
433  $conn = new $class( $params );
434  if ( $connect === self::NEW_CONNECTED ) {
435  $conn->initConnection();
436  }
437  } else {
438  $conn = null;
439  }
440 
441  return $conn;
442  }
443 
451  final public static function attributesFromType( $dbType, $driver = null ) {
452  static $defaults = [
453  self::ATTR_DB_IS_FILE => false,
454  self::ATTR_DB_LEVEL_LOCKING => false,
455  self::ATTR_SCHEMAS_AS_TABLE_GROUPS => false
456  ];
457 
458  $class = self::getClass( $dbType, $driver );
459 
460  return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
461  }
462 
469  private static function getClass( $dbType, $driver = null ) {
470  // For database types with built-in support, the below maps type to IDatabase
471  // implementations. For types with multiple driver implementations (PHP extensions),
472  // an array can be used, keyed by extension name. In case of an array, the
473  // optional 'driver' parameter can be used to force a specific driver. Otherwise,
474  // we auto-detect the first available driver. For types without built-in support,
475  // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
476  static $builtinTypes = [
477  'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
478  'sqlite' => DatabaseSqlite::class,
479  'postgres' => DatabasePostgres::class,
480  ];
481 
482  $dbType = strtolower( $dbType );
483  $class = false;
484 
485  if ( isset( $builtinTypes[$dbType] ) ) {
486  $possibleDrivers = $builtinTypes[$dbType];
487  if ( is_string( $possibleDrivers ) ) {
488  $class = $possibleDrivers;
489  } elseif ( (string)$driver !== '' ) {
490  if ( !isset( $possibleDrivers[$driver] ) ) {
491  throw new InvalidArgumentException( __METHOD__ .
492  " type '$dbType' does not support driver '{$driver}'" );
493  }
494 
495  $class = $possibleDrivers[$driver];
496  } else {
497  foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
498  if ( extension_loaded( $posDriver ) ) {
499  $class = $possibleClass;
500  break;
501  }
502  }
503  }
504  } else {
505  $class = 'Database' . ucfirst( $dbType );
506  }
507 
508  if ( $class === false ) {
509  throw new InvalidArgumentException( __METHOD__ .
510  " no viable database extension found for type '$dbType'" );
511  }
512 
513  return $class;
514  }
515 
521  protected static function getAttributes() {
522  return [];
523  }
524 
532  public function setLogger( LoggerInterface $logger ) {
533  $this->queryLogger = $logger;
534  }
535 
536  public function getServerInfo() {
537  return $this->getServerVersion();
538  }
539 
540  public function getTopologyRole() {
541  return $this->topologyRole;
542  }
543 
544  public function getTopologyRootMaster() {
546  }
547 
548  final public function trxLevel() {
549  return ( $this->trxShortId != '' ) ? 1 : 0;
550  }
551 
552  public function trxTimestamp() {
553  return $this->trxLevel() ? $this->trxTimestamp : null;
554  }
555 
560  public function trxStatus() {
561  return $this->trxStatus;
562  }
563 
564  public function tablePrefix( $prefix = null ) {
565  $old = $this->currentDomain->getTablePrefix();
566  if ( $prefix !== null ) {
567  $this->currentDomain = new DatabaseDomain(
568  $this->currentDomain->getDatabase(),
569  $this->currentDomain->getSchema(),
570  $prefix
571  );
572  }
573 
574  return $old;
575  }
576 
577  public function dbSchema( $schema = null ) {
578  if ( strlen( $schema ) && $this->getDBname() === null ) {
579  throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
580  }
581 
582  $old = $this->currentDomain->getSchema();
583  if ( $schema !== null ) {
584  $this->currentDomain = new DatabaseDomain(
585  $this->currentDomain->getDatabase(),
586  // DatabaseDomain uses null for unspecified schemas
587  strlen( $schema ) ? $schema : null,
588  $this->currentDomain->getTablePrefix()
589  );
590  }
591 
592  return (string)$old;
593  }
594 
599  protected function relationSchemaQualifier() {
600  return $this->dbSchema();
601  }
602 
603  public function getLBInfo( $name = null ) {
604  if ( $name === null ) {
605  return $this->lbInfo;
606  }
607 
608  if ( array_key_exists( $name, $this->lbInfo ) ) {
609  return $this->lbInfo[$name];
610  }
611 
612  return null;
613  }
614 
615  public function setLBInfo( $nameOrArray, $value = null ) {
616  if ( is_array( $nameOrArray ) ) {
617  $this->lbInfo = $nameOrArray;
618  } elseif ( is_string( $nameOrArray ) ) {
619  if ( $value !== null ) {
620  $this->lbInfo[$nameOrArray] = $value;
621  } else {
622  unset( $this->lbInfo[$nameOrArray] );
623  }
624  } else {
625  throw new InvalidArgumentException( "Got non-string key" );
626  }
627  }
628 
635  protected function getLazyMasterHandle() {
637  }
638 
643  public function implicitOrderby() {
644  return true;
645  }
646 
647  public function lastQuery() {
648  return $this->lastQuery;
649  }
650 
651  public function lastDoneWrites() {
652  return $this->lastWriteTime ?: false;
653  }
654 
655  public function writesPending() {
656  return $this->trxLevel() && $this->trxDoneWrites;
657  }
658 
659  public function writesOrCallbacksPending() {
660  return $this->trxLevel() && (
661  $this->trxDoneWrites ||
662  $this->trxIdleCallbacks ||
663  $this->trxPreCommitCallbacks ||
664  $this->trxEndCallbacks ||
666  );
667  }
668 
669  public function preCommitCallbacksPending() {
670  return $this->trxLevel() && $this->trxPreCommitCallbacks;
671  }
672 
676  final protected function getTransactionRoundId() {
677  // If transaction round participation is enabled, see if one is active
678  if ( $this->getFlag( self::DBO_TRX ) ) {
679  $id = $this->getLBInfo( self::LB_TRX_ROUND_ID );
680 
681  return is_string( $id ) ? $id : null;
682  }
683 
684  return null;
685  }
686 
687  public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
688  if ( !$this->trxLevel() ) {
689  return false;
690  } elseif ( !$this->trxDoneWrites ) {
691  return 0.0;
692  }
693 
694  switch ( $type ) {
695  case self::ESTIMATE_DB_APPLY:
696  return $this->pingAndCalculateLastTrxApplyTime();
697  default: // everything
699  }
700  }
701 
705  private function pingAndCalculateLastTrxApplyTime() {
706  $this->ping( $rtt );
707 
708  $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
709  $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
710  // For omitted queries, make them count as something at least
711  $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
712  $applyTime += self::$TINY_WRITE_SEC * $omitted;
713 
714  return $applyTime;
715  }
716 
717  public function pendingWriteCallers() {
718  return $this->trxLevel() ? $this->trxWriteCallers : [];
719  }
720 
721  public function pendingWriteRowsAffected() {
723  }
724 
733  public function pendingWriteAndCallbackCallers() {
734  $fnames = $this->pendingWriteCallers();
735  foreach ( [
736  $this->trxIdleCallbacks,
737  $this->trxPreCommitCallbacks,
738  $this->trxEndCallbacks,
739  $this->trxSectionCancelCallbacks
740  ] as $callbacks ) {
741  foreach ( $callbacks as $callback ) {
742  $fnames[] = $callback[1];
743  }
744  }
745 
746  return $fnames;
747  }
748 
752  private function flatAtomicSectionList() {
753  return array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
754  return $accum === null ? $v[0] : "$accum, " . $v[0];
755  } );
756  }
757 
758  public function isOpen() {
759  return (bool)$this->conn;
760  }
761 
762  public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
763  if ( $flag & ~static::$DBO_MUTABLE ) {
764  throw new DBUnexpectedError(
765  $this,
766  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
767  );
768  }
769 
770  if ( $remember === self::REMEMBER_PRIOR ) {
771  array_push( $this->priorFlags, $this->flags );
772  }
773 
774  $this->flags |= $flag;
775  }
776 
777  public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
778  if ( $flag & ~static::$DBO_MUTABLE ) {
779  throw new DBUnexpectedError(
780  $this,
781  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
782  );
783  }
784 
785  if ( $remember === self::REMEMBER_PRIOR ) {
786  array_push( $this->priorFlags, $this->flags );
787  }
788 
789  $this->flags &= ~$flag;
790  }
791 
792  public function restoreFlags( $state = self::RESTORE_PRIOR ) {
793  if ( !$this->priorFlags ) {
794  return;
795  }
796 
797  if ( $state === self::RESTORE_INITIAL ) {
798  $this->flags = reset( $this->priorFlags );
799  $this->priorFlags = [];
800  } else {
801  $this->flags = array_pop( $this->priorFlags );
802  }
803  }
804 
805  public function getFlag( $flag ) {
806  return ( ( $this->flags & $flag ) === $flag );
807  }
808 
809  public function getDomainID() {
810  return $this->currentDomain->getId();
811  }
812 
822  abstract public function indexInfo( $table, $index, $fname = __METHOD__ );
823 
831  abstract public function strencode( $s );
832 
836  protected function installErrorHandler() {
837  $this->lastPhpError = false;
838  $this->htmlErrors = ini_set( 'html_errors', '0' );
839  set_error_handler( [ $this, 'connectionErrorLogger' ] );
840  }
841 
847  protected function restoreErrorHandler() {
848  restore_error_handler();
849  if ( $this->htmlErrors !== false ) {
850  ini_set( 'html_errors', $this->htmlErrors );
851  }
852 
853  return $this->getLastPHPError();
854  }
855 
859  protected function getLastPHPError() {
860  if ( $this->lastPhpError ) {
861  $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
862  $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
863 
864  return $error;
865  }
866 
867  return false;
868  }
869 
877  public function connectionErrorLogger( $errno, $errstr ) {
878  $this->lastPhpError = $errstr;
879  }
880 
887  protected function getLogContext( array $extras = [] ) {
888  return array_merge(
889  [
890  'db_server' => $this->server,
891  'db_name' => $this->getDBname(),
892  'db_user' => $this->user,
893  ],
894  $extras
895  );
896  }
897 
898  final public function close( $fname = __METHOD__, $owner = null ) {
899  $error = null; // error to throw after disconnecting
900 
901  $wasOpen = (bool)$this->conn;
902  // This should mostly do nothing if the connection is already closed
903  if ( $this->conn ) {
904  // Roll back any dangling transaction first
905  if ( $this->trxLevel() ) {
906  if ( $this->trxAtomicLevels ) {
907  // Cannot let incomplete atomic sections be committed
908  $levels = $this->flatAtomicSectionList();
909  $error = "$fname: atomic sections $levels are still open";
910  } elseif ( $this->trxAutomatic ) {
911  // Only the connection manager can commit non-empty DBO_TRX transactions
912  // (empty ones we can silently roll back)
913  if ( $this->writesOrCallbacksPending() ) {
914  $error = "$fname: " .
915  "expected mass rollback of all peer transactions (DBO_TRX set)";
916  }
917  } else {
918  // Manual transactions should have been committed or rolled
919  // back, even if empty.
920  $error = "$fname: transaction is still open (from {$this->trxFname})";
921  }
922 
923  if ( $this->trxEndCallbacksSuppressed && $error === null ) {
924  $error = "$fname: callbacks are suppressed; cannot properly commit";
925  }
926 
927  // Rollback the changes and run any callbacks as needed
928  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
929  }
930 
931  // Close the actual connection in the binding handle
932  $closed = $this->closeConnection();
933  } else {
934  $closed = true; // already closed; nothing to do
935  }
936 
937  $this->conn = null;
938 
939  // Log or throw any unexpected errors after having disconnected
940  if ( $error !== null ) {
941  // T217819, T231443: if this is probably just LoadBalancer trying to recover from
942  // errors and shutdown, then log any problems and move on since the request has to
943  // end one way or another. Throwing errors is not very useful at some point.
944  if ( $this->ownerId !== null && $owner === $this->ownerId ) {
945  $this->queryLogger->error( $error );
946  } else {
947  throw new DBUnexpectedError( $this, $error );
948  }
949  }
950 
951  // Note that various subclasses call close() at the start of open(), which itself is
952  // called by replaceLostConnection(). In that case, just because onTransactionResolution()
953  // callbacks are pending does not mean that an exception should be thrown. Rather, they
954  // will be executed after the reconnection step.
955  if ( $wasOpen ) {
956  // Sanity check that no callbacks are dangling
957  $fnames = $this->pendingWriteAndCallbackCallers();
958  if ( $fnames ) {
959  throw new RuntimeException(
960  "Transaction callbacks are still pending: " . implode( ', ', $fnames )
961  );
962  }
963  }
964 
965  return $closed;
966  }
967 
976  final protected function assertHasConnectionHandle() {
977  if ( !$this->isOpen() ) {
978  throw new DBUnexpectedError( $this, "DB connection was already closed" );
979  }
980  }
981 
987  protected function assertIsWritableMaster() {
988  $info = $this->getReadOnlyReason();
989  if ( $info ) {
990  list( $reason, $source ) = $info;
991  if ( $source === 'role' ) {
992  throw new DBReadOnlyRoleError( $this, "Database is read-only: $reason" );
993  } else {
994  throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
995  }
996  }
997  }
998 
1004  abstract protected function closeConnection();
1005 
1035  abstract protected function doQuery( $sql );
1036 
1054  protected function isWriteQuery( $sql, $flags ) {
1055  if (
1056  $this->fieldHasBit( $flags, self::QUERY_CHANGE_ROWS ) ||
1057  $this->fieldHasBit( $flags, self::QUERY_CHANGE_SCHEMA )
1058  ) {
1059  return true;
1060  } elseif ( $this->fieldHasBit( $flags, self::QUERY_CHANGE_NONE ) ) {
1061  return false;
1062  }
1063  // BEGIN and COMMIT queries are considered read queries here.
1064  // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1065  // treat these as write queries, in that their results have "affected rows"
1066  // as meta data as from writes, instead of "num rows" as from reads.
1067  // But, we treat them as read queries because when reading data (from
1068  // either replica or master) we use transactions to enable repeatable-read
1069  // snapshots, which ensures we get consistent results from the same snapshot
1070  // for all queries within a request. Use cases:
1071  // - Treating these as writes would trigger ChronologyProtector (see method doc).
1072  // - We use this method to reject writes to replicas, but we need to allow
1073  // use of transactions on replicas for read snapshots. This is fine given
1074  // that transactions by themselves don't make changes, only actual writes
1075  // within the transaction matter, which we still detect.
1076  return !preg_match(
1077  '/^\s*(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\‍(SELECT)\b/i',
1078  $sql
1079  );
1080  }
1081 
1086  protected function getQueryVerb( $sql ) {
1087  return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
1088  }
1089 
1104  protected function isTransactableQuery( $sql ) {
1105  return !in_array(
1106  $this->getQueryVerb( $sql ),
1107  [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1108  true
1109  );
1110  }
1111 
1120  protected function getTempTableWrites( $sql, $pseudoPermanent ) {
1121  // Regexes for basic queries that can create/change/drop temporary tables.
1122  // For simplicity, this only looks for tables with sane, alphanumeric, names;
1123  // temporary tables only need simple programming names anyway.
1124  static $regexes = null;
1125  if ( $regexes === null ) {
1126  // Regex with a group for quoted table 0 and a group for quoted tables 1..N
1127  $qts = '((?:\w+|`\w+`|\'\w+\'|"\w+")(?:\s*,\s*(?:\w+|`\w+`|\'\w+\'|"\w+"))*)';
1128  // Regex to get query verb, table 0, and tables 1..N
1129  $regexes = [
1130  // DML write queries
1131  "/^(INSERT|REPLACE)\s+(?:\w+\s+)*?INTO\s+$qts/i",
1132  "/^(UPDATE)(?:\s+OR\s+\w+|\s+IGNORE|\s+ONLY)?\s+$qts/i",
1133  "/^(DELETE)\s+(?:\w+\s+)*?FROM(?:\s+ONLY)?\s+$qts/i",
1134  // DDL write queries
1135  "/^(CREATE)\s+TEMPORARY\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+$qts/i",
1136  "/^(DROP)\s+(?:TEMPORARY\s+)?TABLE(?:\s+IF\s+EXISTS)?\s+$qts/i",
1137  "/^(TRUNCATE)\s+(?:TEMPORARY\s+)?TABLE\s+$qts/i",
1138  "/^(ALTER)\s+TABLE\s+$qts/i"
1139  ];
1140  }
1141 
1142  $queryVerb = null;
1143  $queryTables = [];
1144  foreach ( $regexes as $regex ) {
1145  if ( preg_match( $regex, $sql, $m, PREG_UNMATCHED_AS_NULL ) ) {
1146  $queryVerb = $m[1];
1147  $allTables = preg_split( '/\s*,\s*/', $m[2] );
1148  foreach ( $allTables as $quotedTable ) {
1149  $queryTables[] = trim( $quotedTable, "\"'`" );
1150  }
1151  break;
1152  }
1153  }
1154 
1155  $tempTableChanges = [];
1156  foreach ( $queryTables as $table ) {
1157  if ( $queryVerb === 'CREATE' ) {
1158  // Record the type of temporary table being created
1159  $tableType = $pseudoPermanent ? self::$TEMP_PSEUDO_PERMANENT : self::$TEMP_NORMAL;
1160  } else {
1161  $tableType = $this->sessionTempTables[$table] ?? null;
1162  }
1163 
1164  if ( $tableType !== null ) {
1165  $tempTableChanges[] = [ $tableType, $queryVerb, $table ];
1166  }
1167  }
1168 
1169  return $tempTableChanges;
1170  }
1171 
1176  protected function registerTempWrites( $ret, array $changes ) {
1177  if ( $ret === false ) {
1178  return;
1179  }
1180 
1181  foreach ( $changes as list( $tmpTableType, $verb, $table ) ) {
1182  switch ( $verb ) {
1183  case 'CREATE':
1184  $this->sessionTempTables[$table] = $tmpTableType;
1185  break;
1186  case 'DROP':
1187  unset( $this->sessionTempTables[$table] );
1188  unset( $this->sessionDirtyTempTables[$table] );
1189  break;
1190  case 'TRUNCATE':
1191  unset( $this->sessionDirtyTempTables[$table] );
1192  break;
1193  default:
1194  $this->sessionDirtyTempTables[$table] = 1;
1195  break;
1196  }
1197  }
1198  }
1199 
1207  protected function isPristineTemporaryTable( $table ) {
1208  $rawTable = $this->tableName( $table, 'raw' );
1209 
1210  return (
1211  isset( $this->sessionTempTables[$rawTable] ) &&
1212  !isset( $this->sessionDirtyTempTables[$rawTable] )
1213  );
1214  }
1215 
1216  public function query( $sql, $fname = __METHOD__, $flags = self::QUERY_NORMAL ) {
1217  $flags = (int)$flags; // b/c; this field used to be a bool
1218  // Sanity check that the SQL query is appropriate in the current context and is
1219  // allowed for an outside caller (e.g. does not break transaction/session tracking).
1220  $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1221 
1222  // Send the query to the server and fetch any corresponding errors
1223  list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1224  if ( $ret === false ) {
1225  $ignoreErrors = $this->fieldHasBit( $flags, self::QUERY_SILENCE_ERRORS );
1226  // Throw an error unless both the ignore flag was set and a rollback is not needed
1227  $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1228  }
1229 
1230  return $this->resultObject( $ret );
1231  }
1232 
1253  final protected function executeQuery( $sql, $fname, $flags ) {
1254  $this->assertHasConnectionHandle();
1255 
1256  $priorTransaction = $this->trxLevel();
1257 
1258  if ( $this->isWriteQuery( $sql, $flags ) ) {
1259  // Do not treat temporary table writes as "meaningful writes" since they are only
1260  // visible to one session and are not permanent. Profile them as reads. Integration
1261  // tests can override this behavior via $flags.
1262  $pseudoPermanent = $this->fieldHasBit( $flags, self::QUERY_PSEUDO_PERMANENT );
1263  $tempTableChanges = $this->getTempTableWrites( $sql, $pseudoPermanent );
1264  $isPermWrite = !$tempTableChanges;
1265  foreach ( $tempTableChanges as list( $tmpType ) ) {
1266  $isPermWrite = $isPermWrite || ( $tmpType !== self::$TEMP_NORMAL );
1267  }
1268 
1269  // Permit temporary table writes on replica DB connections
1270  // but require a writable master connection for any persistent writes.
1271  if ( $isPermWrite ) {
1272  $this->assertIsWritableMaster();
1273 
1274  // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1275  if ( $this->fieldHasBit( $flags, self::QUERY_REPLICA_ROLE ) ) {
1276  throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1277  }
1278  }
1279  } else {
1280  // No permanent writes in this query
1281  $isPermWrite = false;
1282  // No temporary tables written to either
1283  $tempTableChanges = [];
1284  }
1285 
1286  // Add trace comment to the begin of the sql string, right after the operator.
1287  // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1288  $encAgent = str_replace( '/', '-', $this->agent );
1289  $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1290 
1291  // Send the query to the server and fetch any corresponding errors.
1292  // This also doubles as a "ping" to see if the connection was dropped.
1293  list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1294  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1295 
1296  // Check if the query failed due to a recoverable connection loss
1297  $allowRetry = !$this->fieldHasBit( $flags, self::QUERY_NO_RETRY );
1298  if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1299  // Silently resend the query to the server since it is safe and possible
1300  list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1301  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1302  }
1303 
1304  // Register creation and dropping of temporary tables
1305  $this->registerTempWrites( $ret, $tempTableChanges );
1306 
1307  $corruptedTrx = false;
1308 
1309  if ( $ret === false ) {
1310  if ( $priorTransaction ) {
1311  if ( $recoverableSR ) {
1312  # We're ignoring an error that caused just the current query to be aborted.
1313  # But log the cause so we can log a deprecation notice if a caller actually
1314  # does ignore it.
1315  $this->trxStatusIgnoredCause = [ $err, $errno, $fname ];
1316  } elseif ( !$recoverableCL ) {
1317  # Either the query was aborted or all queries after BEGIN where aborted.
1318  # In the first case, the only options going forward are (a) ROLLBACK, or
1319  # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1320  # option is ROLLBACK, since the snapshots would have been released.
1321  $corruptedTrx = true; // cannot recover
1322  $this->trxStatus = self::STATUS_TRX_ERROR;
1323  $this->trxStatusCause = $this->getQueryException( $err, $errno, $sql, $fname );
1324  $this->trxStatusIgnoredCause = null;
1325  }
1326  }
1327  }
1328 
1329  return [ $ret, $err, $errno, $corruptedTrx ];
1330  }
1331 
1350  private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1351  $priorWritesPending = $this->writesOrCallbacksPending();
1352 
1353  if ( ( $flags & self::QUERY_IGNORE_DBO_TRX ) == 0 ) {
1354  $this->beginIfImplied( $sql, $fname );
1355  }
1356 
1357  // Keep track of whether the transaction has write queries pending
1358  if ( $isPermWrite ) {
1359  $this->lastWriteTime = microtime( true );
1360  if ( $this->trxLevel() && !$this->trxDoneWrites ) {
1361  $this->trxDoneWrites = true;
1362  $this->trxProfiler->transactionWritingIn(
1363  $this->server, $this->getDomainID(), $this->trxShortId );
1364  }
1365  }
1366 
1367  $prefix = $this->topologyRole ? 'query-m: ' : 'query: ';
1368  $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId, $prefix );
1369 
1370  $startTime = microtime( true );
1371  $ps = $this->profiler
1372  ? ( $this->profiler )( $generalizedSql->stringify() )
1373  : null;
1374  $this->affectedRowCount = null;
1375  $this->lastQuery = $sql;
1376  $ret = $this->doQuery( $commentedSql );
1377  $lastError = $this->lastError();
1378  $lastErrno = $this->lastErrno();
1379 
1380  $this->affectedRowCount = $this->affectedRows();
1381  unset( $ps ); // profile out (if set)
1382  $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1383 
1384  $recoverableSR = false; // recoverable statement rollback?
1385  $recoverableCL = false; // recoverable connection loss?
1386  $reconnected = false; // reconnection both attempted and succeeded?
1387 
1388  if ( $ret !== false ) {
1389  $this->lastPing = $startTime;
1390  if ( $isPermWrite && $this->trxLevel() ) {
1391  $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1392  $this->trxWriteCallers[] = $fname;
1393  }
1394  } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1395  # Check if no meaningful session state was lost
1396  $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1397  # Update session state tracking and try to restore the connection
1398  $reconnected = $this->replaceLostConnection( __METHOD__ );
1399  } else {
1400  # Check if only the last query was rolled back
1401  $recoverableSR = $this->wasKnownStatementRollbackError();
1402  }
1403 
1404  if ( $sql === self::$PING_QUERY ) {
1405  $this->lastRoundTripEstimate = $queryRuntime;
1406  }
1407 
1408  $this->trxProfiler->recordQueryCompletion(
1409  $generalizedSql,
1410  $startTime,
1411  $isPermWrite,
1412  $isPermWrite ? $this->affectedRows() : $this->numRows( $ret )
1413  );
1414 
1415  // Avoid the overhead of logging calls unless debug mode is enabled
1416  if ( $this->getFlag( self::DBO_DEBUG ) ) {
1417  $this->queryLogger->debug(
1418  "{method} [{runtime}s] {db_host}: {sql}",
1419  [
1420  'method' => $fname,
1421  'db_host' => $this->getServer(),
1422  'sql' => $sql,
1423  'domain' => $this->getDomainID(),
1424  'runtime' => round( $queryRuntime, 3 )
1425  ]
1426  );
1427  }
1428 
1429  return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1430  }
1431 
1438  private function beginIfImplied( $sql, $fname ) {
1439  if (
1440  !$this->trxLevel() &&
1441  $this->getFlag( self::DBO_TRX ) &&
1442  $this->isTransactableQuery( $sql )
1443  ) {
1444  $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1445  $this->trxAutomatic = true;
1446  }
1447  }
1448 
1461  private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1462  // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1463  $indicativeOfReplicaRuntime = true;
1464  if ( $runtime > self::$SLOW_WRITE_SEC ) {
1465  $verb = $this->getQueryVerb( $sql );
1466  // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1467  if ( $verb === 'INSERT' ) {
1468  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS;
1469  } elseif ( $verb === 'REPLACE' ) {
1470  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS / 2;
1471  }
1472  }
1473 
1474  $this->trxWriteDuration += $runtime;
1475  $this->trxWriteQueryCount += 1;
1476  $this->trxWriteAffectedRows += $affected;
1477  if ( $indicativeOfReplicaRuntime ) {
1478  $this->trxWriteAdjDuration += $runtime;
1479  $this->trxWriteAdjQueryCount += 1;
1480  }
1481  }
1482 
1490  private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1491  $verb = $this->getQueryVerb( $sql );
1492  if ( $verb === 'USE' ) {
1493  throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1494  }
1495 
1496  if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1497  return;
1498  }
1499 
1500  if ( $this->trxStatus < self::STATUS_TRX_OK ) {
1501  throw new DBTransactionStateError(
1502  $this,
1503  "Cannot execute query from $fname while transaction status is ERROR",
1504  [],
1505  $this->trxStatusCause
1506  );
1507  } elseif ( $this->trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1508  list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause;
1509  call_user_func( $this->deprecationLogger,
1510  "Caller from $fname ignored an error originally raised from $iFname: " .
1511  "[$iLastErrno] $iLastError"
1512  );
1513  $this->trxStatusIgnoredCause = null;
1514  }
1515  }
1516 
1517  public function assertNoOpenTransactions() {
1518  if ( $this->explicitTrxActive() ) {
1519  throw new DBTransactionError(
1520  $this,
1521  "Explicit transaction still active. A caller may have caught an error. "
1522  . "Open transactions: " . $this->flatAtomicSectionList()
1523  );
1524  }
1525  }
1526 
1536  private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1537  # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1538  # Dropped connections also mean that named locks are automatically released.
1539  # Only allow error suppression in autocommit mode or when the lost transaction
1540  # didn't matter anyway (aside from DBO_TRX snapshot loss).
1541  if ( $this->sessionNamedLocks ) {
1542  return false; // possible critical section violation
1543  } elseif ( $this->sessionTempTables ) {
1544  return false; // tables might be queried latter
1545  } elseif ( $sql === 'COMMIT' ) {
1546  return !$priorWritesPending; // nothing written anyway? (T127428)
1547  } elseif ( $sql === 'ROLLBACK' ) {
1548  return true; // transaction lost...which is also what was requested :)
1549  } elseif ( $this->explicitTrxActive() ) {
1550  return false; // don't drop atomicity and explicit snapshots
1551  } elseif ( $priorWritesPending ) {
1552  return false; // prior writes lost from implicit transaction
1553  }
1554 
1555  return true;
1556  }
1557 
1561  private function handleSessionLossPreconnect() {
1562  // Clean up tracking of session-level things...
1563  // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1564  // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1565  $this->sessionTempTables = [];
1566  $this->sessionDirtyTempTables = [];
1567  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1568  // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1569  $this->sessionNamedLocks = [];
1570  // Session loss implies transaction loss
1571  $oldTrxShortId = $this->consumeTrxShortId();
1572  $this->trxAtomicCounter = 0;
1573  $this->trxIdleCallbacks = []; // T67263; transaction already lost
1574  $this->trxPreCommitCallbacks = []; // T67263; transaction already lost
1575  // Clear additional subclass fields
1577  // @note: leave trxRecurringCallbacks in place
1578  if ( $this->trxDoneWrites ) {
1579  $this->trxProfiler->transactionWritingOut(
1580  $this->server,
1581  $this->getDomainID(),
1582  $oldTrxShortId,
1583  $this->pendingWriteQueryDuration( self::ESTIMATE_TOTAL ),
1584  $this->trxWriteAffectedRows
1585  );
1586  }
1587  }
1588 
1593  protected function doHandleSessionLossPreconnect() {
1594  // no-op
1595  }
1596 
1600  private function handleSessionLossPostconnect() {
1601  try {
1602  // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1603  // If callback suppression is set then the array will remain unhandled.
1604  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1605  } catch ( Throwable $ex ) {
1606  // Already logged; move on...
1607  }
1608  try {
1609  // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1610  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1611  } catch ( Throwable $ex ) {
1612  // Already logged; move on...
1613  }
1614  }
1615 
1621  private function consumeTrxShortId() {
1622  $old = $this->trxShortId;
1623  $this->trxShortId = '';
1624 
1625  return $old;
1626  }
1627 
1639  protected function wasQueryTimeout( $error, $errno ) {
1640  return false;
1641  }
1642 
1654  public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1655  if ( $ignore ) {
1656  $this->queryLogger->debug( "SQL ERROR (ignored): $error" );
1657  } else {
1658  throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1659  }
1660  }
1661 
1669  private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1670  // Information that instances of the same problem have in common should
1671  // not be normalized (T255202).
1672  $this->queryLogger->error(
1673  "Error $errno from $fname, {error} {sql1line} {db_server}",
1674  $this->getLogContext( [
1675  'method' => __METHOD__,
1676  'errno' => $errno,
1677  'error' => $error,
1678  'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1679  'fname' => $fname,
1680  'exception' => new RuntimeException()
1681  ] )
1682  );
1683  return $this->getQueryException( $error, $errno, $sql, $fname );
1684  }
1685 
1693  private function getQueryException( $error, $errno, $sql, $fname ) {
1694  if ( $this->wasQueryTimeout( $error, $errno ) ) {
1695  return new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1696  } elseif ( $this->wasConnectionError( $errno ) ) {
1697  return new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1698  } else {
1699  return new DBQueryError( $this, $error, $errno, $sql, $fname );
1700  }
1701  }
1702 
1707  final protected function newExceptionAfterConnectError( $error ) {
1708  // Connection was not fully initialized and is not safe for use
1709  $this->conn = null;
1710 
1711  $this->connLogger->error(
1712  "Error connecting to {db_server} as user {db_user}: {error}",
1713  $this->getLogContext( [
1714  'error' => $error,
1715  'exception' => new RuntimeException()
1716  ] )
1717  );
1718 
1719  return new DBConnectionError( $this, $error );
1720  }
1721 
1726  public function freeResult( $res ) {
1727  }
1728 
1732  public function newSelectQueryBuilder() {
1733  return new SelectQueryBuilder( $this );
1734  }
1735 
1736  public function selectField(
1737  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1738  ) {
1739  if ( $var === '*' ) { // sanity
1740  throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1741  }
1742 
1743  $options = $this->normalizeOptions( $options );
1744  $options['LIMIT'] = 1;
1745 
1746  $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1747  if ( $res === false ) {
1748  throw new DBUnexpectedError( $this, "Got false from select()" );
1749  }
1750 
1751  $row = $this->fetchRow( $res );
1752  if ( $row === false ) {
1753  return false;
1754  }
1755 
1756  return reset( $row );
1757  }
1758 
1759  public function selectFieldValues(
1760  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1761  ) {
1762  if ( $var === '*' ) { // sanity
1763  throw new DBUnexpectedError( $this, "Cannot use a * field" );
1764  } elseif ( !is_string( $var ) ) { // sanity
1765  throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1766  }
1767 
1768  $options = $this->normalizeOptions( $options );
1769  $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1770  if ( $res === false ) {
1771  throw new DBUnexpectedError( $this, "Got false from select()" );
1772  }
1773 
1774  $values = [];
1775  foreach ( $res as $row ) {
1776  $values[] = $row->value;
1777  }
1778 
1779  return $values;
1780  }
1781 
1793  protected function makeSelectOptions( array $options ) {
1794  $preLimitTail = $postLimitTail = '';
1795  $startOpts = '';
1796 
1797  $noKeyOptions = [];
1798 
1799  foreach ( $options as $key => $option ) {
1800  if ( is_numeric( $key ) ) {
1801  $noKeyOptions[$option] = true;
1802  }
1803  }
1804 
1805  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1806 
1807  $preLimitTail .= $this->makeOrderBy( $options );
1808 
1809  if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1810  $postLimitTail .= ' FOR UPDATE';
1811  }
1812 
1813  if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1814  $postLimitTail .= ' LOCK IN SHARE MODE';
1815  }
1816 
1817  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1818  $startOpts .= 'DISTINCT';
1819  }
1820 
1821  # Various MySQL extensions
1822  if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1823  $startOpts .= ' /*! STRAIGHT_JOIN */';
1824  }
1825 
1826  if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1827  $startOpts .= ' SQL_BIG_RESULT';
1828  }
1829 
1830  if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1831  $startOpts .= ' SQL_BUFFER_RESULT';
1832  }
1833 
1834  if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1835  $startOpts .= ' SQL_SMALL_RESULT';
1836  }
1837 
1838  if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1839  $startOpts .= ' SQL_CALC_FOUND_ROWS';
1840  }
1841 
1842  if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1843  $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1844  } else {
1845  $useIndex = '';
1846  }
1847  if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1848  $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1849  } else {
1850  $ignoreIndex = '';
1851  }
1852 
1853  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1854  }
1855 
1864  protected function makeGroupByWithHaving( $options ) {
1865  $sql = '';
1866  if ( isset( $options['GROUP BY'] ) ) {
1867  $gb = is_array( $options['GROUP BY'] )
1868  ? implode( ',', $options['GROUP BY'] )
1869  : $options['GROUP BY'];
1870  $sql .= ' GROUP BY ' . $gb;
1871  }
1872  if ( isset( $options['HAVING'] ) ) {
1873  $having = is_array( $options['HAVING'] )
1874  ? $this->makeList( $options['HAVING'], self::LIST_AND )
1875  : $options['HAVING'];
1876  $sql .= ' HAVING ' . $having;
1877  }
1878 
1879  return $sql;
1880  }
1881 
1890  protected function makeOrderBy( $options ) {
1891  if ( isset( $options['ORDER BY'] ) ) {
1892  $ob = is_array( $options['ORDER BY'] )
1893  ? implode( ',', $options['ORDER BY'] )
1894  : $options['ORDER BY'];
1895 
1896  return ' ORDER BY ' . $ob;
1897  }
1898 
1899  return '';
1900  }
1901 
1902  public function select(
1903  $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1904  ) {
1905  $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1906 
1907  return $this->query( $sql, $fname, self::QUERY_CHANGE_NONE );
1908  }
1909 
1914  public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1915  $options = [], $join_conds = []
1916  ) {
1917  if ( is_array( $vars ) ) {
1918  $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1919  } else {
1920  $fields = $vars;
1921  }
1922 
1923  $options = (array)$options;
1924  $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1925  ? $options['USE INDEX']
1926  : [];
1927  $ignoreIndexes = (
1928  isset( $options['IGNORE INDEX'] ) &&
1929  is_array( $options['IGNORE INDEX'] )
1930  )
1931  ? $options['IGNORE INDEX']
1932  : [];
1933 
1934  if (
1935  $this->selectOptionsIncludeLocking( $options ) &&
1936  $this->selectFieldsOrOptionsAggregate( $vars, $options )
1937  ) {
1938  // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
1939  // functions. Discourage use of such queries to encourage compatibility.
1940  call_user_func(
1941  $this->deprecationLogger,
1942  __METHOD__ . ": aggregation used with a locking SELECT ($fname)"
1943  );
1944  }
1945 
1946  if ( is_array( $table ) ) {
1947  if ( count( $table ) === 0 ) {
1948  $from = '';
1949  } else {
1950  $from = ' FROM ' .
1952  $table, $useIndexes, $ignoreIndexes, $join_conds );
1953  }
1954  } elseif ( $table != '' ) {
1955  $from = ' FROM ' .
1957  [ $table ], $useIndexes, $ignoreIndexes, [] );
1958  } else {
1959  $from = '';
1960  }
1961 
1962  list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1963  $this->makeSelectOptions( $options );
1964 
1965  if ( is_array( $conds ) ) {
1966  $conds = $this->makeList( $conds, self::LIST_AND );
1967  }
1968 
1969  if ( $conds === null || $conds === false ) {
1970  $this->queryLogger->warning(
1971  __METHOD__
1972  . ' called from '
1973  . $fname
1974  . ' with incorrect parameters: $conds must be a string or an array'
1975  );
1976  $conds = '';
1977  }
1978 
1979  if ( $conds === '' || $conds === '*' ) {
1980  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1981  } elseif ( is_string( $conds ) ) {
1982  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1983  "WHERE $conds $preLimitTail";
1984  } else {
1985  throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1986  }
1987 
1988  if ( isset( $options['LIMIT'] ) ) {
1989  $sql = $this->limitResult( $sql, $options['LIMIT'],
1990  $options['OFFSET'] ?? false );
1991  }
1992  $sql = "$sql $postLimitTail";
1993 
1994  if ( isset( $options['EXPLAIN'] ) ) {
1995  $sql = 'EXPLAIN ' . $sql;
1996  }
1997 
1998  return $sql;
1999  }
2000 
2001  public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
2002  $options = [], $join_conds = []
2003  ) {
2004  $options = (array)$options;
2005  $options['LIMIT'] = 1;
2006 
2007  $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
2008  if ( $res === false ) {
2009  throw new DBUnexpectedError( $this, "Got false from select()" );
2010  }
2011 
2012  if ( !$this->numRows( $res ) ) {
2013  return false;
2014  }
2015 
2016  return $this->fetchObject( $res );
2017  }
2018 
2023  public function estimateRowCount(
2024  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2025  ) {
2026  $conds = $this->normalizeConditions( $conds, $fname );
2027  $column = $this->extractSingleFieldFromList( $var );
2028  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
2029  $conds[] = "$column IS NOT NULL";
2030  }
2031 
2032  $res = $this->select(
2033  $tables, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
2034  );
2035  $row = $res ? $this->fetchRow( $res ) : [];
2036 
2037  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
2038  }
2039 
2040  public function selectRowCount(
2041  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2042  ) {
2043  $conds = $this->normalizeConditions( $conds, $fname );
2044  $column = $this->extractSingleFieldFromList( $var );
2045  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
2046  $conds[] = "$column IS NOT NULL";
2047  }
2048 
2049  $res = $this->select(
2050  [
2051  'tmp_count' => $this->buildSelectSubquery(
2052  $tables,
2053  '1',
2054  $conds,
2055  $fname,
2056  $options,
2057  $join_conds
2058  )
2059  ],
2060  [ 'rowcount' => 'COUNT(*)' ],
2061  [],
2062  $fname
2063  );
2064  $row = $res ? $this->fetchRow( $res ) : [];
2065 
2066  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
2067  }
2068 
2073  private function selectOptionsIncludeLocking( $options ) {
2074  $options = (array)$options;
2075  foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
2076  if ( in_array( $lock, $options, true ) ) {
2077  return true;
2078  }
2079  }
2080 
2081  return false;
2082  }
2083 
2089  private function selectFieldsOrOptionsAggregate( $fields, $options ) {
2090  foreach ( (array)$options as $key => $value ) {
2091  if ( is_string( $key ) ) {
2092  if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
2093  return true;
2094  }
2095  } elseif ( is_string( $value ) ) {
2096  if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
2097  return true;
2098  }
2099  }
2100  }
2101 
2102  $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
2103  foreach ( (array)$fields as $field ) {
2104  if ( is_string( $field ) && preg_match( $regex, $field ) ) {
2105  return true;
2106  }
2107  }
2108 
2109  return false;
2110  }
2111 
2117  final protected function normalizeRowArray( array $rowOrRows ) {
2118  if ( !$rowOrRows ) {
2119  $rows = [];
2120  } elseif ( isset( $rowOrRows[0] ) ) {
2121  $rows = $rowOrRows;
2122  } else {
2123  $rows = [ $rowOrRows ];
2124  }
2125 
2126  foreach ( $rows as $row ) {
2127  if ( !is_array( $row ) ) {
2128  throw new DBUnexpectedError( $this, "Got non-array in row array" );
2129  } elseif ( !$row ) {
2130  throw new DBUnexpectedError( $this, "Got empty array in row array" );
2131  }
2132  }
2133 
2134  return $rows;
2135  }
2136 
2143  final protected function normalizeConditions( $conds, $fname ) {
2144  if ( $conds === null || $conds === false ) {
2145  $this->queryLogger->warning(
2146  __METHOD__
2147  . ' called from '
2148  . $fname
2149  . ' with incorrect parameters: $conds must be a string or an array'
2150  );
2151  return [];
2152  } elseif ( $conds === '' ) {
2153  return [];
2154  }
2155 
2156  return is_array( $conds ) ? $conds : [ $conds ];
2157  }
2158 
2164  final protected function normalizeUpsertKeys( $uniqueKeys ) {
2165  if ( is_string( $uniqueKeys ) ) {
2166  return [ [ $uniqueKeys ] ];
2167  }
2168 
2169  if ( !is_array( $uniqueKeys ) || !$uniqueKeys ) {
2170  throw new DBUnexpectedError( $this, 'Invalid or empty unique key array' );
2171  }
2172 
2173  $oldStyle = false;
2174  $uniqueColumnSets = [];
2175  foreach ( $uniqueKeys as $i => $uniqueKey ) {
2176  if ( !is_int( $i ) ) {
2177  throw new DBUnexpectedError( $this, 'Unique key array should be a list' );
2178  } elseif ( is_string( $uniqueKey ) ) {
2179  $oldStyle = true;
2180  $uniqueColumnSets[] = [ $uniqueKey ];
2181  } elseif ( is_array( $uniqueKey ) && $uniqueKey ) {
2182  $uniqueColumnSets[] = $uniqueKey;
2183  } else {
2184  throw new DBUnexpectedError( $this, 'Invalid unique key array entry' );
2185  }
2186  }
2187 
2188  if ( count( $uniqueColumnSets ) > 1 ) {
2189  // If an existing row conflicts with new row X on key A and new row Y on key B,
2190  // it is not well defined how many UPDATEs should apply to the existing row and
2191  // in what order the new rows are checked
2192  $this->queryLogger->warning(
2193  __METHOD__ . " called with multiple unique keys",
2194  [ 'exception' => new RuntimeException() ]
2195  );
2196  }
2197 
2198  if ( $oldStyle ) {
2199  // Passing a list of strings for single-column unique keys is too
2200  // easily confused with passing the columns of composite unique key
2201  $this->queryLogger->warning(
2202  __METHOD__ . " called with deprecated parameter style: " .
2203  "the unique key array should be a string or array of string arrays",
2204  [ 'exception' => new RuntimeException() ]
2205  );
2206  }
2207 
2208  return $uniqueColumnSets;
2209  }
2210 
2216  final protected function normalizeOptions( $options ) {
2217  if ( is_array( $options ) ) {
2218  return $options;
2219  } elseif ( is_string( $options ) ) {
2220  return ( $options === '' ) ? [] : [ $options ];
2221  } else {
2222  throw new DBUnexpectedError( $this, __METHOD__ . ': expected string or array' );
2223  }
2224  }
2225 
2232  final protected function isFlagInOptions( $option, array $options ) {
2233  foreach ( array_keys( $options, $option, true ) as $k ) {
2234  if ( is_int( $k ) ) {
2235  return true;
2236  }
2237  }
2238 
2239  return false;
2240  }
2241 
2246  final protected function extractSingleFieldFromList( $var ) {
2247  if ( is_array( $var ) ) {
2248  if ( !$var ) {
2249  $column = null;
2250  } elseif ( count( $var ) == 1 ) {
2251  $column = $var[0] ?? reset( $var );
2252  } else {
2253  throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns' );
2254  }
2255  } else {
2256  $column = $var;
2257  }
2258 
2259  return $column;
2260  }
2261 
2262  public function lockForUpdate(
2263  $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2264  ) {
2265  if ( !$this->trxLevel() && !$this->getFlag( self::DBO_TRX ) ) {
2266  throw new DBUnexpectedError(
2267  $this,
2268  __METHOD__ . ': no transaction is active nor is DBO_TRX set'
2269  );
2270  }
2271 
2272  $options = (array)$options;
2273  $options[] = 'FOR UPDATE';
2274 
2275  return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2276  }
2277 
2278  public function fieldExists( $table, $field, $fname = __METHOD__ ) {
2279  $info = $this->fieldInfo( $table, $field );
2280 
2281  return (bool)$info;
2282  }
2283 
2284  public function indexExists( $table, $index, $fname = __METHOD__ ) {
2285  if ( !$this->tableExists( $table, $fname ) ) {
2286  return null;
2287  }
2288 
2289  $info = $this->indexInfo( $table, $index, $fname );
2290  if ( $info === null ) {
2291  return null;
2292  } else {
2293  return $info !== false;
2294  }
2295  }
2296 
2297  abstract public function tableExists( $table, $fname = __METHOD__ );
2298 
2303  public function indexUnique( $table, $index, $fname = __METHOD__ ) {
2304  $indexInfo = $this->indexInfo( $table, $index, $fname );
2305 
2306  if ( !$indexInfo ) {
2307  return null;
2308  }
2309 
2310  return !$indexInfo[0]->Non_unique;
2311  }
2312 
2313  public function insert( $table, $rows, $fname = __METHOD__, $options = [] ) {
2314  $rows = $this->normalizeRowArray( $rows );
2315  if ( !$rows ) {
2316  return true;
2317  }
2318 
2319  $options = $this->normalizeOptions( $options );
2320  if ( $this->isFlagInOptions( 'IGNORE', $options ) ) {
2321  $this->doInsertNonConflicting( $table, $rows, $fname );
2322  } else {
2323  $this->doInsert( $table, $rows, $fname );
2324  }
2325 
2326  return true;
2327  }
2328 
2337  protected function doInsert( $table, array $rows, $fname ) {
2338  $encTable = $this->tableName( $table );
2339  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
2340 
2341  $sql = "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples";
2342 
2343  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2344  }
2345 
2354  protected function doInsertNonConflicting( $table, array $rows, $fname ) {
2355  $encTable = $this->tableName( $table );
2356  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
2357  list( $sqlVerb, $sqlOpts ) = $this->makeInsertNonConflictingVerbAndOptions();
2358 
2359  $sql = rtrim( "$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" );
2360 
2361  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2362  }
2363 
2370  return [ 'INSERT IGNORE INTO', '' ];
2371  }
2372 
2383  protected function makeInsertLists( array $rows ) {
2384  $firstRow = $rows[0];
2385  if ( !is_array( $firstRow ) || !$firstRow ) {
2386  throw new DBUnexpectedError( $this, 'Got an empty row list or empty row' );
2387  }
2388  // List of columns that define the value tuple ordering
2389  $tupleColumns = array_keys( $firstRow );
2390 
2391  $valueTuples = [];
2392  foreach ( $rows as $row ) {
2393  $rowColumns = array_keys( $row );
2394  // VALUES(...) requires a uniform correspondance of (column => value)
2395  if ( $rowColumns !== $tupleColumns ) {
2396  throw new DBUnexpectedError(
2397  $this,
2398  'Got row columns (' . implode( ', ', $rowColumns ) . ') ' .
2399  'instead of expected (' . implode( ', ', $tupleColumns ) . ')'
2400  );
2401  }
2402  // Make the value tuple that defines this row
2403  $valueTuples[] = '(' . $this->makeList( $row, self::LIST_COMMA ) . ')';
2404  }
2405 
2406  return [
2407  $this->makeList( $tupleColumns, self::LIST_NAMES ),
2408  implode( ',', $valueTuples )
2409  ];
2410  }
2411 
2419  protected function makeUpdateOptionsArray( $options ) {
2420  $options = $this->normalizeOptions( $options );
2421 
2422  $opts = [];
2423 
2424  if ( in_array( 'IGNORE', $options ) ) {
2425  $opts[] = 'IGNORE';
2426  }
2427 
2428  return $opts;
2429  }
2430 
2438  protected function makeUpdateOptions( $options ) {
2439  $opts = $this->makeUpdateOptionsArray( $options );
2440 
2441  return implode( ' ', $opts );
2442  }
2443 
2444  public function update( $table, $set, $conds, $fname = __METHOD__, $options = [] ) {
2445  $this->assertConditionIsNotEmpty( $conds, __METHOD__, true );
2446  $table = $this->tableName( $table );
2447  $opts = $this->makeUpdateOptions( $options );
2448  $sql = "UPDATE $opts $table SET " . $this->makeList( $set, self::LIST_SET );
2449 
2450  if ( $conds && $conds !== IDatabase::ALL_ROWS ) {
2451  if ( is_array( $conds ) ) {
2452  $conds = $this->makeList( $conds, self::LIST_AND );
2453  }
2454  $sql .= ' WHERE ' . $conds;
2455  }
2456 
2457  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2458 
2459  return true;
2460  }
2461 
2462  public function makeList( array $a, $mode = self::LIST_COMMA ) {
2463  $first = true;
2464  $list = '';
2465 
2466  foreach ( $a as $field => $value ) {
2467  if ( !$first ) {
2468  if ( $mode == self::LIST_AND ) {
2469  $list .= ' AND ';
2470  } elseif ( $mode == self::LIST_OR ) {
2471  $list .= ' OR ';
2472  } else {
2473  $list .= ',';
2474  }
2475  } else {
2476  $first = false;
2477  }
2478 
2479  if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
2480  $list .= "($value)";
2481  } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
2482  $list .= "$value";
2483  } elseif (
2484  ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
2485  ) {
2486  // Remove null from array to be handled separately if found
2487  $includeNull = false;
2488  foreach ( array_keys( $value, null, true ) as $nullKey ) {
2489  $includeNull = true;
2490  unset( $value[$nullKey] );
2491  }
2492  if ( count( $value ) == 0 && !$includeNull ) {
2493  throw new InvalidArgumentException(
2494  __METHOD__ . ": empty input for field $field" );
2495  } elseif ( count( $value ) == 0 ) {
2496  // only check if $field is null
2497  $list .= "$field IS NULL";
2498  } else {
2499  // IN clause contains at least one valid element
2500  if ( $includeNull ) {
2501  // Group subconditions to ensure correct precedence
2502  $list .= '(';
2503  }
2504  if ( count( $value ) == 1 ) {
2505  // Special-case single values, as IN isn't terribly efficient
2506  // Don't necessarily assume the single key is 0; we don't
2507  // enforce linear numeric ordering on other arrays here.
2508  $value = array_values( $value )[0];
2509  $list .= $field . " = " . $this->addQuotes( $value );
2510  } else {
2511  $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2512  }
2513  // if null present in array, append IS NULL
2514  if ( $includeNull ) {
2515  $list .= " OR $field IS NULL)";
2516  }
2517  }
2518  } elseif ( $value === null ) {
2519  if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2520  $list .= "$field IS ";
2521  } elseif ( $mode == self::LIST_SET ) {
2522  $list .= "$field = ";
2523  }
2524  $list .= 'NULL';
2525  } else {
2526  if (
2527  $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2528  ) {
2529  $list .= "$field = ";
2530  }
2531  $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
2532  }
2533  }
2534 
2535  return $list;
2536  }
2537 
2538  public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2539  $conds = [];
2540 
2541  foreach ( $data as $base => $sub ) {
2542  if ( count( $sub ) ) {
2543  $conds[] = $this->makeList(
2544  [ $baseKey => $base, $subKey => array_map( 'strval', array_keys( $sub ) ) ],
2545  self::LIST_AND );
2546  }
2547  }
2548 
2549  if ( $conds ) {
2550  return $this->makeList( $conds, self::LIST_OR );
2551  } else {
2552  // Nothing to search for...
2553  return false;
2554  }
2555  }
2556 
2561  public function aggregateValue( $valuedata, $valuename = 'value' ) {
2562  return $valuename;
2563  }
2564 
2569  public function bitNot( $field ) {
2570  return "(~$field)";
2571  }
2572 
2577  public function bitAnd( $fieldLeft, $fieldRight ) {
2578  return "($fieldLeft & $fieldRight)";
2579  }
2580 
2585  public function bitOr( $fieldLeft, $fieldRight ) {
2586  return "($fieldLeft | $fieldRight)";
2587  }
2588 
2593  public function buildConcat( $stringList ) {
2594  return 'CONCAT(' . implode( ',', $stringList ) . ')';
2595  }
2596 
2601  public function buildGroupConcatField(
2602  $delim, $table, $field, $conds = '', $join_conds = []
2603  ) {
2604  $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2605 
2606  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2607  }
2608 
2613  public function buildGreatest( $fields, $values ) {
2614  return $this->buildSuperlative( 'GREATEST', $fields, $values );
2615  }
2616 
2621  public function buildLeast( $fields, $values ) {
2622  return $this->buildSuperlative( 'LEAST', $fields, $values );
2623  }
2624 
2641  protected function buildSuperlative( $sqlfunc, $fields, $values ) {
2642  $fields = is_array( $fields ) ? $fields : [ $fields ];
2643  $values = is_array( $values ) ? $values : [ $values ];
2644 
2645  $encValues = [];
2646  foreach ( $fields as $alias => $field ) {
2647  if ( is_int( $alias ) ) {
2648  $encValues[] = $this->addIdentifierQuotes( $field );
2649  } else {
2650  $encValues[] = $field; // expression
2651  }
2652  }
2653  foreach ( $values as $value ) {
2654  if ( is_int( $value ) || is_float( $value ) ) {
2655  $encValues[] = $value;
2656  } elseif ( is_string( $value ) ) {
2657  $encValues[] = $this->addQuotes( $value );
2658  } elseif ( $value === null ) {
2659  throw new DBUnexpectedError( $this, 'Null value in superlative' );
2660  } else {
2661  throw new DBUnexpectedError( $this, 'Unexpected value type in superlative' );
2662  }
2663  }
2664 
2665  return $sqlfunc . '(' . implode( ',', $encValues ) . ')';
2666  }
2667 
2672  public function buildSubstring( $input, $startPosition, $length = null ) {
2673  $this->assertBuildSubstringParams( $startPosition, $length );
2674  $functionBody = "$input FROM $startPosition";
2675  if ( $length !== null ) {
2676  $functionBody .= " FOR $length";
2677  }
2678  return 'SUBSTRING(' . $functionBody . ')';
2679  }
2680 
2693  protected function assertBuildSubstringParams( $startPosition, $length ) {
2694  if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2695  throw new InvalidArgumentException(
2696  '$startPosition must be a positive integer'
2697  );
2698  }
2699  if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2700  throw new InvalidArgumentException(
2701  '$length must be null or an integer greater than or equal to 0'
2702  );
2703  }
2704  }
2705 
2719  protected function assertConditionIsNotEmpty( $conds, string $fname, bool $deprecate ) {
2720  $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
2721  if ( !$isCondValid ) {
2722  if ( $deprecate ) {
2723  wfDeprecated( $fname . ' called with empty $conds', '1.35', false, 3 );
2724  } else {
2725  throw new DBUnexpectedError( $this, $fname . ' called with empty conditions' );
2726  }
2727  }
2728  }
2729 
2734  public function buildStringCast( $field ) {
2735  // In theory this should work for any standards-compliant
2736  // SQL implementation, although it may not be the best way to do it.
2737  return "CAST( $field AS CHARACTER )";
2738  }
2739 
2744  public function buildIntegerCast( $field ) {
2745  return 'CAST( ' . $field . ' AS INTEGER )';
2746  }
2747 
2748  public function buildSelectSubquery(
2749  $table, $vars, $conds = '', $fname = __METHOD__,
2750  $options = [], $join_conds = []
2751  ) {
2752  return new Subquery(
2753  $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2754  );
2755  }
2756 
2761  public function databasesAreIndependent() {
2762  return false;
2763  }
2764 
2765  final public function selectDB( $db ) {
2766  $this->selectDomain( new DatabaseDomain(
2767  $db,
2768  $this->currentDomain->getSchema(),
2769  $this->currentDomain->getTablePrefix()
2770  ) );
2771 
2772  return true;
2773  }
2774 
2775  final public function selectDomain( $domain ) {
2776  $this->doSelectDomain( DatabaseDomain::newFromId( $domain ) );
2777  }
2778 
2786  protected function doSelectDomain( DatabaseDomain $domain ) {
2787  $this->currentDomain = $domain;
2788  }
2789 
2790  public function getDBname() {
2791  return $this->currentDomain->getDatabase();
2792  }
2793 
2794  public function getServer() {
2795  return $this->server;
2796  }
2797 
2802  public function tableName( $name, $format = 'quoted' ) {
2803  if ( $name instanceof Subquery ) {
2804  throw new DBUnexpectedError(
2805  $this,
2806  __METHOD__ . ': got Subquery instance when expecting a string'
2807  );
2808  }
2809 
2810  # Skip the entire process when we have a string quoted on both ends.
2811  # Note that we check the end so that we will still quote any use of
2812  # use of `database`.table. But won't break things if someone wants
2813  # to query a database table with a dot in the name.
2814  if ( $this->isQuotedIdentifier( $name ) ) {
2815  return $name;
2816  }
2817 
2818  # Lets test for any bits of text that should never show up in a table
2819  # name. Basically anything like JOIN or ON which are actually part of
2820  # SQL queries, but may end up inside of the table value to combine
2821  # sql. Such as how the API is doing.
2822  # Note that we use a whitespace test rather than a \b test to avoid
2823  # any remote case where a word like on may be inside of a table name
2824  # surrounded by symbols which may be considered word breaks.
2825  if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2826  $this->queryLogger->warning(
2827  __METHOD__ . ": use of subqueries is not supported this way",
2828  [ 'exception' => new RuntimeException() ]
2829  );
2830 
2831  return $name;
2832  }
2833 
2834  # Split database and table into proper variables.
2835  list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2836 
2837  # Quote $table and apply the prefix if not quoted.
2838  # $tableName might be empty if this is called from Database::replaceVars()
2839  $tableName = "{$prefix}{$table}";
2840  if ( $format === 'quoted'
2841  && !$this->isQuotedIdentifier( $tableName )
2842  && $tableName !== ''
2843  ) {
2844  $tableName = $this->addIdentifierQuotes( $tableName );
2845  }
2846 
2847  # Quote $schema and $database and merge them with the table name if needed
2848  $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2849  $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2850 
2851  return $tableName;
2852  }
2853 
2860  protected function qualifiedTableComponents( $name ) {
2861  # We reverse the explode so that database.table and table both output the correct table.
2862  $dbDetails = explode( '.', $name, 3 );
2863  if ( count( $dbDetails ) == 3 ) {
2864  list( $database, $schema, $table ) = $dbDetails;
2865  # We don't want any prefix added in this case
2866  $prefix = '';
2867  } elseif ( count( $dbDetails ) == 2 ) {
2868  list( $database, $table ) = $dbDetails;
2869  # We don't want any prefix added in this case
2870  $prefix = '';
2871  # In dbs that support it, $database may actually be the schema
2872  # but that doesn't affect any of the functionality here
2873  $schema = '';
2874  } else {
2875  list( $table ) = $dbDetails;
2876  if ( isset( $this->tableAliases[$table] ) ) {
2877  $database = $this->tableAliases[$table]['dbname'];
2878  $schema = is_string( $this->tableAliases[$table]['schema'] )
2879  ? $this->tableAliases[$table]['schema']
2880  : $this->relationSchemaQualifier();
2881  $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2882  ? $this->tableAliases[$table]['prefix']
2883  : $this->tablePrefix();
2884  } else {
2885  $database = '';
2886  $schema = $this->relationSchemaQualifier(); # Default schema
2887  $prefix = $this->tablePrefix(); # Default prefix
2888  }
2889  }
2890 
2891  return [ $database, $schema, $prefix, $table ];
2892  }
2893 
2900  private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2901  if ( strlen( $namespace ) ) {
2902  if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2903  $namespace = $this->addIdentifierQuotes( $namespace );
2904  }
2905  $relation = $namespace . '.' . $relation;
2906  }
2907 
2908  return $relation;
2909  }
2910 
2911  public function tableNames( ...$tables ) {
2912  $retVal = [];
2913 
2914  foreach ( $tables as $name ) {
2915  $retVal[$name] = $this->tableName( $name );
2916  }
2917 
2918  return $retVal;
2919  }
2920 
2921  public function tableNamesN( ...$tables ) {
2922  $retVal = [];
2923 
2924  foreach ( $tables as $name ) {
2925  $retVal[] = $this->tableName( $name );
2926  }
2927 
2928  return $retVal;
2929  }
2930 
2942  protected function tableNameWithAlias( $table, $alias = false ) {
2943  if ( is_string( $table ) ) {
2944  $quotedTable = $this->tableName( $table );
2945  } elseif ( $table instanceof Subquery ) {
2946  $quotedTable = (string)$table;
2947  } else {
2948  throw new InvalidArgumentException( "Table must be a string or Subquery" );
2949  }
2950 
2951  if ( $alias === false || $alias === $table ) {
2952  if ( $table instanceof Subquery ) {
2953  throw new InvalidArgumentException( "Subquery table missing alias" );
2954  }
2955 
2956  return $quotedTable;
2957  } else {
2958  return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2959  }
2960  }
2961 
2971  protected function fieldNameWithAlias( $name, $alias = false ) {
2972  if ( !$alias || (string)$alias === (string)$name ) {
2973  return $name;
2974  } else {
2975  return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2976  }
2977  }
2978 
2985  protected function fieldNamesWithAlias( $fields ) {
2986  $retval = [];
2987  foreach ( $fields as $alias => $field ) {
2988  if ( is_numeric( $alias ) ) {
2989  $alias = $field;
2990  }
2991  $retval[] = $this->fieldNameWithAlias( $field, $alias );
2992  }
2993 
2994  return $retval;
2995  }
2996 
3008  $tables, $use_index = [], $ignore_index = [], $join_conds = []
3009  ) {
3010  $ret = [];
3011  $retJOIN = [];
3012  $use_index = (array)$use_index;
3013  $ignore_index = (array)$ignore_index;
3014  $join_conds = (array)$join_conds;
3015 
3016  foreach ( $tables as $alias => $table ) {
3017  if ( !is_string( $alias ) ) {
3018  // No alias? Set it equal to the table name
3019  $alias = $table;
3020  }
3021 
3022  if ( is_array( $table ) ) {
3023  // A parenthesized group
3024  if ( count( $table ) > 1 ) {
3025  $joinedTable = '(' .
3027  $table, $use_index, $ignore_index, $join_conds ) . ')';
3028  } else {
3029  // Degenerate case
3030  $innerTable = reset( $table );
3031  $innerAlias = key( $table );
3032  $joinedTable = $this->tableNameWithAlias(
3033  $innerTable,
3034  is_string( $innerAlias ) ? $innerAlias : $innerTable
3035  );
3036  }
3037  } else {
3038  $joinedTable = $this->tableNameWithAlias( $table, $alias );
3039  }
3040 
3041  // Is there a JOIN clause for this table?
3042  if ( isset( $join_conds[$alias] ) ) {
3043  list( $joinType, $conds ) = $join_conds[$alias];
3044  $tableClause = $joinType;
3045  $tableClause .= ' ' . $joinedTable;
3046  if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
3047  $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
3048  if ( $use != '' ) {
3049  $tableClause .= ' ' . $use;
3050  }
3051  }
3052  if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
3053  $ignore = $this->ignoreIndexClause(
3054  implode( ',', (array)$ignore_index[$alias] ) );
3055  if ( $ignore != '' ) {
3056  $tableClause .= ' ' . $ignore;
3057  }
3058  }
3059  $on = $this->makeList( (array)$conds, self::LIST_AND );
3060  if ( $on != '' ) {
3061  $tableClause .= ' ON (' . $on . ')';
3062  }
3063 
3064  $retJOIN[] = $tableClause;
3065  } elseif ( isset( $use_index[$alias] ) ) {
3066  // Is there an INDEX clause for this table?
3067  $tableClause = $joinedTable;
3068  $tableClause .= ' ' . $this->useIndexClause(
3069  implode( ',', (array)$use_index[$alias] )
3070  );
3071 
3072  $ret[] = $tableClause;
3073  } elseif ( isset( $ignore_index[$alias] ) ) {
3074  // Is there an INDEX clause for this table?
3075  $tableClause = $joinedTable;
3076  $tableClause .= ' ' . $this->ignoreIndexClause(
3077  implode( ',', (array)$ignore_index[$alias] )
3078  );
3079 
3080  $ret[] = $tableClause;
3081  } else {
3082  $tableClause = $joinedTable;
3083 
3084  $ret[] = $tableClause;
3085  }
3086  }
3087 
3088  // We can't separate explicit JOIN clauses with ',', use ' ' for those
3089  $implicitJoins = implode( ',', $ret );
3090  $explicitJoins = implode( ' ', $retJOIN );
3091 
3092  // Compile our final table clause
3093  return implode( ' ', [ $implicitJoins, $explicitJoins ] );
3094  }
3095 
3102  protected function indexName( $index ) {
3103  return $this->indexAliases[$index] ?? $index;
3104  }
3105 
3110  public function addQuotes( $s ) {
3111  if ( $s instanceof Blob ) {
3112  $s = $s->fetch();
3113  }
3114  if ( $s === null ) {
3115  return 'NULL';
3116  } elseif ( is_bool( $s ) ) {
3117  return (string)(int)$s;
3118  } elseif ( is_int( $s ) ) {
3119  return (string)$s;
3120  } else {
3121  return "'" . $this->strencode( $s ) . "'";
3122  }
3123  }
3124 
3129  public function addIdentifierQuotes( $s ) {
3130  return '"' . str_replace( '"', '""', $s ) . '"';
3131  }
3132 
3143  public function isQuotedIdentifier( $name ) {
3144  return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
3145  }
3146 
3153  protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
3154  return str_replace( [ $escapeChar, '%', '_' ],
3155  [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
3156  $s );
3157  }
3158 
3163  public function buildLike( $param, ...$params ) {
3164  if ( is_array( $param ) ) {
3165  $params = $param;
3166  } else {
3167  $params = func_get_args();
3168  }
3169 
3170  $s = '';
3171 
3172  // We use ` instead of \ as the default LIKE escape character, since addQuotes()
3173  // may escape backslashes, creating problems of double escaping. The `
3174  // character has good cross-DBMS compatibility, avoiding special operators
3175  // in MS SQL like ^ and %
3176  $escapeChar = '`';
3177 
3178  foreach ( $params as $value ) {
3179  if ( $value instanceof LikeMatch ) {
3180  $s .= $value->toString();
3181  } else {
3182  $s .= $this->escapeLikeInternal( $value, $escapeChar );
3183  }
3184  }
3185 
3186  return ' LIKE ' .
3187  $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
3188  }
3189 
3190  public function anyChar() {
3191  return new LikeMatch( '_' );
3192  }
3193 
3194  public function anyString() {
3195  return new LikeMatch( '%' );
3196  }
3197 
3198  public function nextSequenceValue( $seqName ) {
3199  return null;
3200  }
3201 
3214  public function useIndexClause( $index ) {
3215  return '';
3216  }
3217 
3230  public function ignoreIndexClause( $index ) {
3231  return '';
3232  }
3233 
3234  public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
3235  $rows = $this->normalizeRowArray( $rows );
3236  if ( !$rows ) {
3237  return;
3238  }
3239 
3240  if ( $uniqueKeys ) {
3241  $uniqueKeys = $this->normalizeUpsertKeys( $uniqueKeys );
3242  $this->doReplace( $table, $uniqueKeys, $rows, $fname );
3243  } else {
3244  $this->queryLogger->warning(
3245  __METHOD__ . " called with no unique keys",
3246  [ 'exception' => new RuntimeException() ]
3247  );
3248  $this->doInsert( $table, $rows, $fname );
3249  }
3250  }
3251 
3261  protected function doReplace( $table, array $uniqueKeys, array $rows, $fname ) {
3262  $affectedRowCount = 0;
3263  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3264  try {
3265  foreach ( $rows as $row ) {
3266  // Delete any conflicting rows (including ones inserted from $rows)
3267  $sqlCondition = $this->makeConditionCollidesUponKeys( [ $row ], $uniqueKeys );
3268  $this->delete( $table, [ $sqlCondition ], $fname );
3269  $affectedRowCount += $this->affectedRows();
3270  // Now insert the row
3271  $this->insert( $table, $row, $fname );
3272  $affectedRowCount += $this->affectedRows();
3273  }
3274  $this->endAtomic( $fname );
3275  } catch ( Throwable $e ) {
3276  $this->cancelAtomic( $fname );
3277  throw $e;
3278  }
3279  $this->affectedRowCount = $affectedRowCount;
3280  }
3281 
3287  private function makeConditionCollidesUponKey( array $rows, array $uniqueKey ) {
3288  if ( !$rows ) {
3289  throw new DBUnexpectedError( $this, "Empty row array" );
3290  } elseif ( !$uniqueKey ) {
3291  throw new DBUnexpectedError( $this, "Empty unique key array" );
3292  }
3293 
3294  if ( count( $uniqueKey ) == 1 ) {
3295  // Use a simple IN(...) clause
3296  $column = reset( $uniqueKey );
3297  $values = array_column( $rows, $column );
3298  if ( count( $values ) !== count( $rows ) ) {
3299  throw new DBUnexpectedError( $this, "Missing values for unique key ($column)" );
3300  }
3301 
3302  return $this->makeList( [ $column => $values ], self::LIST_AND );
3303  }
3304 
3305  $disjunctions = [];
3306  foreach ( $rows as $row ) {
3307  $rowKeyMap = array_intersect_key( $row, array_flip( $uniqueKey ) );
3308  if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
3309  throw new DBUnexpectedError(
3310  $this,
3311  "Missing values for unique key (" . implode( ',', $uniqueKey ) . ")"
3312  );
3313  }
3314  $disjunctions[] = $this->makeList( $rowKeyMap, self::LIST_AND );
3315  }
3316 
3317  return count( $disjunctions ) > 1
3318  ? $this->makeList( $disjunctions, self::LIST_OR )
3319  : $disjunctions[0];
3320  }
3321 
3328  final protected function makeConditionCollidesUponKeys( array $rows, array $uniqueKeys ) {
3329  if ( !$uniqueKeys ) {
3330  throw new DBUnexpectedError( $this, "Empty unique key array" );
3331  }
3332 
3333  $disjunctions = [];
3334  foreach ( $uniqueKeys as $uniqueKey ) {
3335  $disjunctions[] = $this->makeConditionCollidesUponKey( $rows, $uniqueKey );
3336  }
3337 
3338  return count( $disjunctions ) > 1
3339  ? $this->makeList( $disjunctions, self::LIST_OR )
3340  : $disjunctions[0];
3341  }
3342 
3343  public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
3344  $rows = $this->normalizeRowArray( $rows );
3345  if ( !$rows ) {
3346  return true;
3347  }
3348 
3349  if ( $uniqueKeys ) {
3350  $uniqueKeys = $this->normalizeUpsertKeys( $uniqueKeys );
3351  $this->doUpsert( $table, $rows, $uniqueKeys, $set, $fname );
3352  } else {
3353  $this->queryLogger->warning(
3354  __METHOD__ . " called with no unique keys",
3355  [ 'exception' => new RuntimeException() ]
3356  );
3357  $this->doInsert( $table, $rows, $fname );
3358  }
3359 
3360  return true;
3361  }
3362 
3373  protected function doUpsert( $table, array $rows, array $uniqueKeys, array $set, $fname ) {
3374  $affectedRowCount = 0;
3375  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3376  try {
3377  foreach ( $rows as $row ) {
3378  // Update any existing conflicting rows (including ones inserted from $rows)
3379  $sqlConditions = $this->makeConditionCollidesUponKeys( [ $row ], $uniqueKeys );
3380  $this->update( $table, $set, [ $sqlConditions ], $fname );
3381  $rowsUpdated = $this->affectedRows();
3382  $affectedRowCount += $rowsUpdated;
3383  if ( $rowsUpdated <= 0 ) {
3384  // Now insert the row if there are no conflicts
3385  $this->insert( $table, $row, $fname );
3386  $affectedRowCount += $this->affectedRows();
3387  }
3388  }
3389  $this->endAtomic( $fname );
3390  } catch ( Throwable $e ) {
3391  $this->cancelAtomic( $fname );
3392  throw $e;
3393  }
3394  $this->affectedRowCount = $affectedRowCount;
3395  }
3396 
3401  public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3402  $fname = __METHOD__
3403  ) {
3404  if ( !$conds ) {
3405  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
3406  }
3407 
3408  $delTable = $this->tableName( $delTable );
3409  $joinTable = $this->tableName( $joinTable );
3410  $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3411  if ( $conds != '*' ) {
3412  $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
3413  }
3414  $sql .= ')';
3415 
3416  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3417  }
3418 
3423  public function textFieldSize( $table, $field ) {
3424  $table = $this->tableName( $table );
3425  $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
3426  $res = $this->query( $sql, __METHOD__, self::QUERY_CHANGE_NONE );
3427  $row = $this->fetchObject( $res );
3428 
3429  $m = [];
3430 
3431  if ( preg_match( '/\‍((.*)\‍)/', $row->Type, $m ) ) {
3432  $size = $m[1];
3433  } else {
3434  $size = -1;
3435  }
3436 
3437  return $size;
3438  }
3439 
3440  public function delete( $table, $conds, $fname = __METHOD__ ) {
3441  $this->assertConditionIsNotEmpty( $conds, __METHOD__, false );
3442 
3443  $table = $this->tableName( $table );
3444  $sql = "DELETE FROM $table";
3445 
3446  if ( $conds !== IDatabase::ALL_ROWS ) {
3447  if ( is_array( $conds ) ) {
3448  $conds = $this->makeList( $conds, self::LIST_AND );
3449  }
3450  $sql .= ' WHERE ' . $conds;
3451  }
3452 
3453  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3454 
3455  return true;
3456  }
3457 
3458  final public function insertSelect(
3459  $destTable,
3460  $srcTable,
3461  $varMap,
3462  $conds,
3463  $fname = __METHOD__,
3464  $insertOptions = [],
3465  $selectOptions = [],
3466  $selectJoinConds = []
3467  ) {
3468  static $hints = [ 'NO_AUTO_COLUMNS' ];
3469 
3470  $insertOptions = $this->normalizeOptions( $insertOptions );
3471  $selectOptions = $this->normalizeOptions( $selectOptions );
3472 
3473  if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3474  // For massive migrations with downtime, we don't want to select everything
3475  // into memory and OOM, so do all this native on the server side if possible.
3476  $this->doInsertSelectNative(
3477  $destTable,
3478  $srcTable,
3479  $varMap,
3480  $conds,
3481  $fname,
3482  array_diff( $insertOptions, $hints ),
3483  $selectOptions,
3484  $selectJoinConds
3485  );
3486  } else {
3487  $this->doInsertSelectGeneric(
3488  $destTable,
3489  $srcTable,
3490  $varMap,
3491  $conds,
3492  $fname,
3493  array_diff( $insertOptions, $hints ),
3494  $selectOptions,
3495  $selectJoinConds
3496  );
3497  }
3498 
3499  return true;
3500  }
3501 
3509  protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3510  return true;
3511  }
3512 
3527  protected function doInsertSelectGeneric(
3528  $destTable,
3529  $srcTable,
3530  array $varMap,
3531  $conds,
3532  $fname,
3533  array $insertOptions,
3534  array $selectOptions,
3535  $selectJoinConds
3536  ) {
3537  // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3538  // on only the master (without needing row-based-replication). It also makes it easy to
3539  // know how big the INSERT is going to be.
3540  $fields = [];
3541  foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3542  $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3543  }
3544  $res = $this->select(
3545  $srcTable,
3546  implode( ',', $fields ),
3547  $conds,
3548  $fname,
3549  array_merge( $selectOptions, [ 'FOR UPDATE' ] ),
3550  $selectJoinConds
3551  );
3552  if ( !$res ) {
3553  return;
3554  }
3555 
3556  $affectedRowCount = 0;
3557  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3558  try {
3559  $rows = [];
3560  foreach ( $res as $row ) {
3561  $rows[] = (array)$row;
3562  }
3563  // Avoid inserts that are too huge
3564  $rowBatches = array_chunk( $rows, $this->nonNativeInsertSelectBatchSize );
3565  foreach ( $rowBatches as $rows ) {
3566  $this->insert( $destTable, $rows, $fname, $insertOptions );
3567  $affectedRowCount += $this->affectedRows();
3568  }
3569  } catch ( Throwable $e ) {
3570  $this->cancelAtomic( $fname );
3571  throw $e;
3572  }
3573  $this->endAtomic( $fname );
3574  $this->affectedRowCount = $affectedRowCount;
3575  }
3576 
3592  protected function doInsertSelectNative(
3593  $destTable,
3594  $srcTable,
3595  array $varMap,
3596  $conds,
3597  $fname,
3598  array $insertOptions,
3599  array $selectOptions,
3600  $selectJoinConds
3601  ) {
3602  list( $sqlVerb, $sqlOpts ) = $this->isFlagInOptions( 'IGNORE', $insertOptions )
3604  : [ 'INSERT INTO', '' ];
3605  $encDstTable = $this->tableName( $destTable );
3606  $sqlDstColumns = implode( ',', array_keys( $varMap ) );
3607  $selectSql = $this->selectSQLText(
3608  $srcTable,
3609  array_values( $varMap ),
3610  $conds,
3611  $fname,
3612  $selectOptions,
3613  $selectJoinConds
3614  );
3615 
3616  $sql = rtrim( "$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
3617 
3618  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3619  }
3620 
3625  public function limitResult( $sql, $limit, $offset = false ) {
3626  if ( !is_numeric( $limit ) ) {
3627  throw new DBUnexpectedError(
3628  $this,
3629  "Invalid non-numeric limit passed to " . __METHOD__
3630  );
3631  }
3632  // This version works in MySQL and SQLite. It will very likely need to be
3633  // overridden for most other RDBMS subclasses.
3634  return "$sql LIMIT "
3635  . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3636  . "{$limit} ";
3637  }
3638 
3643  public function unionSupportsOrderAndLimit() {
3644  return true; // True for almost every DB supported
3645  }
3646 
3651  public function unionQueries( $sqls, $all ) {
3652  $glue = $all ? ') UNION ALL (' : ') UNION (';
3653 
3654  return '(' . implode( $glue, $sqls ) . ')';
3655  }
3656 
3658  $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
3659  $options = [], $join_conds = []
3660  ) {
3661  // First, build the Cartesian product of $permute_conds
3662  $conds = [ [] ];
3663  foreach ( $permute_conds as $field => $values ) {
3664  if ( !$values ) {
3665  // Skip empty $values
3666  continue;
3667  }
3668  $values = array_unique( $values ); // For sanity
3669  $newConds = [];
3670  foreach ( $conds as $cond ) {
3671  foreach ( $values as $value ) {
3672  $cond[$field] = $value;
3673  $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3674  }
3675  }
3676  $conds = $newConds;
3677  }
3678 
3679  $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
3680 
3681  // If there's just one condition and no subordering, hand off to
3682  // selectSQLText directly.
3683  if ( count( $conds ) === 1 &&
3684  ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
3685  ) {
3686  return $this->selectSQLText(
3687  $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
3688  );
3689  }
3690 
3691  // Otherwise, we need to pull out the order and limit to apply after
3692  // the union. Then build the SQL queries for each set of conditions in
3693  // $conds. Then union them together (using UNION ALL, because the
3694  // product *should* already be distinct).
3695  $orderBy = $this->makeOrderBy( $options );
3696  $limit = $options['LIMIT'] ?? null;
3697  $offset = $options['OFFSET'] ?? false;
3698  $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3699  if ( !$this->unionSupportsOrderAndLimit() ) {
3700  unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3701  } else {
3702  if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3703  $options['ORDER BY'] = $options['INNER ORDER BY'];
3704  }
3705  if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3706  // We need to increase the limit by the offset rather than
3707  // using the offset directly, otherwise it'll skip incorrectly
3708  // in the subqueries.
3709  $options['LIMIT'] = $limit + $offset;
3710  unset( $options['OFFSET'] );
3711  }
3712  }
3713 
3714  $sqls = [];
3715  foreach ( $conds as $cond ) {
3716  $sqls[] = $this->selectSQLText(
3717  $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
3718  );
3719  }
3720  $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3721  if ( $limit !== null ) {
3722  $sql = $this->limitResult( $sql, $limit, $offset );
3723  }
3724 
3725  return $sql;
3726  }
3727 
3732  public function conditional( $cond, $trueVal, $falseVal ) {
3733  if ( is_array( $cond ) ) {
3734  $cond = $this->makeList( $cond, self::LIST_AND );
3735  }
3736 
3737  return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3738  }
3739 
3744  public function strreplace( $orig, $old, $new ) {
3745  return "REPLACE({$orig}, {$old}, {$new})";
3746  }
3747 
3752  public function getServerUptime() {
3753  return 0;
3754  }
3755 
3760  public function wasDeadlock() {
3761  return false;
3762  }
3763 
3768  public function wasLockTimeout() {
3769  return false;
3770  }
3771 
3776  public function wasConnectionLoss() {
3777  return $this->wasConnectionError( $this->lastErrno() );
3778  }
3779 
3784  public function wasReadOnlyError() {
3785  return false;
3786  }
3787 
3788  public function wasErrorReissuable() {
3789  return (
3790  $this->wasDeadlock() ||
3791  $this->wasLockTimeout() ||
3792  $this->wasConnectionLoss()
3793  );
3794  }
3795 
3803  public function wasConnectionError( $errno ) {
3804  return false;
3805  }
3806 
3814  protected function wasKnownStatementRollbackError() {
3815  return false; // don't know; it could have caused a transaction rollback
3816  }
3817 
3822  public function deadlockLoop( ...$args ) {
3823  $function = array_shift( $args );
3824  $tries = self::$DEADLOCK_TRIES;
3825 
3826  $this->begin( __METHOD__ );
3827 
3828  $retVal = null;
3830  $e = null;
3831  do {
3832  try {
3833  $retVal = $function( ...$args );
3834  break;
3835  } catch ( DBQueryError $e ) {
3836  if ( $this->wasDeadlock() ) {
3837  // Retry after a randomized delay
3838  usleep( mt_rand( self::$DEADLOCK_DELAY_MIN, self::$DEADLOCK_DELAY_MAX ) );
3839  } else {
3840  // Throw the error back up
3841  throw $e;
3842  }
3843  }
3844  } while ( --$tries > 0 );
3845 
3846  if ( $tries <= 0 ) {
3847  // Too many deadlocks; give up
3848  $this->rollback( __METHOD__ );
3849  throw $e;
3850  } else {
3851  $this->commit( __METHOD__ );
3852 
3853  return $retVal;
3854  }
3855  }
3856 
3861  public function masterPosWait( DBMasterPos $pos, $timeout ) {
3862  # Real waits are implemented in the subclass.
3863  return 0;
3864  }
3865 
3870  public function getReplicaPos() {
3871  # Stub
3872  return false;
3873  }
3874 
3879  public function getMasterPos() {
3880  # Stub
3881  return false;
3882  }
3883 
3888  public function serverIsReadOnly() {
3889  return false;
3890  }
3891 
3892  final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3893  if ( !$this->trxLevel() ) {
3894  throw new DBUnexpectedError( $this, "No transaction is active" );
3895  }
3896  $this->trxEndCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3897  }
3898 
3899  final public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3900  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3901  // Start an implicit transaction similar to how query() does
3902  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3903  $this->trxAutomatic = true;
3904  }
3905 
3906  $this->trxIdleCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3907  if ( !$this->trxLevel() ) {
3908  $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3909  }
3910  }
3911 
3912  final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3913  $this->onTransactionCommitOrIdle( $callback, $fname );
3914  }
3915 
3916  final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3917  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3918  // Start an implicit transaction similar to how query() does
3919  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3920  $this->trxAutomatic = true;
3921  }
3922 
3923  if ( $this->trxLevel() ) {
3924  $this->trxPreCommitCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3925  } else {
3926  // No transaction is active nor will start implicitly, so make one for this callback
3927  $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3928  try {
3929  $callback( $this );
3930  $this->endAtomic( __METHOD__ );
3931  } catch ( Throwable $e ) {
3932  $this->cancelAtomic( __METHOD__ );
3933  throw $e;
3934  }
3935  }
3936  }
3937 
3938  final public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ) {
3939  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3940  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3941  }
3942  $this->trxSectionCancelCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3943  }
3944 
3948  private function currentAtomicSectionId() {
3949  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
3950  $levelInfo = end( $this->trxAtomicLevels );
3951 
3952  return $levelInfo[1];
3953  }
3954 
3955  return null;
3956  }
3957 
3966  ) {
3967  foreach ( $this->trxPreCommitCallbacks as $key => $info ) {
3968  if ( $info[2] === $old ) {
3969  $this->trxPreCommitCallbacks[$key][2] = $new;
3970  }
3971  }
3972  foreach ( $this->trxIdleCallbacks as $key => $info ) {
3973  if ( $info[2] === $old ) {
3974  $this->trxIdleCallbacks[$key][2] = $new;
3975  }
3976  }
3977  foreach ( $this->trxEndCallbacks as $key => $info ) {
3978  if ( $info[2] === $old ) {
3979  $this->trxEndCallbacks[$key][2] = $new;
3980  }
3981  }
3982  foreach ( $this->trxSectionCancelCallbacks as $key => $info ) {
3983  if ( $info[2] === $old ) {
3984  $this->trxSectionCancelCallbacks[$key][2] = $new;
3985  }
3986  }
3987  }
3988 
4008  private function modifyCallbacksForCancel(
4009  array $sectionIds, AtomicSectionIdentifier $newSectionId = null
4010  ) {
4011  // Cancel the "on commit" callbacks owned by this savepoint
4012  $this->trxIdleCallbacks = array_filter(
4013  $this->trxIdleCallbacks,
4014  function ( $entry ) use ( $sectionIds ) {
4015  return !in_array( $entry[2], $sectionIds, true );
4016  }
4017  );
4018  $this->trxPreCommitCallbacks = array_filter(
4019  $this->trxPreCommitCallbacks,
4020  function ( $entry ) use ( $sectionIds ) {
4021  return !in_array( $entry[2], $sectionIds, true );
4022  }
4023  );
4024  // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
4025  foreach ( $this->trxEndCallbacks as $key => $entry ) {
4026  if ( in_array( $entry[2], $sectionIds, true ) ) {
4027  $callback = $entry[0];
4028  $this->trxEndCallbacks[$key][0] = function () use ( $callback ) {
4029  return $callback( self::TRIGGER_ROLLBACK, $this );
4030  };
4031  // This "on resolution" callback no longer belongs to a section.
4032  $this->trxEndCallbacks[$key][2] = null;
4033  }
4034  }
4035  // Hoist callback ownership for section cancel callbacks to the new top section
4036  foreach ( $this->trxSectionCancelCallbacks as $key => $entry ) {
4037  if ( in_array( $entry[2], $sectionIds, true ) ) {
4038  $this->trxSectionCancelCallbacks[$key][2] = $newSectionId;
4039  }
4040  }
4041  }
4042 
4043  final public function setTransactionListener( $name, callable $callback = null ) {
4044  if ( $callback ) {
4045  $this->trxRecurringCallbacks[$name] = $callback;
4046  } else {
4047  unset( $this->trxRecurringCallbacks[$name] );
4048  }
4049  }
4050 
4059  final public function setTrxEndCallbackSuppression( $suppress ) {
4060  $this->trxEndCallbacksSuppressed = $suppress;
4061  }
4062 
4073  public function runOnTransactionIdleCallbacks( $trigger ) {
4074  if ( $this->trxLevel() ) { // sanity
4075  throw new DBUnexpectedError( $this, __METHOD__ . ': a transaction is still open' );
4076  }
4077 
4078  if ( $this->trxEndCallbacksSuppressed ) {
4079  return 0;
4080  }
4081 
4082  $count = 0;
4083  $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
4085  $e = null; // first exception
4086  do { // callbacks may add callbacks :)
4087  $callbacks = array_merge(
4088  $this->trxIdleCallbacks,
4089  $this->trxEndCallbacks // include "transaction resolution" callbacks
4090  );
4091  $this->trxIdleCallbacks = []; // consumed (and recursion guard)
4092  $this->trxEndCallbacks = []; // consumed (recursion guard)
4093 
4094  // Only run trxSectionCancelCallbacks on rollback, not commit.
4095  // But always consume them.
4096  if ( $trigger === self::TRIGGER_ROLLBACK ) {
4097  $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks );
4098  }
4099  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
4100 
4101  foreach ( $callbacks as $callback ) {
4102  ++$count;
4103  list( $phpCallback ) = $callback;
4104  $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
4105  try {
4106  call_user_func( $phpCallback, $trigger, $this );
4107  } catch ( Throwable $ex ) {
4108  call_user_func( $this->errorLogger, $ex );
4109  $e = $e ?: $ex;
4110  // Some callbacks may use startAtomic/endAtomic, so make sure
4111  // their transactions are ended so other callbacks don't fail
4112  if ( $this->trxLevel() ) {
4113  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
4114  }
4115  } finally {
4116  if ( $autoTrx ) {
4117  $this->setFlag( self::DBO_TRX ); // restore automatic begin()
4118  } else {
4119  $this->clearFlag( self::DBO_TRX ); // restore auto-commit
4120  }
4121  }
4122  }
4123  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4124  } while ( count( $this->trxIdleCallbacks ) );
4125 
4126  if ( $e instanceof Throwable ) {
4127  throw $e; // re-throw any first exception
4128  }
4129 
4130  return $count;
4131  }
4132 
4143  $count = 0;
4144 
4145  $e = null; // first exception
4146  do { // callbacks may add callbacks :)
4147  $callbacks = $this->trxPreCommitCallbacks;
4148  $this->trxPreCommitCallbacks = []; // consumed (and recursion guard)
4149  foreach ( $callbacks as $callback ) {
4150  try {
4151  ++$count;
4152  list( $phpCallback ) = $callback;
4153  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
4154  $phpCallback( $this );
4155  } catch ( Throwable $ex ) {
4156  ( $this->errorLogger )( $ex );
4157  $e = $e ?: $ex;
4158  }
4159  }
4160  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4161  } while ( count( $this->trxPreCommitCallbacks ) );
4162 
4163  if ( $e instanceof Throwable ) {
4164  throw $e; // re-throw any first exception
4165  }
4166 
4167  return $count;
4168  }
4169 
4178  $trigger, array $sectionIds = null
4179  ) {
4181  $e = null; // first exception
4182 
4183  $notCancelled = [];
4184  do {
4185  $callbacks = $this->trxSectionCancelCallbacks;
4186  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
4187  foreach ( $callbacks as $entry ) {
4188  if ( $sectionIds === null || in_array( $entry[2], $sectionIds, true ) ) {
4189  try {
4190  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
4191  $entry[0]( $trigger, $this );
4192  } catch ( Throwable $ex ) {
4193  ( $this->errorLogger )( $ex );
4194  $e = $e ?: $ex;
4195  }
4196  } else {
4197  $notCancelled[] = $entry;
4198  }
4199  }
4200  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4201  } while ( count( $this->trxSectionCancelCallbacks ) );
4202  $this->trxSectionCancelCallbacks = $notCancelled;
4203 
4204  if ( $e !== null ) {
4205  throw $e; // re-throw any first Throwable
4206  }
4207  }
4208 
4218  public function runTransactionListenerCallbacks( $trigger ) {
4219  if ( $this->trxEndCallbacksSuppressed ) {
4220  return;
4221  }
4222 
4224  $e = null; // first exception
4225 
4226  foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
4227  try {
4228  $phpCallback( $trigger, $this );
4229  } catch ( Throwable $ex ) {
4230  ( $this->errorLogger )( $ex );
4231  $e = $e ?: $ex;
4232  }
4233  }
4234 
4235  if ( $e instanceof Throwable ) {
4236  throw $e; // re-throw any first exception
4237  }
4238  }
4239 
4251  protected function doSavepoint( $identifier, $fname ) {
4252  $sql = 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4253  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4254  }
4255 
4267  protected function doReleaseSavepoint( $identifier, $fname ) {
4268  $sql = 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4269  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4270  }
4271 
4283  protected function doRollbackToSavepoint( $identifier, $fname ) {
4284  $sql = 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4285  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4286  }
4287 
4292  private function nextSavepointId( $fname ) {
4293  $savepointId = self::$SAVEPOINT_PREFIX . ++$this->trxAtomicCounter;
4294  if ( strlen( $savepointId ) > 30 ) {
4295  // 30 == Oracle's identifier length limit (pre 12c)
4296  // With a 22 character prefix, that puts the highest number at 99999999.
4297  throw new DBUnexpectedError(
4298  $this,
4299  'There have been an excessively large number of atomic sections in a transaction'
4300  . " started by $this->trxFname (at $fname)"
4301  );
4302  }
4303 
4304  return $savepointId;
4305  }
4306 
4307  final public function startAtomic(
4308  $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE
4309  ) {
4310  $savepointId = $cancelable === self::ATOMIC_CANCELABLE ? self::$NOT_APPLICABLE : null;
4311 
4312  if ( !$this->trxLevel() ) {
4313  $this->begin( $fname, self::TRANSACTION_INTERNAL ); // sets trxAutomatic
4314  // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
4315  // in all changes being in one transaction to keep requests transactional.
4316  if ( $this->getFlag( self::DBO_TRX ) ) {
4317  // Since writes could happen in between the topmost atomic sections as part
4318  // of the transaction, those sections will need savepoints.
4319  $savepointId = $this->nextSavepointId( $fname );
4320  $this->doSavepoint( $savepointId, $fname );
4321  } else {
4322  $this->trxAutomaticAtomic = true;
4323  }
4324  } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
4325  $savepointId = $this->nextSavepointId( $fname );
4326  $this->doSavepoint( $savepointId, $fname );
4327  }
4328 
4329  $sectionId = new AtomicSectionIdentifier;
4330  $this->trxAtomicLevels[] = [ $fname, $sectionId, $savepointId ];
4331  $this->queryLogger->debug( 'startAtomic: entering level ' .
4332  ( count( $this->trxAtomicLevels ) - 1 ) . " ($fname)" );
4333 
4334  return $sectionId;
4335  }
4336 
4337  final public function endAtomic( $fname = __METHOD__ ) {
4338  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
4339  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
4340  }
4341 
4342  // Check if the current section matches $fname
4343  $pos = count( $this->trxAtomicLevels ) - 1;
4344  list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
4345  $this->queryLogger->debug( "endAtomic: leaving level $pos ($fname)" );
4346 
4347  if ( $savedFname !== $fname ) {
4348  throw new DBUnexpectedError(
4349  $this,
4350  "Invalid atomic section ended (got $fname but expected $savedFname)"
4351  );
4352  }
4353 
4354  // Remove the last section (no need to re-index the array)
4355  array_pop( $this->trxAtomicLevels );
4356 
4357  if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
4358  $this->commit( $fname, self::FLUSHING_INTERNAL );
4359  } elseif ( $savepointId !== null && $savepointId !== self::$NOT_APPLICABLE ) {
4360  $this->doReleaseSavepoint( $savepointId, $fname );
4361  }
4362 
4363  // Hoist callback ownership for callbacks in the section that just ended;
4364  // all callbacks should have an owner that is present in trxAtomicLevels.
4365  $currentSectionId = $this->currentAtomicSectionId();
4366  if ( $currentSectionId ) {
4367  $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
4368  }
4369  }
4370 
4371  final public function cancelAtomic(
4372  $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null
4373  ) {
4374  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
4375  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
4376  }
4377 
4378  $excisedIds = [];
4379  $newTopSection = $this->currentAtomicSectionId();
4380  try {
4381  $excisedFnames = [];
4382  if ( $sectionId !== null ) {
4383  // Find the (last) section with the given $sectionId
4384  $pos = -1;
4385  foreach ( $this->trxAtomicLevels as $i => list( $asFname, $asId, $spId ) ) {
4386  if ( $asId === $sectionId ) {
4387  $pos = $i;
4388  }
4389  }
4390  if ( $pos < 0 ) {
4391  throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
4392  }
4393  // Remove all descendant sections and re-index the array
4394  $len = count( $this->trxAtomicLevels );
4395  for ( $i = $pos + 1; $i < $len; ++$i ) {
4396  $excisedFnames[] = $this->trxAtomicLevels[$i][0];
4397  $excisedIds[] = $this->trxAtomicLevels[$i][1];
4398  }
4399  $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
4400  $newTopSection = $this->currentAtomicSectionId();
4401  }
4402 
4403  // Check if the current section matches $fname
4404  $pos = count( $this->trxAtomicLevels ) - 1;
4405  list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
4406 
4407  if ( $excisedFnames ) {
4408  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
4409  "and descendants " . implode( ', ', $excisedFnames ) );
4410  } else {
4411  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
4412  }
4413 
4414  if ( $savedFname !== $fname ) {
4415  throw new DBUnexpectedError(
4416  $this,
4417  "Invalid atomic section ended (got $fname but expected $savedFname)"
4418  );
4419  }
4420 
4421  // Remove the last section (no need to re-index the array)
4422  array_pop( $this->trxAtomicLevels );
4423  $excisedIds[] = $savedSectionId;
4424  $newTopSection = $this->currentAtomicSectionId();
4425 
4426  if ( $savepointId !== null ) {
4427  // Rollback the transaction to the state just before this atomic section
4428  if ( $savepointId === self::$NOT_APPLICABLE ) {
4429  $this->rollback( $fname, self::FLUSHING_INTERNAL );
4430  // Note: rollback() will run trxSectionCancelCallbacks
4431  } else {
4432  $this->doRollbackToSavepoint( $savepointId, $fname );
4433  $this->trxStatus = self::STATUS_TRX_OK; // no exception; recovered
4434  $this->trxStatusIgnoredCause = null;
4435 
4436  // Run trxSectionCancelCallbacks now.
4437  $this->runOnAtomicSectionCancelCallbacks( self::TRIGGER_CANCEL, $excisedIds );
4438  }
4439  } elseif ( $this->trxStatus > self::STATUS_TRX_ERROR ) {
4440  // Put the transaction into an error state if it's not already in one
4441  $this->trxStatus = self::STATUS_TRX_ERROR;
4442  $this->trxStatusCause = new DBUnexpectedError(
4443  $this,
4444  "Uncancelable atomic section canceled (got $fname)"
4445  );
4446  }
4447  } finally {
4448  // Fix up callbacks owned by the sections that were just cancelled.
4449  // All callbacks should have an owner that is present in trxAtomicLevels.
4450  $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
4451  }
4452 
4453  $this->affectedRowCount = 0; // for the sake of consistency
4454  }
4455 
4456  final public function doAtomicSection(
4457  $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
4458  ) {
4459  $sectionId = $this->startAtomic( $fname, $cancelable );
4460  try {
4461  $res = $callback( $this, $fname );
4462  } catch ( Throwable $e ) {
4463  $this->cancelAtomic( $fname, $sectionId );
4464 
4465  throw $e;
4466  }
4467  $this->endAtomic( $fname );
4468 
4469  return $res;
4470  }
4471 
4472  final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
4473  static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
4474  if ( !in_array( $mode, $modes, true ) ) {
4475  throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
4476  }
4477 
4478  // Protect against mismatched atomic section, transaction nesting, and snapshot loss
4479  if ( $this->trxLevel() ) {
4480  if ( $this->trxAtomicLevels ) {
4481  $levels = $this->flatAtomicSectionList();
4482  $msg = "$fname: got explicit BEGIN while atomic section(s) $levels are open";
4483  throw new DBUnexpectedError( $this, $msg );
4484  } elseif ( !$this->trxAutomatic ) {
4485  $msg = "$fname: explicit transaction already active (from {$this->trxFname})";
4486  throw new DBUnexpectedError( $this, $msg );
4487  } else {
4488  $msg = "$fname: implicit transaction already active (from {$this->trxFname})";
4489  throw new DBUnexpectedError( $this, $msg );
4490  }
4491  } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
4492  $msg = "$fname: implicit transaction expected (DBO_TRX set)";
4493  throw new DBUnexpectedError( $this, $msg );
4494  }
4495 
4496  $this->assertHasConnectionHandle();
4497 
4498  $this->doBegin( $fname );
4499  $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4500  $this->trxStatus = self::STATUS_TRX_OK;
4501  $this->trxStatusIgnoredCause = null;
4502  $this->trxAtomicCounter = 0;
4503  $this->trxTimestamp = microtime( true );
4504  $this->trxFname = $fname;
4505  $this->trxDoneWrites = false;
4506  $this->trxAutomaticAtomic = false;
4507  $this->trxAtomicLevels = [];
4508  $this->trxWriteDuration = 0.0;
4509  $this->trxWriteQueryCount = 0;
4510  $this->trxWriteAffectedRows = 0;
4511  $this->trxWriteAdjDuration = 0.0;
4512  $this->trxWriteAdjQueryCount = 0;
4513  $this->trxWriteCallers = [];
4514  // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4515  // Get an estimate of the replication lag before any such queries.
4516  $this->trxReplicaLag = null; // clear cached value first
4517  $this->trxReplicaLag = $this->getApproximateLagStatus()['lag'];
4518  // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4519  // caller will think its OK to muck around with the transaction just because startAtomic()
4520  // has not yet completed (e.g. setting trxAtomicLevels).
4521  $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
4522  }
4523 
4532  protected function doBegin( $fname ) {
4533  $this->query( 'BEGIN', $fname, self::QUERY_CHANGE_TRX );
4534  }
4535 
4536  final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4537  static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
4538  if ( !in_array( $flush, $modes, true ) ) {
4539  throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4540  }
4541 
4542  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
4543  // There are still atomic sections open; this cannot be ignored
4544  $levels = $this->flatAtomicSectionList();
4545  throw new DBUnexpectedError(
4546  $this,
4547  "$fname: got COMMIT while atomic sections $levels are still open"
4548  );
4549  }
4550 
4551  if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
4552  if ( !$this->trxLevel() ) {
4553  return; // nothing to do
4554  } elseif ( !$this->trxAutomatic ) {
4555  throw new DBUnexpectedError(
4556  $this,
4557  "$fname: flushing an explicit transaction, getting out of sync"
4558  );
4559  }
4560  } elseif ( !$this->trxLevel() ) {
4561  $this->queryLogger->error(
4562  "$fname: no transaction to commit, something got out of sync",
4563  [ 'exception' => new RuntimeException() ]
4564  );
4565 
4566  return; // nothing to do
4567  } elseif ( $this->trxAutomatic ) {
4568  throw new DBUnexpectedError(
4569  $this,
4570  "$fname: expected mass commit of all peer transactions (DBO_TRX set)"
4571  );
4572  }
4573 
4574  $this->assertHasConnectionHandle();
4575 
4577 
4578  $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
4579  $this->doCommit( $fname );
4580  $oldTrxShortId = $this->consumeTrxShortId();
4581  $this->trxStatus = self::STATUS_TRX_NONE;
4582 
4583  if ( $this->trxDoneWrites ) {
4584  $this->lastWriteTime = microtime( true );
4585  $this->trxProfiler->transactionWritingOut(
4586  $this->server,
4587  $this->getDomainID(),
4588  $oldTrxShortId,
4589  $writeTime,
4590  $this->trxWriteAffectedRows
4591  );
4592  }
4593 
4594  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4595  if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4596  $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
4597  $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
4598  }
4599  }
4600 
4609  protected function doCommit( $fname ) {
4610  if ( $this->trxLevel() ) {
4611  $this->query( 'COMMIT', $fname, self::QUERY_CHANGE_TRX );
4612  }
4613  }
4614 
4615  final public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4616  $trxActive = $this->trxLevel();
4617 
4618  if ( $flush !== self::FLUSHING_INTERNAL
4619  && $flush !== self::FLUSHING_ALL_PEERS
4620  && $this->getFlag( self::DBO_TRX )
4621  ) {
4622  throw new DBUnexpectedError(
4623  $this,
4624  "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4625  );
4626  }
4627 
4628  if ( $trxActive ) {
4629  $this->assertHasConnectionHandle();
4630 
4631  $this->doRollback( $fname );
4632  $oldTrxShortId = $this->consumeTrxShortId();
4633  $this->trxStatus = self::STATUS_TRX_NONE;
4634  $this->trxAtomicLevels = [];
4635  // Estimate the RTT via a query now that trxStatus is OK
4636  $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4637 
4638  if ( $this->trxDoneWrites ) {
4639  $this->trxProfiler->transactionWritingOut(
4640  $this->server,
4641  $this->getDomainID(),
4642  $oldTrxShortId,
4643  $writeTime,
4644  $this->trxWriteAffectedRows
4645  );
4646  }
4647  }
4648 
4649  // Clear any commit-dependant callbacks. They might even be present
4650  // only due to transaction rounds, with no SQL transaction being active
4651  $this->trxIdleCallbacks = [];
4652  $this->trxPreCommitCallbacks = [];
4653 
4654  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4655  if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4656  try {
4657  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
4658  } catch ( Throwable $e ) {
4659  // already logged; finish and let LoadBalancer move on during mass-rollback
4660  }
4661  try {
4662  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
4663  } catch ( Throwable $e ) {
4664  // already logged; let LoadBalancer move on during mass-rollback
4665  }
4666 
4667  $this->affectedRowCount = 0; // for the sake of consistency
4668  }
4669  }
4670 
4679  protected function doRollback( $fname ) {
4680  if ( $this->trxLevel() ) {
4681  # Disconnects cause rollback anyway, so ignore those errors
4682  $this->query( 'ROLLBACK', $fname, self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_TRX );
4683  }
4684  }
4685 
4686  public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4687  if ( $this->explicitTrxActive() ) {
4688  // Committing this transaction would break callers that assume it is still open
4689  throw new DBUnexpectedError(
4690  $this,
4691  "$fname: Cannot flush snapshot; " .
4692  "explicit transaction '{$this->trxFname}' is still open"
4693  );
4694  } elseif ( $this->writesOrCallbacksPending() ) {
4695  // This only flushes transactions to clear snapshots, not to write data
4696  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4697  throw new DBUnexpectedError(
4698  $this,
4699  "$fname: Cannot flush snapshot; " .
4700  "writes from transaction {$this->trxFname} are still pending ($fnames)"
4701  );
4702  } elseif (
4703  $this->trxLevel() &&
4704  $this->getTransactionRoundId() &&
4705  $flush !== self::FLUSHING_INTERNAL &&
4706  $flush !== self::FLUSHING_ALL_PEERS
4707  ) {
4708  $this->queryLogger->warning(
4709  "$fname: Expected mass snapshot flush of all peer transactions " .
4710  "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4711  [ 'exception' => new RuntimeException() ]
4712  );
4713  }
4714 
4715  $this->commit( $fname, self::FLUSHING_INTERNAL );
4716  }
4717 
4718  public function explicitTrxActive() {
4719  return $this->trxLevel() && ( $this->trxAtomicLevels || !$this->trxAutomatic );
4720  }
4721 
4726  public function duplicateTableStructure(
4727  $oldName, $newName, $temporary = false, $fname = __METHOD__
4728  ) {
4729  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4730  }
4731 
4736  public function listTables( $prefix = null, $fname = __METHOD__ ) {
4737  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4738  }
4739 
4744  public function listViews( $prefix = null, $fname = __METHOD__ ) {
4745  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4746  }
4747 
4752  public function timestamp( $ts = 0 ) {
4753  $t = new ConvertibleTimestamp( $ts );
4754  // Let errors bubble up to avoid putting garbage in the DB
4755  return $t->getTimestamp( TS_MW );
4756  }
4757 
4758  public function timestampOrNull( $ts = null ) {
4759  if ( $ts === null ) {
4760  return null;
4761  } else {
4762  return $this->timestamp( $ts );
4763  }
4764  }
4765 
4766  public function affectedRows() {
4767  return ( $this->affectedRowCount === null )
4768  ? $this->fetchAffectedRowCount() // default to driver value
4770  }
4771 
4775  abstract protected function fetchAffectedRowCount();
4776 
4789  protected function resultObject( $result ) {
4790  if ( !$result ) {
4791  return false; // failed query
4792  } elseif ( $result instanceof IResultWrapper ) {
4793  return $result;
4794  } elseif ( $result === true ) {
4795  return $result; // successful write query
4796  } else {
4797  return new ResultWrapper( $this, $result );
4798  }
4799  }
4800 
4801  public function ping( &$rtt = null ) {
4802  // Avoid hitting the server if it was hit recently
4803  if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::$PING_TTL ) {
4804  if ( !func_num_args() || $this->lastRoundTripEstimate > 0 ) {
4806  return true; // don't care about $rtt
4807  }
4808  }
4809 
4810  // This will reconnect if possible or return false if not
4811  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_NONE;
4812  $ok = ( $this->query( self::$PING_QUERY, __METHOD__, $flags ) !== false );
4813  if ( $ok ) {
4815  }
4816 
4817  return $ok;
4818  }
4819 
4826  protected function replaceLostConnection( $fname ) {
4827  $this->closeConnection();
4828  $this->conn = null;
4829 
4830  $this->handleSessionLossPreconnect();
4831 
4832  try {
4833  $this->open(
4834  $this->server,
4835  $this->user,
4836  $this->password,
4837  $this->currentDomain->getDatabase(),
4838  $this->currentDomain->getSchema(),
4839  $this->tablePrefix()
4840  );
4841  $this->lastPing = microtime( true );
4842  $ok = true;
4843 
4844  $this->connLogger->warning(
4845  $fname . ': lost connection to {dbserver}; reconnected',
4846  [
4847  'dbserver' => $this->getServer(),
4848  'exception' => new RuntimeException()
4849  ]
4850  );
4851  } catch ( DBConnectionError $e ) {
4852  $ok = false;
4853 
4854  $this->connLogger->error(
4855  $fname . ': lost connection to {dbserver} permanently',
4856  [ 'dbserver' => $this->getServer() ]
4857  );
4858  }
4859 
4861 
4862  return $ok;
4863  }
4864 
4865  public function getSessionLagStatus() {
4866  return $this->getRecordedTransactionLagStatus() ?: $this->getApproximateLagStatus();
4867  }
4868 
4882  final protected function getRecordedTransactionLagStatus() {
4883  return ( $this->trxLevel() && $this->trxReplicaLag !== null )
4884  ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
4885  : null;
4886  }
4887 
4897  protected function getApproximateLagStatus() {
4898  return [
4899  'lag' => ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) ? $this->getLag() : 0,
4900  'since' => microtime( true )
4901  ];
4902  }
4903 
4923  public static function getCacheSetOptions( IDatabase $db1, IDatabase $db2 = null ) {
4924  $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
4925  foreach ( func_get_args() as $db ) {
4927  $status = $db->getSessionLagStatus();
4928  if ( $status['lag'] === false ) {
4929  $res['lag'] = false;
4930  } elseif ( $res['lag'] !== false ) {
4931  $res['lag'] = max( $res['lag'], $status['lag'] );
4932  }
4933  $res['since'] = min( $res['since'], $status['since'] );
4934  $res['pending'] = $res['pending'] ?: $db->writesPending();
4935  }
4936 
4937  return $res;
4938  }
4939 
4940  public function getLag() {
4941  if ( $this->topologyRole === self::ROLE_STREAMING_MASTER ) {
4942  return 0; // this is the master
4943  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
4944  return 0; // static dataset
4945  }
4946 
4947  return $this->doGetLag();
4948  }
4949 
4954  protected function doGetLag() {
4955  return 0;
4956  }
4957 
4962  public function maxListLen() {
4963  return 0;
4964  }
4965 
4970  public function encodeBlob( $b ) {
4971  return $b;
4972  }
4973 
4978  public function decodeBlob( $b ) {
4979  if ( $b instanceof Blob ) {
4980  $b = $b->fetch();
4981  }
4982  return $b;
4983  }
4984 
4989  public function setSessionOptions( array $options ) {
4990  }
4991 
4992  public function sourceFile(
4993  $filename,
4994  callable $lineCallback = null,
4995  callable $resultCallback = null,
4996  $fname = false,
4997  callable $inputCallback = null
4998  ) {
4999  AtEase::suppressWarnings();
5000  $fp = fopen( $filename, 'r' );
5001  AtEase::restoreWarnings();
5002 
5003  if ( $fp === false ) {
5004  throw new RuntimeException( "Could not open \"{$filename}\"" );
5005  }
5006 
5007  if ( !$fname ) {
5008  $fname = __METHOD__ . "( $filename )";
5009  }
5010 
5011  try {
5012  $error = $this->sourceStream(
5013  $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
5014  } catch ( Throwable $e ) {
5015  fclose( $fp );
5016  throw $e;
5017  }
5018 
5019  fclose( $fp );
5020 
5021  return $error;
5022  }
5023 
5024  public function setSchemaVars( $vars ) {
5025  $this->schemaVars = is_array( $vars ) ? $vars : null;
5026  }
5027 
5028  public function sourceStream(
5029  $fp,
5030  callable $lineCallback = null,
5031  callable $resultCallback = null,
5032  $fname = __METHOD__,
5033  callable $inputCallback = null
5034  ) {
5035  $delimiterReset = new ScopedCallback(
5036  function ( $delimiter ) {
5037  $this->delimiter = $delimiter;
5038  },
5039  [ $this->delimiter ]
5040  );
5041  $cmd = '';
5042 
5043  while ( !feof( $fp ) ) {
5044  if ( $lineCallback ) {
5045  call_user_func( $lineCallback );
5046  }
5047 
5048  $line = trim( fgets( $fp ) );
5049 
5050  if ( $line == '' ) {
5051  continue;
5052  }
5053 
5054  if ( $line[0] == '-' && $line[1] == '-' ) {
5055  continue;
5056  }
5057 
5058  if ( $cmd != '' ) {
5059  $cmd .= ' ';
5060  }
5061 
5062  $done = $this->streamStatementEnd( $cmd, $line );
5063 
5064  $cmd .= "$line\n";
5065 
5066  if ( $done || feof( $fp ) ) {
5067  $cmd = $this->replaceVars( $cmd );
5068 
5069  if ( $inputCallback ) {
5070  $callbackResult = $inputCallback( $cmd );
5071 
5072  if ( is_string( $callbackResult ) || !$callbackResult ) {
5073  $cmd = $callbackResult;
5074  }
5075  }
5076 
5077  if ( $cmd ) {
5078  $res = $this->query( $cmd, $fname );
5079 
5080  if ( $resultCallback ) {
5081  $resultCallback( $res, $this );
5082  }
5083 
5084  if ( $res === false ) {
5085  $err = $this->lastError();
5086 
5087  return "Query \"{$cmd}\" failed with error code \"$err\".\n";
5088  }
5089  }
5090  $cmd = '';
5091  }
5092  }
5093 
5094  ScopedCallback::consume( $delimiterReset );
5095  return true;
5096  }
5097 
5106  public function streamStatementEnd( &$sql, &$newLine ) {
5107  if ( $this->delimiter ) {
5108  $prev = $newLine;
5109  $newLine = preg_replace(
5110  '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
5111  if ( $newLine != $prev ) {
5112  return true;
5113  }
5114  }
5115 
5116  return false;
5117  }
5118 
5140  protected function replaceVars( $ins ) {
5141  $vars = $this->getSchemaVars();
5142  return preg_replace_callback(
5143  '!
5144  /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
5145  \'\{\$ (\w+) }\' | # 3. addQuotes
5146  `\{\$ (\w+) }` | # 4. addIdentifierQuotes
5147  /\*\$ (\w+) \*/ # 5. leave unencoded
5148  !x',
5149  function ( $m ) use ( $vars ) {
5150  // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
5151  // check for both nonexistent keys *and* the empty string.
5152  if ( isset( $m[1] ) && $m[1] !== '' ) {
5153  if ( $m[1] === 'i' ) {
5154  return $this->indexName( $m[2] );
5155  } else {
5156  return $this->tableName( $m[2] );
5157  }
5158  } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
5159  return $this->addQuotes( $vars[$m[3]] );
5160  } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
5161  return $this->addIdentifierQuotes( $vars[$m[4]] );
5162  } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
5163  return $vars[$m[5]];
5164  } else {
5165  return $m[0];
5166  }
5167  },
5168  $ins
5169  );
5170  }
5171 
5178  protected function getSchemaVars() {
5179  return $this->schemaVars ?? $this->getDefaultSchemaVars();
5180  }
5181 
5191  protected function getDefaultSchemaVars() {
5192  return [];
5193  }
5194 
5199  public function lockIsFree( $lockName, $method ) {
5200  // RDBMs methods for checking named locks may or may not count this thread itself.
5201  // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
5202  // the behavior chosen by the interface for this method.
5203  return !isset( $this->sessionNamedLocks[$lockName] );
5204  }
5205 
5210  public function lock( $lockName, $method, $timeout = 5 ) {
5211  $this->sessionNamedLocks[$lockName] = 1;
5212 
5213  return true;
5214  }
5215 
5220  public function unlock( $lockName, $method ) {
5221  unset( $this->sessionNamedLocks[$lockName] );
5222 
5223  return true;
5224  }
5225 
5226  public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
5227  if ( $this->writesOrCallbacksPending() ) {
5228  // This only flushes transactions to clear snapshots, not to write data
5229  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
5230  throw new DBUnexpectedError(
5231  $this,
5232  "$fname: Cannot flush pre-lock snapshot; " .
5233  "writes from transaction {$this->trxFname} are still pending ($fnames)"
5234  );
5235  }
5236 
5237  if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
5238  return null;
5239  }
5240 
5241  $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
5242  if ( $this->trxLevel() ) {
5243  // There is a good chance an exception was thrown, causing any early return
5244  // from the caller. Let any error handler get a chance to issue rollback().
5245  // If there isn't one, let the error bubble up and trigger server-side rollback.
5246  $this->onTransactionResolution(
5247  function () use ( $lockKey, $fname ) {
5248  $this->unlock( $lockKey, $fname );
5249  },
5250  $fname
5251  );
5252  } else {
5253  $this->unlock( $lockKey, $fname );
5254  }
5255  } );
5256 
5257  $this->commit( $fname, self::FLUSHING_INTERNAL );
5258 
5259  return $unlocker;
5260  }
5261 
5266  public function namedLocksEnqueue() {
5267  return false;
5268  }
5269 
5271  return true;
5272  }
5273 
5274  final public function lockTables( array $read, array $write, $method ) {
5275  if ( $this->writesOrCallbacksPending() ) {
5276  throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
5277  }
5278 
5279  if ( $this->tableLocksHaveTransactionScope() ) {
5280  $this->startAtomic( $method );
5281  }
5282 
5283  return $this->doLockTables( $read, $write, $method );
5284  }
5285 
5295  protected function doLockTables( array $read, array $write, $method ) {
5296  return true;
5297  }
5298 
5299  final public function unlockTables( $method ) {
5300  if ( $this->tableLocksHaveTransactionScope() ) {
5301  $this->endAtomic( $method );
5302 
5303  return true; // locks released on COMMIT/ROLLBACK
5304  }
5305 
5306  return $this->doUnlockTables( $method );
5307  }
5308 
5316  protected function doUnlockTables( $method ) {
5317  return true;
5318  }
5319 
5320  public function dropTable( $table, $fname = __METHOD__ ) {
5321  if ( !$this->tableExists( $table, $fname ) ) {
5322  return false;
5323  }
5324 
5325  $this->doDropTable( $table, $fname );
5326 
5327  return true;
5328  }
5329 
5336  protected function doDropTable( $table, $fname ) {
5337  // https://mariadb.com/kb/en/drop-table/
5338  // https://dev.mysql.com/doc/refman/8.0/en/drop-table.html
5339  // https://www.postgresql.org/docs/9.2/sql-truncate.html
5340  $sql = "DROP TABLE " . $this->tableName( $table ) . " CASCADE";
5341  $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
5342  }
5343 
5344  public function truncate( $tables, $fname = __METHOD__ ) {
5345  $tables = is_array( $tables ) ? $tables : [ $tables ];
5346 
5347  $tablesTruncate = [];
5348  foreach ( $tables as $table ) {
5349  // Skip TEMPORARY tables with no writes nor sequence updates detected.
5350  // This mostly is an optimization for integration testing.
5351  if ( !$this->isPristineTemporaryTable( $table ) ) {
5352  $tablesTruncate[] = $table;
5353  }
5354  }
5355 
5356  if ( $tablesTruncate ) {
5357  $this->doTruncate( $tablesTruncate, $fname );
5358  }
5359  }
5360 
5367  protected function doTruncate( array $tables, $fname ) {
5368  foreach ( $tables as $table ) {
5369  $sql = "TRUNCATE TABLE " . $this->tableName( $table );
5370  $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
5371  }
5372  }
5373 
5378  public function getInfinity() {
5379  return 'infinity';
5380  }
5381 
5382  public function encodeExpiry( $expiry ) {
5383  return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
5384  ? $this->getInfinity()
5385  : $this->timestamp( $expiry );
5386  }
5387 
5388  public function decodeExpiry( $expiry, $format = TS_MW ) {
5389  if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
5390  return 'infinity';
5391  }
5392 
5393  return ConvertibleTimestamp::convert( $format, $expiry );
5394  }
5395 
5400  public function setBigSelects( $value = true ) {
5401  // no-op
5402  }
5403 
5404  public function isReadOnly() {
5405  return ( $this->getReadOnlyReason() !== false );
5406  }
5407 
5411  protected function getReadOnlyReason() {
5412  if ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) {
5413  return [ 'Server is configured as a read-only replica database.', 'role' ];
5414  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
5415  return [ 'Server is configured as a read-only static clone database.', 'role' ];
5416  }
5417 
5418  $reason = $this->getLBInfo( self::LB_READ_ONLY_REASON );
5419  if ( is_string( $reason ) ) {
5420  return [ $reason, 'lb' ];
5421  }
5422 
5423  return false;
5424  }
5425 
5430  public function setTableAliases( array $aliases ) {
5431  $this->tableAliases = $aliases;
5432  }
5433 
5438  public function setIndexAliases( array $aliases ) {
5439  $this->indexAliases = $aliases;
5440  }
5441 
5448  final protected function fieldHasBit( $field, $flags ) {
5449  return ( ( $field & $flags ) === $flags );
5450  }
5451 
5464  protected function getBindingHandle() {
5465  if ( !$this->conn ) {
5466  throw new DBUnexpectedError(
5467  $this,
5468  'DB connection was already closed or the connection dropped'
5469  );
5470  }
5471 
5472  return $this->conn;
5473  }
5474 
5475  public function __toString() {
5476  // spl_object_id is PHP >= 7.2
5477  $id = function_exists( 'spl_object_id' )
5478  ? spl_object_id( $this )
5479  : spl_object_hash( $this );
5480 
5481  $description = $this->getType() . ' object #' . $id;
5482  if ( is_resource( $this->conn ) ) {
5483  $description .= ' (' . (string)$this->conn . ')'; // "resource id #<ID>"
5484  } elseif ( is_object( $this->conn ) ) {
5485  // spl_object_id is PHP >= 7.2
5486  $handleId = function_exists( 'spl_object_id' )
5487  ? spl_object_id( $this->conn )
5488  : spl_object_hash( $this->conn );
5489  $description .= " (handle id #$handleId)";
5490  }
5491 
5492  return $description;
5493  }
5494 
5499  public function __clone() {
5500  $this->connLogger->warning(
5501  "Cloning " . static::class . " is not recommended; forking connection",
5502  [ 'exception' => new RuntimeException() ]
5503  );
5504 
5505  if ( $this->isOpen() ) {
5506  // Open a new connection resource without messing with the old one
5507  $this->conn = null;
5508  $this->trxEndCallbacks = []; // don't copy
5509  $this->trxSectionCancelCallbacks = []; // don't copy
5510  $this->handleSessionLossPreconnect(); // no trx or locks anymore
5511  $this->open(
5512  $this->server,
5513  $this->user,
5514  $this->password,
5515  $this->currentDomain->getDatabase(),
5516  $this->currentDomain->getSchema(),
5517  $this->tablePrefix()
5518  );
5519  $this->lastPing = microtime( true );
5520  }
5521  }
5522 
5528  public function __sleep() {
5529  throw new RuntimeException( 'Database serialization may cause problems, since ' .
5530  'the connection is not restored on wakeup' );
5531  }
5532 
5536  public function __destruct() {
5537  if ( $this->trxLevel() && $this->trxDoneWrites ) {
5538  trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
5539  }
5540 
5541  $danglingWriters = $this->pendingWriteAndCallbackCallers();
5542  if ( $danglingWriters ) {
5543  $fnames = implode( ', ', $danglingWriters );
5544  trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
5545  }
5546 
5547  if ( $this->conn ) {
5548  // Avoid connection leaks for sanity. Normally, resources close at script completion.
5549  // The connection might already be closed in PHP by now, so suppress warnings.
5550  AtEase::suppressWarnings();
5551  $this->closeConnection();
5552  AtEase::restoreWarnings();
5553  $this->conn = null;
5554  }
5555  }
5556 }
5557 
5561 class_alias( Database::class, 'DatabaseBase' );
5562 
5566 class_alias( Database::class, 'Database' );
Wikimedia\Rdbms\Database\implicitOrderby
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
Definition: Database.php:643
Wikimedia\Rdbms\Database\$PING_TTL
static int $PING_TTL
How long before it is worth doing a dummy query to test the connection.
Definition: Database.php:229
Wikimedia\Rdbms\Database\$schemaVars
array null $schemaVars
Current variables use for schema element placeholders.
Definition: Database.php:109
Wikimedia\Rdbms\Database\tablePrefix
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition: Database.php:564
Wikimedia\Rdbms\Database\$trxFname
string $trxFname
Name of the function that start the last transaction.
Definition: Database.php:136
Wikimedia\Rdbms\Database\getLastPHPError
getLastPHPError()
Definition: Database.php:859
Wikimedia\Rdbms\Database\setSessionOptions
setSessionOptions(array $options)
Override database's default behavior.$options include: 'connTimeout' : Set the connection timeout val...
Definition: Database.php:4989
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:50
Wikimedia\Rdbms\Database\limitResult
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.The SQL should be adjusted so that only the first $limit...
Definition: Database.php:3625
Wikimedia\Rdbms\Database\$trxDoneWrites
bool $trxDoneWrites
Whether possible write queries were done in the last transaction started.
Definition: Database.php:138
Wikimedia\Rdbms\Database\$trxEndCallbacksSuppressed
bool $trxEndCallbacksSuppressed
Whether to suppress triggering of transaction end callbacks.
Definition: Database.php:173
Wikimedia\Rdbms\Database\$DBO_MUTABLE
static int $DBO_MUTABLE
Bit field of all DBO_* flags that can be changed after connection.
Definition: Database.php:248
Wikimedia\Rdbms\Database\makeUpdateOptionsArray
makeUpdateOptionsArray( $options)
Make UPDATE options array for Database::makeUpdateOptions.
Definition: Database.php:2419
Wikimedia\Rdbms\Database\replaceLostConnection
replaceLostConnection( $fname)
Close any existing (dead) database connection and open a new connection.
Definition: Database.php:4826
Wikimedia\Rdbms\Database\$trxWriteAdjQueryCount
int $trxWriteAdjQueryCount
Number of write queries counted in trxWriteAdjDuration.
Definition: Database.php:158
Wikimedia\Rdbms\Database\getBindingHandle
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:5464
Wikimedia\Rdbms\Database\$lastPhpError
string bool $lastPhpError
Definition: Database.php:185
Wikimedia\Rdbms\Database\canRecoverFromDisconnect
canRecoverFromDisconnect( $sql, $priorWritesPending)
Determine whether it is safe to retry queries after a database connection is lost.
Definition: Database.php:1536
Wikimedia\Rdbms\Database\doInsert
doInsert( $table, array $rows, $fname)
Definition: Database.php:2337
Wikimedia\Rdbms\Database\buildGroupConcatField
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.This is useful for combining a field for sev...
Definition: Database.php:2601
Wikimedia\Rdbms\Database\doInitConnection
doInitConnection()
Actually connect to the database over the wire (or to local files)
Definition: Database.php:319
Wikimedia\Rdbms\Database\$trxReplicaLag
float $trxReplicaLag
Replication lag estimate at the time of BEGIN for the last transaction.
Definition: Database.php:134
Wikimedia\Rdbms\Database\isQuotedIdentifier
isQuotedIdentifier( $name)
Returns if the given identifier looks quoted or not according to the database convention for quoting ...
Definition: Database.php:3143
Wikimedia\Rdbms\IDatabase\getServerVersion
getServerVersion()
A string describing the current software version, like from mysql_get_server_info()
Wikimedia\Rdbms\Database\upsert
upsert( $table, array $rows, $uniqueKeys, array $set, $fname=__METHOD__)
Upsert the given row(s) into a table.
Definition: Database.php:3343
Wikimedia\Rdbms\Database\fieldExists
fieldExists( $table, $field, $fname=__METHOD__)
Determines whether a field exists in a table.
Definition: Database.php:2278
Wikimedia\Rdbms\Database\deadlockLoop
deadlockLoop(... $args)
Perform a deadlock-prone transaction.This function invokes a callback function to perform a set of wr...
Definition: Database.php:3822
Wikimedia\Rdbms\Database\bitOr
bitOr( $fieldLeft, $fieldRight)
string Stable to override
Definition: Database.php:2585
Wikimedia\Rdbms\Database\update
update( $table, $set, $conds, $fname=__METHOD__, $options=[])
Update all rows in a table that match a given condition.
Definition: Database.php:2444
Wikimedia\Rdbms\Database\selectRowCount
selectRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
Definition: Database.php:2040
Wikimedia\Rdbms\Database\ignoreIndexClause
ignoreIndexClause( $index)
IGNORE INDEX clause.
Definition: Database.php:3230
Wikimedia\Rdbms\Database\$sessionDirtyTempTables
array $sessionDirtyTempTables
Map of (table name => 1) for current TEMPORARY tables.
Definition: Database.php:121
Wikimedia\Rdbms\Database\trxStatus
trxStatus()
Definition: Database.php:560
Wikimedia\Rdbms\Database\listTables
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.Only show tables with this prefix, e.g. mw_ Calling function name arr...
Definition: Database.php:4736
Wikimedia\Rdbms\Database\indexUnique
indexUnique( $table, $index, $fname=__METHOD__)
Determines if a given index is unique.Calling function namebool Stable to override
Definition: Database.php:2303
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:32
Wikimedia\Rdbms\Database\updateTrxWriteQueryTime
updateTrxWriteQueryTime( $sql, $runtime, $affected)
Update the estimated run-time of a query, not counting large row lock times.
Definition: Database.php:1461
Wikimedia\Rdbms\Database\makeWhereFrom2d
makeWhereFrom2d( $data, $baseKey, $subKey)
Build a partial where clause from a 2-d array such as used for LinkBatch.
Definition: Database.php:2538
Wikimedia\Rdbms\Database\$queryLogger
LoggerInterface $queryLogger
Definition: Database.php:56
Wikimedia\Rdbms\DatabaseDomain\newFromId
static newFromId( $domain)
Definition: DatabaseDomain.php:77
Wikimedia\Rdbms\Database\encodeBlob
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
Definition: Database.php:4970
Wikimedia\Rdbms\Database\tableNamesN
tableNamesN(... $tables)
Fetch a number of table names into an zero-indexed numerical array This is handy when you need to con...
Definition: Database.php:2921
Wikimedia\Rdbms\Database\getDomainID
getDomainID()
Return the currently selected domain ID.
Definition: Database.php:809
Wikimedia\Rdbms\Database\getClass
static getClass( $dbType, $driver=null)
Definition: Database.php:469
Wikimedia\Rdbms\Database\pingAndCalculateLastTrxApplyTime
pingAndCalculateLastTrxApplyTime()
Definition: Database.php:705
Wikimedia\Rdbms\Database\$topologyRole
string $topologyRole
Replication topology role of the server; one of the class ROLE_* constants.
Definition: Database.php:88
Wikimedia\Rdbms\IDatabase\numRows
numRows( $res)
Get the number of rows in a query result.
Wikimedia\Rdbms\Database\assertHasConnectionHandle
assertHasConnectionHandle()
Make sure there is an open connection handle (alive or not) as a sanity check.
Definition: Database.php:976
Wikimedia\Rdbms\Database\onTransactionPreCommitOrIdle
onTransactionPreCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback before the current transaction commits or now if there is none.
Definition: Database.php:3916
Wikimedia\Rdbms\Database\tableLocksHaveTransactionScope
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
Definition: Database.php:5270
Wikimedia\Rdbms\Database\wasErrorReissuable
wasErrorReissuable()
Determines if the last query error was due to something outside of the query itself.
Definition: Database.php:3788
Wikimedia\Rdbms\Database\deleteJoin
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.MySQL overrides this to use a multi-table DELETE syntax,...
Definition: Database.php:3401
Wikimedia\Rdbms\Database\setIndexAliases
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.Note that this applies to ind...
Definition: Database.php:5438
Wikimedia\Rdbms\Database\$password
string $password
Password used to establish the current connection.
Definition: Database.php:82
Wikimedia\Rdbms\Database\decodeBlob
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects....
Definition: Database.php:4978
Wikimedia\Rdbms\Database\unionConditionPermutations
unionConditionPermutations( $table, $vars, array $permute_conds, $extra_conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Construct a UNION query for permutations of conditions.
Definition: Database.php:3657
Wikimedia\Rdbms\Database\factory
static factory( $type, $params=[], $connect=self::NEW_CONNECTED)
Construct a Database subclass instance given a database type and parameters.
Definition: Database.php:396
Wikimedia\Rdbms\Database\maxListLen
maxListLen()
Return the maximum number of items allowed in a list, or 0 for unlimited.int Stable to override
Definition: Database.php:4962
Wikimedia\Rdbms\Database\selectDomain
selectDomain( $domain)
Set the current domain (database, schema, and table prefix)
Definition: Database.php:2775
Wikimedia\Rdbms\Database\buildIntegerCast
buildIntegerCast( $field)
Field or column to cast string 1.31 Stable to override
Definition: Database.php:2744
Wikimedia\Rdbms\Database\getServerUptime
getServerUptime()
Determines how long the server has been up.int Stable to override
Definition: Database.php:3752
Wikimedia\Rdbms\Database\prependDatabaseOrSchema
prependDatabaseOrSchema( $namespace, $relation, $format)
Definition: Database.php:2900
Wikimedia\Rdbms\Database\$delimiter
string $delimiter
Current SQL query delimiter.
Definition: Database.php:103
Wikimedia\Rdbms\Database\__destruct
__destruct()
Run a few simple sanity checks and close dangling connections.
Definition: Database.php:5536
Wikimedia\Rdbms\Database\endAtomic
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
Definition: Database.php:4337
Wikimedia\Rdbms\Database\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:3102
Wikimedia\Rdbms\Database\executeQuery
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
Definition: Database.php:1253
Wikimedia\Rdbms\IDatabase\lastError
lastError()
Get a description of the last error.
DBO_DEBUG
const DBO_DEBUG
Definition: defines.php:9
Wikimedia\Rdbms\Database\setBigSelects
setBigSelects( $value=true)
Allow or deny "big selects" for this session only.This is done by setting the sql_big_selects session...
Definition: Database.php:5400
Wikimedia\Rdbms\Database\doDropTable
doDropTable( $table, $fname)
Definition: Database.php:5336
Wikimedia\Rdbms\Database\doReplace
doReplace( $table, array $uniqueKeys, array $rows, $fname)
Definition: Database.php:3261
Wikimedia\Rdbms\DBReadOnlyRoleError
Exception class for attempted DB write access to a DBConnRef with the DB_REPLICA role.
Definition: DBReadOnlyRoleError.php:30
Wikimedia\Rdbms\DBTransactionStateError
@newable
Definition: DBTransactionStateError.php:28
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\Database\timestampOrNull
timestampOrNull( $ts=null)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
Definition: Database.php:4758
Wikimedia\Rdbms\Database\decodeExpiry
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
Definition: Database.php:5388
Wikimedia\Rdbms\Database\$trxAutomaticAtomic
bool $trxAutomaticAtomic
Whether the current transaction was started implicitly by startAtomic()
Definition: Database.php:146
Wikimedia\Rdbms\Database\initConnection
initConnection()
Initialize the connection to the database over the wire (or to local files)
Definition: Database.php:305
Wikimedia\Rdbms\Database\normalizeConditions
normalizeConditions( $conds, $fname)
Definition: Database.php:2143
Wikimedia\Rdbms\Database\anyString
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
Definition: Database.php:3194
Wikimedia\Rdbms\Database\unionSupportsOrderAndLimit
unionSupportsOrderAndLimit()
Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION....
Definition: Database.php:3643
Wikimedia\Rdbms\DBMasterPos
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:14
Wikimedia\Rdbms\Database\isInsertSelectSafe
isInsertSelectSafe(array $insertOptions, array $selectOptions)
Stable to override.
Definition: Database.php:3509
Wikimedia\Rdbms\Database\fieldNameWithAlias
fieldNameWithAlias( $name, $alias=false)
Get an aliased field name e.g.
Definition: Database.php:2971
Wikimedia\Rdbms\Database\assertIsWritableMaster
assertIsWritableMaster()
Make sure that this server is not marked as a replica nor read-only as a sanity check.
Definition: Database.php:987
Wikimedia\Rdbms\Database\normalizeOptions
normalizeOptions( $options)
Definition: Database.php:2216
Wikimedia\Rdbms\Database\getDefaultSchemaVars
getDefaultSchemaVars()
Get schema variables to use if none have been set via setSchemaVars().
Definition: Database.php:5191
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:71
Wikimedia\Rdbms\GeneralizedSql
Lazy-loaded wrapper for simplification and scrubbing of SQL queries for profiling.
Definition: GeneralizedSql.php:30
$s
$s
Definition: mergeMessageFileList.php:184
Wikimedia\Rdbms\Database\extractSingleFieldFromList
extractSingleFieldFromList( $var)
Definition: Database.php:2246
Wikimedia\Rdbms\Database\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.Note that unlike most database abstract...
Definition: Database.php:4726
Wikimedia\Rdbms\Database\$trxSectionCancelCallbacks
array[] $trxSectionCancelCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:169
Wikimedia\Rdbms\Database\doTruncate
doTruncate(array $tables, $fname)
Definition: Database.php:5367
Wikimedia\Rdbms\Database\onTransactionCommitOrIdle
onTransactionCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback as soon as there is no transaction pending.
Definition: Database.php:3899
Wikimedia\Rdbms\Database\registerTempWrites
registerTempWrites( $ret, array $changes)
Definition: Database.php:1176
Wikimedia\Rdbms\Database\namedLocksEnqueue
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.bool 1.26 Stable to override
Definition: Database.php:5266
Wikimedia\Rdbms\Database\buildSubstring
buildSubstring( $input, $startPosition, $length=null)
Stable to override
Definition: Database.php:2672
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:23
Wikimedia\Rdbms\IDatabase\getSessionLagStatus
getSessionLagStatus()
Get the replica DB lag when the current transaction started or a general lag estimate if not transact...
Wikimedia\Rdbms\Database\tableNamesWithIndexClauseOrJOIN
tableNamesWithIndexClauseOrJOIN( $tables, $use_index=[], $ignore_index=[], $join_conds=[])
Get the aliased table name clause for a FROM clause which might have a JOIN and/or USE INDEX or IGNOR...
Definition: Database.php:3007
Wikimedia\Rdbms\Database\getReplicaPos
getReplicaPos()
Get the replication position of this replica DB.DBMasterPos|bool False if this is not a replica DB If...
Definition: Database.php:3870
Wikimedia\Rdbms\Database\getSchemaVars
getSchemaVars()
Get schema variables.
Definition: Database.php:5178
Wikimedia\Rdbms\Database\setLogger
setLogger(LoggerInterface $logger)
Set the PSR-3 logger interface to use for query logging.
Definition: Database.php:532
Wikimedia\Rdbms\Database\__clone
__clone()
Make sure that copies do not share the same client binding handle.
Definition: Database.php:5499
$res
$res
Definition: testCompression.php:57
Wikimedia\Rdbms\Database\cancelAtomic
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
Definition: Database.php:4371
$base
$base
Definition: generateLocalAutoload.php:11
Wikimedia\Rdbms\Database\getFlag
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
Definition: Database.php:805
Wikimedia\Rdbms\Database\doInsertSelectGeneric
doInsertSelectGeneric( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
Implementation of insertSelect() based on select() and insert()
Definition: Database.php:3527
Wikimedia\Rdbms\Database\conditional
conditional( $cond, $trueVal, $falseVal)
Returns an SQL expression for a simple conditional.This doesn't need to be overridden unless CASE isn...
Definition: Database.php:3732
Wikimedia\Rdbms\Database\$trxAtomicLevels
array $trxAtomicLevels
List of (name, unique ID, savepoint ID) for each active atomic section level.
Definition: Database.php:144
Wikimedia\Rdbms\Database\$PING_QUERY
static string $PING_QUERY
Dummy SQL query.
Definition: Database.php:231
Wikimedia\Rdbms\Database\handleSessionLossPostconnect
handleSessionLossPostconnect()
Clean things up after session (and thus transaction) loss after reconnect.
Definition: Database.php:1600
Wikimedia\Rdbms\Database\isPristineTemporaryTable
isPristineTemporaryTable( $table)
Check if the table is both a TEMPORARY table and has not yet received CRUD operations.
Definition: Database.php:1207
Wikimedia\Rdbms\Database\$connectionVariables
string[] int[] float[] $connectionVariables
SQL variables values to use for all new connections.
Definition: Database.php:94
Wikimedia\Rdbms\Database\$lastQuery
string $lastQuery
The last SQL query attempted.
Definition: Database.php:181
Wikimedia\Rdbms\Database\$trxStatusIgnoredCause
array null $trxStatusIgnoredCause
Error details of the last statement-only rollback.
Definition: Database.php:130
DBO_TRX
const DBO_TRX
Definition: defines.php:12
Wikimedia\Rdbms\Database\textFieldSize
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".int Stable to override
Definition: Database.php:3423
Wikimedia\Rdbms\Database\buildConcat
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.Raw SQL expression list; caller is responsible fo...
Definition: Database.php:2593
Wikimedia\Rdbms\Database\bitNot
bitNot( $field)
string Stable to override
Definition: Database.php:2569
Wikimedia\Rdbms\Database\nextSavepointId
nextSavepointId( $fname)
Definition: Database.php:4292
LIST_AND
const LIST_AND
Definition: Defines.php:48
Wikimedia\Rdbms\Database\$agent
string $agent
Agent name for query profiling.
Definition: Database.php:86
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
Wikimedia\Rdbms\Database\__sleep
__sleep()
Called by serialize.
Definition: Database.php:5528
DBO_NOBUFFER
const DBO_NOBUFFER
Definition: defines.php:10
Wikimedia\Rdbms\Database\getTopologyRole
getTopologyRole()
Get the replication topology role of this server.
Definition: Database.php:540
Wikimedia\Rdbms\Database\doBegin
doBegin( $fname)
Issues the BEGIN command to the database server.
Definition: Database.php:4532
Wikimedia\Rdbms\Database\$trxIdleCallbacks
array[] $trxIdleCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:160
Wikimedia\Rdbms\Database\makeConditionCollidesUponKeys
makeConditionCollidesUponKeys(array $rows, array $uniqueKeys)
Definition: Database.php:3328
Wikimedia\Rdbms\Database\isWriteQuery
isWriteQuery( $sql, $flags)
Determine whether a query writes to the DB.
Definition: Database.php:1054
Wikimedia\Rdbms\Database\isFlagInOptions
isFlagInOptions( $option, array $options)
Definition: Database.php:2232
Wikimedia\Rdbms\Database\clearFlag
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
Definition: Database.php:777
Wikimedia\Rdbms\Database\getQueryExceptionAndLog
getQueryExceptionAndLog( $error, $errno, $sql, $fname)
Definition: Database.php:1669
Wikimedia\Rdbms\Database\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Definition: Database.php:4472
Wikimedia\Rdbms\IDatabase\fetchObject
fetchObject( $res)
Fetch the next row from the given result object, in object form.
Wikimedia\Rdbms\Database\resultObject
resultObject( $result)
Take a query result and wrap it in an iterable result wrapper if necessary.
Definition: Database.php:4789
Wikimedia\Rdbms\Database\doHandleSessionLossPreconnect
doHandleSessionLossPreconnect()
Reset any additional subclass trx* and session* fields Stable to override.
Definition: Database.php:1593
Wikimedia\Rdbms\Database\$lastWriteTime
float bool $lastWriteTime
UNIX timestamp of last write query.
Definition: Database.php:183
Wikimedia\Rdbms\Database\doQuery
doQuery( $sql)
Run a query and return a DBMS-dependent wrapper or boolean.
Wikimedia\Rdbms\Database\runOnTransactionIdleCallbacks
runOnTransactionIdleCallbacks( $trigger)
Actually consume and run any "on transaction idle/resolution" callbacks.
Definition: Database.php:4073
Wikimedia\Rdbms\Database\$trxStatusCause
Exception null $trxStatusCause
The last error that caused the status to become STATUS_TRX_ERROR.
Definition: Database.php:128
Wikimedia\Rdbms\Database\close
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition: Database.php:898
Wikimedia\Rdbms\Database\replaceVars
replaceVars( $ins)
Database independent variable replacement.
Definition: Database.php:5140
Wikimedia\Rdbms\Database\handleSessionLossPreconnect
handleSessionLossPreconnect()
Clean things up after session (and thus transaction) loss before reconnect.
Definition: Database.php:1561
Wikimedia\Rdbms\Database\doInsertNonConflicting
doInsertNonConflicting( $table, array $rows, $fname)
Definition: Database.php:2354
Wikimedia\Rdbms\Database\$NOT_APPLICABLE
static string $NOT_APPLICABLE
Idiom used when a cancelable atomic section started the transaction.
Definition: Database.php:212
Wikimedia\Rdbms\Database\$trxStatus
int $trxStatus
Transaction status.
Definition: Database.php:126
Wikimedia\Rdbms\Database\runOnTransactionPreCommitCallbacks
runOnTransactionPreCommitCallbacks()
Actually consume and run any "on transaction pre-commit" callbacks.
Definition: Database.php:4142
Wikimedia\Rdbms\Database\wasLockTimeout
wasLockTimeout()
Determines if the last failure was due to a lock timeout.Note that during a lock wait timeout,...
Definition: Database.php:3768
Wikimedia\Rdbms\Database\$affectedRowCount
integer null $affectedRowCount
Rows affected by the last query to query() or its CRUD wrappers.
Definition: Database.php:176
Wikimedia\Rdbms\Database\$currentDomain
DatabaseDomain $currentDomain
Definition: Database.php:69
LIST_OR
const LIST_OR
Definition: Defines.php:51
Wikimedia\Rdbms\Database\getLag
getLag()
Get the amount of replication lag for this database server.
Definition: Database.php:4940
Wikimedia\Rdbms\Database\$sessionTempTables
array $sessionTempTables
Map of (table name => 1) for current TEMPORARY tables.
Definition: Database.php:119
Wikimedia\Rdbms\Database\buildSelectSubquery
buildSelectSubquery( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Equivalent to IDatabase::selectSQLText() except wraps the result in Subquery.
Definition: Database.php:2748
Wikimedia\Rdbms\Database\$TEMP_PSEUDO_PERMANENT
static int $TEMP_PSEUDO_PERMANENT
Writes to this temporary table effect lastDoneWrites()
Definition: Database.php:219
Wikimedia\Rdbms\Database\assertBuildSubstringParams
assertBuildSubstringParams( $startPosition, $length)
Check type and bounds for parameters to self::buildSubstring()
Definition: Database.php:2693
Wikimedia\Rdbms\Database\isReadOnly
isReadOnly()
Definition: Database.php:5404
Wikimedia\Rdbms\Database\buildStringCast
buildStringCast( $field)
Field or column to cast string 1.28 Stable to override
Definition: Database.php:2734
Wikimedia\Rdbms\Database\$lazyMasterHandle
IDatabase null $lazyMasterHandle
Lazy handle to the master DB this server replicates from.
Definition: Database.php:75
Wikimedia\Rdbms\Database\unlockTables
unlockTables( $method)
Unlock all tables locked via lockTables()
Definition: Database.php:5299
Wikimedia\Rdbms\Database\getSessionLagStatus
getSessionLagStatus()
Get the replica DB lag when the current transaction started or a general lag estimate if not transact...
Definition: Database.php:4865
Wikimedia\Rdbms\Database\$trxWriteDuration
float $trxWriteDuration
Seconds spent in write queries for the current transaction.
Definition: Database.php:150
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
Wikimedia\Rdbms\Database\doRollbackToSavepoint
doRollbackToSavepoint( $identifier, $fname)
Rollback to a savepoint.
Definition: Database.php:4283
Wikimedia\Rdbms\Database\dropTable
dropTable( $table, $fname=__METHOD__)
Delete a table.
Definition: Database.php:5320
Wikimedia\Rdbms\Database\getTempTableWrites
getTempTableWrites( $sql, $pseudoPermanent)
Definition: Database.php:1120
Wikimedia\Rdbms\Database\doInsertSelectNative
doInsertSelectNative( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
Native server-side implementation of insertSelect() for situations where we don't want to select ever...
Definition: Database.php:3592
Wikimedia\Rdbms\Database\startAtomic
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Definition: Database.php:4307
Wikimedia\Rdbms\DBQueryTimeoutError
Error thrown when a query times out.
Definition: DBQueryTimeoutError.php:30
Wikimedia\Rdbms\Database\selectOptionsIncludeLocking
selectOptionsIncludeLocking( $options)
Definition: Database.php:2073
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
Wikimedia\Rdbms\Database\getCacheSetOptions
static getCacheSetOptions(IDatabase $db1, IDatabase $db2=null)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Definition: Database.php:4923
Wikimedia\Rdbms\Database\open
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
Wikimedia\Rdbms\Database\lock
lock( $lockName, $method, $timeout=5)
Acquire a named lock.Named locks are not related to transactionsName of lock to aquire Name of the ca...
Definition: Database.php:5210
Wikimedia\Rdbms\Database\getTransactionRoundId
getTransactionRoundId()
Definition: Database.php:676
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:548
Wikimedia\Rdbms\Database\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Definition: Database.php:762
Wikimedia\Rdbms\Database\rollback
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
Definition: Database.php:4615
Wikimedia\Rdbms\Database\assertQueryIsCurrentlyAllowed
assertQueryIsCurrentlyAllowed( $sql, $fname)
Error out if the DB is not in a valid state for a query via query()
Definition: Database.php:1490
Wikimedia\Rdbms\Database\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Run a callback after each time any transaction commits or rolls back.
Definition: Database.php:4043
Wikimedia\Rdbms\Database\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
Stable to override.
Definition: Database.php:3153
Wikimedia\Rdbms\Database\$tableAliases
array[] $tableAliases
Current map of (table => (dbname, schema, prefix) map)
Definition: Database.php:105
Wikimedia\Rdbms\Database\reportQueryError
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
Definition: Database.php:1654
Wikimedia\Rdbms\Database\$cliMode
bool $cliMode
Whether this PHP instance is for a CLI script.
Definition: Database.php:84
Wikimedia\Rdbms\Database\$trxShortId
string $trxShortId
ID of the active transaction or the empty string otherwise.
Definition: Database.php:124
Wikimedia\Rdbms\Database\isTransactableQuery
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
Definition: Database.php:1104
Wikimedia\Rdbms\Database\lockForUpdate
lockForUpdate( $table, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Lock all rows meeting the given conditions/options FOR UPDATE.
Definition: Database.php:2262
LIST_SET
const LIST_SET
Definition: Defines.php:49
Wikimedia\Rdbms\Database\indexExists
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists.
Definition: Database.php:2284
Wikimedia\Rdbms\Database\writesOrCallbacksPending
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...
Definition: Database.php:659
Wikimedia\Rdbms\Database\sourceStream
sourceStream( $fp, callable $lineCallback=null, callable $resultCallback=null, $fname=__METHOD__, callable $inputCallback=null)
Read and execute commands from an open file handle.
Definition: Database.php:5028
Wikimedia\Rdbms\Database\selectSQLText
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Take the same arguments as IDatabase::select() and return the SQL it would use.This can be useful for...
Definition: Database.php:1914
Wikimedia\Rdbms\SelectQueryBuilder
Definition: SelectQueryBuilder.php:5
Wikimedia\Rdbms\Database\makeInsertLists
makeInsertLists(array $rows)
Make SQL lists of columns, row tuples for INSERT/VALUES expressions.
Definition: Database.php:2383
$args
if( $line===false) $args
Definition: mcc.php:124
Wikimedia\Rdbms\Database\$TEMP_NORMAL
static int $TEMP_NORMAL
Writes to this temporary table do not affect lastDoneWrites()
Definition: Database.php:217
Wikimedia\Rdbms\Database\$trxWriteCallers
string[] $trxWriteCallers
Write query callers of the current transaction.
Definition: Database.php:148
Wikimedia\Rdbms\Database\doUpsert
doUpsert( $table, array $rows, array $uniqueKeys, array $set, $fname)
Definition: Database.php:3373
Wikimedia\Rdbms\Database\$lastPing
float $lastPing
UNIX timestamp.
Definition: Database.php:179
Wikimedia\Rdbms\Database\bitAnd
bitAnd( $fieldLeft, $fieldRight)
string Stable to override
Definition: Database.php:2577
Wikimedia\Rdbms\Database\buildLike
buildLike( $param,... $params)
LIKE statement wrapper.This takes a variable-length argument list with parts of pattern to match cont...
Definition: Database.php:3163
Wikimedia\Rdbms\Database\$trxProfiler
TransactionProfiler $trxProfiler
Definition: Database.php:66
Wikimedia\Rdbms\Database\$user
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:80
Wikimedia\Rdbms\Database\assertNoOpenTransactions
assertNoOpenTransactions()
Assert that all explicit transactions or atomic sections have been closed.
Definition: Database.php:1517
Wikimedia\Rdbms\Database\selectDB
selectDB( $db)
Change the current database.
Definition: Database.php:2765
Wikimedia\Rdbms\Database\wasQueryTimeout
wasQueryTimeout( $error, $errno)
Checks whether the cause of the error is detected to be a timeout.
Definition: Database.php:1639
Wikimedia\Rdbms\Database\closeConnection
closeConnection()
Closes underlying database connection.
Wikimedia\Rdbms\Database\lastDoneWrites
lastDoneWrites()
Get the last time the connection may have been used for a write query.
Definition: Database.php:651
Wikimedia\Rdbms\Database\$SLOW_WRITE_SEC
static float $SLOW_WRITE_SEC
Consider a write slow if it took more than this many seconds.
Definition: Database.php:236
Wikimedia\Rdbms\Database\wasReadOnlyError
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.bool Stable to override
Definition: Database.php:3784
Wikimedia\Rdbms\Database\beginIfImplied
beginIfImplied( $sql, $fname)
Start an implicit transaction if DBO_TRX is enabled and no transaction is active.
Definition: Database.php:1438
Wikimedia\Rdbms\Database\getQueryException
getQueryException( $error, $errno, $sql, $fname)
Definition: Database.php:1693
Wikimedia\Rdbms\Database\getServerInfo
getServerInfo()
Get a human-readable string describing the current software version.
Definition: Database.php:536
Wikimedia\Rdbms\Database\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Definition: Database.php:4536
Wikimedia\Rdbms\Database\buildLeast
buildLeast( $fields, $values)
Build a LEAST function statement comparing columns/values.Integer and float values in $values will no...
Definition: Database.php:2621
Wikimedia\Rdbms\Database\restoreFlags
restoreFlags( $state=self::RESTORE_PRIOR)
Restore the flags to their prior state before the last setFlag/clearFlag call.
Definition: Database.php:792
Wikimedia\Rdbms\Database\connectionErrorLogger
connectionErrorLogger( $errno, $errstr)
Error handler for logging errors during database connection This method should not be used outside of...
Definition: Database.php:877
Wikimedia\Rdbms\Database\setLBInfo
setLBInfo( $nameOrArray, $value=null)
Set the entire array or a particular key of the managing load balancer info array.
Definition: Database.php:615
Wikimedia\Rdbms\Database\getScopedLockAndFlush
getScopedLockAndFlush( $lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
Definition: Database.php:5226
Wikimedia\Rdbms\Database\fieldNamesWithAlias
fieldNamesWithAlias( $fields)
Gets an array of aliased field names.
Definition: Database.php:2985
Wikimedia\Rdbms\Database\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:603
Wikimedia\Rdbms\DBReadOnlyError
@newable
Definition: DBReadOnlyError.php:28
Wikimedia\Rdbms\Database\$trxWriteAffectedRows
int $trxWriteAffectedRows
Number of rows affected by write queries for the current transaction.
Definition: Database.php:154
Wikimedia\Rdbms\Database\$trxWriteAdjDuration
float $trxWriteAdjDuration
Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries.
Definition: Database.php:156
Wikimedia\Rdbms\Database\insertSelect
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper.
Definition: Database.php:3458
Wikimedia\Rdbms\Database\normalizeRowArray
normalizeRowArray(array $rowOrRows)
Definition: Database.php:2117
Wikimedia\Rdbms\Database\selectRow
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
Definition: Database.php:2001
Wikimedia\Rdbms\DBQueryError
@newable Stable to extend
Definition: DBQueryError.php:29
Wikimedia\Rdbms\Database\useIndexClause
useIndexClause( $index)
USE INDEX clause.
Definition: Database.php:3214
Wikimedia\Rdbms\Database\makeUpdateOptions
makeUpdateOptions( $options)
Make UPDATE options for the Database::update function.
Definition: Database.php:2438
LIST_COMMA
const LIST_COMMA
Definition: Defines.php:47
Wikimedia\Rdbms\Database\getReadOnlyReason
getReadOnlyReason()
Definition: Database.php:5411
Wikimedia\Rdbms\Database\buildSuperlative
buildSuperlative( $sqlfunc, $fields, $values)
Build a superlative function statement comparing columns/values.
Definition: Database.php:2641
Wikimedia\Rdbms\DBQueryDisconnectedError
@newable
Definition: DBQueryDisconnectedError.php:29
Wikimedia\Rdbms\Database\$priorFlags
int[] $priorFlags
Prior flags member variable values.
Definition: Database.php:114
Wikimedia\Rdbms\Database\doGetLag
doGetLag()
Stable to override
Definition: Database.php:4954
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:836
Wikimedia\Rdbms\Database\aggregateValue
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.array|string Since 1.33 Stable to override
Definition: Database.php:2561
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:847
Wikimedia\Rdbms\Database\preCommitCallbacksPending
preCommitCallbacksPending()
Definition: Database.php:669
Wikimedia\Rdbms\Database\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Stable to override.
Definition: Database.php:3814
Wikimedia\Rdbms\Database\pendingWriteAndCallbackCallers
pendingWriteAndCallbackCallers()
List the methods that have write queries or callbacks for the current transaction.
Definition: Database.php:733
Wikimedia\Rdbms\Database\$trxPreCommitCallbacks
array[] $trxPreCommitCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:162
Wikimedia\Rdbms\Database\$htmlErrors
string bool null $htmlErrors
Stashed value of html_errors INI setting.
Definition: Database.php:112
Wikimedia\Rdbms\Database\tableExists
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
Wikimedia\Rdbms\Database\$SAVEPOINT_PREFIX
static string $SAVEPOINT_PREFIX
Prefix to the atomic section counter used to make savepoint IDs.
Definition: Database.php:214
Wikimedia\Rdbms\Database\pendingWriteCallers
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
Definition: Database.php:717
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MAX
static int $DEADLOCK_DELAY_MAX
Maximum time to wait before retry.
Definition: Database.php:226
Wikimedia\Rdbms\Database\$trxEndCallbacks
array[] $trxEndCallbacks
List of (callable, method name, atomic section id) -var array<array{0:callable,1:string,...
Definition: Database.php:167
Wikimedia\Rdbms\Database\tableNames
tableNames(... $tables)
Fetch a number of table names into an array This is handy when you need to construct SQL for joins.
Definition: Database.php:2911
Wikimedia\Rdbms\Database\__toString
__toString()
Get a debugging string that mentions the database type, the ID of this instance, and the ID of any un...
Definition: Database.php:5475
Wikimedia\Rdbms\Database\$lastRoundTripEstimate
float $lastRoundTripEstimate
Query round trip time estimate.
Definition: Database.php:187
Wikimedia\Rdbms\Database\getLogContext
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: Database.php:887
Wikimedia\Rdbms\Database\$connectionParams
array $connectionParams
Parameters used by initConnection() to establish a connection.
Definition: Database.php:92
DBO_DDLMODE
const DBO_DDLMODE
Definition: defines.php:16
Wikimedia\Rdbms\Database\$trxAutomatic
bool $trxAutomatic
Whether the current transaction was started implicitly due to DBO_TRX.
Definition: Database.php:140
Wikimedia\Rdbms\Database\flushSnapshot
flushSnapshot( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commit any transaction but error out if writes or callbacks are pending.
Definition: Database.php:4686
Wikimedia\Rdbms\Database\pendingWriteRowsAffected
pendingWriteRowsAffected()
Get the number of affected rows from pending write queries.
Definition: Database.php:721
Wikimedia\Rdbms\Database\$trxWriteQueryCount
int $trxWriteQueryCount
Number of write queries for the current transaction.
Definition: Database.php:152
Wikimedia\Rdbms\AtomicSectionIdentifier
Class used for token representing identifiers for atomic sections from IDatabase instances.
Definition: AtomicSectionIdentifier.php:26
Wikimedia\Rdbms\Database\doReleaseSavepoint
doReleaseSavepoint( $identifier, $fname)
Release a savepoint.
Definition: Database.php:4267
Wikimedia\Rdbms\Database\executeQueryAttempt
executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags)
Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count tracking,...
Definition: Database.php:1350
$line
$line
Definition: mcc.php:119
Wikimedia\Rdbms\Database\currentAtomicSectionId
currentAtomicSectionId()
Definition: Database.php:3948
Wikimedia\Rdbms\Database\modifyCallbacksForCancel
modifyCallbacksForCancel(array $sectionIds, AtomicSectionIdentifier $newSectionId=null)
Update callbacks that were owned by cancelled atomic sections.
Definition: Database.php:4008
Wikimedia\Rdbms\Database\setTrxEndCallbackSuppression
setTrxEndCallbackSuppression( $suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
Definition: Database.php:4059
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $flags=self::QUERY_NORMAL)
Run an SQL query and return the result.
Definition: Database.php:1216
Wikimedia\Rdbms\IDatabase\fetchRow
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
Wikimedia\Rdbms\Database\getMasterPos
getMasterPos()
Get the position of this master.DBMasterPos|bool False if this is not a master If an error occurs,...
Definition: Database.php:3879
Wikimedia\Rdbms\Database\pendingWriteQueryDuration
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
Definition: Database.php:687
Wikimedia\Rdbms\Database\$indexAliases
string[] $indexAliases
Current map of (index alias => index)
Definition: Database.php:107
Wikimedia\Rdbms\LikeMatch
Used by Database::buildLike() to represent characters that have special meaning in SQL LIKE clauses a...
Definition: LikeMatch.php:10
Wikimedia\Rdbms\Database\tableName
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.This does two important things: it quo...
Definition: Database.php:2802
Wikimedia\Rdbms\Database\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: Database.php:3803
Wikimedia\Rdbms\Database\doAtomicSection
doAtomicSection( $fname, callable $callback, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Perform an atomic section of reversable SQL statements from a callback.
Definition: Database.php:4456
Wikimedia\Rdbms\Database\replace
replace( $table, $uniqueKeys, $rows, $fname=__METHOD__)
Insert row(s) into a table, deleting all conflicting rows beforehand.
Definition: Database.php:3234
Wikimedia\Rdbms\Database\getRecordedTransactionLagStatus
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
Definition: Database.php:4882
Wikimedia\Rdbms\Database\strencode
strencode( $s)
Wrapper for addslashes()
Wikimedia\Rdbms\Database\runOnAtomicSectionCancelCallbacks
runOnAtomicSectionCancelCallbacks( $trigger, array $sectionIds=null)
Actually run any "atomic section cancel" callbacks.
Definition: Database.php:4177
Wikimedia\Rdbms\Database\getServer
getServer()
Get the server hostname or IP address.
Definition: Database.php:2794
Wikimedia\Rdbms\DBUnexpectedError
@newable Stable to extend
Definition: DBUnexpectedError.php:29
Wikimedia\Rdbms\Database\doLockTables
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
Definition: Database.php:5295
Wikimedia\Rdbms\Database\doUnlockTables
doUnlockTables( $method)
Helper function for unlockTables() that handles the actual table unlocking.
Definition: Database.php:5316
Wikimedia\Rdbms\Database\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
Definition: Database.php:4752
Wikimedia\Rdbms\Database\selectField
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
Definition: Database.php:1736
Wikimedia\Rdbms\Database\anyChar
anyChar()
Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
Definition: Database.php:3190
Wikimedia\Rdbms\Database\onTransactionIdle
onTransactionIdle(callable $callback, $fname=__METHOD__)
Alias for onTransactionCommitOrIdle() for backwards-compatibility.
Definition: Database.php:3912
Wikimedia\Rdbms\Database\unlock
unlock( $lockName, $method)
Release a lock.Named locks are not related to transactionsName of lock to release Name of the calling...
Definition: Database.php:5220
Wikimedia\Rdbms\Database\$profiler
callable null $profiler
Definition: Database.php:64
Wikimedia\Rdbms\Database\$SMALL_WRITE_ROWS
static float $SMALL_WRITE_ROWS
Assume an insert of this many rows or less should be fast to replicate.
Definition: Database.php:238
Wikimedia\Rdbms\Database\addIdentifierQuotes
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.table, column, database) for use in a SQL queryDepending on the database...
Definition: Database.php:3129
Wikimedia\Rdbms\Database\getLazyMasterHandle
getLazyMasterHandle()
Get a handle to the master server of the cluster to which this server belongs.
Definition: Database.php:635
Wikimedia\Rdbms\Database\consumeTrxShortId
consumeTrxShortId()
Reset the transaction ID and return the old one.
Definition: Database.php:1621
Wikimedia\Rdbms\Database\estimateRowCount
estimateRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate the number of rows in dataset.MySQL allows you to estimate the number of rows that would be ...
Definition: Database.php:2023
Wikimedia\Rdbms\Database\truncate
truncate( $tables, $fname=__METHOD__)
Delete all data in a table(s) and reset any sequences owned by that table(s)
Definition: Database.php:5344
Wikimedia\Rdbms\Database\dbSchema
dbSchema( $schema=null)
Get/set the db schema.
Definition: Database.php:577
Wikimedia\Rdbms\Database\$trxRecurringCallbacks
callable[] $trxRecurringCallbacks
Map of (name => callable)
Definition: Database.php:171
Wikimedia\Rdbms\Database\getQueryVerb
getQueryVerb( $sql)
Definition: Database.php:1086
Wikimedia\Rdbms\Database\unionQueries
unionQueries( $sqls, $all)
Construct a UNION query.This is used for providing overload point for other DB abstractions not compa...
Definition: Database.php:3651
Wikimedia\Rdbms\DBTransactionError
@newable Stable to extend
Definition: DBTransactionError.php:29
Wikimedia\Rdbms\Database\reassignCallbacksForSection
reassignCallbacksForSection(AtomicSectionIdentifier $old, AtomicSectionIdentifier $new)
Hoist callback ownership for callbacks in a section to a parent section.
Definition: Database.php:3964
Wikimedia\Rdbms\Database\insert
insert( $table, $rows, $fname=__METHOD__, $options=[])
Insert the given row(s) into a table.
Definition: Database.php:2313
Wikimedia\Rdbms\IDatabase\lastErrno
lastErrno()
Get the last error number.
Wikimedia\Rdbms\Database\relationSchemaQualifier
relationSchemaQualifier()
Stable to override.
Definition: Database.php:599
Wikimedia\Rdbms\Database\$DEADLOCK_TRIES
static int $DEADLOCK_TRIES
Number of times to re-try an operation in case of deadlock.
Definition: Database.php:222
Wikimedia\Rdbms\Database\makeInsertNonConflictingVerbAndOptions
makeInsertNonConflictingVerbAndOptions()
Stable to override.
Definition: Database.php:2369
Wikimedia\Rdbms\Database\newExceptionAfterConnectError
newExceptionAfterConnectError( $error)
Definition: Database.php:1707
Wikimedia\Rdbms\Database\lockTables
lockTables(array $read, array $write, $method)
Lock specific tables.
Definition: Database.php:5274
Wikimedia\Rdbms\Database\$trxAtomicCounter
int $trxAtomicCounter
Counter for atomic savepoint identifiers (reset with each transaction)
Definition: Database.php:142
Wikimedia\Rdbms\Database\encodeExpiry
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
Definition: Database.php:5382
Wikimedia\Rdbms\Database\$srvCache
BagOStuff $srvCache
APC cache.
Definition: Database.php:52
Wikimedia\Rdbms\Database\buildGreatest
buildGreatest( $fields, $values)
Build a GREATEST function statement comparing columns/values.Integer and float values in $values will...
Definition: Database.php:2613
Wikimedia\Rdbms\Database\doSavepoint
doSavepoint( $identifier, $fname)
Create a savepoint.
Definition: Database.php:4251
Wikimedia\Rdbms\Database\setSchemaVars
setSchemaVars( $vars)
Set schema variables to be used when streaming commands from SQL files or stdin.
Definition: Database.php:5024
Wikimedia\Rdbms\Database\__construct
__construct(array $params)
Definition: Database.php:257
Wikimedia\Rdbms\Database\trxTimestamp
trxTimestamp()
Get the UNIX timestamp of the time that the transaction was established.
Definition: Database.php:552
Wikimedia\Rdbms\Database\$trxTimestamp
float null $trxTimestamp
UNIX timestamp at the time of BEGIN for the last transaction.
Definition: Database.php:132
Wikimedia\Rdbms\Database\makeGroupByWithHaving
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1864
Wikimedia\Rdbms\Database\tableNameWithAlias
tableNameWithAlias( $table, $alias=false)
Get an aliased table name.
Definition: Database.php:2942
Wikimedia\Rdbms\Database\getAttributes
static getAttributes()
Stable to override.
Definition: Database.php:521
Wikimedia\Rdbms\Database\writesPending
writesPending()
Definition: Database.php:655
Wikimedia\Rdbms\Database\normalizeUpsertKeys
normalizeUpsertKeys( $uniqueKeys)
Definition: Database.php:2164
Wikimedia\Rdbms\Database\selectFieldsOrOptionsAggregate
selectFieldsOrOptionsAggregate( $fields, $options)
Definition: Database.php:2089
Wikimedia\Rdbms\Database\lockIsFree
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)Name of lock to poll Name of m...
Definition: Database.php:5199
Wikimedia\Rdbms\Database\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Definition: Database.php:4801
Wikimedia\Rdbms\Database\$nonNativeInsertSelectBatchSize
int $nonNativeInsertSelectBatchSize
Row batch size to use for emulated INSERT SELECT queries.
Definition: Database.php:96
Wikimedia\Rdbms\Database\runTransactionListenerCallbacks
runTransactionListenerCallbacks( $trigger)
Actually run any "transaction listener" callbacks.
Definition: Database.php:4218
Wikimedia\Rdbms\Database\onAtomicSectionCancel
onAtomicSectionCancel(callable $callback, $fname=__METHOD__)
Run a callback when the atomic section is cancelled.
Definition: Database.php:3938
Wikimedia\Rdbms\Database\getTopologyRootMaster
getTopologyRootMaster()
Get the host (or address) of the root master server for the replication topology.
Definition: Database.php:544
Wikimedia\Rdbms\DBConnectionError
@newable
Definition: DBConnectionError.php:27
Wikimedia\Rdbms\Database\setTableAliases
setTableAliases(array $aliases)
Make certain table names use their own database, schema, and table prefix when passed into SQL querie...
Definition: Database.php:5430
Wikimedia\Rdbms\Database\$MUTABLE_FLAGS
static string[] $MUTABLE_FLAGS
List of DBO_* flags that can be changed after connection.
Definition: Database.php:241
Wikimedia\Rdbms\Database\masterPosWait
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.Note that this does not start any new ...
Definition: Database.php:3861
Wikimedia\Rdbms\Database\onTransactionResolution
onTransactionResolution(callable $callback, $fname=__METHOD__)
Run a callback as soon as the current transaction commits or rolls back.
Definition: Database.php:3892
Wikimedia\Rdbms\IDatabase\getType
getType()
Get the type of the DBMS (e.g.
Wikimedia\Rdbms\Database\explicitTrxActive
explicitTrxActive()
Definition: Database.php:4718
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:78
Wikimedia\Rdbms\Database\freeResult
freeResult( $res)
Free a result object returned by query() or select()It's usually not necessary to call this,...
Definition: Database.php:1726
Wikimedia\Rdbms\Database\isOpen
isOpen()
Definition: Database.php:758
Wikimedia\Rdbms\Database\doCommit
doCommit( $fname)
Issues the COMMIT command to the database server.
Definition: Database.php:4609
$source
$source
Definition: mwdoc-filter.php:34
Wikimedia\Rdbms\IMaintainableDatabase\fieldInfo
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
Wikimedia\Rdbms\Database\$topologyRootMaster
string null $topologyRootMaster
Host (or address) of the root master server for the replication topology.
Definition: Database.php:90
Wikimedia\Rdbms\Database\makeOrderBy
makeOrderBy( $options)
Returns an optional ORDER BY.
Definition: Database.php:1890
Wikimedia\Rdbms\Database\$flags
int $flags
Current bit field of class DBO_* constants.
Definition: Database.php:99
Wikimedia\Rdbms\Database\serverIsReadOnly
serverIsReadOnly()
bool Whether the DB is marked as read-only server-side 1.28 Stable to override
Definition: Database.php:3888
Wikimedia\Rdbms\Database\makeSelectOptions
makeSelectOptions(array $options)
Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the quer...
Definition: Database.php:1793
Wikimedia\Rdbms\Database\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1902
Wikimedia\Rdbms\Database\attributesFromType
static attributesFromType( $dbType, $driver=null)
Definition: Database.php:451
Wikimedia\Rdbms\Database\lastQuery
lastQuery()
Get the last query that sent on account of IDatabase::query()
Definition: Database.php:647
Wikimedia\Rdbms\Database\wasConnectionLoss
wasConnectionLoss()
Determines if the last query error was due to a dropped connection.Note that during a connection loss...
Definition: Database.php:3776
Wikimedia\Rdbms\Database\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.Note that during a deadlock, the prior transacti...
Definition: Database.php:3760
$t
$t
Definition: testCompression.php:74
Wikimedia\Rdbms\Database\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Stable to override.
Definition: Database.php:2786
Wikimedia\Rdbms\Database\$connLogger
LoggerInterface $connLogger
Definition: Database.php:54
Wikimedia\Rdbms\Database\addQuotes
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.string Stable to override
Definition: Database.php:3110
LIST_NAMES
const LIST_NAMES
Definition: Defines.php:50
Wikimedia\Rdbms\Database\$replLogger
LoggerInterface $replLogger
Definition: Database.php:58
Wikimedia\Rdbms\Database\assertConditionIsNotEmpty
assertConditionIsNotEmpty( $conds, string $fname, bool $deprecate)
Check type and bounds conditions parameters for update.
Definition: Database.php:2719
Wikimedia\Rdbms\Database\getApproximateLagStatus
getApproximateLagStatus()
Get a replica DB lag estimate for this server at the start of a transaction.
Definition: Database.php:4897
Wikimedia\Rdbms\Database\qualifiedTableComponents
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
Definition: Database.php:2860
Wikimedia\Rdbms\Database\affectedRows
affectedRows()
Get the number of rows affected by the last write query.
Definition: Database.php:4766
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MIN
static int $DEADLOCK_DELAY_MIN
Minimum time to wait before retry, in microseconds.
Definition: Database.php:224
Wikimedia\Rdbms\Database\fetchAffectedRowCount
fetchAffectedRowCount()
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/schema/prefix specifications for IDatabase.
Definition: DatabaseDomain.php:40
Wikimedia\Rdbms\Database\databasesAreIndependent
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.In systems like mysql/mariadb,...
Definition: Database.php:2761
Wikimedia\Rdbms\TransactionProfiler
Detect high-contention DB queries via profiling calls.
Definition: TransactionProfiler.php:38
Wikimedia\Rdbms\Database\indexInfo
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.
Wikimedia\Rdbms\Database\strreplace
strreplace( $orig, $old, $new)
Returns a SQL expression for simple string replacement (e.g.REPLACE() in mysql)Column to modify Colum...
Definition: Database.php:3744
Wikimedia\Rdbms\Database\$ownerId
int null $ownerId
Integer ID of the managing LBFactory instance or null if none.
Definition: Database.php:190
Wikimedia\Rdbms\Database\fieldHasBit
fieldHasBit( $field, $flags)
Definition: Database.php:5448
Wikimedia\Rdbms\Database\sourceFile
sourceFile( $filename, callable $lineCallback=null, callable $resultCallback=null, $fname=false, callable $inputCallback=null)
Read and execute SQL commands from a file.
Definition: Database.php:4992
Wikimedia\Rdbms\Database\listViews
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.Only show VIEWs with this prefix, eg. unit_test_ Name of calling ...
Definition: Database.php:4744
Wikimedia\Rdbms\Database\newSelectQueryBuilder
newSelectQueryBuilder()
Create an empty SelectQueryBuilder which can be used to run queries against this connection....
Definition: Database.php:1732
Wikimedia\Rdbms\Database\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
Definition: Database.php:5106
Wikimedia\Rdbms\Database\makeList
makeList(array $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2462
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
Wikimedia\Rdbms\Database\nextSequenceValue
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
Definition: Database.php:3198
Wikimedia\Rdbms\Subquery
Definition: Subquery.php:27
Wikimedia\Rdbms\Database\makeConditionCollidesUponKey
makeConditionCollidesUponKey(array $rows, array $uniqueKey)
Definition: Database.php:3287
Wikimedia\Rdbms\Database\selectFieldValues
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
Definition: Database.php:1759
Wikimedia\Rdbms\Database\flatAtomicSectionList
flatAtomicSectionList()
Definition: Database.php:752
Wikimedia\Rdbms\Database\$deprecationLogger
callable $deprecationLogger
Deprecation logging callback.
Definition: Database.php:62
Wikimedia\Rdbms\Database\$errorLogger
callable $errorLogger
Error logging callback.
Definition: Database.php:60
Wikimedia\Rdbms\Database\$conn
object resource null $conn
Database connection.
Definition: Database.php:72
Wikimedia\Rdbms\Database\doRollback
doRollback( $fname)
Issues the ROLLBACK command to the database server.
Definition: Database.php:4679
Wikimedia\Rdbms\Database\$TINY_WRITE_SEC
static float $TINY_WRITE_SEC
Guess of how many seconds it takes to replicate a small insert.
Definition: Database.php:234
Wikimedia\Rdbms\Database\$lbInfo
array $lbInfo
Current LoadBalancer tracking information.
Definition: Database.php:101
Wikimedia\Rdbms\Database\getDBname
getDBname()
Get the current DB name.
Definition: Database.php:2790
Wikimedia\Rdbms\Blob
@newable Stable to extend
Definition: Blob.php:9
Wikimedia\Rdbms\Database\getInfinity
getInfinity()
Find out when 'infinity' is.Most DBMSes support this. This is a special keyword for timestamps in Pos...
Definition: Database.php:5378
$type
$type
Definition: testCompression.php:52
Wikimedia\Rdbms\Database\$sessionNamedLocks
array $sessionNamedLocks
Map of (name => 1) for locks obtained via lock()
Definition: Database.php:117