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;
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 
484  if ( !isset( $builtinTypes[$dbType] ) ) {
485  // Not a built in type, assume standard naming scheme
486  return 'Database' . ucfirst( $dbType );
487  }
488 
489  $class = false;
490  $possibleDrivers = $builtinTypes[$dbType];
491  if ( is_string( $possibleDrivers ) ) {
492  $class = $possibleDrivers;
493  } elseif ( (string)$driver !== '' ) {
494  if ( !isset( $possibleDrivers[$driver] ) ) {
495  throw new InvalidArgumentException( __METHOD__ .
496  " type '$dbType' does not support driver '{$driver}'" );
497  }
498 
499  $class = $possibleDrivers[$driver];
500  } else {
501  foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
502  if ( extension_loaded( $posDriver ) ) {
503  $class = $possibleClass;
504  break;
505  }
506  }
507  }
508 
509  if ( $class === false ) {
510  throw new InvalidArgumentException( __METHOD__ .
511  " no viable database extension found for type '$dbType'" );
512  }
513 
514  return $class;
515  }
516 
522  protected static function getAttributes() {
523  return [];
524  }
525 
533  public function setLogger( LoggerInterface $logger ) {
534  $this->queryLogger = $logger;
535  }
536 
537  public function getServerInfo() {
538  return $this->getServerVersion();
539  }
540 
541  public function getTopologyRole() {
542  return $this->topologyRole;
543  }
544 
545  public function getTopologyRootMaster() {
547  }
548 
549  final public function trxLevel() {
550  return ( $this->trxShortId != '' ) ? 1 : 0;
551  }
552 
553  public function trxTimestamp() {
554  return $this->trxLevel() ? $this->trxTimestamp : null;
555  }
556 
561  public function trxStatus() {
562  return $this->trxStatus;
563  }
564 
565  public function tablePrefix( $prefix = null ) {
566  $old = $this->currentDomain->getTablePrefix();
567  if ( $prefix !== null ) {
568  $this->currentDomain = new DatabaseDomain(
569  $this->currentDomain->getDatabase(),
570  $this->currentDomain->getSchema(),
571  $prefix
572  );
573  }
574 
575  return $old;
576  }
577 
578  public function dbSchema( $schema = null ) {
579  if ( strlen( $schema ) && $this->getDBname() === null ) {
580  throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
581  }
582 
583  $old = $this->currentDomain->getSchema();
584  if ( $schema !== null ) {
585  $this->currentDomain = new DatabaseDomain(
586  $this->currentDomain->getDatabase(),
587  // DatabaseDomain uses null for unspecified schemas
588  strlen( $schema ) ? $schema : null,
589  $this->currentDomain->getTablePrefix()
590  );
591  }
592 
593  return (string)$old;
594  }
595 
600  protected function relationSchemaQualifier() {
601  return $this->dbSchema();
602  }
603 
604  public function getLBInfo( $name = null ) {
605  if ( $name === null ) {
606  return $this->lbInfo;
607  }
608 
609  if ( array_key_exists( $name, $this->lbInfo ) ) {
610  return $this->lbInfo[$name];
611  }
612 
613  return null;
614  }
615 
616  public function setLBInfo( $nameOrArray, $value = null ) {
617  if ( is_array( $nameOrArray ) ) {
618  $this->lbInfo = $nameOrArray;
619  } elseif ( is_string( $nameOrArray ) ) {
620  if ( $value !== null ) {
621  $this->lbInfo[$nameOrArray] = $value;
622  } else {
623  unset( $this->lbInfo[$nameOrArray] );
624  }
625  } else {
626  throw new InvalidArgumentException( "Got non-string key" );
627  }
628  }
629 
636  protected function getLazyMasterHandle() {
638  }
639 
644  public function implicitOrderby() {
645  return true;
646  }
647 
648  public function lastQuery() {
649  return $this->lastQuery;
650  }
651 
652  public function lastDoneWrites() {
653  return $this->lastWriteTime ?: false;
654  }
655 
656  public function writesPending() {
657  return $this->trxLevel() && $this->trxDoneWrites;
658  }
659 
660  public function writesOrCallbacksPending() {
661  return $this->trxLevel() && (
662  $this->trxDoneWrites ||
663  $this->trxPostCommitOrIdleCallbacks ||
664  $this->trxPreCommitOrIdleCallbacks ||
665  $this->trxEndCallbacks ||
667  );
668  }
669 
670  public function preCommitCallbacksPending() {
671  return $this->trxLevel() && $this->trxPreCommitOrIdleCallbacks;
672  }
673 
677  final protected function getTransactionRoundId() {
678  // If transaction round participation is enabled, see if one is active
679  if ( $this->getFlag( self::DBO_TRX ) ) {
680  $id = $this->getLBInfo( self::LB_TRX_ROUND_ID );
681 
682  return is_string( $id ) ? $id : null;
683  }
684 
685  return null;
686  }
687 
688  public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
689  if ( !$this->trxLevel() ) {
690  return false;
691  } elseif ( !$this->trxDoneWrites ) {
692  return 0.0;
693  }
694 
695  switch ( $type ) {
696  case self::ESTIMATE_DB_APPLY:
697  return $this->pingAndCalculateLastTrxApplyTime();
698  default: // everything
700  }
701  }
702 
706  private function pingAndCalculateLastTrxApplyTime() {
707  // passed by reference
708  $rtt = null;
709  $this->ping( $rtt );
710 
711  $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
712  $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
713  // For omitted queries, make them count as something at least
714  $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
715  $applyTime += self::$TINY_WRITE_SEC * $omitted;
716 
717  return $applyTime;
718  }
719 
720  public function pendingWriteCallers() {
721  return $this->trxLevel() ? $this->trxWriteCallers : [];
722  }
723 
724  public function pendingWriteRowsAffected() {
726  }
727 
736  public function pendingWriteAndCallbackCallers() {
737  $fnames = $this->pendingWriteCallers();
738  foreach ( [
739  $this->trxPostCommitOrIdleCallbacks,
740  $this->trxPreCommitOrIdleCallbacks,
741  $this->trxEndCallbacks,
742  $this->trxSectionCancelCallbacks
743  ] as $callbacks ) {
744  foreach ( $callbacks as $callback ) {
745  $fnames[] = $callback[1];
746  }
747  }
748 
749  return $fnames;
750  }
751 
755  private function flatAtomicSectionList() {
756  return array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
757  return $accum === null ? $v[0] : "$accum, " . $v[0];
758  } );
759  }
760 
761  public function isOpen() {
762  return (bool)$this->conn;
763  }
764 
765  public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
766  if ( $flag & ~static::$DBO_MUTABLE ) {
767  throw new DBUnexpectedError(
768  $this,
769  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
770  );
771  }
772 
773  if ( $remember === self::REMEMBER_PRIOR ) {
774  $this->priorFlags[] = $this->flags;
775  }
776 
777  $this->flags |= $flag;
778  }
779 
780  public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
781  if ( $flag & ~static::$DBO_MUTABLE ) {
782  throw new DBUnexpectedError(
783  $this,
784  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
785  );
786  }
787 
788  if ( $remember === self::REMEMBER_PRIOR ) {
789  $this->priorFlags[] = $this->flags;
790  }
791 
792  $this->flags &= ~$flag;
793  }
794 
795  public function restoreFlags( $state = self::RESTORE_PRIOR ) {
796  if ( !$this->priorFlags ) {
797  return;
798  }
799 
800  if ( $state === self::RESTORE_INITIAL ) {
801  $this->flags = reset( $this->priorFlags );
802  $this->priorFlags = [];
803  } else {
804  $this->flags = array_pop( $this->priorFlags );
805  }
806  }
807 
808  public function getFlag( $flag ) {
809  return ( ( $this->flags & $flag ) === $flag );
810  }
811 
812  public function getDomainID() {
813  return $this->currentDomain->getId();
814  }
815 
825  abstract public function indexInfo( $table, $index, $fname = __METHOD__ );
826 
834  abstract public function strencode( $s );
835 
839  protected function installErrorHandler() {
840  $this->lastPhpError = false;
841  $this->htmlErrors = ini_set( 'html_errors', '0' );
842  set_error_handler( [ $this, 'connectionErrorLogger' ] );
843  }
844 
850  protected function restoreErrorHandler() {
851  restore_error_handler();
852  if ( $this->htmlErrors !== false ) {
853  ini_set( 'html_errors', $this->htmlErrors );
854  }
855 
856  return $this->getLastPHPError();
857  }
858 
862  protected function getLastPHPError() {
863  if ( $this->lastPhpError ) {
864  $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
865  $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
866 
867  return $error;
868  }
869 
870  return false;
871  }
872 
880  public function connectionErrorLogger( $errno, $errstr ) {
881  $this->lastPhpError = $errstr;
882  }
883 
890  protected function getLogContext( array $extras = [] ) {
891  return array_merge(
892  [
893  'db_server' => $this->server,
894  'db_name' => $this->getDBname(),
895  'db_user' => $this->user,
896  ],
897  $extras
898  );
899  }
900 
901  final public function close( $fname = __METHOD__, $owner = null ) {
902  $error = null; // error to throw after disconnecting
903 
904  $wasOpen = (bool)$this->conn;
905  // This should mostly do nothing if the connection is already closed
906  if ( $this->conn ) {
907  // Roll back any dangling transaction first
908  if ( $this->trxLevel() ) {
909  if ( $this->trxAtomicLevels ) {
910  // Cannot let incomplete atomic sections be committed
911  $levels = $this->flatAtomicSectionList();
912  $error = "$fname: atomic sections $levels are still open";
913  } elseif ( $this->trxAutomatic ) {
914  // Only the connection manager can commit non-empty DBO_TRX transactions
915  // (empty ones we can silently roll back)
916  if ( $this->writesOrCallbacksPending() ) {
917  $error = "$fname: " .
918  "expected mass rollback of all peer transactions (DBO_TRX set)";
919  }
920  } else {
921  // Manual transactions should have been committed or rolled
922  // back, even if empty.
923  $error = "$fname: transaction is still open (from {$this->trxFname})";
924  }
925 
926  if ( $this->trxEndCallbacksSuppressed && $error === null ) {
927  $error = "$fname: callbacks are suppressed; cannot properly commit";
928  }
929 
930  // Rollback the changes and run any callbacks as needed
931  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
932  }
933 
934  // Close the actual connection in the binding handle
935  $closed = $this->closeConnection();
936  } else {
937  $closed = true; // already closed; nothing to do
938  }
939 
940  $this->conn = null;
941 
942  // Log or throw any unexpected errors after having disconnected
943  if ( $error !== null ) {
944  // T217819, T231443: if this is probably just LoadBalancer trying to recover from
945  // errors and shutdown, then log any problems and move on since the request has to
946  // end one way or another. Throwing errors is not very useful at some point.
947  if ( $this->ownerId !== null && $owner === $this->ownerId ) {
948  $this->queryLogger->error( $error );
949  } else {
950  throw new DBUnexpectedError( $this, $error );
951  }
952  }
953 
954  // Note that various subclasses call close() at the start of open(), which itself is
955  // called by replaceLostConnection(). In that case, just because onTransactionResolution()
956  // callbacks are pending does not mean that an exception should be thrown. Rather, they
957  // will be executed after the reconnection step.
958  if ( $wasOpen ) {
959  // Sanity check that no callbacks are dangling
960  $fnames = $this->pendingWriteAndCallbackCallers();
961  if ( $fnames ) {
962  throw new RuntimeException(
963  "Transaction callbacks are still pending: " . implode( ', ', $fnames )
964  );
965  }
966  }
967 
968  return $closed;
969  }
970 
979  final protected function assertHasConnectionHandle() {
980  if ( !$this->isOpen() ) {
981  throw new DBUnexpectedError( $this, "DB connection was already closed" );
982  }
983  }
984 
990  protected function assertIsWritableMaster() {
991  $info = $this->getReadOnlyReason();
992  if ( $info ) {
993  list( $reason, $source ) = $info;
994  if ( $source === 'role' ) {
995  throw new DBReadOnlyRoleError( $this, "Database is read-only: $reason" );
996  } else {
997  throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
998  }
999  }
1000  }
1001 
1007  abstract protected function closeConnection();
1008 
1038  abstract protected function doQuery( $sql );
1039 
1057  protected function isWriteQuery( $sql, $flags ) {
1058  if (
1059  $this->fieldHasBit( $flags, self::QUERY_CHANGE_ROWS ) ||
1060  $this->fieldHasBit( $flags, self::QUERY_CHANGE_SCHEMA )
1061  ) {
1062  return true;
1063  } elseif ( $this->fieldHasBit( $flags, self::QUERY_CHANGE_NONE ) ) {
1064  return false;
1065  }
1066  // BEGIN and COMMIT queries are considered read queries here.
1067  // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1068  // treat these as write queries, in that their results have "affected rows"
1069  // as meta data as from writes, instead of "num rows" as from reads.
1070  // But, we treat them as read queries because when reading data (from
1071  // either replica or master) we use transactions to enable repeatable-read
1072  // snapshots, which ensures we get consistent results from the same snapshot
1073  // for all queries within a request. Use cases:
1074  // - Treating these as writes would trigger ChronologyProtector (see method doc).
1075  // - We use this method to reject writes to replicas, but we need to allow
1076  // use of transactions on replicas for read snapshots. This is fine given
1077  // that transactions by themselves don't make changes, only actual writes
1078  // within the transaction matter, which we still detect.
1079  return !preg_match(
1080  '/^\s*(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\‍(SELECT)\b/i',
1081  $sql
1082  );
1083  }
1084 
1089  protected function getQueryVerb( $sql ) {
1090  return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
1091  }
1092 
1107  protected function isTransactableQuery( $sql ) {
1108  return !in_array(
1109  $this->getQueryVerb( $sql ),
1110  [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1111  true
1112  );
1113  }
1114 
1123  protected function getTempTableWrites( $sql, $pseudoPermanent ) {
1124  // Regexes for basic queries that can create/change/drop temporary tables.
1125  // For simplicity, this only looks for tables with sane, alphanumeric, names;
1126  // temporary tables only need simple programming names anyway.
1127  static $regexes = null;
1128  if ( $regexes === null ) {
1129  // Regex with a group for quoted table 0 and a group for quoted tables 1..N
1130  $qts = '((?:\w+|`\w+`|\'\w+\'|"\w+")(?:\s*,\s*(?:\w+|`\w+`|\'\w+\'|"\w+"))*)';
1131  // Regex to get query verb, table 0, and tables 1..N
1132  $regexes = [
1133  // DML write queries
1134  "/^(INSERT|REPLACE)\s+(?:\w+\s+)*?INTO\s+$qts/i",
1135  "/^(UPDATE)(?:\s+OR\s+\w+|\s+IGNORE|\s+ONLY)?\s+$qts/i",
1136  "/^(DELETE)\s+(?:\w+\s+)*?FROM(?:\s+ONLY)?\s+$qts/i",
1137  // DDL write queries
1138  "/^(CREATE)\s+TEMPORARY\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+$qts/i",
1139  "/^(DROP)\s+(?:TEMPORARY\s+)?TABLE(?:\s+IF\s+EXISTS)?\s+$qts/i",
1140  "/^(TRUNCATE)\s+(?:TEMPORARY\s+)?TABLE\s+$qts/i",
1141  "/^(ALTER)\s+TABLE\s+$qts/i"
1142  ];
1143  }
1144 
1145  $queryVerb = null;
1146  $queryTables = [];
1147  foreach ( $regexes as $regex ) {
1148  if ( preg_match( $regex, $sql, $m, PREG_UNMATCHED_AS_NULL ) ) {
1149  $queryVerb = $m[1];
1150  $allTables = preg_split( '/\s*,\s*/', $m[2] );
1151  foreach ( $allTables as $quotedTable ) {
1152  $queryTables[] = trim( $quotedTable, "\"'`" );
1153  }
1154  break;
1155  }
1156  }
1157 
1158  $tempTableChanges = [];
1159  foreach ( $queryTables as $table ) {
1160  if ( $queryVerb === 'CREATE' ) {
1161  // Record the type of temporary table being created
1162  $tableType = $pseudoPermanent ? self::$TEMP_PSEUDO_PERMANENT : self::$TEMP_NORMAL;
1163  } else {
1164  $tableType = $this->sessionTempTables[$table] ?? null;
1165  }
1166 
1167  if ( $tableType !== null ) {
1168  $tempTableChanges[] = [ $tableType, $queryVerb, $table ];
1169  }
1170  }
1171 
1172  return $tempTableChanges;
1173  }
1174 
1179  protected function registerTempWrites( $ret, array $changes ) {
1180  if ( $ret === false ) {
1181  return;
1182  }
1183 
1184  foreach ( $changes as list( $tmpTableType, $verb, $table ) ) {
1185  switch ( $verb ) {
1186  case 'CREATE':
1187  $this->sessionTempTables[$table] = $tmpTableType;
1188  break;
1189  case 'DROP':
1190  unset( $this->sessionTempTables[$table] );
1191  unset( $this->sessionDirtyTempTables[$table] );
1192  break;
1193  case 'TRUNCATE':
1194  unset( $this->sessionDirtyTempTables[$table] );
1195  break;
1196  default:
1197  $this->sessionDirtyTempTables[$table] = 1;
1198  break;
1199  }
1200  }
1201  }
1202 
1210  protected function isPristineTemporaryTable( $table ) {
1211  $rawTable = $this->tableName( $table, 'raw' );
1212 
1213  return (
1214  isset( $this->sessionTempTables[$rawTable] ) &&
1215  !isset( $this->sessionDirtyTempTables[$rawTable] )
1216  );
1217  }
1218 
1219  public function query( $sql, $fname = __METHOD__, $flags = self::QUERY_NORMAL ) {
1220  $flags = (int)$flags; // b/c; this field used to be a bool
1221  // Sanity check that the SQL query is appropriate in the current context and is
1222  // allowed for an outside caller (e.g. does not break transaction/session tracking).
1223  $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1224 
1225  // Send the query to the server and fetch any corresponding errors
1226  list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1227  if ( $ret === false ) {
1228  $ignoreErrors = $this->fieldHasBit( $flags, self::QUERY_SILENCE_ERRORS );
1229  // Throw an error unless both the ignore flag was set and a rollback is not needed
1230  $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1231  }
1232 
1233  return $this->resultObject( $ret );
1234  }
1235 
1256  final protected function executeQuery( $sql, $fname, $flags ) {
1257  $this->assertHasConnectionHandle();
1258 
1259  $priorTransaction = $this->trxLevel();
1260 
1261  if ( $this->isWriteQuery( $sql, $flags ) ) {
1262  // Do not treat temporary table writes as "meaningful writes" since they are only
1263  // visible to one session and are not permanent. Profile them as reads. Integration
1264  // tests can override this behavior via $flags.
1265  $pseudoPermanent = $this->fieldHasBit( $flags, self::QUERY_PSEUDO_PERMANENT );
1266  $tempTableChanges = $this->getTempTableWrites( $sql, $pseudoPermanent );
1267  $isPermWrite = !$tempTableChanges;
1268  foreach ( $tempTableChanges as list( $tmpType ) ) {
1269  $isPermWrite = $isPermWrite || ( $tmpType !== self::$TEMP_NORMAL );
1270  }
1271 
1272  // Permit temporary table writes on replica DB connections
1273  // but require a writable master connection for any persistent writes.
1274  if ( $isPermWrite ) {
1275  $this->assertIsWritableMaster();
1276 
1277  // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1278  if ( $this->fieldHasBit( $flags, self::QUERY_REPLICA_ROLE ) ) {
1279  throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1280  }
1281  }
1282  } else {
1283  // No permanent writes in this query
1284  $isPermWrite = false;
1285  // No temporary tables written to either
1286  $tempTableChanges = [];
1287  }
1288 
1289  // Add trace comment to the begin of the sql string, right after the operator.
1290  // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1291  $encAgent = str_replace( '/', '-', $this->agent );
1292  $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1293 
1294  // Send the query to the server and fetch any corresponding errors.
1295  // This also doubles as a "ping" to see if the connection was dropped.
1296  list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1297  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1298 
1299  // Check if the query failed due to a recoverable connection loss
1300  $allowRetry = !$this->fieldHasBit( $flags, self::QUERY_NO_RETRY );
1301  if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1302  // Silently resend the query to the server since it is safe and possible
1303  list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1304  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1305  }
1306 
1307  // Register creation and dropping of temporary tables
1308  $this->registerTempWrites( $ret, $tempTableChanges );
1309 
1310  $corruptedTrx = false;
1311 
1312  if ( $ret === false ) {
1313  if ( $priorTransaction ) {
1314  if ( $recoverableSR ) {
1315  # We're ignoring an error that caused just the current query to be aborted.
1316  # But log the cause so we can log a deprecation notice if a caller actually
1317  # does ignore it.
1318  $this->trxStatusIgnoredCause = [ $err, $errno, $fname ];
1319  } elseif ( !$recoverableCL ) {
1320  # Either the query was aborted or all queries after BEGIN where aborted.
1321  # In the first case, the only options going forward are (a) ROLLBACK, or
1322  # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1323  # option is ROLLBACK, since the snapshots would have been released.
1324  $corruptedTrx = true; // cannot recover
1325  $this->trxStatus = self::STATUS_TRX_ERROR;
1326  $this->trxStatusCause = $this->getQueryException( $err, $errno, $sql, $fname );
1327  $this->trxStatusIgnoredCause = null;
1328  }
1329  }
1330  }
1331 
1332  return [ $ret, $err, $errno, $corruptedTrx ];
1333  }
1334 
1353  private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1354  $priorWritesPending = $this->writesOrCallbacksPending();
1355 
1356  if ( ( $flags & self::QUERY_IGNORE_DBO_TRX ) == 0 ) {
1357  $this->beginIfImplied( $sql, $fname );
1358  }
1359 
1360  // Keep track of whether the transaction has write queries pending
1361  if ( $isPermWrite ) {
1362  $this->lastWriteTime = microtime( true );
1363  if ( $this->trxLevel() && !$this->trxDoneWrites ) {
1364  $this->trxDoneWrites = true;
1365  $this->trxProfiler->transactionWritingIn(
1366  $this->server, $this->getDomainID(), $this->trxShortId );
1367  }
1368  }
1369 
1370  $prefix = $this->topologyRole ? 'query-m: ' : 'query: ';
1371  $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId, $prefix );
1372 
1373  $startTime = microtime( true );
1374  $ps = $this->profiler
1375  ? ( $this->profiler )( $generalizedSql->stringify() )
1376  : null;
1377  $this->affectedRowCount = null;
1378  $this->lastQuery = $sql;
1379  $ret = $this->doQuery( $commentedSql );
1380  $lastError = $this->lastError();
1381  $lastErrno = $this->lastErrno();
1382 
1383  $this->affectedRowCount = $this->affectedRows();
1384  unset( $ps ); // profile out (if set)
1385  $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1386 
1387  $recoverableSR = false; // recoverable statement rollback?
1388  $recoverableCL = false; // recoverable connection loss?
1389  $reconnected = false; // reconnection both attempted and succeeded?
1390 
1391  if ( $ret !== false ) {
1392  $this->lastPing = $startTime;
1393  if ( $isPermWrite && $this->trxLevel() ) {
1394  $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1395  $this->trxWriteCallers[] = $fname;
1396  }
1397  } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1398  # Check if no meaningful session state was lost
1399  $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1400  # Update session state tracking and try to restore the connection
1401  $reconnected = $this->replaceLostConnection( __METHOD__ );
1402  } else {
1403  # Check if only the last query was rolled back
1404  $recoverableSR = $this->wasKnownStatementRollbackError();
1405  }
1406 
1407  if ( $sql === self::$PING_QUERY ) {
1408  $this->lastRoundTripEstimate = $queryRuntime;
1409  }
1410 
1411  $this->trxProfiler->recordQueryCompletion(
1412  $generalizedSql,
1413  $startTime,
1414  $isPermWrite,
1415  $isPermWrite ? $this->affectedRows() : $this->numRows( $ret )
1416  );
1417 
1418  // Avoid the overhead of logging calls unless debug mode is enabled
1419  if ( $this->getFlag( self::DBO_DEBUG ) ) {
1420  $this->queryLogger->debug(
1421  "{method} [{runtime}s] {db_host}: {sql}",
1422  [
1423  'method' => $fname,
1424  'db_host' => $this->getServer(),
1425  'sql' => $sql,
1426  'domain' => $this->getDomainID(),
1427  'runtime' => round( $queryRuntime, 3 )
1428  ]
1429  );
1430  }
1431 
1432  return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1433  }
1434 
1441  private function beginIfImplied( $sql, $fname ) {
1442  if (
1443  !$this->trxLevel() &&
1444  $this->getFlag( self::DBO_TRX ) &&
1445  $this->isTransactableQuery( $sql )
1446  ) {
1447  $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1448  $this->trxAutomatic = true;
1449  }
1450  }
1451 
1464  private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1465  // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1466  $indicativeOfReplicaRuntime = true;
1467  if ( $runtime > self::$SLOW_WRITE_SEC ) {
1468  $verb = $this->getQueryVerb( $sql );
1469  // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1470  if ( $verb === 'INSERT' ) {
1471  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS;
1472  } elseif ( $verb === 'REPLACE' ) {
1473  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS / 2;
1474  }
1475  }
1476 
1477  $this->trxWriteDuration += $runtime;
1478  $this->trxWriteQueryCount += 1;
1479  $this->trxWriteAffectedRows += $affected;
1480  if ( $indicativeOfReplicaRuntime ) {
1481  $this->trxWriteAdjDuration += $runtime;
1482  $this->trxWriteAdjQueryCount += 1;
1483  }
1484  }
1485 
1493  private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1494  $verb = $this->getQueryVerb( $sql );
1495  if ( $verb === 'USE' ) {
1496  throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1497  }
1498 
1499  if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1500  return;
1501  }
1502 
1503  if ( $this->trxStatus < self::STATUS_TRX_OK ) {
1504  throw new DBTransactionStateError(
1505  $this,
1506  "Cannot execute query from $fname while transaction status is ERROR",
1507  [],
1508  $this->trxStatusCause
1509  );
1510  } elseif ( $this->trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1511  list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause;
1512  call_user_func( $this->deprecationLogger,
1513  "Caller from $fname ignored an error originally raised from $iFname: " .
1514  "[$iLastErrno] $iLastError"
1515  );
1516  $this->trxStatusIgnoredCause = null;
1517  }
1518  }
1519 
1520  public function assertNoOpenTransactions() {
1521  if ( $this->explicitTrxActive() ) {
1522  throw new DBTransactionError(
1523  $this,
1524  "Explicit transaction still active. A caller may have caught an error. "
1525  . "Open transactions: " . $this->flatAtomicSectionList()
1526  );
1527  }
1528  }
1529 
1539  private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1540  # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1541  # Dropped connections also mean that named locks are automatically released.
1542  # Only allow error suppression in autocommit mode or when the lost transaction
1543  # didn't matter anyway (aside from DBO_TRX snapshot loss).
1544  if ( $this->sessionNamedLocks ) {
1545  return false; // possible critical section violation
1546  } elseif ( $this->sessionTempTables ) {
1547  return false; // tables might be queried latter
1548  } elseif ( $sql === 'COMMIT' ) {
1549  return !$priorWritesPending; // nothing written anyway? (T127428)
1550  } elseif ( $sql === 'ROLLBACK' ) {
1551  return true; // transaction lost...which is also what was requested :)
1552  } elseif ( $this->explicitTrxActive() ) {
1553  return false; // don't drop atomicity and explicit snapshots
1554  } elseif ( $priorWritesPending ) {
1555  return false; // prior writes lost from implicit transaction
1556  }
1557 
1558  return true;
1559  }
1560 
1564  private function handleSessionLossPreconnect() {
1565  // Clean up tracking of session-level things...
1566  // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1567  // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1568  $this->sessionTempTables = [];
1569  $this->sessionDirtyTempTables = [];
1570  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1571  // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1572  $this->sessionNamedLocks = [];
1573  // Session loss implies transaction loss
1574  $oldTrxShortId = $this->consumeTrxShortId();
1575  $this->trxAtomicCounter = 0;
1576  $this->trxPostCommitOrIdleCallbacks = []; // T67263; transaction already lost
1577  $this->trxPreCommitOrIdleCallbacks = []; // T67263; transaction already lost
1578  // Clear additional subclass fields
1580  // @note: leave trxRecurringCallbacks in place
1581  if ( $this->trxDoneWrites ) {
1582  $this->trxProfiler->transactionWritingOut(
1583  $this->server,
1584  $this->getDomainID(),
1585  $oldTrxShortId,
1586  $this->pendingWriteQueryDuration( self::ESTIMATE_TOTAL ),
1587  $this->trxWriteAffectedRows
1588  );
1589  }
1590  }
1591 
1596  protected function doHandleSessionLossPreconnect() {
1597  // no-op
1598  }
1599 
1603  private function handleSessionLossPostconnect() {
1604  try {
1605  // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1606  // If callback suppression is set then the array will remain unhandled.
1607  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1608  } catch ( Throwable $ex ) {
1609  // Already logged; move on...
1610  }
1611  try {
1612  // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1613  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1614  } catch ( Throwable $ex ) {
1615  // Already logged; move on...
1616  }
1617  }
1618 
1624  private function consumeTrxShortId() {
1625  $old = $this->trxShortId;
1626  $this->trxShortId = '';
1627 
1628  return $old;
1629  }
1630 
1642  protected function wasQueryTimeout( $error, $errno ) {
1643  return false;
1644  }
1645 
1657  public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1658  if ( $ignore ) {
1659  $this->queryLogger->debug( "SQL ERROR (ignored): $error" );
1660  } else {
1661  throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1662  }
1663  }
1664 
1672  private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1673  // Information that instances of the same problem have in common should
1674  // not be normalized (T255202).
1675  $this->queryLogger->error(
1676  "Error $errno from $fname, {error} {sql1line} {db_server}",
1677  $this->getLogContext( [
1678  'method' => __METHOD__,
1679  'errno' => $errno,
1680  'error' => $error,
1681  'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1682  'fname' => $fname,
1683  'exception' => new RuntimeException()
1684  ] )
1685  );
1686  return $this->getQueryException( $error, $errno, $sql, $fname );
1687  }
1688 
1696  private function getQueryException( $error, $errno, $sql, $fname ) {
1697  if ( $this->wasQueryTimeout( $error, $errno ) ) {
1698  return new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1699  } elseif ( $this->wasConnectionError( $errno ) ) {
1700  return new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1701  } else {
1702  return new DBQueryError( $this, $error, $errno, $sql, $fname );
1703  }
1704  }
1705 
1710  final protected function newExceptionAfterConnectError( $error ) {
1711  // Connection was not fully initialized and is not safe for use
1712  $this->conn = null;
1713 
1714  $this->connLogger->error(
1715  "Error connecting to {db_server} as user {db_user}: {error}",
1716  $this->getLogContext( [
1717  'error' => $error,
1718  'exception' => new RuntimeException()
1719  ] )
1720  );
1721 
1722  return new DBConnectionError( $this, $error );
1723  }
1724 
1729  public function freeResult( $res ) {
1730  }
1731 
1735  public function newSelectQueryBuilder() {
1736  return new SelectQueryBuilder( $this );
1737  }
1738 
1739  public function selectField(
1740  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1741  ) {
1742  if ( $var === '*' ) { // sanity
1743  throw new DBUnexpectedError( $this, "Cannot use a * field" );
1744  }
1745 
1746  $options = $this->normalizeOptions( $options );
1747  $options['LIMIT'] = 1;
1748 
1749  $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1750  if ( $res === false ) {
1751  throw new DBUnexpectedError( $this, "Got false from select()" );
1752  }
1753 
1754  $row = $this->fetchRow( $res );
1755  if ( $row === false ) {
1756  return false;
1757  }
1758 
1759  return reset( $row );
1760  }
1761 
1762  public function selectFieldValues(
1763  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1764  ) {
1765  if ( $var === '*' ) { // sanity
1766  throw new DBUnexpectedError( $this, "Cannot use a * field" );
1767  } elseif ( !is_string( $var ) ) { // sanity
1768  throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1769  }
1770 
1771  $options = $this->normalizeOptions( $options );
1772  $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1773  if ( $res === false ) {
1774  throw new DBUnexpectedError( $this, "Got false from select()" );
1775  }
1776 
1777  $values = [];
1778  foreach ( $res as $row ) {
1779  $values[] = $row->value;
1780  }
1781 
1782  return $values;
1783  }
1784 
1796  protected function makeSelectOptions( array $options ) {
1797  $preLimitTail = $postLimitTail = '';
1798  $startOpts = '';
1799 
1800  $noKeyOptions = [];
1801 
1802  foreach ( $options as $key => $option ) {
1803  if ( is_numeric( $key ) ) {
1804  $noKeyOptions[$option] = true;
1805  }
1806  }
1807 
1808  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1809 
1810  $preLimitTail .= $this->makeOrderBy( $options );
1811 
1812  if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1813  $postLimitTail .= ' FOR UPDATE';
1814  }
1815 
1816  if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1817  $postLimitTail .= ' LOCK IN SHARE MODE';
1818  }
1819 
1820  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1821  $startOpts .= 'DISTINCT';
1822  }
1823 
1824  # Various MySQL extensions
1825  if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1826  $startOpts .= ' /*! STRAIGHT_JOIN */';
1827  }
1828 
1829  if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1830  $startOpts .= ' SQL_BIG_RESULT';
1831  }
1832 
1833  if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1834  $startOpts .= ' SQL_BUFFER_RESULT';
1835  }
1836 
1837  if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1838  $startOpts .= ' SQL_SMALL_RESULT';
1839  }
1840 
1841  if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1842  $startOpts .= ' SQL_CALC_FOUND_ROWS';
1843  }
1844 
1845  if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1846  $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1847  } else {
1848  $useIndex = '';
1849  }
1850  if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1851  $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1852  } else {
1853  $ignoreIndex = '';
1854  }
1855 
1856  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1857  }
1858 
1867  protected function makeGroupByWithHaving( $options ) {
1868  $sql = '';
1869  if ( isset( $options['GROUP BY'] ) ) {
1870  $gb = is_array( $options['GROUP BY'] )
1871  ? implode( ',', $options['GROUP BY'] )
1872  : $options['GROUP BY'];
1873  $sql .= ' GROUP BY ' . $gb;
1874  }
1875  if ( isset( $options['HAVING'] ) ) {
1876  $having = is_array( $options['HAVING'] )
1877  ? $this->makeList( $options['HAVING'], self::LIST_AND )
1878  : $options['HAVING'];
1879  $sql .= ' HAVING ' . $having;
1880  }
1881 
1882  return $sql;
1883  }
1884 
1893  protected function makeOrderBy( $options ) {
1894  if ( isset( $options['ORDER BY'] ) ) {
1895  $ob = is_array( $options['ORDER BY'] )
1896  ? implode( ',', $options['ORDER BY'] )
1897  : $options['ORDER BY'];
1898 
1899  return ' ORDER BY ' . $ob;
1900  }
1901 
1902  return '';
1903  }
1904 
1905  public function select(
1906  $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1907  ) {
1908  $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1909 
1910  return $this->query( $sql, $fname, self::QUERY_CHANGE_NONE );
1911  }
1912 
1917  public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1918  $options = [], $join_conds = []
1919  ) {
1920  if ( is_array( $vars ) ) {
1921  $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1922  } else {
1923  $fields = $vars;
1924  }
1925 
1926  $options = (array)$options;
1927  $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1928  ? $options['USE INDEX']
1929  : [];
1930  $ignoreIndexes = (
1931  isset( $options['IGNORE INDEX'] ) &&
1932  is_array( $options['IGNORE INDEX'] )
1933  )
1934  ? $options['IGNORE INDEX']
1935  : [];
1936 
1937  if (
1938  $this->selectOptionsIncludeLocking( $options ) &&
1939  $this->selectFieldsOrOptionsAggregate( $vars, $options )
1940  ) {
1941  // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
1942  // functions. Discourage use of such queries to encourage compatibility.
1943  call_user_func(
1944  $this->deprecationLogger,
1945  __METHOD__ . ": aggregation used with a locking SELECT ($fname)"
1946  );
1947  }
1948 
1949  if ( is_array( $table ) ) {
1950  if ( count( $table ) === 0 ) {
1951  $from = '';
1952  } else {
1953  $from = ' FROM ' .
1955  $table, $useIndexes, $ignoreIndexes, $join_conds );
1956  }
1957  } elseif ( $table != '' ) {
1958  $from = ' FROM ' .
1960  [ $table ], $useIndexes, $ignoreIndexes, [] );
1961  } else {
1962  $from = '';
1963  }
1964 
1965  list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1966  $this->makeSelectOptions( $options );
1967 
1968  if ( is_array( $conds ) ) {
1969  $conds = $this->makeList( $conds, self::LIST_AND );
1970  }
1971 
1972  if ( $conds === null || $conds === false ) {
1973  $this->queryLogger->warning(
1974  __METHOD__
1975  . ' called from '
1976  . $fname
1977  . ' with incorrect parameters: $conds must be a string or an array'
1978  );
1979  $conds = '';
1980  }
1981 
1982  if ( $conds === '' || $conds === '*' ) {
1983  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1984  } elseif ( is_string( $conds ) ) {
1985  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1986  "WHERE $conds $preLimitTail";
1987  } else {
1988  throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1989  }
1990 
1991  if ( isset( $options['LIMIT'] ) ) {
1992  $sql = $this->limitResult( $sql, $options['LIMIT'],
1993  $options['OFFSET'] ?? false );
1994  }
1995  $sql = "$sql $postLimitTail";
1996 
1997  if ( isset( $options['EXPLAIN'] ) ) {
1998  $sql = 'EXPLAIN ' . $sql;
1999  }
2000 
2001  return $sql;
2002  }
2003 
2004  public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
2005  $options = [], $join_conds = []
2006  ) {
2007  $options = (array)$options;
2008  $options['LIMIT'] = 1;
2009 
2010  $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
2011  if ( $res === false ) {
2012  throw new DBUnexpectedError( $this, "Got false from select()" );
2013  }
2014 
2015  if ( !$this->numRows( $res ) ) {
2016  return false;
2017  }
2018 
2019  return $this->fetchObject( $res );
2020  }
2021 
2026  public function estimateRowCount(
2027  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2028  ) {
2029  $conds = $this->normalizeConditions( $conds, $fname );
2030  $column = $this->extractSingleFieldFromList( $var );
2031  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
2032  $conds[] = "$column IS NOT NULL";
2033  }
2034 
2035  $res = $this->select(
2036  $tables, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
2037  );
2038  $row = $res ? $this->fetchRow( $res ) : [];
2039 
2040  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
2041  }
2042 
2043  public function selectRowCount(
2044  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2045  ) {
2046  $conds = $this->normalizeConditions( $conds, $fname );
2047  $column = $this->extractSingleFieldFromList( $var );
2048  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
2049  $conds[] = "$column IS NOT NULL";
2050  }
2051 
2052  $res = $this->select(
2053  [
2054  'tmp_count' => $this->buildSelectSubquery(
2055  $tables,
2056  '1',
2057  $conds,
2058  $fname,
2059  $options,
2060  $join_conds
2061  )
2062  ],
2063  [ 'rowcount' => 'COUNT(*)' ],
2064  [],
2065  $fname
2066  );
2067  $row = $res ? $this->fetchRow( $res ) : [];
2068 
2069  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
2070  }
2071 
2076  private function selectOptionsIncludeLocking( $options ) {
2077  $options = (array)$options;
2078  foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
2079  if ( in_array( $lock, $options, true ) ) {
2080  return true;
2081  }
2082  }
2083 
2084  return false;
2085  }
2086 
2092  private function selectFieldsOrOptionsAggregate( $fields, $options ) {
2093  foreach ( (array)$options as $key => $value ) {
2094  if ( is_string( $key ) ) {
2095  if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
2096  return true;
2097  }
2098  } elseif ( is_string( $value ) ) {
2099  if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
2100  return true;
2101  }
2102  }
2103  }
2104 
2105  $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
2106  foreach ( (array)$fields as $field ) {
2107  if ( is_string( $field ) && preg_match( $regex, $field ) ) {
2108  return true;
2109  }
2110  }
2111 
2112  return false;
2113  }
2114 
2120  final protected function normalizeRowArray( array $rowOrRows ) {
2121  if ( !$rowOrRows ) {
2122  $rows = [];
2123  } elseif ( isset( $rowOrRows[0] ) ) {
2124  $rows = $rowOrRows;
2125  } else {
2126  $rows = [ $rowOrRows ];
2127  }
2128 
2129  foreach ( $rows as $row ) {
2130  if ( !is_array( $row ) ) {
2131  throw new DBUnexpectedError( $this, "Got non-array in row array" );
2132  } elseif ( !$row ) {
2133  throw new DBUnexpectedError( $this, "Got empty array in row array" );
2134  }
2135  }
2136 
2137  return $rows;
2138  }
2139 
2146  final protected function normalizeConditions( $conds, $fname ) {
2147  if ( $conds === null || $conds === false ) {
2148  $this->queryLogger->warning(
2149  __METHOD__
2150  . ' called from '
2151  . $fname
2152  . ' with incorrect parameters: $conds must be a string or an array'
2153  );
2154  return [];
2155  } elseif ( $conds === '' ) {
2156  return [];
2157  }
2158 
2159  return is_array( $conds ) ? $conds : [ $conds ];
2160  }
2161 
2167  final protected function normalizeUpsertKeys( $uniqueKeys ) {
2168  if ( is_string( $uniqueKeys ) ) {
2169  return [ [ $uniqueKeys ] ];
2170  }
2171 
2172  if ( !is_array( $uniqueKeys ) || !$uniqueKeys ) {
2173  throw new DBUnexpectedError( $this, 'Invalid or empty unique key array' );
2174  }
2175 
2176  $oldStyle = false;
2177  $uniqueColumnSets = [];
2178  foreach ( $uniqueKeys as $i => $uniqueKey ) {
2179  if ( !is_int( $i ) ) {
2180  throw new DBUnexpectedError( $this, 'Unique key array should be a list' );
2181  } elseif ( is_string( $uniqueKey ) ) {
2182  $oldStyle = true;
2183  $uniqueColumnSets[] = [ $uniqueKey ];
2184  } elseif ( is_array( $uniqueKey ) && $uniqueKey ) {
2185  $uniqueColumnSets[] = $uniqueKey;
2186  } else {
2187  throw new DBUnexpectedError( $this, 'Invalid unique key array entry' );
2188  }
2189  }
2190 
2191  if ( count( $uniqueColumnSets ) > 1 ) {
2192  // If an existing row conflicts with new row X on key A and new row Y on key B,
2193  // it is not well defined how many UPDATEs should apply to the existing row and
2194  // in what order the new rows are checked
2195  $this->queryLogger->warning(
2196  __METHOD__ . " called with multiple unique keys",
2197  [ 'exception' => new RuntimeException() ]
2198  );
2199  }
2200 
2201  if ( $oldStyle ) {
2202  // Passing a list of strings for single-column unique keys is too
2203  // easily confused with passing the columns of composite unique key
2204  $this->queryLogger->warning(
2205  __METHOD__ . " called with deprecated parameter style: " .
2206  "the unique key array should be a string or array of string arrays",
2207  [ 'exception' => new RuntimeException() ]
2208  );
2209  }
2210 
2211  return $uniqueColumnSets;
2212  }
2213 
2219  final protected function normalizeOptions( $options ) {
2220  if ( is_array( $options ) ) {
2221  return $options;
2222  } elseif ( is_string( $options ) ) {
2223  return ( $options === '' ) ? [] : [ $options ];
2224  } else {
2225  throw new DBUnexpectedError( $this, __METHOD__ . ': expected string or array' );
2226  }
2227  }
2228 
2235  final protected function isFlagInOptions( $option, array $options ) {
2236  foreach ( array_keys( $options, $option, true ) as $k ) {
2237  if ( is_int( $k ) ) {
2238  return true;
2239  }
2240  }
2241 
2242  return false;
2243  }
2244 
2249  final protected function extractSingleFieldFromList( $var ) {
2250  if ( is_array( $var ) ) {
2251  if ( !$var ) {
2252  $column = null;
2253  } elseif ( count( $var ) == 1 ) {
2254  $column = $var[0] ?? reset( $var );
2255  } else {
2256  throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns' );
2257  }
2258  } else {
2259  $column = $var;
2260  }
2261 
2262  return $column;
2263  }
2264 
2265  public function lockForUpdate(
2266  $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2267  ) {
2268  if ( !$this->trxLevel() && !$this->getFlag( self::DBO_TRX ) ) {
2269  throw new DBUnexpectedError(
2270  $this,
2271  __METHOD__ . ': no transaction is active nor is DBO_TRX set'
2272  );
2273  }
2274 
2275  $options = (array)$options;
2276  $options[] = 'FOR UPDATE';
2277 
2278  return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2279  }
2280 
2281  public function fieldExists( $table, $field, $fname = __METHOD__ ) {
2282  $info = $this->fieldInfo( $table, $field );
2283 
2284  return (bool)$info;
2285  }
2286 
2287  public function indexExists( $table, $index, $fname = __METHOD__ ) {
2288  if ( !$this->tableExists( $table, $fname ) ) {
2289  return null;
2290  }
2291 
2292  $info = $this->indexInfo( $table, $index, $fname );
2293  if ( $info === null ) {
2294  return null;
2295  } else {
2296  return $info !== false;
2297  }
2298  }
2299 
2300  abstract public function tableExists( $table, $fname = __METHOD__ );
2301 
2306  public function indexUnique( $table, $index, $fname = __METHOD__ ) {
2307  $indexInfo = $this->indexInfo( $table, $index, $fname );
2308 
2309  if ( !$indexInfo ) {
2310  return null;
2311  }
2312 
2313  return !$indexInfo[0]->Non_unique;
2314  }
2315 
2316  public function insert( $table, $rows, $fname = __METHOD__, $options = [] ) {
2317  $rows = $this->normalizeRowArray( $rows );
2318  if ( !$rows ) {
2319  return true;
2320  }
2321 
2322  $options = $this->normalizeOptions( $options );
2323  if ( $this->isFlagInOptions( 'IGNORE', $options ) ) {
2324  $this->doInsertNonConflicting( $table, $rows, $fname );
2325  } else {
2326  $this->doInsert( $table, $rows, $fname );
2327  }
2328 
2329  return true;
2330  }
2331 
2340  protected function doInsert( $table, array $rows, $fname ) {
2341  $encTable = $this->tableName( $table );
2342  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
2343 
2344  $sql = "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples";
2345 
2346  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2347  }
2348 
2357  protected function doInsertNonConflicting( $table, array $rows, $fname ) {
2358  $encTable = $this->tableName( $table );
2359  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
2360  list( $sqlVerb, $sqlOpts ) = $this->makeInsertNonConflictingVerbAndOptions();
2361 
2362  $sql = rtrim( "$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" );
2363 
2364  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2365  }
2366 
2373  return [ 'INSERT IGNORE INTO', '' ];
2374  }
2375 
2386  protected function makeInsertLists( array $rows ) {
2387  $firstRow = $rows[0];
2388  if ( !is_array( $firstRow ) || !$firstRow ) {
2389  throw new DBUnexpectedError( $this, 'Got an empty row list or empty row' );
2390  }
2391  // List of columns that define the value tuple ordering
2392  $tupleColumns = array_keys( $firstRow );
2393 
2394  $valueTuples = [];
2395  foreach ( $rows as $row ) {
2396  $rowColumns = array_keys( $row );
2397  // VALUES(...) requires a uniform correspondance of (column => value)
2398  if ( $rowColumns !== $tupleColumns ) {
2399  throw new DBUnexpectedError(
2400  $this,
2401  'Got row columns (' . implode( ', ', $rowColumns ) . ') ' .
2402  'instead of expected (' . implode( ', ', $tupleColumns ) . ')'
2403  );
2404  }
2405  // Make the value tuple that defines this row
2406  $valueTuples[] = '(' . $this->makeList( $row, self::LIST_COMMA ) . ')';
2407  }
2408 
2409  return [
2410  $this->makeList( $tupleColumns, self::LIST_NAMES ),
2411  implode( ',', $valueTuples )
2412  ];
2413  }
2414 
2422  protected function makeUpdateOptionsArray( $options ) {
2423  $options = $this->normalizeOptions( $options );
2424 
2425  $opts = [];
2426 
2427  if ( in_array( 'IGNORE', $options ) ) {
2428  $opts[] = 'IGNORE';
2429  }
2430 
2431  return $opts;
2432  }
2433 
2441  protected function makeUpdateOptions( $options ) {
2442  $opts = $this->makeUpdateOptionsArray( $options );
2443 
2444  return implode( ' ', $opts );
2445  }
2446 
2447  public function update( $table, $set, $conds, $fname = __METHOD__, $options = [] ) {
2448  $this->assertConditionIsNotEmpty( $conds, __METHOD__, true );
2449  $table = $this->tableName( $table );
2450  $opts = $this->makeUpdateOptions( $options );
2451  $sql = "UPDATE $opts $table SET " . $this->makeList( $set, self::LIST_SET );
2452 
2453  if ( $conds && $conds !== IDatabase::ALL_ROWS ) {
2454  if ( is_array( $conds ) ) {
2455  $conds = $this->makeList( $conds, self::LIST_AND );
2456  }
2457  $sql .= ' WHERE ' . $conds;
2458  }
2459 
2460  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2461 
2462  return true;
2463  }
2464 
2465  public function makeList( array $a, $mode = self::LIST_COMMA ) {
2466  $first = true;
2467  $list = '';
2468 
2469  foreach ( $a as $field => $value ) {
2470  if ( $first ) {
2471  $first = false;
2472  } else {
2473  if ( $mode == self::LIST_AND ) {
2474  $list .= ' AND ';
2475  } elseif ( $mode == self::LIST_OR ) {
2476  $list .= ' OR ';
2477  } else {
2478  $list .= ',';
2479  }
2480  }
2481 
2482  if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
2483  $list .= "($value)";
2484  } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
2485  $list .= "$value";
2486  } elseif (
2487  ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
2488  ) {
2489  // Remove null from array to be handled separately if found
2490  $includeNull = false;
2491  foreach ( array_keys( $value, null, true ) as $nullKey ) {
2492  $includeNull = true;
2493  unset( $value[$nullKey] );
2494  }
2495  if ( count( $value ) == 0 && !$includeNull ) {
2496  throw new InvalidArgumentException(
2497  __METHOD__ . ": empty input for field $field" );
2498  } elseif ( count( $value ) == 0 ) {
2499  // only check if $field is null
2500  $list .= "$field IS NULL";
2501  } else {
2502  // IN clause contains at least one valid element
2503  if ( $includeNull ) {
2504  // Group subconditions to ensure correct precedence
2505  $list .= '(';
2506  }
2507  if ( count( $value ) == 1 ) {
2508  // Special-case single values, as IN isn't terribly efficient
2509  // Don't necessarily assume the single key is 0; we don't
2510  // enforce linear numeric ordering on other arrays here.
2511  $value = array_values( $value )[0];
2512  $list .= $field . " = " . $this->addQuotes( $value );
2513  } else {
2514  $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2515  }
2516  // if null present in array, append IS NULL
2517  if ( $includeNull ) {
2518  $list .= " OR $field IS NULL)";
2519  }
2520  }
2521  } elseif ( $value === null ) {
2522  if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2523  $list .= "$field IS ";
2524  } elseif ( $mode == self::LIST_SET ) {
2525  $list .= "$field = ";
2526  }
2527  $list .= 'NULL';
2528  } else {
2529  if (
2530  $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2531  ) {
2532  $list .= "$field = ";
2533  }
2534  $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
2535  }
2536  }
2537 
2538  return $list;
2539  }
2540 
2541  public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2542  $conds = [];
2543 
2544  foreach ( $data as $base => $sub ) {
2545  if ( count( $sub ) ) {
2546  $conds[] = $this->makeList(
2547  [ $baseKey => $base, $subKey => array_map( 'strval', array_keys( $sub ) ) ],
2549  );
2550  }
2551  }
2552 
2553  if ( $conds ) {
2554  return $this->makeList( $conds, self::LIST_OR );
2555  } else {
2556  // Nothing to search for...
2557  return false;
2558  }
2559  }
2560 
2565  public function aggregateValue( $valuedata, $valuename = 'value' ) {
2566  return $valuename;
2567  }
2568 
2573  public function bitNot( $field ) {
2574  return "(~$field)";
2575  }
2576 
2581  public function bitAnd( $fieldLeft, $fieldRight ) {
2582  return "($fieldLeft & $fieldRight)";
2583  }
2584 
2589  public function bitOr( $fieldLeft, $fieldRight ) {
2590  return "($fieldLeft | $fieldRight)";
2591  }
2592 
2597  public function buildConcat( $stringList ) {
2598  return 'CONCAT(' . implode( ',', $stringList ) . ')';
2599  }
2600 
2605  public function buildGroupConcatField(
2606  $delim, $table, $field, $conds = '', $join_conds = []
2607  ) {
2608  $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2609 
2610  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2611  }
2612 
2617  public function buildGreatest( $fields, $values ) {
2618  return $this->buildSuperlative( 'GREATEST', $fields, $values );
2619  }
2620 
2625  public function buildLeast( $fields, $values ) {
2626  return $this->buildSuperlative( 'LEAST', $fields, $values );
2627  }
2628 
2645  protected function buildSuperlative( $sqlfunc, $fields, $values ) {
2646  $fields = is_array( $fields ) ? $fields : [ $fields ];
2647  $values = is_array( $values ) ? $values : [ $values ];
2648 
2649  $encValues = [];
2650  foreach ( $fields as $alias => $field ) {
2651  if ( is_int( $alias ) ) {
2652  $encValues[] = $this->addIdentifierQuotes( $field );
2653  } else {
2654  $encValues[] = $field; // expression
2655  }
2656  }
2657  foreach ( $values as $value ) {
2658  if ( is_int( $value ) || is_float( $value ) ) {
2659  $encValues[] = $value;
2660  } elseif ( is_string( $value ) ) {
2661  $encValues[] = $this->addQuotes( $value );
2662  } elseif ( $value === null ) {
2663  throw new DBUnexpectedError( $this, 'Null value in superlative' );
2664  } else {
2665  throw new DBUnexpectedError( $this, 'Unexpected value type in superlative' );
2666  }
2667  }
2668 
2669  return $sqlfunc . '(' . implode( ',', $encValues ) . ')';
2670  }
2671 
2676  public function buildSubstring( $input, $startPosition, $length = null ) {
2677  $this->assertBuildSubstringParams( $startPosition, $length );
2678  $functionBody = "$input FROM $startPosition";
2679  if ( $length !== null ) {
2680  $functionBody .= " FOR $length";
2681  }
2682  return 'SUBSTRING(' . $functionBody . ')';
2683  }
2684 
2697  protected function assertBuildSubstringParams( $startPosition, $length ) {
2698  if ( $startPosition === 0 ) {
2699  // The DBMSs we support use 1-based indexing here.
2700  throw new InvalidArgumentException( 'Use 1 as $startPosition for the beginning of the string' );
2701  }
2702  if ( !is_int( $startPosition ) || $startPosition < 0 ) {
2703  throw new InvalidArgumentException(
2704  '$startPosition must be a positive integer'
2705  );
2706  }
2707  if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2708  throw new InvalidArgumentException(
2709  '$length must be null or an integer greater than or equal to 0'
2710  );
2711  }
2712  }
2713 
2727  protected function assertConditionIsNotEmpty( $conds, string $fname, bool $deprecate ) {
2728  $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
2729  if ( !$isCondValid ) {
2730  if ( $deprecate ) {
2731  wfDeprecated( $fname . ' called with empty $conds', '1.35', false, 3 );
2732  } else {
2733  throw new DBUnexpectedError( $this, $fname . ' called with empty conditions' );
2734  }
2735  }
2736  }
2737 
2742  public function buildStringCast( $field ) {
2743  // In theory this should work for any standards-compliant
2744  // SQL implementation, although it may not be the best way to do it.
2745  return "CAST( $field AS CHARACTER )";
2746  }
2747 
2752  public function buildIntegerCast( $field ) {
2753  return 'CAST( ' . $field . ' AS INTEGER )';
2754  }
2755 
2756  public function buildSelectSubquery(
2757  $table, $vars, $conds = '', $fname = __METHOD__,
2758  $options = [], $join_conds = []
2759  ) {
2760  return new Subquery(
2761  $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2762  );
2763  }
2764 
2769  public function databasesAreIndependent() {
2770  return false;
2771  }
2772 
2773  final public function selectDB( $db ) {
2774  $this->selectDomain( new DatabaseDomain(
2775  $db,
2776  $this->currentDomain->getSchema(),
2777  $this->currentDomain->getTablePrefix()
2778  ) );
2779 
2780  return true;
2781  }
2782 
2783  final public function selectDomain( $domain ) {
2784  $this->doSelectDomain( DatabaseDomain::newFromId( $domain ) );
2785  }
2786 
2794  protected function doSelectDomain( DatabaseDomain $domain ) {
2795  $this->currentDomain = $domain;
2796  }
2797 
2798  public function getDBname() {
2799  return $this->currentDomain->getDatabase();
2800  }
2801 
2802  public function getServer() {
2803  return $this->server;
2804  }
2805 
2810  public function tableName( $name, $format = 'quoted' ) {
2811  if ( $name instanceof Subquery ) {
2812  throw new DBUnexpectedError(
2813  $this,
2814  __METHOD__ . ': got Subquery instance when expecting a string'
2815  );
2816  }
2817 
2818  # Skip the entire process when we have a string quoted on both ends.
2819  # Note that we check the end so that we will still quote any use of
2820  # use of `database`.table. But won't break things if someone wants
2821  # to query a database table with a dot in the name.
2822  if ( $this->isQuotedIdentifier( $name ) ) {
2823  return $name;
2824  }
2825 
2826  # Lets test for any bits of text that should never show up in a table
2827  # name. Basically anything like JOIN or ON which are actually part of
2828  # SQL queries, but may end up inside of the table value to combine
2829  # sql. Such as how the API is doing.
2830  # Note that we use a whitespace test rather than a \b test to avoid
2831  # any remote case where a word like on may be inside of a table name
2832  # surrounded by symbols which may be considered word breaks.
2833  if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2834  $this->queryLogger->warning(
2835  __METHOD__ . ": use of subqueries is not supported this way",
2836  [ 'exception' => new RuntimeException() ]
2837  );
2838 
2839  return $name;
2840  }
2841 
2842  # Split database and table into proper variables.
2843  list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2844 
2845  # Quote $table and apply the prefix if not quoted.
2846  # $tableName might be empty if this is called from Database::replaceVars()
2847  $tableName = "{$prefix}{$table}";
2848  if ( $format === 'quoted'
2849  && !$this->isQuotedIdentifier( $tableName )
2850  && $tableName !== ''
2851  ) {
2852  $tableName = $this->addIdentifierQuotes( $tableName );
2853  }
2854 
2855  # Quote $schema and $database and merge them with the table name if needed
2856  $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2857  $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2858 
2859  return $tableName;
2860  }
2861 
2868  protected function qualifiedTableComponents( $name ) {
2869  # We reverse the explode so that database.table and table both output the correct table.
2870  $dbDetails = explode( '.', $name, 3 );
2871  if ( count( $dbDetails ) == 3 ) {
2872  list( $database, $schema, $table ) = $dbDetails;
2873  # We don't want any prefix added in this case
2874  $prefix = '';
2875  } elseif ( count( $dbDetails ) == 2 ) {
2876  list( $database, $table ) = $dbDetails;
2877  # We don't want any prefix added in this case
2878  $prefix = '';
2879  # In dbs that support it, $database may actually be the schema
2880  # but that doesn't affect any of the functionality here
2881  $schema = '';
2882  } else {
2883  list( $table ) = $dbDetails;
2884  if ( isset( $this->tableAliases[$table] ) ) {
2885  $database = $this->tableAliases[$table]['dbname'];
2886  $schema = is_string( $this->tableAliases[$table]['schema'] )
2887  ? $this->tableAliases[$table]['schema']
2888  : $this->relationSchemaQualifier();
2889  $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2890  ? $this->tableAliases[$table]['prefix']
2891  : $this->tablePrefix();
2892  } else {
2893  $database = '';
2894  $schema = $this->relationSchemaQualifier(); # Default schema
2895  $prefix = $this->tablePrefix(); # Default prefix
2896  }
2897  }
2898 
2899  return [ $database, $schema, $prefix, $table ];
2900  }
2901 
2908  private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2909  if ( strlen( $namespace ) ) {
2910  if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2911  $namespace = $this->addIdentifierQuotes( $namespace );
2912  }
2913  $relation = $namespace . '.' . $relation;
2914  }
2915 
2916  return $relation;
2917  }
2918 
2919  public function tableNames( ...$tables ) {
2920  $retVal = [];
2921 
2922  foreach ( $tables as $name ) {
2923  $retVal[$name] = $this->tableName( $name );
2924  }
2925 
2926  return $retVal;
2927  }
2928 
2929  public function tableNamesN( ...$tables ) {
2930  $retVal = [];
2931 
2932  foreach ( $tables as $name ) {
2933  $retVal[] = $this->tableName( $name );
2934  }
2935 
2936  return $retVal;
2937  }
2938 
2950  protected function tableNameWithAlias( $table, $alias = false ) {
2951  if ( is_string( $table ) ) {
2952  $quotedTable = $this->tableName( $table );
2953  } elseif ( $table instanceof Subquery ) {
2954  $quotedTable = (string)$table;
2955  } else {
2956  throw new InvalidArgumentException( "Table must be a string or Subquery" );
2957  }
2958 
2959  if ( $alias === false || $alias === $table ) {
2960  if ( $table instanceof Subquery ) {
2961  throw new InvalidArgumentException( "Subquery table missing alias" );
2962  }
2963 
2964  return $quotedTable;
2965  } else {
2966  return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2967  }
2968  }
2969 
2979  protected function fieldNameWithAlias( $name, $alias = false ) {
2980  if ( !$alias || (string)$alias === (string)$name ) {
2981  return $name;
2982  } else {
2983  return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2984  }
2985  }
2986 
2993  protected function fieldNamesWithAlias( $fields ) {
2994  $retval = [];
2995  foreach ( $fields as $alias => $field ) {
2996  if ( is_numeric( $alias ) ) {
2997  $alias = $field;
2998  }
2999  $retval[] = $this->fieldNameWithAlias( $field, $alias );
3000  }
3001 
3002  return $retval;
3003  }
3004 
3016  $tables,
3017  $use_index = [],
3018  $ignore_index = [],
3019  $join_conds = []
3020  ) {
3021  $ret = [];
3022  $retJOIN = [];
3023  $use_index = (array)$use_index;
3024  $ignore_index = (array)$ignore_index;
3025  $join_conds = (array)$join_conds;
3026 
3027  foreach ( $tables as $alias => $table ) {
3028  if ( !is_string( $alias ) ) {
3029  // No alias? Set it equal to the table name
3030  $alias = $table;
3031  }
3032 
3033  if ( is_array( $table ) ) {
3034  // A parenthesized group
3035  if ( count( $table ) > 1 ) {
3036  $joinedTable = '(' .
3038  $table, $use_index, $ignore_index, $join_conds ) . ')';
3039  } else {
3040  // Degenerate case
3041  $innerTable = reset( $table );
3042  $innerAlias = key( $table );
3043  $joinedTable = $this->tableNameWithAlias(
3044  $innerTable,
3045  is_string( $innerAlias ) ? $innerAlias : $innerTable
3046  );
3047  }
3048  } else {
3049  $joinedTable = $this->tableNameWithAlias( $table, $alias );
3050  }
3051 
3052  // Is there a JOIN clause for this table?
3053  if ( isset( $join_conds[$alias] ) ) {
3054  list( $joinType, $conds ) = $join_conds[$alias];
3055  $tableClause = $joinType;
3056  $tableClause .= ' ' . $joinedTable;
3057  if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
3058  $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
3059  if ( $use != '' ) {
3060  $tableClause .= ' ' . $use;
3061  }
3062  }
3063  if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
3064  $ignore = $this->ignoreIndexClause(
3065  implode( ',', (array)$ignore_index[$alias] ) );
3066  if ( $ignore != '' ) {
3067  $tableClause .= ' ' . $ignore;
3068  }
3069  }
3070  $on = $this->makeList( (array)$conds, self::LIST_AND );
3071  if ( $on != '' ) {
3072  $tableClause .= ' ON (' . $on . ')';
3073  }
3074 
3075  $retJOIN[] = $tableClause;
3076  } elseif ( isset( $use_index[$alias] ) ) {
3077  // Is there an INDEX clause for this table?
3078  $tableClause = $joinedTable;
3079  $tableClause .= ' ' . $this->useIndexClause(
3080  implode( ',', (array)$use_index[$alias] )
3081  );
3082 
3083  $ret[] = $tableClause;
3084  } elseif ( isset( $ignore_index[$alias] ) ) {
3085  // Is there an INDEX clause for this table?
3086  $tableClause = $joinedTable;
3087  $tableClause .= ' ' . $this->ignoreIndexClause(
3088  implode( ',', (array)$ignore_index[$alias] )
3089  );
3090 
3091  $ret[] = $tableClause;
3092  } else {
3093  $tableClause = $joinedTable;
3094 
3095  $ret[] = $tableClause;
3096  }
3097  }
3098 
3099  // We can't separate explicit JOIN clauses with ',', use ' ' for those
3100  $implicitJoins = implode( ',', $ret );
3101  $explicitJoins = implode( ' ', $retJOIN );
3102 
3103  // Compile our final table clause
3104  return implode( ' ', [ $implicitJoins, $explicitJoins ] );
3105  }
3106 
3113  protected function indexName( $index ) {
3114  return $this->indexAliases[$index] ?? $index;
3115  }
3116 
3121  public function addQuotes( $s ) {
3122  if ( $s instanceof Blob ) {
3123  $s = $s->fetch();
3124  }
3125  if ( $s === null ) {
3126  return 'NULL';
3127  } elseif ( is_bool( $s ) ) {
3128  return (string)(int)$s;
3129  } elseif ( is_int( $s ) ) {
3130  return (string)$s;
3131  } else {
3132  return "'" . $this->strencode( $s ) . "'";
3133  }
3134  }
3135 
3140  public function addIdentifierQuotes( $s ) {
3141  return '"' . str_replace( '"', '""', $s ) . '"';
3142  }
3143 
3154  public function isQuotedIdentifier( $name ) {
3155  return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
3156  }
3157 
3164  protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
3165  return str_replace(
3166  [ $escapeChar, '%', '_' ],
3167  [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
3168  $s
3169  );
3170  }
3171 
3176  public function buildLike( $param, ...$params ) {
3177  if ( is_array( $param ) ) {
3178  $params = $param;
3179  } else {
3180  $params = func_get_args();
3181  }
3182 
3183  $s = '';
3184 
3185  // We use ` instead of \ as the default LIKE escape character, since addQuotes()
3186  // may escape backslashes, creating problems of double escaping. The `
3187  // character has good cross-DBMS compatibility, avoiding special operators
3188  // in MS SQL like ^ and %
3189  $escapeChar = '`';
3190 
3191  foreach ( $params as $value ) {
3192  if ( $value instanceof LikeMatch ) {
3193  $s .= $value->toString();
3194  } else {
3195  $s .= $this->escapeLikeInternal( $value, $escapeChar );
3196  }
3197  }
3198 
3199  return ' LIKE ' .
3200  $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
3201  }
3202 
3203  public function anyChar() {
3204  return new LikeMatch( '_' );
3205  }
3206 
3207  public function anyString() {
3208  return new LikeMatch( '%' );
3209  }
3210 
3211  public function nextSequenceValue( $seqName ) {
3212  return null;
3213  }
3214 
3227  public function useIndexClause( $index ) {
3228  return '';
3229  }
3230 
3243  public function ignoreIndexClause( $index ) {
3244  return '';
3245  }
3246 
3247  public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
3248  $rows = $this->normalizeRowArray( $rows );
3249  if ( !$rows ) {
3250  return;
3251  }
3252 
3253  if ( $uniqueKeys ) {
3254  $uniqueKeys = $this->normalizeUpsertKeys( $uniqueKeys );
3255  $this->doReplace( $table, $uniqueKeys, $rows, $fname );
3256  } else {
3257  $this->queryLogger->warning(
3258  __METHOD__ . " called with no unique keys",
3259  [ 'exception' => new RuntimeException() ]
3260  );
3261  $this->doInsert( $table, $rows, $fname );
3262  }
3263  }
3264 
3274  protected function doReplace( $table, array $uniqueKeys, array $rows, $fname ) {
3275  $affectedRowCount = 0;
3276  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3277  try {
3278  foreach ( $rows as $row ) {
3279  // Delete any conflicting rows (including ones inserted from $rows)
3280  $sqlCondition = $this->makeConditionCollidesUponKeys( [ $row ], $uniqueKeys );
3281  $this->delete( $table, [ $sqlCondition ], $fname );
3282  $affectedRowCount += $this->affectedRows();
3283  // Now insert the row
3284  $this->insert( $table, $row, $fname );
3285  $affectedRowCount += $this->affectedRows();
3286  }
3287  $this->endAtomic( $fname );
3288  } catch ( Throwable $e ) {
3289  $this->cancelAtomic( $fname );
3290  throw $e;
3291  }
3292  $this->affectedRowCount = $affectedRowCount;
3293  }
3294 
3300  private function makeConditionCollidesUponKey( array $rows, array $uniqueKey ) {
3301  if ( !$rows ) {
3302  throw new DBUnexpectedError( $this, "Empty row array" );
3303  } elseif ( !$uniqueKey ) {
3304  throw new DBUnexpectedError( $this, "Empty unique key array" );
3305  }
3306 
3307  if ( count( $uniqueKey ) == 1 ) {
3308  // Use a simple IN(...) clause
3309  $column = reset( $uniqueKey );
3310  $values = array_column( $rows, $column );
3311  if ( count( $values ) !== count( $rows ) ) {
3312  throw new DBUnexpectedError( $this, "Missing values for unique key ($column)" );
3313  }
3314 
3315  return $this->makeList( [ $column => $values ], self::LIST_AND );
3316  }
3317 
3318  $disjunctions = [];
3319  foreach ( $rows as $row ) {
3320  $rowKeyMap = array_intersect_key( $row, array_flip( $uniqueKey ) );
3321  if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
3322  throw new DBUnexpectedError(
3323  $this,
3324  "Missing values for unique key (" . implode( ',', $uniqueKey ) . ")"
3325  );
3326  }
3327  $disjunctions[] = $this->makeList( $rowKeyMap, self::LIST_AND );
3328  }
3329 
3330  return count( $disjunctions ) > 1
3331  ? $this->makeList( $disjunctions, self::LIST_OR )
3332  : $disjunctions[0];
3333  }
3334 
3341  final protected function makeConditionCollidesUponKeys( array $rows, array $uniqueKeys ) {
3342  if ( !$uniqueKeys ) {
3343  throw new DBUnexpectedError( $this, "Empty unique key array" );
3344  }
3345 
3346  $disjunctions = [];
3347  foreach ( $uniqueKeys as $uniqueKey ) {
3348  $disjunctions[] = $this->makeConditionCollidesUponKey( $rows, $uniqueKey );
3349  }
3350 
3351  return count( $disjunctions ) > 1
3352  ? $this->makeList( $disjunctions, self::LIST_OR )
3353  : $disjunctions[0];
3354  }
3355 
3356  public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
3357  $rows = $this->normalizeRowArray( $rows );
3358  if ( !$rows ) {
3359  return true;
3360  }
3361 
3362  if ( $uniqueKeys ) {
3363  $uniqueKeys = $this->normalizeUpsertKeys( $uniqueKeys );
3364  $this->doUpsert( $table, $rows, $uniqueKeys, $set, $fname );
3365  } else {
3366  $this->queryLogger->warning(
3367  __METHOD__ . " called with no unique keys",
3368  [ 'exception' => new RuntimeException() ]
3369  );
3370  $this->doInsert( $table, $rows, $fname );
3371  }
3372 
3373  return true;
3374  }
3375 
3386  protected function doUpsert( $table, array $rows, array $uniqueKeys, array $set, $fname ) {
3387  $affectedRowCount = 0;
3388  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3389  try {
3390  foreach ( $rows as $row ) {
3391  // Update any existing conflicting rows (including ones inserted from $rows)
3392  $sqlConditions = $this->makeConditionCollidesUponKeys( [ $row ], $uniqueKeys );
3393  $this->update( $table, $set, [ $sqlConditions ], $fname );
3394  $rowsUpdated = $this->affectedRows();
3395  $affectedRowCount += $rowsUpdated;
3396  if ( $rowsUpdated <= 0 ) {
3397  // Now insert the row if there are no conflicts
3398  $this->insert( $table, $row, $fname );
3399  $affectedRowCount += $this->affectedRows();
3400  }
3401  }
3402  $this->endAtomic( $fname );
3403  } catch ( Throwable $e ) {
3404  $this->cancelAtomic( $fname );
3405  throw $e;
3406  }
3407  $this->affectedRowCount = $affectedRowCount;
3408  }
3409 
3414  public function deleteJoin(
3415  $delTable,
3416  $joinTable,
3417  $delVar,
3418  $joinVar,
3419  $conds,
3420  $fname = __METHOD__
3421  ) {
3422  if ( !$conds ) {
3423  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
3424  }
3425 
3426  $delTable = $this->tableName( $delTable );
3427  $joinTable = $this->tableName( $joinTable );
3428  $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3429  if ( $conds != '*' ) {
3430  $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
3431  }
3432  $sql .= ')';
3433 
3434  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3435  }
3436 
3441  public function textFieldSize( $table, $field ) {
3442  $table = $this->tableName( $table );
3443  $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
3444  $res = $this->query( $sql, __METHOD__, self::QUERY_CHANGE_NONE );
3445  $row = $this->fetchObject( $res );
3446 
3447  $m = [];
3448 
3449  if ( preg_match( '/\‍((.*)\‍)/', $row->Type, $m ) ) {
3450  $size = $m[1];
3451  } else {
3452  $size = -1;
3453  }
3454 
3455  return $size;
3456  }
3457 
3458  public function delete( $table, $conds, $fname = __METHOD__ ) {
3459  $this->assertConditionIsNotEmpty( $conds, __METHOD__, false );
3460 
3461  $table = $this->tableName( $table );
3462  $sql = "DELETE FROM $table";
3463 
3464  if ( $conds !== IDatabase::ALL_ROWS ) {
3465  if ( is_array( $conds ) ) {
3466  $conds = $this->makeList( $conds, self::LIST_AND );
3467  }
3468  $sql .= ' WHERE ' . $conds;
3469  }
3470 
3471  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3472 
3473  return true;
3474  }
3475 
3476  final public function insertSelect(
3477  $destTable,
3478  $srcTable,
3479  $varMap,
3480  $conds,
3481  $fname = __METHOD__,
3482  $insertOptions = [],
3483  $selectOptions = [],
3484  $selectJoinConds = []
3485  ) {
3486  static $hints = [ 'NO_AUTO_COLUMNS' ];
3487 
3488  $insertOptions = $this->normalizeOptions( $insertOptions );
3489  $selectOptions = $this->normalizeOptions( $selectOptions );
3490 
3491  if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3492  // For massive migrations with downtime, we don't want to select everything
3493  // into memory and OOM, so do all this native on the server side if possible.
3494  $this->doInsertSelectNative(
3495  $destTable,
3496  $srcTable,
3497  $varMap,
3498  $conds,
3499  $fname,
3500  array_diff( $insertOptions, $hints ),
3501  $selectOptions,
3502  $selectJoinConds
3503  );
3504  } else {
3505  $this->doInsertSelectGeneric(
3506  $destTable,
3507  $srcTable,
3508  $varMap,
3509  $conds,
3510  $fname,
3511  array_diff( $insertOptions, $hints ),
3512  $selectOptions,
3513  $selectJoinConds
3514  );
3515  }
3516 
3517  return true;
3518  }
3519 
3527  protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3528  return true;
3529  }
3530 
3545  protected function doInsertSelectGeneric(
3546  $destTable,
3547  $srcTable,
3548  array $varMap,
3549  $conds,
3550  $fname,
3551  array $insertOptions,
3552  array $selectOptions,
3553  $selectJoinConds
3554  ) {
3555  // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3556  // on only the master (without needing row-based-replication). It also makes it easy to
3557  // know how big the INSERT is going to be.
3558  $fields = [];
3559  foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3560  $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3561  }
3562  $res = $this->select(
3563  $srcTable,
3564  implode( ',', $fields ),
3565  $conds,
3566  $fname,
3567  array_merge( $selectOptions, [ 'FOR UPDATE' ] ),
3568  $selectJoinConds
3569  );
3570  if ( !$res ) {
3571  return;
3572  }
3573 
3574  $affectedRowCount = 0;
3575  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3576  try {
3577  $rows = [];
3578  foreach ( $res as $row ) {
3579  $rows[] = (array)$row;
3580  }
3581  // Avoid inserts that are too huge
3582  $rowBatches = array_chunk( $rows, $this->nonNativeInsertSelectBatchSize );
3583  foreach ( $rowBatches as $rows ) {
3584  $this->insert( $destTable, $rows, $fname, $insertOptions );
3585  $affectedRowCount += $this->affectedRows();
3586  }
3587  } catch ( Throwable $e ) {
3588  $this->cancelAtomic( $fname );
3589  throw $e;
3590  }
3591  $this->endAtomic( $fname );
3592  $this->affectedRowCount = $affectedRowCount;
3593  }
3594 
3610  protected function doInsertSelectNative(
3611  $destTable,
3612  $srcTable,
3613  array $varMap,
3614  $conds,
3615  $fname,
3616  array $insertOptions,
3617  array $selectOptions,
3618  $selectJoinConds
3619  ) {
3620  list( $sqlVerb, $sqlOpts ) = $this->isFlagInOptions( 'IGNORE', $insertOptions )
3622  : [ 'INSERT INTO', '' ];
3623  $encDstTable = $this->tableName( $destTable );
3624  $sqlDstColumns = implode( ',', array_keys( $varMap ) );
3625  $selectSql = $this->selectSQLText(
3626  $srcTable,
3627  array_values( $varMap ),
3628  $conds,
3629  $fname,
3630  $selectOptions,
3631  $selectJoinConds
3632  );
3633 
3634  $sql = rtrim( "$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
3635 
3636  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3637  }
3638 
3643  public function limitResult( $sql, $limit, $offset = false ) {
3644  if ( !is_numeric( $limit ) ) {
3645  throw new DBUnexpectedError(
3646  $this,
3647  "Invalid non-numeric limit passed to " . __METHOD__
3648  );
3649  }
3650  // This version works in MySQL and SQLite. It will very likely need to be
3651  // overridden for most other RDBMS subclasses.
3652  return "$sql LIMIT "
3653  . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3654  . "{$limit} ";
3655  }
3656 
3661  public function unionSupportsOrderAndLimit() {
3662  return true; // True for almost every DB supported
3663  }
3664 
3669  public function unionQueries( $sqls, $all ) {
3670  $glue = $all ? ') UNION ALL (' : ') UNION (';
3671 
3672  return '(' . implode( $glue, $sqls ) . ')';
3673  }
3674 
3676  $table,
3677  $vars,
3678  array $permute_conds,
3679  $extra_conds = '',
3680  $fname = __METHOD__,
3681  $options = [],
3682  $join_conds = []
3683  ) {
3684  // First, build the Cartesian product of $permute_conds
3685  $conds = [ [] ];
3686  foreach ( $permute_conds as $field => $values ) {
3687  if ( !$values ) {
3688  // Skip empty $values
3689  continue;
3690  }
3691  $values = array_unique( $values ); // For sanity
3692  $newConds = [];
3693  foreach ( $conds as $cond ) {
3694  foreach ( $values as $value ) {
3695  $cond[$field] = $value;
3696  $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3697  }
3698  }
3699  $conds = $newConds;
3700  }
3701 
3702  $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
3703 
3704  // If there's just one condition and no subordering, hand off to
3705  // selectSQLText directly.
3706  if ( count( $conds ) === 1 &&
3707  ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
3708  ) {
3709  return $this->selectSQLText(
3710  $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
3711  );
3712  }
3713 
3714  // Otherwise, we need to pull out the order and limit to apply after
3715  // the union. Then build the SQL queries for each set of conditions in
3716  // $conds. Then union them together (using UNION ALL, because the
3717  // product *should* already be distinct).
3718  $orderBy = $this->makeOrderBy( $options );
3719  $limit = $options['LIMIT'] ?? null;
3720  $offset = $options['OFFSET'] ?? false;
3721  $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3722  if ( !$this->unionSupportsOrderAndLimit() ) {
3723  unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3724  } else {
3725  if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3726  $options['ORDER BY'] = $options['INNER ORDER BY'];
3727  }
3728  if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3729  // We need to increase the limit by the offset rather than
3730  // using the offset directly, otherwise it'll skip incorrectly
3731  // in the subqueries.
3732  $options['LIMIT'] = $limit + $offset;
3733  unset( $options['OFFSET'] );
3734  }
3735  }
3736 
3737  $sqls = [];
3738  foreach ( $conds as $cond ) {
3739  $sqls[] = $this->selectSQLText(
3740  $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
3741  );
3742  }
3743  $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3744  if ( $limit !== null ) {
3745  $sql = $this->limitResult( $sql, $limit, $offset );
3746  }
3747 
3748  return $sql;
3749  }
3750 
3755  public function conditional( $cond, $trueVal, $falseVal ) {
3756  if ( is_array( $cond ) ) {
3757  $cond = $this->makeList( $cond, self::LIST_AND );
3758  }
3759 
3760  return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3761  }
3762 
3767  public function strreplace( $orig, $old, $new ) {
3768  return "REPLACE({$orig}, {$old}, {$new})";
3769  }
3770 
3775  public function getServerUptime() {
3776  return 0;
3777  }
3778 
3783  public function wasDeadlock() {
3784  return false;
3785  }
3786 
3791  public function wasLockTimeout() {
3792  return false;
3793  }
3794 
3799  public function wasConnectionLoss() {
3800  return $this->wasConnectionError( $this->lastErrno() );
3801  }
3802 
3807  public function wasReadOnlyError() {
3808  return false;
3809  }
3810 
3811  public function wasErrorReissuable() {
3812  return (
3813  $this->wasDeadlock() ||
3814  $this->wasLockTimeout() ||
3815  $this->wasConnectionLoss()
3816  );
3817  }
3818 
3826  public function wasConnectionError( $errno ) {
3827  return false;
3828  }
3829 
3837  protected function wasKnownStatementRollbackError() {
3838  return false; // don't know; it could have caused a transaction rollback
3839  }
3840 
3845  public function deadlockLoop( ...$args ) {
3846  $function = array_shift( $args );
3847  $tries = self::$DEADLOCK_TRIES;
3848 
3849  $this->begin( __METHOD__ );
3850 
3851  $retVal = null;
3853  $e = null;
3854  do {
3855  try {
3856  $retVal = $function( ...$args );
3857  break;
3858  } catch ( DBQueryError $e ) {
3859  if ( $this->wasDeadlock() ) {
3860  // Retry after a randomized delay
3861  usleep( mt_rand( self::$DEADLOCK_DELAY_MIN, self::$DEADLOCK_DELAY_MAX ) );
3862  } else {
3863  // Throw the error back up
3864  throw $e;
3865  }
3866  }
3867  } while ( --$tries > 0 );
3868 
3869  if ( $tries <= 0 ) {
3870  // Too many deadlocks; give up
3871  $this->rollback( __METHOD__ );
3872  throw $e;
3873  } else {
3874  $this->commit( __METHOD__ );
3875 
3876  return $retVal;
3877  }
3878  }
3879 
3884  public function masterPosWait( DBMasterPos $pos, $timeout ) {
3885  # Real waits are implemented in the subclass.
3886  return 0;
3887  }
3888 
3893  public function getReplicaPos() {
3894  # Stub
3895  return false;
3896  }
3897 
3902  public function getMasterPos() {
3903  # Stub
3904  return false;
3905  }
3906 
3911  public function serverIsReadOnly() {
3912  return false;
3913  }
3914 
3915  final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3916  if ( !$this->trxLevel() ) {
3917  throw new DBUnexpectedError( $this, "No transaction is active" );
3918  }
3919  $this->trxEndCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3920  }
3921 
3922  final public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3923  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3924  // Start an implicit transaction similar to how query() does
3925  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3926  $this->trxAutomatic = true;
3927  }
3928 
3929  $this->trxPostCommitOrIdleCallbacks[] = [
3930  $callback,
3931  $fname,
3932  $this->currentAtomicSectionId()
3933  ];
3934 
3935  if ( !$this->trxLevel() ) {
3936  $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3937  }
3938  }
3939 
3940  final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3941  $this->onTransactionCommitOrIdle( $callback, $fname );
3942  }
3943 
3944  final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3945  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3946  // Start an implicit transaction similar to how query() does
3947  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3948  $this->trxAutomatic = true;
3949  }
3950 
3951  if ( $this->trxLevel() ) {
3952  $this->trxPreCommitOrIdleCallbacks[] = [
3953  $callback,
3954  $fname,
3955  $this->currentAtomicSectionId()
3956  ];
3957  } else {
3958  // No transaction is active nor will start implicitly, so make one for this callback
3959  $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3960  try {
3961  $callback( $this );
3962  $this->endAtomic( __METHOD__ );
3963  } catch ( Throwable $e ) {
3964  $this->cancelAtomic( __METHOD__ );
3965  throw $e;
3966  }
3967  }
3968  }
3969 
3970  final public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ) {
3971  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3972  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3973  }
3974  $this->trxSectionCancelCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3975  }
3976 
3980  private function currentAtomicSectionId() {
3981  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
3982  $levelInfo = end( $this->trxAtomicLevels );
3983 
3984  return $levelInfo[1];
3985  }
3986 
3987  return null;
3988  }
3989 
3999  ) {
4000  foreach ( $this->trxPreCommitOrIdleCallbacks as $key => $info ) {
4001  if ( $info[2] === $old ) {
4002  $this->trxPreCommitOrIdleCallbacks[$key][2] = $new;
4003  }
4004  }
4005  foreach ( $this->trxPostCommitOrIdleCallbacks as $key => $info ) {
4006  if ( $info[2] === $old ) {
4007  $this->trxPostCommitOrIdleCallbacks[$key][2] = $new;
4008  }
4009  }
4010  foreach ( $this->trxEndCallbacks as $key => $info ) {
4011  if ( $info[2] === $old ) {
4012  $this->trxEndCallbacks[$key][2] = $new;
4013  }
4014  }
4015  foreach ( $this->trxSectionCancelCallbacks as $key => $info ) {
4016  if ( $info[2] === $old ) {
4017  $this->trxSectionCancelCallbacks[$key][2] = $new;
4018  }
4019  }
4020  }
4021 
4041  private function modifyCallbacksForCancel(
4042  array $sectionIds,
4043  AtomicSectionIdentifier $newSectionId = null
4044  ) {
4045  // Cancel the "on commit" callbacks owned by this savepoint
4046  $this->trxPostCommitOrIdleCallbacks = array_filter(
4047  $this->trxPostCommitOrIdleCallbacks,
4048  function ( $entry ) use ( $sectionIds ) {
4049  return !in_array( $entry[2], $sectionIds, true );
4050  }
4051  );
4052  $this->trxPreCommitOrIdleCallbacks = array_filter(
4053  $this->trxPreCommitOrIdleCallbacks,
4054  function ( $entry ) use ( $sectionIds ) {
4055  return !in_array( $entry[2], $sectionIds, true );
4056  }
4057  );
4058  // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
4059  foreach ( $this->trxEndCallbacks as $key => $entry ) {
4060  if ( in_array( $entry[2], $sectionIds, true ) ) {
4061  $callback = $entry[0];
4062  $this->trxEndCallbacks[$key][0] = function () use ( $callback ) {
4063  return $callback( self::TRIGGER_ROLLBACK, $this );
4064  };
4065  // This "on resolution" callback no longer belongs to a section.
4066  $this->trxEndCallbacks[$key][2] = null;
4067  }
4068  }
4069  // Hoist callback ownership for section cancel callbacks to the new top section
4070  foreach ( $this->trxSectionCancelCallbacks as $key => $entry ) {
4071  if ( in_array( $entry[2], $sectionIds, true ) ) {
4072  $this->trxSectionCancelCallbacks[$key][2] = $newSectionId;
4073  }
4074  }
4075  }
4076 
4077  final public function setTransactionListener( $name, callable $callback = null ) {
4078  if ( $callback ) {
4079  $this->trxRecurringCallbacks[$name] = $callback;
4080  } else {
4081  unset( $this->trxRecurringCallbacks[$name] );
4082  }
4083  }
4084 
4093  final public function setTrxEndCallbackSuppression( $suppress ) {
4094  $this->trxEndCallbacksSuppressed = $suppress;
4095  }
4096 
4107  public function runOnTransactionIdleCallbacks( $trigger ) {
4108  if ( $this->trxLevel() ) { // sanity
4109  throw new DBUnexpectedError( $this, __METHOD__ . ': a transaction is still open' );
4110  }
4111 
4112  if ( $this->trxEndCallbacksSuppressed ) {
4113  return 0;
4114  }
4115 
4116  $count = 0;
4117  $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
4119  $e = null; // first exception
4120  do { // callbacks may add callbacks :)
4121  $callbacks = array_merge(
4122  $this->trxPostCommitOrIdleCallbacks,
4123  $this->trxEndCallbacks // include "transaction resolution" callbacks
4124  );
4125  $this->trxPostCommitOrIdleCallbacks = []; // consumed (and recursion guard)
4126  $this->trxEndCallbacks = []; // consumed (recursion guard)
4127 
4128  // Only run trxSectionCancelCallbacks on rollback, not commit.
4129  // But always consume them.
4130  if ( $trigger === self::TRIGGER_ROLLBACK ) {
4131  $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks );
4132  }
4133  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
4134 
4135  foreach ( $callbacks as $callback ) {
4136  ++$count;
4137  list( $phpCallback ) = $callback;
4138  $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
4139  try {
4140  call_user_func( $phpCallback, $trigger, $this );
4141  } catch ( Throwable $ex ) {
4142  call_user_func( $this->errorLogger, $ex );
4143  $e = $e ?: $ex;
4144  // Some callbacks may use startAtomic/endAtomic, so make sure
4145  // their transactions are ended so other callbacks don't fail
4146  if ( $this->trxLevel() ) {
4147  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
4148  }
4149  } finally {
4150  if ( $autoTrx ) {
4151  $this->setFlag( self::DBO_TRX ); // restore automatic begin()
4152  } else {
4153  $this->clearFlag( self::DBO_TRX ); // restore auto-commit
4154  }
4155  }
4156  }
4157  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4158  } while ( count( $this->trxPostCommitOrIdleCallbacks ) );
4159 
4160  if ( $e instanceof Throwable ) {
4161  throw $e; // re-throw any first exception
4162  }
4163 
4164  return $count;
4165  }
4166 
4177  $count = 0;
4178 
4179  $e = null; // first exception
4180  do { // callbacks may add callbacks :)
4182  $this->trxPreCommitOrIdleCallbacks = []; // consumed (and recursion guard)
4183  foreach ( $callbacks as $callback ) {
4184  try {
4185  ++$count;
4186  list( $phpCallback ) = $callback;
4187  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
4188  $phpCallback( $this );
4189  } catch ( Throwable $ex ) {
4190  ( $this->errorLogger )( $ex );
4191  $e = $e ?: $ex;
4192  }
4193  }
4194  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4195  } while ( count( $this->trxPreCommitOrIdleCallbacks ) );
4196 
4197  if ( $e instanceof Throwable ) {
4198  throw $e; // re-throw any first exception
4199  }
4200 
4201  return $count;
4202  }
4203 
4212  $trigger, array $sectionIds = null
4213  ) {
4215  $e = null; // first exception
4216 
4217  $notCancelled = [];
4218  do {
4219  $callbacks = $this->trxSectionCancelCallbacks;
4220  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
4221  foreach ( $callbacks as $entry ) {
4222  if ( $sectionIds === null || in_array( $entry[2], $sectionIds, true ) ) {
4223  try {
4224  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
4225  $entry[0]( $trigger, $this );
4226  } catch ( Throwable $ex ) {
4227  ( $this->errorLogger )( $ex );
4228  $e = $e ?: $ex;
4229  }
4230  } else {
4231  $notCancelled[] = $entry;
4232  }
4233  }
4234  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4235  } while ( count( $this->trxSectionCancelCallbacks ) );
4236  $this->trxSectionCancelCallbacks = $notCancelled;
4237 
4238  if ( $e !== null ) {
4239  throw $e; // re-throw any first Throwable
4240  }
4241  }
4242 
4252  public function runTransactionListenerCallbacks( $trigger ) {
4253  if ( $this->trxEndCallbacksSuppressed ) {
4254  return;
4255  }
4256 
4258  $e = null; // first exception
4259 
4260  foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
4261  try {
4262  $phpCallback( $trigger, $this );
4263  } catch ( Throwable $ex ) {
4264  ( $this->errorLogger )( $ex );
4265  $e = $e ?: $ex;
4266  }
4267  }
4268 
4269  if ( $e instanceof Throwable ) {
4270  throw $e; // re-throw any first exception
4271  }
4272  }
4273 
4285  protected function doSavepoint( $identifier, $fname ) {
4286  $sql = 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4287  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4288  }
4289 
4301  protected function doReleaseSavepoint( $identifier, $fname ) {
4302  $sql = 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4303  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4304  }
4305 
4317  protected function doRollbackToSavepoint( $identifier, $fname ) {
4318  $sql = 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4319  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4320  }
4321 
4326  private function nextSavepointId( $fname ) {
4327  $savepointId = self::$SAVEPOINT_PREFIX . ++$this->trxAtomicCounter;
4328  if ( strlen( $savepointId ) > 30 ) {
4329  // 30 == Oracle's identifier length limit (pre 12c)
4330  // With a 22 character prefix, that puts the highest number at 99999999.
4331  throw new DBUnexpectedError(
4332  $this,
4333  'There have been an excessively large number of atomic sections in a transaction'
4334  . " started by $this->trxFname (at $fname)"
4335  );
4336  }
4337 
4338  return $savepointId;
4339  }
4340 
4341  final public function startAtomic(
4342  $fname = __METHOD__,
4343  $cancelable = self::ATOMIC_NOT_CANCELABLE
4344  ) {
4345  $savepointId = $cancelable === self::ATOMIC_CANCELABLE ? self::$NOT_APPLICABLE : null;
4346 
4347  if ( !$this->trxLevel() ) {
4348  $this->begin( $fname, self::TRANSACTION_INTERNAL ); // sets trxAutomatic
4349  // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
4350  // in all changes being in one transaction to keep requests transactional.
4351  if ( $this->getFlag( self::DBO_TRX ) ) {
4352  // Since writes could happen in between the topmost atomic sections as part
4353  // of the transaction, those sections will need savepoints.
4354  $savepointId = $this->nextSavepointId( $fname );
4355  $this->doSavepoint( $savepointId, $fname );
4356  } else {
4357  $this->trxAutomaticAtomic = true;
4358  }
4359  } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
4360  $savepointId = $this->nextSavepointId( $fname );
4361  $this->doSavepoint( $savepointId, $fname );
4362  }
4363 
4364  $sectionId = new AtomicSectionIdentifier;
4365  $this->trxAtomicLevels[] = [ $fname, $sectionId, $savepointId ];
4366  $this->queryLogger->debug( 'startAtomic: entering level ' .
4367  ( count( $this->trxAtomicLevels ) - 1 ) . " ($fname)" );
4368 
4369  return $sectionId;
4370  }
4371 
4372  final public function endAtomic( $fname = __METHOD__ ) {
4373  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
4374  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
4375  }
4376 
4377  // Check if the current section matches $fname
4378  $pos = count( $this->trxAtomicLevels ) - 1;
4379  list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
4380  $this->queryLogger->debug( "endAtomic: leaving level $pos ($fname)" );
4381 
4382  if ( $savedFname !== $fname ) {
4383  throw new DBUnexpectedError(
4384  $this,
4385  "Invalid atomic section ended (got $fname but expected $savedFname)"
4386  );
4387  }
4388 
4389  // Remove the last section (no need to re-index the array)
4390  array_pop( $this->trxAtomicLevels );
4391 
4392  if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
4393  $this->commit( $fname, self::FLUSHING_INTERNAL );
4394  } elseif ( $savepointId !== null && $savepointId !== self::$NOT_APPLICABLE ) {
4395  $this->doReleaseSavepoint( $savepointId, $fname );
4396  }
4397 
4398  // Hoist callback ownership for callbacks in the section that just ended;
4399  // all callbacks should have an owner that is present in trxAtomicLevels.
4400  $currentSectionId = $this->currentAtomicSectionId();
4401  if ( $currentSectionId ) {
4402  $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
4403  }
4404  }
4405 
4406  final public function cancelAtomic(
4407  $fname = __METHOD__,
4408  AtomicSectionIdentifier $sectionId = null
4409  ) {
4410  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
4411  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
4412  }
4413 
4414  $excisedIds = [];
4415  $newTopSection = $this->currentAtomicSectionId();
4416  try {
4417  $excisedFnames = [];
4418  if ( $sectionId !== null ) {
4419  // Find the (last) section with the given $sectionId
4420  $pos = -1;
4421  foreach ( $this->trxAtomicLevels as $i => list( $asFname, $asId, $spId ) ) {
4422  if ( $asId === $sectionId ) {
4423  $pos = $i;
4424  }
4425  }
4426  if ( $pos < 0 ) {
4427  throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
4428  }
4429  // Remove all descendant sections and re-index the array
4430  $len = count( $this->trxAtomicLevels );
4431  for ( $i = $pos + 1; $i < $len; ++$i ) {
4432  $excisedFnames[] = $this->trxAtomicLevels[$i][0];
4433  $excisedIds[] = $this->trxAtomicLevels[$i][1];
4434  }
4435  $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
4436  $newTopSection = $this->currentAtomicSectionId();
4437  }
4438 
4439  // Check if the current section matches $fname
4440  $pos = count( $this->trxAtomicLevels ) - 1;
4441  list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
4442 
4443  if ( $excisedFnames ) {
4444  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
4445  "and descendants " . implode( ', ', $excisedFnames ) );
4446  } else {
4447  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
4448  }
4449 
4450  if ( $savedFname !== $fname ) {
4451  throw new DBUnexpectedError(
4452  $this,
4453  "Invalid atomic section ended (got $fname but expected $savedFname)"
4454  );
4455  }
4456 
4457  // Remove the last section (no need to re-index the array)
4458  array_pop( $this->trxAtomicLevels );
4459  $excisedIds[] = $savedSectionId;
4460  $newTopSection = $this->currentAtomicSectionId();
4461 
4462  if ( $savepointId !== null ) {
4463  // Rollback the transaction to the state just before this atomic section
4464  if ( $savepointId === self::$NOT_APPLICABLE ) {
4465  $this->rollback( $fname, self::FLUSHING_INTERNAL );
4466  // Note: rollback() will run trxSectionCancelCallbacks
4467  } else {
4468  $this->doRollbackToSavepoint( $savepointId, $fname );
4469  $this->trxStatus = self::STATUS_TRX_OK; // no exception; recovered
4470  $this->trxStatusIgnoredCause = null;
4471 
4472  // Run trxSectionCancelCallbacks now.
4473  $this->runOnAtomicSectionCancelCallbacks( self::TRIGGER_CANCEL, $excisedIds );
4474  }
4475  } elseif ( $this->trxStatus > self::STATUS_TRX_ERROR ) {
4476  // Put the transaction into an error state if it's not already in one
4477  $this->trxStatus = self::STATUS_TRX_ERROR;
4478  $this->trxStatusCause = new DBUnexpectedError(
4479  $this,
4480  "Uncancelable atomic section canceled (got $fname)"
4481  );
4482  }
4483  } finally {
4484  // Fix up callbacks owned by the sections that were just cancelled.
4485  // All callbacks should have an owner that is present in trxAtomicLevels.
4486  $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
4487  }
4488 
4489  $this->affectedRowCount = 0; // for the sake of consistency
4490  }
4491 
4492  final public function doAtomicSection(
4493  $fname,
4494  callable $callback,
4495  $cancelable = self::ATOMIC_NOT_CANCELABLE
4496  ) {
4497  $sectionId = $this->startAtomic( $fname, $cancelable );
4498  try {
4499  $res = $callback( $this, $fname );
4500  } catch ( Throwable $e ) {
4501  $this->cancelAtomic( $fname, $sectionId );
4502 
4503  throw $e;
4504  }
4505  $this->endAtomic( $fname );
4506 
4507  return $res;
4508  }
4509 
4510  final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
4511  static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
4512  if ( !in_array( $mode, $modes, true ) ) {
4513  throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
4514  }
4515 
4516  // Protect against mismatched atomic section, transaction nesting, and snapshot loss
4517  if ( $this->trxLevel() ) {
4518  if ( $this->trxAtomicLevels ) {
4519  $levels = $this->flatAtomicSectionList();
4520  $msg = "$fname: got explicit BEGIN while atomic section(s) $levels are open";
4521  throw new DBUnexpectedError( $this, $msg );
4522  } elseif ( !$this->trxAutomatic ) {
4523  $msg = "$fname: explicit transaction already active (from {$this->trxFname})";
4524  throw new DBUnexpectedError( $this, $msg );
4525  } else {
4526  $msg = "$fname: implicit transaction already active (from {$this->trxFname})";
4527  throw new DBUnexpectedError( $this, $msg );
4528  }
4529  } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
4530  $msg = "$fname: implicit transaction expected (DBO_TRX set)";
4531  throw new DBUnexpectedError( $this, $msg );
4532  }
4533 
4534  $this->assertHasConnectionHandle();
4535 
4536  $this->doBegin( $fname );
4537  $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4538  $this->trxStatus = self::STATUS_TRX_OK;
4539  $this->trxStatusIgnoredCause = null;
4540  $this->trxAtomicCounter = 0;
4541  $this->trxTimestamp = microtime( true );
4542  $this->trxFname = $fname;
4543  $this->trxDoneWrites = false;
4544  $this->trxAutomaticAtomic = false;
4545  $this->trxAtomicLevels = [];
4546  $this->trxWriteDuration = 0.0;
4547  $this->trxWriteQueryCount = 0;
4548  $this->trxWriteAffectedRows = 0;
4549  $this->trxWriteAdjDuration = 0.0;
4550  $this->trxWriteAdjQueryCount = 0;
4551  $this->trxWriteCallers = [];
4552  // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4553  // Get an estimate of the replication lag before any such queries.
4554  $this->trxReplicaLag = null; // clear cached value first
4555  $this->trxReplicaLag = $this->getApproximateLagStatus()['lag'];
4556  // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4557  // caller will think its OK to muck around with the transaction just because startAtomic()
4558  // has not yet completed (e.g. setting trxAtomicLevels).
4559  $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
4560  }
4561 
4570  protected function doBegin( $fname ) {
4571  $this->query( 'BEGIN', $fname, self::QUERY_CHANGE_TRX );
4572  }
4573 
4574  final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4575  static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
4576  if ( !in_array( $flush, $modes, true ) ) {
4577  throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4578  }
4579 
4580  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
4581  // There are still atomic sections open; this cannot be ignored
4582  $levels = $this->flatAtomicSectionList();
4583  throw new DBUnexpectedError(
4584  $this,
4585  "$fname: got COMMIT while atomic sections $levels are still open"
4586  );
4587  }
4588 
4589  if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
4590  if ( !$this->trxLevel() ) {
4591  return; // nothing to do
4592  } elseif ( !$this->trxAutomatic ) {
4593  throw new DBUnexpectedError(
4594  $this,
4595  "$fname: flushing an explicit transaction, getting out of sync"
4596  );
4597  }
4598  } elseif ( !$this->trxLevel() ) {
4599  $this->queryLogger->error(
4600  "$fname: no transaction to commit, something got out of sync",
4601  [ 'exception' => new RuntimeException() ]
4602  );
4603 
4604  return; // nothing to do
4605  } elseif ( $this->trxAutomatic ) {
4606  throw new DBUnexpectedError(
4607  $this,
4608  "$fname: expected mass commit of all peer transactions (DBO_TRX set)"
4609  );
4610  }
4611 
4612  $this->assertHasConnectionHandle();
4613 
4615 
4616  $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
4617  $this->doCommit( $fname );
4618  $oldTrxShortId = $this->consumeTrxShortId();
4619  $this->trxStatus = self::STATUS_TRX_NONE;
4620 
4621  if ( $this->trxDoneWrites ) {
4622  $this->lastWriteTime = microtime( true );
4623  $this->trxProfiler->transactionWritingOut(
4624  $this->server,
4625  $this->getDomainID(),
4626  $oldTrxShortId,
4627  $writeTime,
4628  $this->trxWriteAffectedRows
4629  );
4630  }
4631 
4632  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4633  if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4634  $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
4635  $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
4636  }
4637  }
4638 
4647  protected function doCommit( $fname ) {
4648  if ( $this->trxLevel() ) {
4649  $this->query( 'COMMIT', $fname, self::QUERY_CHANGE_TRX );
4650  }
4651  }
4652 
4653  final public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4654  $trxActive = $this->trxLevel();
4655 
4656  if ( $flush !== self::FLUSHING_INTERNAL
4657  && $flush !== self::FLUSHING_ALL_PEERS
4658  && $this->getFlag( self::DBO_TRX )
4659  ) {
4660  throw new DBUnexpectedError(
4661  $this,
4662  "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4663  );
4664  }
4665 
4666  if ( $trxActive ) {
4667  $this->assertHasConnectionHandle();
4668 
4669  $this->doRollback( $fname );
4670  $oldTrxShortId = $this->consumeTrxShortId();
4671  $this->trxStatus = self::STATUS_TRX_NONE;
4672  $this->trxAtomicLevels = [];
4673  // Estimate the RTT via a query now that trxStatus is OK
4674  $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4675 
4676  if ( $this->trxDoneWrites ) {
4677  $this->trxProfiler->transactionWritingOut(
4678  $this->server,
4679  $this->getDomainID(),
4680  $oldTrxShortId,
4681  $writeTime,
4682  $this->trxWriteAffectedRows
4683  );
4684  }
4685  }
4686 
4687  // Clear any commit-dependant callbacks. They might even be present
4688  // only due to transaction rounds, with no SQL transaction being active
4689  $this->trxPostCommitOrIdleCallbacks = [];
4690  $this->trxPreCommitOrIdleCallbacks = [];
4691 
4692  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4693  if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4694  try {
4695  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
4696  } catch ( Throwable $e ) {
4697  // already logged; finish and let LoadBalancer move on during mass-rollback
4698  }
4699  try {
4700  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
4701  } catch ( Throwable $e ) {
4702  // already logged; let LoadBalancer move on during mass-rollback
4703  }
4704 
4705  $this->affectedRowCount = 0; // for the sake of consistency
4706  }
4707  }
4708 
4717  protected function doRollback( $fname ) {
4718  if ( $this->trxLevel() ) {
4719  # Disconnects cause rollback anyway, so ignore those errors
4720  $this->query( 'ROLLBACK', $fname, self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_TRX );
4721  }
4722  }
4723 
4724  public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4725  if ( $this->explicitTrxActive() ) {
4726  // Committing this transaction would break callers that assume it is still open
4727  throw new DBUnexpectedError(
4728  $this,
4729  "$fname: Cannot flush snapshot; " .
4730  "explicit transaction '{$this->trxFname}' is still open"
4731  );
4732  } elseif ( $this->writesOrCallbacksPending() ) {
4733  // This only flushes transactions to clear snapshots, not to write data
4734  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4735  throw new DBUnexpectedError(
4736  $this,
4737  "$fname: Cannot flush snapshot; " .
4738  "writes from transaction {$this->trxFname} are still pending ($fnames)"
4739  );
4740  } elseif (
4741  $this->trxLevel() &&
4742  $this->getTransactionRoundId() &&
4743  $flush !== self::FLUSHING_INTERNAL &&
4744  $flush !== self::FLUSHING_ALL_PEERS
4745  ) {
4746  $this->queryLogger->warning(
4747  "$fname: Expected mass snapshot flush of all peer transactions " .
4748  "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4749  [ 'exception' => new RuntimeException() ]
4750  );
4751  }
4752 
4753  $this->commit( $fname, self::FLUSHING_INTERNAL );
4754  }
4755 
4756  public function explicitTrxActive() {
4757  return $this->trxLevel() && ( $this->trxAtomicLevels || !$this->trxAutomatic );
4758  }
4759 
4764  public function duplicateTableStructure(
4765  $oldName,
4766  $newName,
4767  $temporary = false,
4768  $fname = __METHOD__
4769  ) {
4770  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4771  }
4772 
4777  public function listTables( $prefix = null, $fname = __METHOD__ ) {
4778  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4779  }
4780 
4785  public function listViews( $prefix = null, $fname = __METHOD__ ) {
4786  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4787  }
4788 
4793  public function timestamp( $ts = 0 ) {
4794  $t = new ConvertibleTimestamp( $ts );
4795  // Let errors bubble up to avoid putting garbage in the DB
4796  return $t->getTimestamp( TS_MW );
4797  }
4798 
4799  public function timestampOrNull( $ts = null ) {
4800  if ( $ts === null ) {
4801  return null;
4802  } else {
4803  return $this->timestamp( $ts );
4804  }
4805  }
4806 
4807  public function affectedRows() {
4808  return ( $this->affectedRowCount === null )
4809  ? $this->fetchAffectedRowCount() // default to driver value
4811  }
4812 
4816  abstract protected function fetchAffectedRowCount();
4817 
4830  protected function resultObject( $result ) {
4831  if ( !$result ) {
4832  return false; // failed query
4833  } elseif ( $result instanceof IResultWrapper ) {
4834  return $result;
4835  } elseif ( $result === true ) {
4836  return $result; // successful write query
4837  } else {
4838  return new ResultWrapper( $this, $result );
4839  }
4840  }
4841 
4842  public function ping( &$rtt = null ) {
4843  // Avoid hitting the server if it was hit recently
4844  if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::$PING_TTL ) {
4845  if ( !func_num_args() || $this->lastRoundTripEstimate > 0 ) {
4847  return true; // don't care about $rtt
4848  }
4849  }
4850 
4851  // This will reconnect if possible or return false if not
4852  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_NONE;
4853  $ok = ( $this->query( self::$PING_QUERY, __METHOD__, $flags ) !== false );
4854  if ( $ok ) {
4856  }
4857 
4858  return $ok;
4859  }
4860 
4867  protected function replaceLostConnection( $fname ) {
4868  $this->closeConnection();
4869  $this->conn = null;
4870 
4871  $this->handleSessionLossPreconnect();
4872 
4873  try {
4874  $this->open(
4875  $this->server,
4876  $this->user,
4877  $this->password,
4878  $this->currentDomain->getDatabase(),
4879  $this->currentDomain->getSchema(),
4880  $this->tablePrefix()
4881  );
4882  $this->lastPing = microtime( true );
4883  $ok = true;
4884 
4885  $this->connLogger->warning(
4886  $fname . ': lost connection to {dbserver}; reconnected',
4887  [
4888  'dbserver' => $this->getServer(),
4889  'exception' => new RuntimeException()
4890  ]
4891  );
4892  } catch ( DBConnectionError $e ) {
4893  $ok = false;
4894 
4895  $this->connLogger->error(
4896  $fname . ': lost connection to {dbserver} permanently',
4897  [ 'dbserver' => $this->getServer() ]
4898  );
4899  }
4900 
4902 
4903  return $ok;
4904  }
4905 
4906  public function getSessionLagStatus() {
4907  return $this->getRecordedTransactionLagStatus() ?: $this->getApproximateLagStatus();
4908  }
4909 
4923  final protected function getRecordedTransactionLagStatus() {
4924  return ( $this->trxLevel() && $this->trxReplicaLag !== null )
4925  ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
4926  : null;
4927  }
4928 
4938  protected function getApproximateLagStatus() {
4939  return [
4940  'lag' => ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) ? $this->getLag() : 0,
4941  'since' => microtime( true )
4942  ];
4943  }
4944 
4967  public static function getCacheSetOptions( ?IDatabase ...$dbs ) {
4968  $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
4969 
4970  foreach ( func_get_args() as $db ) {
4971  if ( $db instanceof IDatabase ) {
4972  $status = $db->getSessionLagStatus();
4973 
4974  if ( $status['lag'] === false ) {
4975  $res['lag'] = false;
4976  } elseif ( $res['lag'] !== false ) {
4977  $res['lag'] = max( $res['lag'], $status['lag'] );
4978  }
4979  $res['since'] = min( $res['since'], $status['since'] );
4980  $res['pending'] = $res['pending'] ?: $db->writesPending();
4981  }
4982  }
4983 
4984  return $res;
4985  }
4986 
4987  public function getLag() {
4988  if ( $this->topologyRole === self::ROLE_STREAMING_MASTER ) {
4989  return 0; // this is the master
4990  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
4991  return 0; // static dataset
4992  }
4993 
4994  return $this->doGetLag();
4995  }
4996 
5001  protected function doGetLag() {
5002  return 0;
5003  }
5004 
5009  public function maxListLen() {
5010  return 0;
5011  }
5012 
5017  public function encodeBlob( $b ) {
5018  return $b;
5019  }
5020 
5025  public function decodeBlob( $b ) {
5026  if ( $b instanceof Blob ) {
5027  $b = $b->fetch();
5028  }
5029  return $b;
5030  }
5031 
5036  public function setSessionOptions( array $options ) {
5037  }
5038 
5039  public function sourceFile(
5040  $filename,
5041  callable $lineCallback = null,
5042  callable $resultCallback = null,
5043  $fname = false,
5044  callable $inputCallback = null
5045  ) {
5046  AtEase::suppressWarnings();
5047  $fp = fopen( $filename, 'r' );
5048  AtEase::restoreWarnings();
5049 
5050  if ( $fp === false ) {
5051  throw new RuntimeException( "Could not open \"{$filename}\"" );
5052  }
5053 
5054  if ( !$fname ) {
5055  $fname = __METHOD__ . "( $filename )";
5056  }
5057 
5058  try {
5059  $error = $this->sourceStream(
5060  $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
5061  } catch ( Throwable $e ) {
5062  fclose( $fp );
5063  throw $e;
5064  }
5065 
5066  fclose( $fp );
5067 
5068  return $error;
5069  }
5070 
5071  public function setSchemaVars( $vars ) {
5072  $this->schemaVars = is_array( $vars ) ? $vars : null;
5073  }
5074 
5075  public function sourceStream(
5076  $fp,
5077  callable $lineCallback = null,
5078  callable $resultCallback = null,
5079  $fname = __METHOD__,
5080  callable $inputCallback = null
5081  ) {
5082  $delimiterReset = new ScopedCallback(
5083  function ( $delimiter ) {
5084  $this->delimiter = $delimiter;
5085  },
5086  [ $this->delimiter ]
5087  );
5088  $cmd = '';
5089 
5090  while ( !feof( $fp ) ) {
5091  if ( $lineCallback ) {
5092  call_user_func( $lineCallback );
5093  }
5094 
5095  $line = trim( fgets( $fp ) );
5096 
5097  if ( $line == '' ) {
5098  continue;
5099  }
5100 
5101  if ( $line[0] == '-' && $line[1] == '-' ) {
5102  continue;
5103  }
5104 
5105  if ( $cmd != '' ) {
5106  $cmd .= ' ';
5107  }
5108 
5109  $done = $this->streamStatementEnd( $cmd, $line );
5110 
5111  $cmd .= "$line\n";
5112 
5113  if ( $done || feof( $fp ) ) {
5114  $cmd = $this->replaceVars( $cmd );
5115 
5116  if ( $inputCallback ) {
5117  $callbackResult = $inputCallback( $cmd );
5118 
5119  if ( is_string( $callbackResult ) || !$callbackResult ) {
5120  $cmd = $callbackResult;
5121  }
5122  }
5123 
5124  if ( $cmd ) {
5125  $res = $this->query( $cmd, $fname );
5126 
5127  if ( $resultCallback ) {
5128  $resultCallback( $res, $this );
5129  }
5130 
5131  if ( $res === false ) {
5132  $err = $this->lastError();
5133 
5134  return "Query \"{$cmd}\" failed with error code \"$err\".\n";
5135  }
5136  }
5137  $cmd = '';
5138  }
5139  }
5140 
5141  ScopedCallback::consume( $delimiterReset );
5142  return true;
5143  }
5144 
5153  public function streamStatementEnd( &$sql, &$newLine ) {
5154  if ( $this->delimiter ) {
5155  $prev = $newLine;
5156  $newLine = preg_replace(
5157  '/' . preg_quote( $this->delimiter, '/' ) . '$/',
5158  '',
5159  $newLine
5160  );
5161  if ( $newLine != $prev ) {
5162  return true;
5163  }
5164  }
5165 
5166  return false;
5167  }
5168 
5190  protected function replaceVars( $ins ) {
5191  $vars = $this->getSchemaVars();
5192  return preg_replace_callback(
5193  '!
5194  /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
5195  \'\{\$ (\w+) }\' | # 3. addQuotes
5196  `\{\$ (\w+) }` | # 4. addIdentifierQuotes
5197  /\*\$ (\w+) \*/ # 5. leave unencoded
5198  !x',
5199  function ( $m ) use ( $vars ) {
5200  // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
5201  // check for both nonexistent keys *and* the empty string.
5202  if ( isset( $m[1] ) && $m[1] !== '' ) {
5203  if ( $m[1] === 'i' ) {
5204  return $this->indexName( $m[2] );
5205  } else {
5206  return $this->tableName( $m[2] );
5207  }
5208  } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
5209  return $this->addQuotes( $vars[$m[3]] );
5210  } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
5211  return $this->addIdentifierQuotes( $vars[$m[4]] );
5212  } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
5213  return $vars[$m[5]];
5214  } else {
5215  return $m[0];
5216  }
5217  },
5218  $ins
5219  );
5220  }
5221 
5228  protected function getSchemaVars() {
5229  return $this->schemaVars ?? $this->getDefaultSchemaVars();
5230  }
5231 
5241  protected function getDefaultSchemaVars() {
5242  return [];
5243  }
5244 
5249  public function lockIsFree( $lockName, $method ) {
5250  // RDBMs methods for checking named locks may or may not count this thread itself.
5251  // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
5252  // the behavior chosen by the interface for this method.
5253  return !isset( $this->sessionNamedLocks[$lockName] );
5254  }
5255 
5260  public function lock( $lockName, $method, $timeout = 5 ) {
5261  $this->sessionNamedLocks[$lockName] = 1;
5262 
5263  return true;
5264  }
5265 
5270  public function unlock( $lockName, $method ) {
5271  unset( $this->sessionNamedLocks[$lockName] );
5272 
5273  return true;
5274  }
5275 
5276  public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
5277  if ( $this->writesOrCallbacksPending() ) {
5278  // This only flushes transactions to clear snapshots, not to write data
5279  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
5280  throw new DBUnexpectedError(
5281  $this,
5282  "$fname: Cannot flush pre-lock snapshot; " .
5283  "writes from transaction {$this->trxFname} are still pending ($fnames)"
5284  );
5285  }
5286 
5287  if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
5288  return null;
5289  }
5290 
5291  $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
5292  if ( $this->trxLevel() ) {
5293  // There is a good chance an exception was thrown, causing any early return
5294  // from the caller. Let any error handler get a chance to issue rollback().
5295  // If there isn't one, let the error bubble up and trigger server-side rollback.
5296  $this->onTransactionResolution(
5297  function () use ( $lockKey, $fname ) {
5298  $this->unlock( $lockKey, $fname );
5299  },
5300  $fname
5301  );
5302  } else {
5303  $this->unlock( $lockKey, $fname );
5304  }
5305  } );
5306 
5307  $this->commit( $fname, self::FLUSHING_INTERNAL );
5308 
5309  return $unlocker;
5310  }
5311 
5316  public function namedLocksEnqueue() {
5317  return false;
5318  }
5319 
5321  return true;
5322  }
5323 
5324  final public function lockTables( array $read, array $write, $method ) {
5325  if ( $this->writesOrCallbacksPending() ) {
5326  throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
5327  }
5328 
5329  if ( $this->tableLocksHaveTransactionScope() ) {
5330  $this->startAtomic( $method );
5331  }
5332 
5333  return $this->doLockTables( $read, $write, $method );
5334  }
5335 
5345  protected function doLockTables( array $read, array $write, $method ) {
5346  return true;
5347  }
5348 
5349  final public function unlockTables( $method ) {
5350  if ( $this->tableLocksHaveTransactionScope() ) {
5351  $this->endAtomic( $method );
5352 
5353  return true; // locks released on COMMIT/ROLLBACK
5354  }
5355 
5356  return $this->doUnlockTables( $method );
5357  }
5358 
5366  protected function doUnlockTables( $method ) {
5367  return true;
5368  }
5369 
5370  public function dropTable( $table, $fname = __METHOD__ ) {
5371  if ( !$this->tableExists( $table, $fname ) ) {
5372  return false;
5373  }
5374 
5375  $this->doDropTable( $table, $fname );
5376 
5377  return true;
5378  }
5379 
5386  protected function doDropTable( $table, $fname ) {
5387  // https://mariadb.com/kb/en/drop-table/
5388  // https://dev.mysql.com/doc/refman/8.0/en/drop-table.html
5389  // https://www.postgresql.org/docs/9.2/sql-truncate.html
5390  $sql = "DROP TABLE " . $this->tableName( $table ) . " CASCADE";
5391  $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
5392  }
5393 
5394  public function truncate( $tables, $fname = __METHOD__ ) {
5395  $tables = is_array( $tables ) ? $tables : [ $tables ];
5396 
5397  $tablesTruncate = [];
5398  foreach ( $tables as $table ) {
5399  // Skip TEMPORARY tables with no writes nor sequence updates detected.
5400  // This mostly is an optimization for integration testing.
5401  if ( !$this->isPristineTemporaryTable( $table ) ) {
5402  $tablesTruncate[] = $table;
5403  }
5404  }
5405 
5406  if ( $tablesTruncate ) {
5407  $this->doTruncate( $tablesTruncate, $fname );
5408  }
5409  }
5410 
5417  protected function doTruncate( array $tables, $fname ) {
5418  foreach ( $tables as $table ) {
5419  $sql = "TRUNCATE TABLE " . $this->tableName( $table );
5420  $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
5421  }
5422  }
5423 
5428  public function getInfinity() {
5429  return 'infinity';
5430  }
5431 
5432  public function encodeExpiry( $expiry ) {
5433  return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
5434  ? $this->getInfinity()
5435  : $this->timestamp( $expiry );
5436  }
5437 
5438  public function decodeExpiry( $expiry, $format = TS_MW ) {
5439  if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
5440  return 'infinity';
5441  }
5442 
5443  return ConvertibleTimestamp::convert( $format, $expiry );
5444  }
5445 
5450  public function setBigSelects( $value = true ) {
5451  // no-op
5452  }
5453 
5454  public function isReadOnly() {
5455  return ( $this->getReadOnlyReason() !== false );
5456  }
5457 
5461  protected function getReadOnlyReason() {
5462  if ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) {
5463  return [ 'Server is configured as a read-only replica database.', 'role' ];
5464  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
5465  return [ 'Server is configured as a read-only static clone database.', 'role' ];
5466  }
5467 
5468  $reason = $this->getLBInfo( self::LB_READ_ONLY_REASON );
5469  if ( is_string( $reason ) ) {
5470  return [ $reason, 'lb' ];
5471  }
5472 
5473  return false;
5474  }
5475 
5480  public function setTableAliases( array $aliases ) {
5481  $this->tableAliases = $aliases;
5482  }
5483 
5488  public function setIndexAliases( array $aliases ) {
5489  $this->indexAliases = $aliases;
5490  }
5491 
5498  final protected function fieldHasBit( int $flags, int $bit ) {
5499  return ( ( $flags & $bit ) === $bit );
5500  }
5501 
5514  protected function getBindingHandle() {
5515  if ( !$this->conn ) {
5516  throw new DBUnexpectedError(
5517  $this,
5518  'DB connection was already closed or the connection dropped'
5519  );
5520  }
5521 
5522  return $this->conn;
5523  }
5524 
5525  public function __toString() {
5526  // spl_object_id is PHP >= 7.2
5527  $id = function_exists( 'spl_object_id' )
5528  ? spl_object_id( $this )
5529  : spl_object_hash( $this );
5530 
5531  $description = $this->getType() . ' object #' . $id;
5532  if ( is_resource( $this->conn ) ) {
5533  $description .= ' (' . (string)$this->conn . ')'; // "resource id #<ID>"
5534  } elseif ( is_object( $this->conn ) ) {
5535  // spl_object_id is PHP >= 7.2
5536  $handleId = function_exists( 'spl_object_id' )
5537  ? spl_object_id( $this->conn )
5538  : spl_object_hash( $this->conn );
5539  $description .= " (handle id #$handleId)";
5540  }
5541 
5542  return $description;
5543  }
5544 
5549  public function __clone() {
5550  $this->connLogger->warning(
5551  "Cloning " . static::class . " is not recommended; forking connection",
5552  [ 'exception' => new RuntimeException() ]
5553  );
5554 
5555  if ( $this->isOpen() ) {
5556  // Open a new connection resource without messing with the old one
5557  $this->conn = null;
5558  $this->trxEndCallbacks = []; // don't copy
5559  $this->trxSectionCancelCallbacks = []; // don't copy
5560  $this->handleSessionLossPreconnect(); // no trx or locks anymore
5561  $this->open(
5562  $this->server,
5563  $this->user,
5564  $this->password,
5565  $this->currentDomain->getDatabase(),
5566  $this->currentDomain->getSchema(),
5567  $this->tablePrefix()
5568  );
5569  $this->lastPing = microtime( true );
5570  }
5571  }
5572 
5578  public function __sleep() {
5579  throw new RuntimeException( 'Database serialization may cause problems, since ' .
5580  'the connection is not restored on wakeup' );
5581  }
5582 
5586  public function __destruct() {
5587  if ( $this->trxLevel() && $this->trxDoneWrites ) {
5588  trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
5589  }
5590 
5591  $danglingWriters = $this->pendingWriteAndCallbackCallers();
5592  if ( $danglingWriters ) {
5593  $fnames = implode( ', ', $danglingWriters );
5594  trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
5595  }
5596 
5597  if ( $this->conn ) {
5598  // Avoid connection leaks for sanity. Normally, resources close at script completion.
5599  // The connection might already be closed in PHP by now, so suppress warnings.
5600  AtEase::suppressWarnings();
5601  $this->closeConnection();
5602  AtEase::restoreWarnings();
5603  $this->conn = null;
5604  }
5605  }
5606 }
5607 
5611 class_alias( Database::class, 'DatabaseBase' );
5612 
5616 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:644
LIST_OR
const LIST_OR
Definition: Defines.php:45
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:565
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:862
Wikimedia\Rdbms\Database\setSessionOptions
setSessionOptions(array $options)
Override database's default behavior.$options include: 'connTimeout' : Set the connection timeout val...
Definition: Database.php:5036
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:3643
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:2422
Wikimedia\Rdbms\Database\replaceLostConnection
replaceLostConnection( $fname)
Close any existing (dead) database connection and open a new connection.
Definition: Database.php:4867
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:5514
LIST_NAMES
const LIST_NAMES
Definition: Defines.php:44
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:1539
Wikimedia\Rdbms\Database\doInsert
doInsert( $table, array $rows, $fname)
Definition: Database.php:2340
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:2605
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:3154
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:3356
Wikimedia\Rdbms\Database\fieldExists
fieldExists( $table, $field, $fname=__METHOD__)
Determines whether a field exists in a table.
Definition: Database.php:2281
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:3845
Wikimedia\Rdbms\Database\bitOr
bitOr( $fieldLeft, $fieldRight)
string Stable to override
Definition: Database.php:2589
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:2447
Wikimedia\Rdbms\Database\selectRowCount
selectRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
Definition: Database.php:2043
Wikimedia\Rdbms\Database\ignoreIndexClause
ignoreIndexClause( $index)
IGNORE INDEX clause.
Definition: Database.php:3243
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:561
Wikimedia\Rdbms\Database\fieldHasBit
fieldHasBit(int $flags, int $bit)
Definition: Database.php:5498
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:4777
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:2306
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:1464
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:2541
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:5017
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:2929
Wikimedia\Rdbms\Database\getDomainID
getDomainID()
Return the currently selected domain ID.
Definition: Database.php:812
Wikimedia\Rdbms\Database\getClass
static getClass( $dbType, $driver=null)
Definition: Database.php:469
Wikimedia\Rdbms\Database\pingAndCalculateLastTrxApplyTime
pingAndCalculateLastTrxApplyTime()
Definition: Database.php:706
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:979
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:3944
Wikimedia\Rdbms\Database\tableLocksHaveTransactionScope
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
Definition: Database.php:5320
Wikimedia\Rdbms\Database\wasErrorReissuable
wasErrorReissuable()
Determines if the last query error was due to something outside of the query itself.
Definition: Database.php:3811
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:3414
Wikimedia\Rdbms\Database\$trxPostCommitOrIdleCallbacks
array[] $trxPostCommitOrIdleCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:160
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:5488
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:5025
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:3675
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:5009
Wikimedia\Rdbms\Database\selectDomain
selectDomain( $domain)
Set the current domain (database, schema, and table prefix)
Definition: Database.php:2783
Wikimedia\Rdbms\Database\buildIntegerCast
buildIntegerCast( $field)
Field or column to cast string 1.31 Stable to override
Definition: Database.php:2752
Wikimedia\Rdbms\Database\getServerUptime
getServerUptime()
Determines how long the server has been up.int Stable to override
Definition: Database.php:3775
LIST_AND
const LIST_AND
Definition: Defines.php:42
Wikimedia\Rdbms\Database\prependDatabaseOrSchema
prependDatabaseOrSchema( $namespace, $relation, $format)
Definition: Database.php:2908
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:5586
Wikimedia\Rdbms\Database\endAtomic
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
Definition: Database.php:4372
Wikimedia\Rdbms\Database\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:3113
Wikimedia\Rdbms\Database\executeQuery
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
Definition: Database.php:1256
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:5450
Wikimedia\Rdbms\Database\doDropTable
doDropTable( $table, $fname)
Definition: Database.php:5386
Wikimedia\Rdbms\Database\doReplace
doReplace( $table, array $uniqueKeys, array $rows, $fname)
Definition: Database.php:3274
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:4799
Wikimedia\Rdbms\Database\decodeExpiry
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
Definition: Database.php:5438
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:2146
Wikimedia\Rdbms\Database\anyString
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
Definition: Database.php:3207
Wikimedia\Rdbms\Database\unionSupportsOrderAndLimit
unionSupportsOrderAndLimit()
Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION....
Definition: Database.php:3661
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:3527
LIST_SET
const LIST_SET
Definition: Defines.php:43
Wikimedia\Rdbms\Database\fieldNameWithAlias
fieldNameWithAlias( $name, $alias=false)
Get an aliased field name e.g.
Definition: Database.php:2979
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:990
Wikimedia\Rdbms\Database\normalizeOptions
normalizeOptions( $options)
Definition: Database.php:2219
Wikimedia\Rdbms\Database\getDefaultSchemaVars
getDefaultSchemaVars()
Get schema variables to use if none have been set via setSchemaVars().
Definition: Database.php:5241
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:186
Wikimedia\Rdbms\Database\extractSingleFieldFromList
extractSingleFieldFromList( $var)
Definition: Database.php:2249
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:4764
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:5417
Wikimedia\Rdbms\Database\onTransactionCommitOrIdle
onTransactionCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback as soon as there is no transaction pending.
Definition: Database.php:3922
Wikimedia\Rdbms\Database\registerTempWrites
registerTempWrites( $ret, array $changes)
Definition: Database.php:1179
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:5316
Wikimedia\Rdbms\Database\buildSubstring
buildSubstring( $input, $startPosition, $length=null)
Stable to override
Definition: Database.php:2676
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:23
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:3015
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:3893
Wikimedia\Rdbms\Database\getSchemaVars
getSchemaVars()
Get schema variables.
Definition: Database.php:5228
Wikimedia\Rdbms\Database\setLogger
setLogger(LoggerInterface $logger)
Set the PSR-3 logger interface to use for query logging.
Definition: Database.php:533
Wikimedia\Rdbms\Database\__clone
__clone()
Make sure that copies do not share the same client binding handle.
Definition: Database.php:5549
$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:4406
$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:808
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:3545
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:3755
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
LIST_COMMA
const LIST_COMMA
Definition: Defines.php:41
Wikimedia\Rdbms\Database\handleSessionLossPostconnect
handleSessionLossPostconnect()
Clean things up after session (and thus transaction) loss after reconnect.
Definition: Database.php:1603
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:1210
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:3441
Wikimedia\Rdbms\Database\$affectedRowCount
int null $affectedRowCount
Rows affected by the last query to query() or its CRUD wrappers.
Definition: Database.php:176
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:2597
Wikimedia\Rdbms\Database\bitNot
bitNot( $field)
string Stable to override
Definition: Database.php:2573
Wikimedia\Rdbms\Database\nextSavepointId
nextSavepointId( $fname)
Definition: Database.php:4326
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:5578
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:541
Wikimedia\Rdbms\Database\doBegin
doBegin( $fname)
Issues the BEGIN command to the database server.
Definition: Database.php:4570
Wikimedia\Rdbms\Database\makeConditionCollidesUponKeys
makeConditionCollidesUponKeys(array $rows, array $uniqueKeys)
Definition: Database.php:3341
Wikimedia\Rdbms\Database\isWriteQuery
isWriteQuery( $sql, $flags)
Determine whether a query writes to the DB.
Definition: Database.php:1057
Wikimedia\Rdbms\Database\isFlagInOptions
isFlagInOptions( $option, array $options)
Definition: Database.php:2235
Wikimedia\Rdbms\Database\clearFlag
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
Definition: Database.php:780
Wikimedia\Rdbms\Database\getQueryExceptionAndLog
getQueryExceptionAndLog( $error, $errno, $sql, $fname)
Definition: Database.php:1672
Wikimedia\Rdbms\Database\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Definition: Database.php:4510
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:4830
Wikimedia\Rdbms\Database\doHandleSessionLossPreconnect
doHandleSessionLossPreconnect()
Reset any additional subclass trx* and session* fields Stable to override.
Definition: Database.php:1596
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:4107
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:901
Wikimedia\Rdbms\Database\replaceVars
replaceVars( $ins)
Database-independent variable replacement.
Definition: Database.php:5190
Wikimedia\Rdbms\Database\handleSessionLossPreconnect
handleSessionLossPreconnect()
Clean things up after session (and thus transaction) loss before reconnect.
Definition: Database.php:1564
Wikimedia\Rdbms\Database\doInsertNonConflicting
doInsertNonConflicting( $table, array $rows, $fname)
Definition: Database.php:2357
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:4176
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:3791
Wikimedia\Rdbms\Database\$currentDomain
DatabaseDomain $currentDomain
Definition: Database.php:69
Wikimedia\Rdbms\Database\getLag
getLag()
Get the amount of replication lag for this database server.
Definition: Database.php:4987
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:2756
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\getCacheSetOptions
static getCacheSetOptions(?IDatabase ... $dbs)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Definition: Database.php:4967
Wikimedia\Rdbms\Database\assertBuildSubstringParams
assertBuildSubstringParams( $startPosition, $length)
Check type and bounds for parameters to self::buildSubstring()
Definition: Database.php:2697
Wikimedia\Rdbms\Database\isReadOnly
isReadOnly()
Definition: Database.php:5454
Wikimedia\Rdbms\Database\buildStringCast
buildStringCast( $field)
Field or column to cast string 1.28 Stable to override
Definition: Database.php:2742
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:5349
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:4906
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:1033
Wikimedia\Rdbms\Database\doRollbackToSavepoint
doRollbackToSavepoint( $identifier, $fname)
Rollback to a savepoint.
Definition: Database.php:4317
Wikimedia\Rdbms\Database\dropTable
dropTable( $table, $fname=__METHOD__)
Delete a table.
Definition: Database.php:5370
Wikimedia\Rdbms\Database\getTempTableWrites
getTempTableWrites( $sql, $pseudoPermanent)
Definition: Database.php:1123
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:3610
Wikimedia\Rdbms\Database\startAtomic
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Definition: Database.php:4341
Wikimedia\Rdbms\DBQueryTimeoutError
Error thrown when a query times out.
Definition: DBQueryTimeoutError.php:30
Wikimedia\Rdbms\Database\selectOptionsIncludeLocking
selectOptionsIncludeLocking( $options)
Definition: Database.php:2076
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
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:5260
Wikimedia\Rdbms\Database\getTransactionRoundId
getTransactionRoundId()
Definition: Database.php:677
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:549
Wikimedia\Rdbms\Database\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Definition: Database.php:765
Wikimedia\Rdbms\Database\rollback
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
Definition: Database.php:4653
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:1493
Wikimedia\Rdbms\Database\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Run a callback after each time any transaction commits or rolls back.
Definition: Database.php:4077
Wikimedia\Rdbms\Database\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
Stable to override.
Definition: Database.php:3164
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:1657
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:1107
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:2265
Wikimedia\Rdbms\Database\indexExists
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists.
Definition: Database.php:2287
Wikimedia\Rdbms\Database\writesOrCallbacksPending
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...
Definition: Database.php:660
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:5075
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:1917
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:2386
$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:3386
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:2581
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:3176
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:1520
Wikimedia\Rdbms\Database\selectDB
selectDB( $db)
Change the current database.
Definition: Database.php:2773
Wikimedia\Rdbms\Database\wasQueryTimeout
wasQueryTimeout( $error, $errno)
Checks whether the cause of the error is detected to be a timeout.
Definition: Database.php:1642
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:652
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:3807
Wikimedia\Rdbms\Database\beginIfImplied
beginIfImplied( $sql, $fname)
Start an implicit transaction if DBO_TRX is enabled and no transaction is active.
Definition: Database.php:1441
Wikimedia\Rdbms\Database\getQueryException
getQueryException( $error, $errno, $sql, $fname)
Definition: Database.php:1696
Wikimedia\Rdbms\Database\getServerInfo
getServerInfo()
Get a human-readable string describing the current software version.
Definition: Database.php:537
Wikimedia\Rdbms\Database\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Definition: Database.php:4574
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:2625
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:795
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:880
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:616
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:5276
Wikimedia\Rdbms\Database\fieldNamesWithAlias
fieldNamesWithAlias( $fields)
Gets an array of aliased field names.
Definition: Database.php:2993
Wikimedia\Rdbms\Database\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:604
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:3476
Wikimedia\Rdbms\Database\normalizeRowArray
normalizeRowArray(array $rowOrRows)
Definition: Database.php:2120
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:2004
Wikimedia\Rdbms\DBQueryError
@newable Stable to extend
Definition: DBQueryError.php:29
Wikimedia\Rdbms\Database\useIndexClause
useIndexClause( $index)
USE INDEX clause.
Definition: Database.php:3227
Wikimedia\Rdbms\Database\makeUpdateOptions
makeUpdateOptions( $options)
Make UPDATE options for the Database::update function.
Definition: Database.php:2441
Wikimedia\Rdbms\Database\getReadOnlyReason
getReadOnlyReason()
Definition: Database.php:5461
Wikimedia\Rdbms\Database\buildSuperlative
buildSuperlative( $sqlfunc, $fields, $values)
Build a superlative function statement comparing columns/values.
Definition: Database.php:2645
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:5001
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:839
Wikimedia\Rdbms\Database\aggregateValue
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.array|string Since 1.33 Stable to override
Definition: Database.php:2565
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:850
Wikimedia\Rdbms\Database\preCommitCallbacksPending
preCommitCallbacksPending()
Definition: Database.php:670
Wikimedia\Rdbms\Database\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Stable to override.
Definition: Database.php:3837
Wikimedia\Rdbms\Database\pendingWriteAndCallbackCallers
pendingWriteAndCallbackCallers()
List the methods that have write queries or callbacks for the current transaction.
Definition: Database.php:736
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:720
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:2919
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:5525
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:890
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:4724
Wikimedia\Rdbms\Database\pendingWriteRowsAffected
pendingWriteRowsAffected()
Get the number of affected rows from pending write queries.
Definition: Database.php:724
Wikimedia\Rdbms\Database\$trxPreCommitOrIdleCallbacks
array[] $trxPreCommitOrIdleCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:162
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:4301
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:1353
$line
$line
Definition: mcc.php:119
Wikimedia\Rdbms\Database\currentAtomicSectionId
currentAtomicSectionId()
Definition: Database.php:3980
Wikimedia\Rdbms\Database\modifyCallbacksForCancel
modifyCallbacksForCancel(array $sectionIds, AtomicSectionIdentifier $newSectionId=null)
Update callbacks that were owned by cancelled atomic sections.
Definition: Database.php:4041
Wikimedia\Rdbms\Database\setTrxEndCallbackSuppression
setTrxEndCallbackSuppression( $suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
Definition: Database.php:4093
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $flags=self::QUERY_NORMAL)
Run an SQL query and return the result.
Definition: Database.php:1219
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:3902
Wikimedia\Rdbms\Database\pendingWriteQueryDuration
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
Definition: Database.php:688
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:2810
Wikimedia\Rdbms\Database\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: Database.php:3826
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:4492
Wikimedia\Rdbms\Database\replace
replace( $table, $uniqueKeys, $rows, $fname=__METHOD__)
Insert row(s) into a table, deleting all conflicting rows beforehand.
Definition: Database.php:3247
Wikimedia\Rdbms\Database\getRecordedTransactionLagStatus
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
Definition: Database.php:4923
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:4211
Wikimedia\Rdbms\Database\getServer
getServer()
Get the server hostname or IP address.
Definition: Database.php:2802
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:5345
Wikimedia\Rdbms\Database\doUnlockTables
doUnlockTables( $method)
Helper function for unlockTables() that handles the actual table unlocking.
Definition: Database.php:5366
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:4793
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:1739
Wikimedia\Rdbms\Database\anyChar
anyChar()
Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
Definition: Database.php:3203
Wikimedia\Rdbms\Database\onTransactionIdle
onTransactionIdle(callable $callback, $fname=__METHOD__)
Alias for onTransactionCommitOrIdle() for backwards-compatibility.
Definition: Database.php:3940
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:5270
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:3140
Wikimedia\Rdbms\Database\getLazyMasterHandle
getLazyMasterHandle()
Get a handle to the master server of the cluster to which this server belongs.
Definition: Database.php:636
Wikimedia\Rdbms\Database\consumeTrxShortId
consumeTrxShortId()
Reset the transaction ID and return the old one.
Definition: Database.php:1624
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:2026
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:5394
Wikimedia\Rdbms\Database\dbSchema
dbSchema( $schema=null)
Get/set the db schema.
Definition: Database.php:578
Wikimedia\Rdbms\Database\$trxRecurringCallbacks
callable[] $trxRecurringCallbacks
Map of (name => callable)
Definition: Database.php:171
Wikimedia\Rdbms\Database\getQueryVerb
getQueryVerb( $sql)
Definition: Database.php:1089
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:3669
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:3996
Wikimedia\Rdbms\Database\insert
insert( $table, $rows, $fname=__METHOD__, $options=[])
Insert the given row(s) into a table.
Definition: Database.php:2316
Wikimedia\Rdbms\IDatabase\lastErrno
lastErrno()
Get the last error number.
Wikimedia\Rdbms\Database\relationSchemaQualifier
relationSchemaQualifier()
Stable to override.
Definition: Database.php:600
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:2372
Wikimedia\Rdbms\Database\newExceptionAfterConnectError
newExceptionAfterConnectError( $error)
Definition: Database.php:1710
Wikimedia\Rdbms\Database\lockTables
lockTables(array $read, array $write, $method)
Lock specific tables.
Definition: Database.php:5324
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:5432
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:2617
Wikimedia\Rdbms\Database\doSavepoint
doSavepoint( $identifier, $fname)
Create a savepoint.
Definition: Database.php:4285
Wikimedia\Rdbms\Database\setSchemaVars
setSchemaVars( $vars)
Set schema variables to be used when streaming commands from SQL files or stdin.
Definition: Database.php:5071
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:553
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:1867
Wikimedia\Rdbms\Database\tableNameWithAlias
tableNameWithAlias( $table, $alias=false)
Get an aliased table name.
Definition: Database.php:2950
Wikimedia\Rdbms\Database\getAttributes
static getAttributes()
Stable to override.
Definition: Database.php:522
Wikimedia\Rdbms\Database\writesPending
writesPending()
Definition: Database.php:656
Wikimedia\Rdbms\Database\normalizeUpsertKeys
normalizeUpsertKeys( $uniqueKeys)
Definition: Database.php:2167
Wikimedia\Rdbms\Database\selectFieldsOrOptionsAggregate
selectFieldsOrOptionsAggregate( $fields, $options)
Definition: Database.php:2092
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:5249
Wikimedia\Rdbms\Database\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Definition: Database.php:4842
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:4252
Wikimedia\Rdbms\Database\onAtomicSectionCancel
onAtomicSectionCancel(callable $callback, $fname=__METHOD__)
Run a callback when the atomic section is cancelled.
Definition: Database.php:3970
Wikimedia\Rdbms\Database\getTopologyRootMaster
getTopologyRootMaster()
Get the host (or address) of the root master server for the replication topology.
Definition: Database.php:545
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:5480
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:3884
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:3915
Wikimedia\Rdbms\IDatabase\getType
getType()
Get the type of the DBMS (e.g.
Wikimedia\Rdbms\Database\explicitTrxActive
explicitTrxActive()
Definition: Database.php:4756
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:1729
Wikimedia\Rdbms\Database\isOpen
isOpen()
Definition: Database.php:761
Wikimedia\Rdbms\Database\doCommit
doCommit( $fname)
Issues the COMMIT command to the database server.
Definition: Database.php:4647
$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:1893
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:3911
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:1796
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:1905
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:648
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:3799
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:3783
$t
$t
Definition: testCompression.php:74
Wikimedia\Rdbms\Database\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Stable to override.
Definition: Database.php:2794
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:3121
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:2727
Wikimedia\Rdbms\Database\getApproximateLagStatus
getApproximateLagStatus()
Get a replica DB lag estimate for this server at the start of a transaction.
Definition: Database.php:4938
Wikimedia\Rdbms\Database\qualifiedTableComponents
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
Definition: Database.php:2868
Wikimedia\Rdbms\Database\affectedRows
affectedRows()
Get the number of rows affected by the last write query.
Definition: Database.php:4807
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:2769
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:3767
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\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:5039
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:4785
Wikimedia\Rdbms\Database\newSelectQueryBuilder
newSelectQueryBuilder()
Create an empty SelectQueryBuilder which can be used to run queries against this connection....
Definition: Database.php:1735
Wikimedia\Rdbms\Database\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
Definition: Database.php:5153
Wikimedia\Rdbms\Database\makeList
makeList(array $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2465
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:3211
Wikimedia\Rdbms\Subquery
Definition: Subquery.php:27
Wikimedia\Rdbms\Database\makeConditionCollidesUponKey
makeConditionCollidesUponKey(array $rows, array $uniqueKey)
Definition: Database.php:3300
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:1762
Wikimedia\Rdbms\Database\flatAtomicSectionList
flatAtomicSectionList()
Definition: Database.php:755
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:4717
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:2798
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:5428
$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