MediaWiki  1.34.4
Database.php
Go to the documentation of this file.
1 <?php
26 namespace Wikimedia\Rdbms;
27 
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\NullLogger;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\Timestamp\ConvertibleTimestamp;
33 use Wikimedia\AtEase\AtEase;
34 use BagOStuff;
35 use HashBagOStuff;
36 use LogicException;
37 use InvalidArgumentException;
38 use UnexpectedValueException;
39 use Exception;
40 use RuntimeException;
41 use Throwable;
42 
49 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
51  protected $srvCache;
53  protected $connLogger;
55  protected $queryLogger;
57  protected $errorLogger;
59  protected $deprecationLogger;
61  protected $profiler;
63  protected $trxProfiler;
64 
66  protected $currentDomain;
67 
69  protected $conn;
70 
73 
75  protected $server;
77  protected $user;
79  protected $password;
81  protected $cliMode;
83  protected $agent;
85  protected $connectionParams;
90 
92  protected $flags;
94  protected $lbInfo = [];
96  protected $delimiter = ';';
98  protected $tableAliases = [];
100  protected $indexAliases = [];
102  protected $schemaVars;
103 
105  private $htmlErrors;
107  private $priorFlags = [];
108 
110  protected $sessionNamedLocks = [];
112  protected $sessionTempTables = [];
113 
115  private $trxShortId = '';
117  private $trxStatus = self::STATUS_TRX_NONE;
123  private $trxTimestamp = null;
125  private $trxReplicaLag = null;
127  private $trxFname = null;
129  private $trxDoneWrites = false;
131  private $trxAutomatic = false;
133  private $trxAtomicCounter = 0;
135  private $trxAtomicLevels = [];
137  private $trxAutomaticAtomic = false;
139  private $trxWriteCallers = [];
141  private $trxWriteDuration = 0.0;
143  private $trxWriteQueryCount = 0;
147  private $trxWriteAdjDuration = 0.0;
151  private $trxIdleCallbacks = [];
155  private $trxEndCallbacks = [];
161  private $trxEndCallbacksSuppressed = false;
162 
164  protected $affectedRowCount;
165 
167  private $lastPing = 0.0;
169  private $lastQuery = '';
171  private $lastWriteTime = false;
173  private $lastPhpError = false;
175  private $lastRoundTripEstimate = 0.0;
176 
178  private $ownerId;
179 
181  const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
183  const ATTR_SCHEMAS_AS_TABLE_GROUPS = 'supports-schemas';
184 
186  const NEW_UNCONNECTED = 0;
188  const NEW_CONNECTED = 1;
189 
191  const STATUS_TRX_ERROR = 1;
193  const STATUS_TRX_OK = 2;
195  const STATUS_TRX_NONE = 3;
196 
198  private static $NOT_APPLICABLE = 'n/a';
200  private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
201 
203  private static $TEMP_NORMAL = 1;
205  private static $TEMP_PSEUDO_PERMANENT = 2;
206 
208  private static $DEADLOCK_TRIES = 4;
210  private static $DEADLOCK_DELAY_MIN = 500000;
212  private static $DEADLOCK_DELAY_MAX = 1500000;
213 
215  private static $PING_TTL = 1.0;
217  private static $PING_QUERY = 'SELECT 1 AS ping';
218 
220  private static $TINY_WRITE_SEC = 0.010;
222  private static $SLOW_WRITE_SEC = 0.500;
224  private static $SMALL_WRITE_ROWS = 100;
225 
227  protected static $MUTABLE_FLAGS = [
228  'DBO_DEBUG',
229  'DBO_NOBUFFER',
230  'DBO_TRX',
231  'DBO_DDLMODE',
232  ];
234  protected static $DBO_MUTABLE = (
236  );
237 
242  public function __construct( array $params ) {
243  $this->connectionParams = [];
244  foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
245  $this->connectionParams[$name] = $params[$name];
246  }
247  $this->connectionVariables = $params['variables'] ?? [];
248  $this->cliMode = $params['cliMode'];
249  $this->agent = $params['agent'];
250  $this->flags = $params['flags'];
251  if ( $this->flags & self::DBO_DEFAULT ) {
252  if ( $this->cliMode ) {
253  $this->flags &= ~self::DBO_TRX;
254  } else {
255  $this->flags |= self::DBO_TRX;
256  }
257  }
258  $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'] ?? 10000;
259 
260  $this->srvCache = $params['srvCache'] ?? new HashBagOStuff();
261  $this->profiler = is_callable( $params['profiler'] ) ? $params['profiler'] : null;
262  $this->trxProfiler = $params['trxProfiler'];
263  $this->connLogger = $params['connLogger'];
264  $this->queryLogger = $params['queryLogger'];
265  $this->errorLogger = $params['errorLogger'];
266  $this->deprecationLogger = $params['deprecationLogger'];
267 
268  // Set initial dummy domain until open() sets the final DB/prefix
269  $this->currentDomain = new DatabaseDomain(
270  $params['dbname'] != '' ? $params['dbname'] : null,
271  $params['schema'] != '' ? $params['schema'] : null,
272  $params['tablePrefix']
273  );
274 
275  $this->ownerId = $params['ownerId'] ?? null;
276  }
277 
286  final public function initConnection() {
287  if ( $this->isOpen() ) {
288  throw new LogicException( __METHOD__ . ': already connected' );
289  }
290  // Establish the connection
291  $this->doInitConnection();
292  }
293 
300  protected function doInitConnection() {
301  $this->open(
302  $this->connectionParams['host'],
303  $this->connectionParams['user'],
304  $this->connectionParams['password'],
305  $this->connectionParams['dbname'],
306  $this->connectionParams['schema'],
307  $this->connectionParams['tablePrefix']
308  );
309  }
310 
322  abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
323 
370  final public static function factory( $type, $params = [], $connect = self::NEW_CONNECTED ) {
371  $class = self::getClass( $type, $params['driver'] ?? null );
372 
373  if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
374  $params += [
375  'host' => null,
376  'user' => null,
377  'password' => null,
378  'dbname' => null,
379  'schema' => null,
380  'tablePrefix' => '',
381  'flags' => 0,
382  'variables' => [],
383  'cliMode' => ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ),
384  'agent' => basename( $_SERVER['SCRIPT_NAME'] ) . '@' . gethostname(),
385  'ownerId' => null
386  ];
387 
388  $normalizedParams = [
389  // Configuration
390  'host' => strlen( $params['host'] ) ? $params['host'] : null,
391  'user' => strlen( $params['user'] ) ? $params['user'] : null,
392  'password' => is_string( $params['password'] ) ? $params['password'] : null,
393  'dbname' => strlen( $params['dbname'] ) ? $params['dbname'] : null,
394  'schema' => strlen( $params['schema'] ) ? $params['schema'] : null,
395  'tablePrefix' => (string)$params['tablePrefix'],
396  'flags' => (int)$params['flags'],
397  'variables' => $params['variables'],
398  'cliMode' => (bool)$params['cliMode'],
399  'agent' => (string)$params['agent'],
400  // Objects and callbacks
401  'srvCache' => $params['srvCache'] ?? new HashBagOStuff(),
402  'profiler' => $params['profiler'] ?? null,
403  'trxProfiler' => $params['trxProfiler'] ?? new TransactionProfiler(),
404  'connLogger' => $params['connLogger'] ?? new NullLogger(),
405  'queryLogger' => $params['queryLogger'] ?? new NullLogger(),
406  'errorLogger' => $params['errorLogger'] ?? function ( Exception $e ) {
407  trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
408  },
409  'deprecationLogger' => $params['deprecationLogger'] ?? function ( $msg ) {
410  trigger_error( $msg, E_USER_DEPRECATED );
411  }
412  ] + $params;
413 
415  $conn = new $class( $normalizedParams );
416  if ( $connect === self::NEW_CONNECTED ) {
417  $conn->initConnection();
418  }
419  } else {
420  $conn = null;
421  }
422 
423  return $conn;
424  }
425 
433  final public static function attributesFromType( $dbType, $driver = null ) {
434  static $defaults = [
435  self::ATTR_DB_LEVEL_LOCKING => false,
436  self::ATTR_SCHEMAS_AS_TABLE_GROUPS => false
437  ];
438 
439  $class = self::getClass( $dbType, $driver );
440 
441  return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
442  }
443 
450  private static function getClass( $dbType, $driver = null ) {
451  // For database types with built-in support, the below maps type to IDatabase
452  // implementations. For types with multipe driver implementations (PHP extensions),
453  // an array can be used, keyed by extension name. In case of an array, the
454  // optional 'driver' parameter can be used to force a specific driver. Otherwise,
455  // we auto-detect the first available driver. For types without built-in support,
456  // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
457  static $builtinTypes = [
458  'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
459  'sqlite' => DatabaseSqlite::class,
460  'postgres' => DatabasePostgres::class,
461  ];
462 
463  $dbType = strtolower( $dbType );
464  $class = false;
465 
466  if ( isset( $builtinTypes[$dbType] ) ) {
467  $possibleDrivers = $builtinTypes[$dbType];
468  if ( is_string( $possibleDrivers ) ) {
469  $class = $possibleDrivers;
470  } elseif ( (string)$driver !== '' ) {
471  if ( !isset( $possibleDrivers[$driver] ) ) {
472  throw new InvalidArgumentException( __METHOD__ .
473  " type '$dbType' does not support driver '{$driver}'" );
474  }
475 
476  $class = $possibleDrivers[$driver];
477  } else {
478  foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
479  if ( extension_loaded( $posDriver ) ) {
480  $class = $possibleClass;
481  break;
482  }
483  }
484  }
485  } else {
486  $class = 'Database' . ucfirst( $dbType );
487  }
488 
489  if ( $class === false ) {
490  throw new InvalidArgumentException( __METHOD__ .
491  " no viable database extension found for type '$dbType'" );
492  }
493 
494  return $class;
495  }
496 
501  protected static function getAttributes() {
502  return [];
503  }
504 
512  public function setLogger( LoggerInterface $logger ) {
513  $this->queryLogger = $logger;
514  }
515 
516  public function getServerInfo() {
517  return $this->getServerVersion();
518  }
519 
527  public function bufferResults( $buffer = null ) {
528  return true;
529  }
530 
531  final public function trxLevel() {
532  return ( $this->trxShortId != '' ) ? 1 : 0;
533  }
534 
535  public function trxTimestamp() {
536  return $this->trxLevel() ? $this->trxTimestamp : null;
537  }
538 
543  public function trxStatus() {
544  return $this->trxStatus;
545  }
546 
547  public function tablePrefix( $prefix = null ) {
548  $old = $this->currentDomain->getTablePrefix();
549  if ( $prefix !== null ) {
550  $this->currentDomain = new DatabaseDomain(
551  $this->currentDomain->getDatabase(),
552  $this->currentDomain->getSchema(),
553  $prefix
554  );
555  }
556 
557  return $old;
558  }
559 
560  public function dbSchema( $schema = null ) {
561  if ( strlen( $schema ) && $this->getDBname() === null ) {
562  throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
563  }
564 
565  $old = $this->currentDomain->getSchema();
566  if ( $schema !== null ) {
567  $this->currentDomain = new DatabaseDomain(
568  $this->currentDomain->getDatabase(),
569  // DatabaseDomain uses null for unspecified schemas
570  strlen( $schema ) ? $schema : null,
571  $this->currentDomain->getTablePrefix()
572  );
573  }
574 
575  return (string)$old;
576  }
577 
581  protected function relationSchemaQualifier() {
582  return $this->dbSchema();
583  }
584 
585  public function getLBInfo( $name = null ) {
586  if ( is_null( $name ) ) {
587  return $this->lbInfo;
588  }
589 
590  if ( array_key_exists( $name, $this->lbInfo ) ) {
591  return $this->lbInfo[$name];
592  }
593 
594  return null;
595  }
596 
597  public function setLBInfo( $nameOrArray, $value = null ) {
598  if ( is_array( $nameOrArray ) ) {
599  $this->lbInfo = $nameOrArray;
600  } elseif ( is_string( $nameOrArray ) ) {
601  if ( $value !== null ) {
602  $this->lbInfo[$nameOrArray] = $value;
603  } else {
604  unset( $this->lbInfo[$nameOrArray] );
605  }
606  } else {
607  throw new InvalidArgumentException( "Got non-string key" );
608  }
609  }
610 
611  public function setLazyMasterHandle( IDatabase $conn ) {
612  $this->lazyMasterHandle = $conn;
613  }
614 
620  protected function getLazyMasterHandle() {
622  }
623 
624  public function implicitOrderby() {
625  return true;
626  }
627 
628  public function lastQuery() {
629  return $this->lastQuery;
630  }
631 
632  public function lastDoneWrites() {
633  return $this->lastWriteTime ?: false;
634  }
635 
636  public function writesPending() {
637  return $this->trxLevel() && $this->trxDoneWrites;
638  }
639 
640  public function writesOrCallbacksPending() {
641  return $this->trxLevel() && (
642  $this->trxDoneWrites ||
643  $this->trxIdleCallbacks ||
644  $this->trxPreCommitCallbacks ||
645  $this->trxEndCallbacks ||
647  );
648  }
649 
650  public function preCommitCallbacksPending() {
651  return $this->trxLevel() && $this->trxPreCommitCallbacks;
652  }
653 
657  final protected function getTransactionRoundId() {
658  // If transaction round participation is enabled, see if one is active
659  if ( $this->getFlag( self::DBO_TRX ) ) {
660  $id = $this->getLBInfo( 'trxRoundId' );
661 
662  return is_string( $id ) ? $id : null;
663  }
664 
665  return null;
666  }
667 
668  public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
669  if ( !$this->trxLevel() ) {
670  return false;
671  } elseif ( !$this->trxDoneWrites ) {
672  return 0.0;
673  }
674 
675  switch ( $type ) {
676  case self::ESTIMATE_DB_APPLY:
677  return $this->pingAndCalculateLastTrxApplyTime();
678  default: // everything
680  }
681  }
682 
686  private function pingAndCalculateLastTrxApplyTime() {
687  $this->ping( $rtt );
688 
689  $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
690  $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
691  // For omitted queries, make them count as something at least
692  $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
693  $applyTime += self::$TINY_WRITE_SEC * $omitted;
694 
695  return $applyTime;
696  }
697 
698  public function pendingWriteCallers() {
699  return $this->trxLevel() ? $this->trxWriteCallers : [];
700  }
701 
702  public function pendingWriteRowsAffected() {
704  }
705 
714  public function pendingWriteAndCallbackCallers() {
715  $fnames = $this->pendingWriteCallers();
716  foreach ( [
717  $this->trxIdleCallbacks,
718  $this->trxPreCommitCallbacks,
719  $this->trxEndCallbacks,
720  $this->trxSectionCancelCallbacks
721  ] as $callbacks ) {
722  foreach ( $callbacks as $callback ) {
723  $fnames[] = $callback[1];
724  }
725  }
726 
727  return $fnames;
728  }
729 
733  private function flatAtomicSectionList() {
734  return array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
735  return $accum === null ? $v[0] : "$accum, " . $v[0];
736  } );
737  }
738 
739  public function isOpen() {
740  return (bool)$this->conn;
741  }
742 
743  public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
744  if ( $flag & ~static::$DBO_MUTABLE ) {
745  throw new DBUnexpectedError(
746  $this,
747  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
748  );
749  }
750 
751  if ( $remember === self::REMEMBER_PRIOR ) {
752  array_push( $this->priorFlags, $this->flags );
753  }
754 
755  $this->flags |= $flag;
756  }
757 
758  public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
759  if ( $flag & ~static::$DBO_MUTABLE ) {
760  throw new DBUnexpectedError(
761  $this,
762  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
763  );
764  }
765 
766  if ( $remember === self::REMEMBER_PRIOR ) {
767  array_push( $this->priorFlags, $this->flags );
768  }
769 
770  $this->flags &= ~$flag;
771  }
772 
773  public function restoreFlags( $state = self::RESTORE_PRIOR ) {
774  if ( !$this->priorFlags ) {
775  return;
776  }
777 
778  if ( $state === self::RESTORE_INITIAL ) {
779  $this->flags = reset( $this->priorFlags );
780  $this->priorFlags = [];
781  } else {
782  $this->flags = array_pop( $this->priorFlags );
783  }
784  }
785 
786  public function getFlag( $flag ) {
787  return ( ( $this->flags & $flag ) === $flag );
788  }
789 
790  public function getDomainID() {
791  return $this->currentDomain->getId();
792  }
793 
801  abstract function indexInfo( $table, $index, $fname = __METHOD__ );
802 
809  abstract function strencode( $s );
810 
814  protected function installErrorHandler() {
815  $this->lastPhpError = false;
816  $this->htmlErrors = ini_set( 'html_errors', '0' );
817  set_error_handler( [ $this, 'connectionErrorLogger' ] );
818  }
819 
825  protected function restoreErrorHandler() {
826  restore_error_handler();
827  if ( $this->htmlErrors !== false ) {
828  ini_set( 'html_errors', $this->htmlErrors );
829  }
830 
831  return $this->getLastPHPError();
832  }
833 
837  protected function getLastPHPError() {
838  if ( $this->lastPhpError ) {
839  $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
840  $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
841 
842  return $error;
843  }
844 
845  return false;
846  }
847 
855  public function connectionErrorLogger( $errno, $errstr ) {
856  $this->lastPhpError = $errstr;
857  }
858 
865  protected function getLogContext( array $extras = [] ) {
866  return array_merge(
867  [
868  'db_server' => $this->server,
869  'db_name' => $this->getDBname(),
870  'db_user' => $this->user,
871  ],
872  $extras
873  );
874  }
875 
876  final public function close( $fname = __METHOD__, $owner = null ) {
877  $error = null; // error to throw after disconnecting
878 
879  $wasOpen = (bool)$this->conn;
880  // This should mostly do nothing if the connection is already closed
881  if ( $this->conn ) {
882  // Roll back any dangling transaction first
883  if ( $this->trxLevel() ) {
884  if ( $this->trxAtomicLevels ) {
885  // Cannot let incomplete atomic sections be committed
886  $levels = $this->flatAtomicSectionList();
887  $error = "$fname: atomic sections $levels are still open";
888  } elseif ( $this->trxAutomatic ) {
889  // Only the connection manager can commit non-empty DBO_TRX transactions
890  // (empty ones we can silently roll back)
891  if ( $this->writesOrCallbacksPending() ) {
892  $error = "$fname: " .
893  "expected mass rollback of all peer transactions (DBO_TRX set)";
894  }
895  } else {
896  // Manual transactions should have been committed or rolled
897  // back, even if empty.
898  $error = "$fname: transaction is still open (from {$this->trxFname})";
899  }
900 
901  if ( $this->trxEndCallbacksSuppressed && $error === null ) {
902  $error = "$fname: callbacks are suppressed; cannot properly commit";
903  }
904 
905  // Rollback the changes and run any callbacks as needed
906  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
907  }
908 
909  // Close the actual connection in the binding handle
910  $closed = $this->closeConnection();
911  } else {
912  $closed = true; // already closed; nothing to do
913  }
914 
915  $this->conn = null;
916 
917  // Log or throw any unexpected errors after having disconnected
918  if ( $error !== null ) {
919  // T217819, T231443: if this is probably just LoadBalancer trying to recover from
920  // errors and shutdown, then log any problems and move on since the request has to
921  // end one way or another. Throwing errors is not very useful at some point.
922  if ( $this->ownerId !== null && $owner === $this->ownerId ) {
923  $this->queryLogger->error( $error );
924  } else {
925  throw new DBUnexpectedError( $this, $error );
926  }
927  }
928 
929  // Note that various subclasses call close() at the start of open(), which itself is
930  // called by replaceLostConnection(). In that case, just because onTransactionResolution()
931  // callbacks are pending does not mean that an exception should be thrown. Rather, they
932  // will be executed after the reconnection step.
933  if ( $wasOpen ) {
934  // Sanity check that no callbacks are dangling
935  $fnames = $this->pendingWriteAndCallbackCallers();
936  if ( $fnames ) {
937  throw new RuntimeException(
938  "Transaction callbacks are still pending: " . implode( ', ', $fnames )
939  );
940  }
941  }
942 
943  return $closed;
944  }
945 
954  final protected function assertHasConnectionHandle() {
955  if ( !$this->isOpen() ) {
956  throw new DBUnexpectedError( $this, "DB connection was already closed" );
957  }
958  }
959 
966  protected function assertIsWritableMaster() {
967  if ( $this->getLBInfo( 'replica' ) ) {
968  throw new DBReadOnlyRoleError(
969  $this,
970  'Write operations are not allowed on replica database connections'
971  );
972  }
973  $reason = $this->getReadOnlyReason();
974  if ( $reason !== false ) {
975  throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
976  }
977  }
978 
984  abstract protected function closeConnection();
985 
1015  abstract protected function doQuery( $sql );
1016 
1033  protected function isWriteQuery( $sql ) {
1034  // BEGIN and COMMIT queries are considered read queries here.
1035  // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1036  // treat these as write queries, in that their results have "affected rows"
1037  // as meta data as from writes, instead of "num rows" as from reads.
1038  // But, we treat them as read queries because when reading data (from
1039  // either replica or master) we use transactions to enable repeatable-read
1040  // snapshots, which ensures we get consistent results from the same snapshot
1041  // for all queries within a request. Use cases:
1042  // - Treating these as writes would trigger ChronologyProtector (see method doc).
1043  // - We use this method to reject writes to replicas, but we need to allow
1044  // use of transactions on replicas for read snapshots. This is fine given
1045  // that transactions by themselves don't make changes, only actual writes
1046  // within the transaction matter, which we still detect.
1047  return !preg_match(
1048  '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\‍(SELECT)\b/i',
1049  $sql
1050  );
1051  }
1052 
1057  protected function getQueryVerb( $sql ) {
1058  return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
1059  }
1060 
1074  protected function isTransactableQuery( $sql ) {
1075  return !in_array(
1076  $this->getQueryVerb( $sql ),
1077  [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1078  true
1079  );
1080  }
1081 
1090  protected function getTempWrites( $sql, $pseudoPermanent ) {
1091  static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1092 
1093  if ( preg_match(
1094  '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1095  $sql,
1096  $matches
1097  ) ) {
1098  $type = $pseudoPermanent ? self::$TEMP_PSEUDO_PERMANENT : self::$TEMP_NORMAL;
1099 
1100  return [ $type, $matches[1], null ];
1101  } elseif ( preg_match(
1102  '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1103  $sql,
1104  $matches
1105  ) ) {
1106  return [ $this->sessionTempTables[$matches[1]] ?? null, null, $matches[1] ];
1107  } elseif ( preg_match(
1108  '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1109  $sql,
1110  $matches
1111  ) ) {
1112  return [ $this->sessionTempTables[$matches[1]] ?? null, null, null ];
1113  } elseif ( preg_match(
1114  '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1115  $sql,
1116  $matches
1117  ) ) {
1118  return [ $this->sessionTempTables[$matches[1]] ?? null, null, null ];
1119  }
1120 
1121  return [ null, null, null ];
1122  }
1123 
1130  protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1131  if ( $ret !== false ) {
1132  if ( $tmpNew !== null ) {
1133  $this->sessionTempTables[$tmpNew] = $tmpType;
1134  }
1135  if ( $tmpDel !== null ) {
1136  unset( $this->sessionTempTables[$tmpDel] );
1137  }
1138  }
1139  }
1140 
1141  public function query( $sql, $fname = __METHOD__, $flags = 0 ) {
1142  $flags = (int)$flags; // b/c; this field used to be a bool
1143  // Sanity check that the SQL query is appropriate in the current context and is
1144  // allowed for an outside caller (e.g. does not break transaction/session tracking).
1145  $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1146 
1147  // Send the query to the server and fetch any corresponding errors
1148  list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1149  if ( $ret === false ) {
1150  $ignoreErrors = $this->fieldHasBit( $flags, self::QUERY_SILENCE_ERRORS );
1151  // Throw an error unless both the ignore flag was set and a rollback is not needed
1152  $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1153  }
1154 
1155  return $this->resultObject( $ret );
1156  }
1157 
1178  final protected function executeQuery( $sql, $fname, $flags ) {
1179  $this->assertHasConnectionHandle();
1180 
1181  $priorTransaction = $this->trxLevel();
1182 
1183  if ( $this->isWriteQuery( $sql ) ) {
1184  // In theory, non-persistent writes are allowed in read-only mode, but due to things
1185  // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1186  $this->assertIsWritableMaster();
1187  // Do not treat temporary table writes as "meaningful writes" since they are only
1188  // visible to one session and are not permanent. Profile them as reads. Integration
1189  // tests can override this behavior via $flags.
1190  $pseudoPermanent = $this->fieldHasBit( $flags, self::QUERY_PSEUDO_PERMANENT );
1191  list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1192  $isPermWrite = ( $tmpType !== self::$TEMP_NORMAL );
1193  // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1194  if ( $isPermWrite && $this->fieldHasBit( $flags, self::QUERY_REPLICA_ROLE ) ) {
1195  throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1196  }
1197  } else {
1198  // No permanent writes in this query
1199  $isPermWrite = false;
1200  // No temporary tables written to either
1201  list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1202  }
1203 
1204  // Add trace comment to the begin of the sql string, right after the operator.
1205  // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1206  $encAgent = str_replace( '/', '-', $this->agent );
1207  $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1208 
1209  // Send the query to the server and fetch any corresponding errors.
1210  // This also doubles as a "ping" to see if the connection was dropped.
1211  list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1212  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1213 
1214  // Check if the query failed due to a recoverable connection loss
1215  $allowRetry = !$this->fieldHasBit( $flags, self::QUERY_NO_RETRY );
1216  if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1217  // Silently resend the query to the server since it is safe and possible
1218  list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1219  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1220  }
1221 
1222  // Register creation and dropping of temporary tables
1223  $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1224 
1225  $corruptedTrx = false;
1226 
1227  if ( $ret === false ) {
1228  if ( $priorTransaction ) {
1229  if ( $recoverableSR ) {
1230  # We're ignoring an error that caused just the current query to be aborted.
1231  # But log the cause so we can log a deprecation notice if a caller actually
1232  # does ignore it.
1233  $this->trxStatusIgnoredCause = [ $err, $errno, $fname ];
1234  } elseif ( !$recoverableCL ) {
1235  # Either the query was aborted or all queries after BEGIN where aborted.
1236  # In the first case, the only options going forward are (a) ROLLBACK, or
1237  # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1238  # option is ROLLBACK, since the snapshots would have been released.
1239  $corruptedTrx = true; // cannot recover
1240  $this->trxStatus = self::STATUS_TRX_ERROR;
1241  $this->trxStatusCause =
1242  $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1243  $this->trxStatusIgnoredCause = null;
1244  }
1245  }
1246  }
1247 
1248  return [ $ret, $err, $errno, $corruptedTrx ];
1249  }
1250 
1269  private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1270  $priorWritesPending = $this->writesOrCallbacksPending();
1271 
1272  if ( ( $flags & self::QUERY_IGNORE_DBO_TRX ) == 0 ) {
1273  $this->beginIfImplied( $sql, $fname );
1274  }
1275 
1276  // Keep track of whether the transaction has write queries pending
1277  if ( $isPermWrite ) {
1278  $this->lastWriteTime = microtime( true );
1279  if ( $this->trxLevel() && !$this->trxDoneWrites ) {
1280  $this->trxDoneWrites = true;
1281  $this->trxProfiler->transactionWritingIn(
1282  $this->server, $this->getDomainID(), $this->trxShortId );
1283  }
1284  }
1285 
1286  $prefix = $this->getLBInfo( 'master' ) ? 'query-m: ' : 'query: ';
1287  $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId, $prefix );
1288 
1289  $startTime = microtime( true );
1290  $ps = $this->profiler
1291  ? ( $this->profiler )( $generalizedSql->stringify() )
1292  : null;
1293  $this->affectedRowCount = null;
1294  $this->lastQuery = $sql;
1295  $ret = $this->doQuery( $commentedSql );
1296  $lastError = $this->lastError();
1297  $lastErrno = $this->lastErrno();
1298 
1299  $this->affectedRowCount = $this->affectedRows();
1300  unset( $ps ); // profile out (if set)
1301  $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1302 
1303  $recoverableSR = false; // recoverable statement rollback?
1304  $recoverableCL = false; // recoverable connection loss?
1305  $reconnected = false; // reconnection both attempted and succeeded?
1306 
1307  if ( $ret !== false ) {
1308  $this->lastPing = $startTime;
1309  if ( $isPermWrite && $this->trxLevel() ) {
1310  $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1311  $this->trxWriteCallers[] = $fname;
1312  }
1313  } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1314  # Check if no meaningful session state was lost
1315  $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1316  # Update session state tracking and try to restore the connection
1317  $reconnected = $this->replaceLostConnection( __METHOD__ );
1318  } else {
1319  # Check if only the last query was rolled back
1320  $recoverableSR = $this->wasKnownStatementRollbackError();
1321  }
1322 
1323  if ( $sql === self::$PING_QUERY ) {
1324  $this->lastRoundTripEstimate = $queryRuntime;
1325  }
1326 
1327  $this->trxProfiler->recordQueryCompletion(
1328  $generalizedSql,
1329  $startTime,
1330  $isPermWrite,
1331  $isPermWrite ? $this->affectedRows() : $this->numRows( $ret )
1332  );
1333 
1334  // Avoid the overhead of logging calls unless debug mode is enabled
1335  if ( $this->getFlag( self::DBO_DEBUG ) ) {
1336  $this->queryLogger->debug(
1337  "{method} [{runtime}s] {db_host}: {sql}",
1338  [
1339  'method' => $fname,
1340  'db_host' => $this->getServer(),
1341  'sql' => $sql,
1342  'domain' => $this->getDomainID(),
1343  'runtime' => round( $queryRuntime, 3 )
1344  ]
1345  );
1346  }
1347 
1348  return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1349  }
1350 
1357  private function beginIfImplied( $sql, $fname ) {
1358  if (
1359  !$this->trxLevel() &&
1360  $this->getFlag( self::DBO_TRX ) &&
1361  $this->isTransactableQuery( $sql )
1362  ) {
1363  $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1364  $this->trxAutomatic = true;
1365  }
1366  }
1367 
1380  private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1381  // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1382  $indicativeOfReplicaRuntime = true;
1383  if ( $runtime > self::$SLOW_WRITE_SEC ) {
1384  $verb = $this->getQueryVerb( $sql );
1385  // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1386  if ( $verb === 'INSERT' ) {
1387  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS;
1388  } elseif ( $verb === 'REPLACE' ) {
1389  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS / 2;
1390  }
1391  }
1392 
1393  $this->trxWriteDuration += $runtime;
1394  $this->trxWriteQueryCount += 1;
1395  $this->trxWriteAffectedRows += $affected;
1396  if ( $indicativeOfReplicaRuntime ) {
1397  $this->trxWriteAdjDuration += $runtime;
1398  $this->trxWriteAdjQueryCount += 1;
1399  }
1400  }
1401 
1409  private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1410  $verb = $this->getQueryVerb( $sql );
1411  if ( $verb === 'USE' ) {
1412  throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1413  }
1414 
1415  if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1416  return;
1417  }
1418 
1419  if ( $this->trxStatus < self::STATUS_TRX_OK ) {
1420  throw new DBTransactionStateError(
1421  $this,
1422  "Cannot execute query from $fname while transaction status is ERROR",
1423  [],
1424  $this->trxStatusCause
1425  );
1426  } elseif ( $this->trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1427  list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause;
1428  call_user_func( $this->deprecationLogger,
1429  "Caller from $fname ignored an error originally raised from $iFname: " .
1430  "[$iLastErrno] $iLastError"
1431  );
1432  $this->trxStatusIgnoredCause = null;
1433  }
1434  }
1435 
1436  public function assertNoOpenTransactions() {
1437  if ( $this->explicitTrxActive() ) {
1438  throw new DBTransactionError(
1439  $this,
1440  "Explicit transaction still active. A caller may have caught an error. "
1441  . "Open transactions: " . $this->flatAtomicSectionList()
1442  );
1443  }
1444  }
1445 
1455  private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1456  # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1457  # Dropped connections also mean that named locks are automatically released.
1458  # Only allow error suppression in autocommit mode or when the lost transaction
1459  # didn't matter anyway (aside from DBO_TRX snapshot loss).
1460  if ( $this->sessionNamedLocks ) {
1461  return false; // possible critical section violation
1462  } elseif ( $this->sessionTempTables ) {
1463  return false; // tables might be queried latter
1464  } elseif ( $sql === 'COMMIT' ) {
1465  return !$priorWritesPending; // nothing written anyway? (T127428)
1466  } elseif ( $sql === 'ROLLBACK' ) {
1467  return true; // transaction lost...which is also what was requested :)
1468  } elseif ( $this->explicitTrxActive() ) {
1469  return false; // don't drop atomocity and explicit snapshots
1470  } elseif ( $priorWritesPending ) {
1471  return false; // prior writes lost from implicit transaction
1472  }
1473 
1474  return true;
1475  }
1476 
1480  private function handleSessionLossPreconnect() {
1481  // Clean up tracking of session-level things...
1482  // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1483  // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1484  $this->sessionTempTables = [];
1485  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1486  // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1487  $this->sessionNamedLocks = [];
1488  // Session loss implies transaction loss
1489  $oldTrxShortId = $this->consumeTrxShortId();
1490  $this->trxAtomicCounter = 0;
1491  $this->trxIdleCallbacks = []; // T67263; transaction already lost
1492  $this->trxPreCommitCallbacks = []; // T67263; transaction already lost
1493  // Clear additional subclass fields
1495  // @note: leave trxRecurringCallbacks in place
1496  if ( $this->trxDoneWrites ) {
1497  $this->trxProfiler->transactionWritingOut(
1498  $this->server,
1499  $this->getDomainID(),
1500  $oldTrxShortId,
1501  $this->pendingWriteQueryDuration( self::ESTIMATE_TOTAL ),
1502  $this->trxWriteAffectedRows
1503  );
1504  }
1505  }
1506 
1510  protected function doHandleSessionLossPreconnect() {
1511  // no-op
1512  }
1513 
1517  private function handleSessionLossPostconnect() {
1518  try {
1519  // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1520  // If callback suppression is set then the array will remain unhandled.
1521  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1522  } catch ( Exception $ex ) {
1523  // Already logged; move on...
1524  }
1525  try {
1526  // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1527  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1528  } catch ( Exception $ex ) {
1529  // Already logged; move on...
1530  }
1531  }
1532 
1538  private function consumeTrxShortId() {
1539  $old = $this->trxShortId;
1540  $this->trxShortId = '';
1541 
1542  return $old;
1543  }
1544 
1555  protected function wasQueryTimeout( $error, $errno ) {
1556  return false;
1557  }
1558 
1570  public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1571  if ( $ignore ) {
1572  $this->queryLogger->debug( "SQL ERROR (ignored): $error" );
1573  } else {
1574  throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1575  }
1576  }
1577 
1585  private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1586  $this->queryLogger->error(
1587  "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1588  $this->getLogContext( [
1589  'method' => __METHOD__,
1590  'errno' => $errno,
1591  'error' => $error,
1592  'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1593  'fname' => $fname,
1594  'exception' => new RuntimeException()
1595  ] )
1596  );
1597 
1598  if ( $this->wasQueryTimeout( $error, $errno ) ) {
1599  $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1600  } elseif ( $this->wasConnectionError( $errno ) ) {
1601  $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1602  } else {
1603  $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1604  }
1605 
1606  return $e;
1607  }
1608 
1613  final protected function newExceptionAfterConnectError( $error ) {
1614  // Connection was not fully initialized and is not safe for use
1615  $this->conn = null;
1616 
1617  $this->connLogger->error(
1618  "Error connecting to {db_server} as user {db_user}: {error}",
1619  $this->getLogContext( [
1620  'error' => $error,
1621  'exception' => new RuntimeException()
1622  ] )
1623  );
1624 
1625  return new DBConnectionError( $this, $error );
1626  }
1627 
1628  public function freeResult( $res ) {
1629  }
1630 
1631  public function selectField(
1632  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1633  ) {
1634  if ( $var === '*' ) { // sanity
1635  throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1636  }
1637 
1638  if ( !is_array( $options ) ) {
1639  $options = [ $options ];
1640  }
1641 
1642  $options['LIMIT'] = 1;
1643 
1644  $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1645  if ( $res === false ) {
1646  throw new DBUnexpectedError( $this, "Got false from select()" );
1647  }
1648 
1649  $row = $this->fetchRow( $res );
1650  if ( $row === false ) {
1651  return false;
1652  }
1653 
1654  return reset( $row );
1655  }
1656 
1657  public function selectFieldValues(
1658  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1659  ) {
1660  if ( $var === '*' ) { // sanity
1661  throw new DBUnexpectedError( $this, "Cannot use a * field" );
1662  } elseif ( !is_string( $var ) ) { // sanity
1663  throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1664  }
1665 
1666  if ( !is_array( $options ) ) {
1667  $options = [ $options ];
1668  }
1669 
1670  $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1671  if ( $res === false ) {
1672  throw new DBUnexpectedError( $this, "Got false from select()" );
1673  }
1674 
1675  $values = [];
1676  foreach ( $res as $row ) {
1677  $values[] = $row->value;
1678  }
1679 
1680  return $values;
1681  }
1682 
1693  protected function makeSelectOptions( array $options ) {
1694  $preLimitTail = $postLimitTail = '';
1695  $startOpts = '';
1696 
1697  $noKeyOptions = [];
1698 
1699  foreach ( $options as $key => $option ) {
1700  if ( is_numeric( $key ) ) {
1701  $noKeyOptions[$option] = true;
1702  }
1703  }
1704 
1705  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1706 
1707  $preLimitTail .= $this->makeOrderBy( $options );
1708 
1709  if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1710  $postLimitTail .= ' FOR UPDATE';
1711  }
1712 
1713  if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1714  $postLimitTail .= ' LOCK IN SHARE MODE';
1715  }
1716 
1717  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1718  $startOpts .= 'DISTINCT';
1719  }
1720 
1721  # Various MySQL extensions
1722  if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1723  $startOpts .= ' /*! STRAIGHT_JOIN */';
1724  }
1725 
1726  if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1727  $startOpts .= ' SQL_BIG_RESULT';
1728  }
1729 
1730  if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1731  $startOpts .= ' SQL_BUFFER_RESULT';
1732  }
1733 
1734  if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1735  $startOpts .= ' SQL_SMALL_RESULT';
1736  }
1737 
1738  if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1739  $startOpts .= ' SQL_CALC_FOUND_ROWS';
1740  }
1741 
1742  if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1743  $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1744  } else {
1745  $useIndex = '';
1746  }
1747  if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1748  $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1749  } else {
1750  $ignoreIndex = '';
1751  }
1752 
1753  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1754  }
1755 
1764  protected function makeGroupByWithHaving( $options ) {
1765  $sql = '';
1766  if ( isset( $options['GROUP BY'] ) ) {
1767  $gb = is_array( $options['GROUP BY'] )
1768  ? implode( ',', $options['GROUP BY'] )
1769  : $options['GROUP BY'];
1770  $sql .= ' GROUP BY ' . $gb;
1771  }
1772  if ( isset( $options['HAVING'] ) ) {
1773  $having = is_array( $options['HAVING'] )
1774  ? $this->makeList( $options['HAVING'], self::LIST_AND )
1775  : $options['HAVING'];
1776  $sql .= ' HAVING ' . $having;
1777  }
1778 
1779  return $sql;
1780  }
1781 
1790  protected function makeOrderBy( $options ) {
1791  if ( isset( $options['ORDER BY'] ) ) {
1792  $ob = is_array( $options['ORDER BY'] )
1793  ? implode( ',', $options['ORDER BY'] )
1794  : $options['ORDER BY'];
1795 
1796  return ' ORDER BY ' . $ob;
1797  }
1798 
1799  return '';
1800  }
1801 
1802  public function select(
1803  $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1804  ) {
1805  $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1806 
1807  return $this->query( $sql, $fname );
1808  }
1809 
1810  public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1811  $options = [], $join_conds = []
1812  ) {
1813  if ( is_array( $vars ) ) {
1814  $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1815  } else {
1816  $fields = $vars;
1817  }
1818 
1819  $options = (array)$options;
1820  $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1821  ? $options['USE INDEX']
1822  : [];
1823  $ignoreIndexes = (
1824  isset( $options['IGNORE INDEX'] ) &&
1825  is_array( $options['IGNORE INDEX'] )
1826  )
1827  ? $options['IGNORE INDEX']
1828  : [];
1829 
1830  if (
1831  $this->selectOptionsIncludeLocking( $options ) &&
1832  $this->selectFieldsOrOptionsAggregate( $vars, $options )
1833  ) {
1834  // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
1835  // functions. Discourage use of such queries to encourage compatibility.
1836  call_user_func(
1837  $this->deprecationLogger,
1838  __METHOD__ . ": aggregation used with a locking SELECT ($fname)"
1839  );
1840  }
1841 
1842  if ( is_array( $table ) ) {
1843  $from = ' FROM ' .
1845  $table, $useIndexes, $ignoreIndexes, $join_conds );
1846  } elseif ( $table != '' ) {
1847  $from = ' FROM ' .
1849  [ $table ], $useIndexes, $ignoreIndexes, [] );
1850  } else {
1851  $from = '';
1852  }
1853 
1854  list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1855  $this->makeSelectOptions( $options );
1856 
1857  if ( is_array( $conds ) ) {
1858  $conds = $this->makeList( $conds, self::LIST_AND );
1859  }
1860 
1861  if ( $conds === null || $conds === false ) {
1862  $this->queryLogger->warning(
1863  __METHOD__
1864  . ' called from '
1865  . $fname
1866  . ' with incorrect parameters: $conds must be a string or an array'
1867  );
1868  $conds = '';
1869  }
1870 
1871  if ( $conds === '' || $conds === '*' ) {
1872  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1873  } elseif ( is_string( $conds ) ) {
1874  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1875  "WHERE $conds $preLimitTail";
1876  } else {
1877  throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1878  }
1879 
1880  if ( isset( $options['LIMIT'] ) ) {
1881  $sql = $this->limitResult( $sql, $options['LIMIT'],
1882  $options['OFFSET'] ?? false );
1883  }
1884  $sql = "$sql $postLimitTail";
1885 
1886  if ( isset( $options['EXPLAIN'] ) ) {
1887  $sql = 'EXPLAIN ' . $sql;
1888  }
1889 
1890  return $sql;
1891  }
1892 
1893  public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1894  $options = [], $join_conds = []
1895  ) {
1896  $options = (array)$options;
1897  $options['LIMIT'] = 1;
1898 
1899  $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1900  if ( $res === false ) {
1901  throw new DBUnexpectedError( $this, "Got false from select()" );
1902  }
1903 
1904  if ( !$this->numRows( $res ) ) {
1905  return false;
1906  }
1907 
1908  return $this->fetchObject( $res );
1909  }
1910 
1911  public function estimateRowCount(
1912  $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1913  ) {
1914  $conds = $this->normalizeConditions( $conds, $fname );
1915  $column = $this->extractSingleFieldFromList( $var );
1916  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1917  $conds[] = "$column IS NOT NULL";
1918  }
1919 
1920  $res = $this->select(
1921  $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1922  );
1923  $row = $res ? $this->fetchRow( $res ) : [];
1924 
1925  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1926  }
1927 
1928  public function selectRowCount(
1929  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1930  ) {
1931  $conds = $this->normalizeConditions( $conds, $fname );
1932  $column = $this->extractSingleFieldFromList( $var );
1933  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1934  $conds[] = "$column IS NOT NULL";
1935  }
1936 
1937  $res = $this->select(
1938  [
1939  'tmp_count' => $this->buildSelectSubquery(
1940  $tables,
1941  '1',
1942  $conds,
1943  $fname,
1944  $options,
1945  $join_conds
1946  )
1947  ],
1948  [ 'rowcount' => 'COUNT(*)' ],
1949  [],
1950  $fname
1951  );
1952  $row = $res ? $this->fetchRow( $res ) : [];
1953 
1954  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1955  }
1956 
1961  private function selectOptionsIncludeLocking( $options ) {
1962  $options = (array)$options;
1963  foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1964  if ( in_array( $lock, $options, true ) ) {
1965  return true;
1966  }
1967  }
1968 
1969  return false;
1970  }
1971 
1977  private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1978  foreach ( (array)$options as $key => $value ) {
1979  if ( is_string( $key ) ) {
1980  if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1981  return true;
1982  }
1983  } elseif ( is_string( $value ) ) {
1984  if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1985  return true;
1986  }
1987  }
1988  }
1989 
1990  $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1991  foreach ( (array)$fields as $field ) {
1992  if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1993  return true;
1994  }
1995  }
1996 
1997  return false;
1998  }
1999 
2005  final protected function normalizeConditions( $conds, $fname ) {
2006  if ( $conds === null || $conds === false ) {
2007  $this->queryLogger->warning(
2008  __METHOD__
2009  . ' called from '
2010  . $fname
2011  . ' with incorrect parameters: $conds must be a string or an array'
2012  );
2013  $conds = '';
2014  }
2015 
2016  if ( !is_array( $conds ) ) {
2017  $conds = ( $conds === '' ) ? [] : [ $conds ];
2018  }
2019 
2020  return $conds;
2021  }
2022 
2028  final protected function extractSingleFieldFromList( $var ) {
2029  if ( is_array( $var ) ) {
2030  if ( !$var ) {
2031  $column = null;
2032  } elseif ( count( $var ) == 1 ) {
2033  $column = $var[0] ?? reset( $var );
2034  } else {
2035  throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns' );
2036  }
2037  } else {
2038  $column = $var;
2039  }
2040 
2041  return $column;
2042  }
2043 
2044  public function lockForUpdate(
2045  $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2046  ) {
2047  if ( !$this->trxLevel() && !$this->getFlag( self::DBO_TRX ) ) {
2048  throw new DBUnexpectedError(
2049  $this,
2050  __METHOD__ . ': no transaction is active nor is DBO_TRX set'
2051  );
2052  }
2053 
2054  $options = (array)$options;
2055  $options[] = 'FOR UPDATE';
2056 
2057  return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2058  }
2059 
2060  public function fieldExists( $table, $field, $fname = __METHOD__ ) {
2061  $info = $this->fieldInfo( $table, $field );
2062 
2063  return (bool)$info;
2064  }
2065 
2066  public function indexExists( $table, $index, $fname = __METHOD__ ) {
2067  if ( !$this->tableExists( $table ) ) {
2068  return null;
2069  }
2070 
2071  $info = $this->indexInfo( $table, $index, $fname );
2072  if ( is_null( $info ) ) {
2073  return null;
2074  } else {
2075  return $info !== false;
2076  }
2077  }
2078 
2079  abstract public function tableExists( $table, $fname = __METHOD__ );
2080 
2081  public function indexUnique( $table, $index ) {
2082  $indexInfo = $this->indexInfo( $table, $index );
2083 
2084  if ( !$indexInfo ) {
2085  return null;
2086  }
2087 
2088  return !$indexInfo[0]->Non_unique;
2089  }
2090 
2097  protected function makeInsertOptions( $options ) {
2098  return implode( ' ', $options );
2099  }
2100 
2101  public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
2102  # No rows to insert, easy just return now
2103  if ( !count( $a ) ) {
2104  return true;
2105  }
2106 
2107  $table = $this->tableName( $table );
2108 
2109  if ( !is_array( $options ) ) {
2110  $options = [ $options ];
2111  }
2112 
2113  $options = $this->makeInsertOptions( $options );
2114 
2115  if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2116  $multi = true;
2117  $keys = array_keys( $a[0] );
2118  } else {
2119  $multi = false;
2120  $keys = array_keys( $a );
2121  }
2122 
2123  $sql = 'INSERT ' . $options .
2124  " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2125 
2126  if ( $multi ) {
2127  $first = true;
2128  foreach ( $a as $row ) {
2129  if ( $first ) {
2130  $first = false;
2131  } else {
2132  $sql .= ',';
2133  }
2134  $sql .= '(' . $this->makeList( $row ) . ')';
2135  }
2136  } else {
2137  $sql .= '(' . $this->makeList( $a ) . ')';
2138  }
2139 
2140  $this->query( $sql, $fname );
2141 
2142  return true;
2143  }
2144 
2151  protected function makeUpdateOptionsArray( $options ) {
2152  if ( !is_array( $options ) ) {
2153  $options = [ $options ];
2154  }
2155 
2156  $opts = [];
2157 
2158  if ( in_array( 'IGNORE', $options ) ) {
2159  $opts[] = 'IGNORE';
2160  }
2161 
2162  return $opts;
2163  }
2164 
2171  protected function makeUpdateOptions( $options ) {
2172  $opts = $this->makeUpdateOptionsArray( $options );
2173 
2174  return implode( ' ', $opts );
2175  }
2176 
2177  public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
2178  $table = $this->tableName( $table );
2179  $opts = $this->makeUpdateOptions( $options );
2180  $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
2181 
2182  // @phan-suppress-next-line PhanTypeComparisonFromArray
2183  if ( $conds !== [] && $conds !== '*' ) {
2184  $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
2185  }
2186 
2187  $this->query( $sql, $fname );
2188 
2189  return true;
2190  }
2191 
2192  public function makeList( $a, $mode = self::LIST_COMMA ) {
2193  if ( !is_array( $a ) ) {
2194  throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
2195  }
2196 
2197  $first = true;
2198  $list = '';
2199 
2200  foreach ( $a as $field => $value ) {
2201  if ( !$first ) {
2202  if ( $mode == self::LIST_AND ) {
2203  $list .= ' AND ';
2204  } elseif ( $mode == self::LIST_OR ) {
2205  $list .= ' OR ';
2206  } else {
2207  $list .= ',';
2208  }
2209  } else {
2210  $first = false;
2211  }
2212 
2213  if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
2214  $list .= "($value)";
2215  } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
2216  $list .= "$value";
2217  } elseif (
2218  ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
2219  ) {
2220  // Remove null from array to be handled separately if found
2221  $includeNull = false;
2222  foreach ( array_keys( $value, null, true ) as $nullKey ) {
2223  $includeNull = true;
2224  unset( $value[$nullKey] );
2225  }
2226  if ( count( $value ) == 0 && !$includeNull ) {
2227  throw new InvalidArgumentException(
2228  __METHOD__ . ": empty input for field $field" );
2229  } elseif ( count( $value ) == 0 ) {
2230  // only check if $field is null
2231  $list .= "$field IS NULL";
2232  } else {
2233  // IN clause contains at least one valid element
2234  if ( $includeNull ) {
2235  // Group subconditions to ensure correct precedence
2236  $list .= '(';
2237  }
2238  if ( count( $value ) == 1 ) {
2239  // Special-case single values, as IN isn't terribly efficient
2240  // Don't necessarily assume the single key is 0; we don't
2241  // enforce linear numeric ordering on other arrays here.
2242  $value = array_values( $value )[0];
2243  $list .= $field . " = " . $this->addQuotes( $value );
2244  } else {
2245  $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2246  }
2247  // if null present in array, append IS NULL
2248  if ( $includeNull ) {
2249  $list .= " OR $field IS NULL)";
2250  }
2251  }
2252  } elseif ( $value === null ) {
2253  if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2254  $list .= "$field IS ";
2255  } elseif ( $mode == self::LIST_SET ) {
2256  $list .= "$field = ";
2257  }
2258  $list .= 'NULL';
2259  } else {
2260  if (
2261  $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2262  ) {
2263  $list .= "$field = ";
2264  }
2265  $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
2266  }
2267  }
2268 
2269  return $list;
2270  }
2271 
2272  public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2273  $conds = [];
2274 
2275  foreach ( $data as $base => $sub ) {
2276  if ( count( $sub ) ) {
2277  $conds[] = $this->makeList(
2278  [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2279  self::LIST_AND );
2280  }
2281  }
2282 
2283  if ( $conds ) {
2284  return $this->makeList( $conds, self::LIST_OR );
2285  } else {
2286  // Nothing to search for...
2287  return false;
2288  }
2289  }
2290 
2291  public function aggregateValue( $valuedata, $valuename = 'value' ) {
2292  return $valuename;
2293  }
2294 
2295  public function bitNot( $field ) {
2296  return "(~$field)";
2297  }
2298 
2299  public function bitAnd( $fieldLeft, $fieldRight ) {
2300  return "($fieldLeft & $fieldRight)";
2301  }
2302 
2303  public function bitOr( $fieldLeft, $fieldRight ) {
2304  return "($fieldLeft | $fieldRight)";
2305  }
2306 
2307  public function buildConcat( $stringList ) {
2308  return 'CONCAT(' . implode( ',', $stringList ) . ')';
2309  }
2310 
2311  public function buildGroupConcatField(
2312  $delim, $table, $field, $conds = '', $join_conds = []
2313  ) {
2314  $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2315 
2316  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2317  }
2318 
2319  public function buildSubstring( $input, $startPosition, $length = null ) {
2320  $this->assertBuildSubstringParams( $startPosition, $length );
2321  $functionBody = "$input FROM $startPosition";
2322  if ( $length !== null ) {
2323  $functionBody .= " FOR $length";
2324  }
2325  return 'SUBSTRING(' . $functionBody . ')';
2326  }
2327 
2340  protected function assertBuildSubstringParams( $startPosition, $length ) {
2341  if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2342  throw new InvalidArgumentException(
2343  '$startPosition must be a positive integer'
2344  );
2345  }
2346  if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2347  throw new InvalidArgumentException(
2348  '$length must be null or an integer greater than or equal to 0'
2349  );
2350  }
2351  }
2352 
2353  public function buildStringCast( $field ) {
2354  // In theory this should work for any standards-compliant
2355  // SQL implementation, although it may not be the best way to do it.
2356  return "CAST( $field AS CHARACTER )";
2357  }
2358 
2359  public function buildIntegerCast( $field ) {
2360  return 'CAST( ' . $field . ' AS INTEGER )';
2361  }
2362 
2363  public function buildSelectSubquery(
2364  $table, $vars, $conds = '', $fname = __METHOD__,
2365  $options = [], $join_conds = []
2366  ) {
2367  return new Subquery(
2368  $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2369  );
2370  }
2371 
2372  public function databasesAreIndependent() {
2373  return false;
2374  }
2375 
2376  final public function selectDB( $db ) {
2377  $this->selectDomain( new DatabaseDomain(
2378  $db,
2379  $this->currentDomain->getSchema(),
2380  $this->currentDomain->getTablePrefix()
2381  ) );
2382 
2383  return true;
2384  }
2385 
2386  final public function selectDomain( $domain ) {
2387  $this->doSelectDomain( DatabaseDomain::newFromId( $domain ) );
2388  }
2389 
2396  protected function doSelectDomain( DatabaseDomain $domain ) {
2397  $this->currentDomain = $domain;
2398  }
2399 
2400  public function getDBname() {
2401  return $this->currentDomain->getDatabase();
2402  }
2403 
2404  public function getServer() {
2405  return $this->server;
2406  }
2407 
2408  public function tableName( $name, $format = 'quoted' ) {
2409  if ( $name instanceof Subquery ) {
2410  throw new DBUnexpectedError(
2411  $this,
2412  __METHOD__ . ': got Subquery instance when expecting a string'
2413  );
2414  }
2415 
2416  # Skip the entire process when we have a string quoted on both ends.
2417  # Note that we check the end so that we will still quote any use of
2418  # use of `database`.table. But won't break things if someone wants
2419  # to query a database table with a dot in the name.
2420  if ( $this->isQuotedIdentifier( $name ) ) {
2421  return $name;
2422  }
2423 
2424  # Lets test for any bits of text that should never show up in a table
2425  # name. Basically anything like JOIN or ON which are actually part of
2426  # SQL queries, but may end up inside of the table value to combine
2427  # sql. Such as how the API is doing.
2428  # Note that we use a whitespace test rather than a \b test to avoid
2429  # any remote case where a word like on may be inside of a table name
2430  # surrounded by symbols which may be considered word breaks.
2431  if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2432  $this->queryLogger->warning(
2433  __METHOD__ . ": use of subqueries is not supported this way",
2434  [ 'exception' => new RuntimeException() ]
2435  );
2436 
2437  return $name;
2438  }
2439 
2440  # Split database and table into proper variables.
2441  list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2442 
2443  # Quote $table and apply the prefix if not quoted.
2444  # $tableName might be empty if this is called from Database::replaceVars()
2445  $tableName = "{$prefix}{$table}";
2446  if ( $format === 'quoted'
2447  && !$this->isQuotedIdentifier( $tableName )
2448  && $tableName !== ''
2449  ) {
2450  $tableName = $this->addIdentifierQuotes( $tableName );
2451  }
2452 
2453  # Quote $schema and $database and merge them with the table name if needed
2454  $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2455  $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2456 
2457  return $tableName;
2458  }
2459 
2466  protected function qualifiedTableComponents( $name ) {
2467  # We reverse the explode so that database.table and table both output the correct table.
2468  $dbDetails = explode( '.', $name, 3 );
2469  if ( count( $dbDetails ) == 3 ) {
2470  list( $database, $schema, $table ) = $dbDetails;
2471  # We don't want any prefix added in this case
2472  $prefix = '';
2473  } elseif ( count( $dbDetails ) == 2 ) {
2474  list( $database, $table ) = $dbDetails;
2475  # We don't want any prefix added in this case
2476  $prefix = '';
2477  # In dbs that support it, $database may actually be the schema
2478  # but that doesn't affect any of the functionality here
2479  $schema = '';
2480  } else {
2481  list( $table ) = $dbDetails;
2482  if ( isset( $this->tableAliases[$table] ) ) {
2483  $database = $this->tableAliases[$table]['dbname'];
2484  $schema = is_string( $this->tableAliases[$table]['schema'] )
2485  ? $this->tableAliases[$table]['schema']
2486  : $this->relationSchemaQualifier();
2487  $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2488  ? $this->tableAliases[$table]['prefix']
2489  : $this->tablePrefix();
2490  } else {
2491  $database = '';
2492  $schema = $this->relationSchemaQualifier(); # Default schema
2493  $prefix = $this->tablePrefix(); # Default prefix
2494  }
2495  }
2496 
2497  return [ $database, $schema, $prefix, $table ];
2498  }
2499 
2506  private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2507  if ( strlen( $namespace ) ) {
2508  if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2509  $namespace = $this->addIdentifierQuotes( $namespace );
2510  }
2511  $relation = $namespace . '.' . $relation;
2512  }
2513 
2514  return $relation;
2515  }
2516 
2517  public function tableNames() {
2518  $inArray = func_get_args();
2519  $retVal = [];
2520 
2521  foreach ( $inArray as $name ) {
2522  $retVal[$name] = $this->tableName( $name );
2523  }
2524 
2525  return $retVal;
2526  }
2527 
2528  public function tableNamesN() {
2529  $inArray = func_get_args();
2530  $retVal = [];
2531 
2532  foreach ( $inArray as $name ) {
2533  $retVal[] = $this->tableName( $name );
2534  }
2535 
2536  return $retVal;
2537  }
2538 
2550  protected function tableNameWithAlias( $table, $alias = false ) {
2551  if ( is_string( $table ) ) {
2552  $quotedTable = $this->tableName( $table );
2553  } elseif ( $table instanceof Subquery ) {
2554  $quotedTable = (string)$table;
2555  } else {
2556  throw new InvalidArgumentException( "Table must be a string or Subquery" );
2557  }
2558 
2559  if ( $alias === false || $alias === $table ) {
2560  if ( $table instanceof Subquery ) {
2561  throw new InvalidArgumentException( "Subquery table missing alias" );
2562  }
2563 
2564  return $quotedTable;
2565  } else {
2566  return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2567  }
2568  }
2569 
2576  protected function tableNamesWithAlias( $tables ) {
2577  $retval = [];
2578  foreach ( $tables as $alias => $table ) {
2579  if ( is_numeric( $alias ) ) {
2580  $alias = $table;
2581  }
2582  $retval[] = $this->tableNameWithAlias( $table, $alias );
2583  }
2584 
2585  return $retval;
2586  }
2587 
2596  protected function fieldNameWithAlias( $name, $alias = false ) {
2597  if ( !$alias || (string)$alias === (string)$name ) {
2598  return $name;
2599  } else {
2600  return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2601  }
2602  }
2603 
2610  protected function fieldNamesWithAlias( $fields ) {
2611  $retval = [];
2612  foreach ( $fields as $alias => $field ) {
2613  if ( is_numeric( $alias ) ) {
2614  $alias = $field;
2615  }
2616  $retval[] = $this->fieldNameWithAlias( $field, $alias );
2617  }
2618 
2619  return $retval;
2620  }
2621 
2633  $tables, $use_index = [], $ignore_index = [], $join_conds = []
2634  ) {
2635  $ret = [];
2636  $retJOIN = [];
2637  $use_index = (array)$use_index;
2638  $ignore_index = (array)$ignore_index;
2639  $join_conds = (array)$join_conds;
2640 
2641  foreach ( $tables as $alias => $table ) {
2642  if ( !is_string( $alias ) ) {
2643  // No alias? Set it equal to the table name
2644  $alias = $table;
2645  }
2646 
2647  if ( is_array( $table ) ) {
2648  // A parenthesized group
2649  if ( count( $table ) > 1 ) {
2650  $joinedTable = '(' .
2652  $table, $use_index, $ignore_index, $join_conds ) . ')';
2653  } else {
2654  // Degenerate case
2655  $innerTable = reset( $table );
2656  $innerAlias = key( $table );
2657  $joinedTable = $this->tableNameWithAlias(
2658  $innerTable,
2659  is_string( $innerAlias ) ? $innerAlias : $innerTable
2660  );
2661  }
2662  } else {
2663  $joinedTable = $this->tableNameWithAlias( $table, $alias );
2664  }
2665 
2666  // Is there a JOIN clause for this table?
2667  if ( isset( $join_conds[$alias] ) ) {
2668  list( $joinType, $conds ) = $join_conds[$alias];
2669  $tableClause = $joinType;
2670  $tableClause .= ' ' . $joinedTable;
2671  if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2672  $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2673  if ( $use != '' ) {
2674  $tableClause .= ' ' . $use;
2675  }
2676  }
2677  if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2678  $ignore = $this->ignoreIndexClause(
2679  implode( ',', (array)$ignore_index[$alias] ) );
2680  if ( $ignore != '' ) {
2681  $tableClause .= ' ' . $ignore;
2682  }
2683  }
2684  $on = $this->makeList( (array)$conds, self::LIST_AND );
2685  if ( $on != '' ) {
2686  $tableClause .= ' ON (' . $on . ')';
2687  }
2688 
2689  $retJOIN[] = $tableClause;
2690  } elseif ( isset( $use_index[$alias] ) ) {
2691  // Is there an INDEX clause for this table?
2692  $tableClause = $joinedTable;
2693  $tableClause .= ' ' . $this->useIndexClause(
2694  implode( ',', (array)$use_index[$alias] )
2695  );
2696 
2697  $ret[] = $tableClause;
2698  } elseif ( isset( $ignore_index[$alias] ) ) {
2699  // Is there an INDEX clause for this table?
2700  $tableClause = $joinedTable;
2701  $tableClause .= ' ' . $this->ignoreIndexClause(
2702  implode( ',', (array)$ignore_index[$alias] )
2703  );
2704 
2705  $ret[] = $tableClause;
2706  } else {
2707  $tableClause = $joinedTable;
2708 
2709  $ret[] = $tableClause;
2710  }
2711  }
2712 
2713  // We can't separate explicit JOIN clauses with ',', use ' ' for those
2714  $implicitJoins = implode( ',', $ret );
2715  $explicitJoins = implode( ' ', $retJOIN );
2716 
2717  // Compile our final table clause
2718  return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2719  }
2720 
2727  protected function indexName( $index ) {
2728  return $this->indexAliases[$index] ?? $index;
2729  }
2730 
2731  public function addQuotes( $s ) {
2732  if ( $s instanceof Blob ) {
2733  $s = $s->fetch();
2734  }
2735  if ( $s === null ) {
2736  return 'NULL';
2737  } elseif ( is_bool( $s ) ) {
2738  return (int)$s;
2739  } else {
2740  # This will also quote numeric values. This should be harmless,
2741  # and protects against weird problems that occur when they really
2742  # _are_ strings such as article titles and string->number->string
2743  # conversion is not 1:1.
2744  return "'" . $this->strencode( $s ) . "'";
2745  }
2746  }
2747 
2748  public function addIdentifierQuotes( $s ) {
2749  return '"' . str_replace( '"', '""', $s ) . '"';
2750  }
2751 
2761  public function isQuotedIdentifier( $name ) {
2762  return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2763  }
2764 
2770  protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2771  return str_replace( [ $escapeChar, '%', '_' ],
2772  [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2773  $s );
2774  }
2775 
2776  public function buildLike( $param, ...$params ) {
2777  if ( is_array( $param ) ) {
2778  $params = $param;
2779  } else {
2780  $params = func_get_args();
2781  }
2782 
2783  $s = '';
2784 
2785  // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2786  // may escape backslashes, creating problems of double escaping. The `
2787  // character has good cross-DBMS compatibility, avoiding special operators
2788  // in MS SQL like ^ and %
2789  $escapeChar = '`';
2790 
2791  foreach ( $params as $value ) {
2792  if ( $value instanceof LikeMatch ) {
2793  $s .= $value->toString();
2794  } else {
2795  $s .= $this->escapeLikeInternal( $value, $escapeChar );
2796  }
2797  }
2798 
2799  return ' LIKE ' .
2800  $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2801  }
2802 
2803  public function anyChar() {
2804  return new LikeMatch( '_' );
2805  }
2806 
2807  public function anyString() {
2808  return new LikeMatch( '%' );
2809  }
2810 
2811  public function nextSequenceValue( $seqName ) {
2812  return null;
2813  }
2814 
2825  public function useIndexClause( $index ) {
2826  return '';
2827  }
2828 
2839  public function ignoreIndexClause( $index ) {
2840  return '';
2841  }
2842 
2843  public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2844  if ( count( $rows ) == 0 ) {
2845  return;
2846  }
2847 
2848  $uniqueIndexes = (array)$uniqueIndexes;
2849  // Single row case
2850  if ( !is_array( reset( $rows ) ) ) {
2851  $rows = [ $rows ];
2852  }
2853 
2854  try {
2855  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2856  $affectedRowCount = 0;
2857  foreach ( $rows as $row ) {
2858  // Delete rows which collide with this one
2859  $indexWhereClauses = [];
2860  foreach ( $uniqueIndexes as $index ) {
2861  $indexColumns = (array)$index;
2862  $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2863  if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2864  throw new DBUnexpectedError(
2865  $this,
2866  'New record does not provide all values for unique key (' .
2867  implode( ', ', $indexColumns ) . ')'
2868  );
2869  } elseif ( in_array( null, $indexRowValues, true ) ) {
2870  throw new DBUnexpectedError(
2871  $this,
2872  'New record has a null value for unique key (' .
2873  implode( ', ', $indexColumns ) . ')'
2874  );
2875  }
2876  $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND );
2877  }
2878 
2879  if ( $indexWhereClauses ) {
2880  $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR ), $fname );
2881  $affectedRowCount += $this->affectedRows();
2882  }
2883 
2884  // Now insert the row
2885  $this->insert( $table, $row, $fname );
2886  $affectedRowCount += $this->affectedRows();
2887  }
2888  $this->endAtomic( $fname );
2889  $this->affectedRowCount = $affectedRowCount;
2890  } catch ( Exception $e ) {
2891  $this->cancelAtomic( $fname );
2892  throw $e;
2893  }
2894  }
2895 
2904  protected function nativeReplace( $table, $rows, $fname ) {
2905  $table = $this->tableName( $table );
2906 
2907  # Single row case
2908  if ( !is_array( reset( $rows ) ) ) {
2909  $rows = [ $rows ];
2910  }
2911 
2912  $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2913  $first = true;
2914 
2915  foreach ( $rows as $row ) {
2916  if ( $first ) {
2917  $first = false;
2918  } else {
2919  $sql .= ',';
2920  }
2921 
2922  $sql .= '(' . $this->makeList( $row ) . ')';
2923  }
2924 
2925  $this->query( $sql, $fname );
2926  }
2927 
2928  public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2929  $fname = __METHOD__
2930  ) {
2931  if ( $rows === [] ) {
2932  return true; // nothing to do
2933  }
2934 
2935  $uniqueIndexes = (array)$uniqueIndexes;
2936  if ( !is_array( reset( $rows ) ) ) {
2937  $rows = [ $rows ];
2938  }
2939 
2940  if ( count( $uniqueIndexes ) ) {
2941  $clauses = []; // list WHERE clauses that each identify a single row
2942  foreach ( $rows as $row ) {
2943  foreach ( $uniqueIndexes as $index ) {
2944  $index = is_array( $index ) ? $index : [ $index ]; // columns
2945  $rowKey = []; // unique key to this row
2946  foreach ( $index as $column ) {
2947  $rowKey[$column] = $row[$column];
2948  }
2949  $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2950  }
2951  }
2952  $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2953  } else {
2954  $where = false;
2955  }
2956 
2957  $affectedRowCount = 0;
2958  try {
2959  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2960  # Update any existing conflicting row(s)
2961  if ( $where !== false ) {
2962  $this->update( $table, $set, $where, $fname );
2963  $affectedRowCount += $this->affectedRows();
2964  }
2965  # Now insert any non-conflicting row(s)
2966  $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2967  $affectedRowCount += $this->affectedRows();
2968  $this->endAtomic( $fname );
2969  $this->affectedRowCount = $affectedRowCount;
2970  } catch ( Exception $e ) {
2971  $this->cancelAtomic( $fname );
2972  throw $e;
2973  }
2974 
2975  return true;
2976  }
2977 
2978  public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2979  $fname = __METHOD__
2980  ) {
2981  if ( !$conds ) {
2982  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2983  }
2984 
2985  $delTable = $this->tableName( $delTable );
2986  $joinTable = $this->tableName( $joinTable );
2987  $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2988  if ( $conds != '*' ) {
2989  $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2990  }
2991  $sql .= ')';
2992 
2993  $this->query( $sql, $fname );
2994  }
2995 
2996  public function textFieldSize( $table, $field ) {
2997  $table = $this->tableName( $table );
2998  $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
2999  $res = $this->query( $sql, __METHOD__ );
3000  $row = $this->fetchObject( $res );
3001 
3002  $m = [];
3003 
3004  if ( preg_match( '/\‍((.*)\‍)/', $row->Type, $m ) ) {
3005  $size = $m[1];
3006  } else {
3007  $size = -1;
3008  }
3009 
3010  return $size;
3011  }
3012 
3013  public function delete( $table, $conds, $fname = __METHOD__ ) {
3014  if ( !$conds ) {
3015  throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
3016  }
3017 
3018  $table = $this->tableName( $table );
3019  $sql = "DELETE FROM $table";
3020 
3021  if ( $conds != '*' ) {
3022  if ( is_array( $conds ) ) {
3023  $conds = $this->makeList( $conds, self::LIST_AND );
3024  }
3025  $sql .= ' WHERE ' . $conds;
3026  }
3027 
3028  $this->query( $sql, $fname );
3029 
3030  return true;
3031  }
3032 
3033  final public function insertSelect(
3034  $destTable, $srcTable, $varMap, $conds,
3035  $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3036  ) {
3037  static $hints = [ 'NO_AUTO_COLUMNS' ];
3038 
3039  $insertOptions = (array)$insertOptions;
3040  $selectOptions = (array)$selectOptions;
3041 
3042  if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3043  // For massive migrations with downtime, we don't want to select everything
3044  // into memory and OOM, so do all this native on the server side if possible.
3045  $this->nativeInsertSelect(
3046  $destTable,
3047  $srcTable,
3048  $varMap,
3049  $conds,
3050  $fname,
3051  array_diff( $insertOptions, $hints ),
3052  $selectOptions,
3053  $selectJoinConds
3054  );
3055  } else {
3056  $this->nonNativeInsertSelect(
3057  $destTable,
3058  $srcTable,
3059  $varMap,
3060  $conds,
3061  $fname,
3062  array_diff( $insertOptions, $hints ),
3063  $selectOptions,
3064  $selectJoinConds
3065  );
3066  }
3067 
3068  return true;
3069  }
3070 
3077  protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3078  return true;
3079  }
3080 
3095  protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3096  $fname = __METHOD__,
3097  $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3098  ) {
3099  // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3100  // on only the master (without needing row-based-replication). It also makes it easy to
3101  // know how big the INSERT is going to be.
3102  $fields = [];
3103  foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3104  $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3105  }
3106  $selectOptions[] = 'FOR UPDATE';
3107  $res = $this->select(
3108  $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3109  );
3110  if ( !$res ) {
3111  return;
3112  }
3113 
3114  try {
3115  $affectedRowCount = 0;
3116  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3117  $rows = [];
3118  $ok = true;
3119  foreach ( $res as $row ) {
3120  $rows[] = (array)$row;
3121 
3122  // Avoid inserts that are too huge
3123  if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize ) {
3124  $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3125  if ( !$ok ) {
3126  break;
3127  }
3128  $affectedRowCount += $this->affectedRows();
3129  $rows = [];
3130  }
3131  }
3132  if ( $rows && $ok ) {
3133  $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3134  if ( $ok ) {
3135  $affectedRowCount += $this->affectedRows();
3136  }
3137  }
3138  if ( $ok ) {
3139  $this->endAtomic( $fname );
3140  $this->affectedRowCount = $affectedRowCount;
3141  } else {
3142  $this->cancelAtomic( $fname );
3143  }
3144  } catch ( Exception $e ) {
3145  $this->cancelAtomic( $fname );
3146  throw $e;
3147  }
3148  }
3149 
3164  protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3165  $fname = __METHOD__,
3166  $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3167  ) {
3168  $destTable = $this->tableName( $destTable );
3169 
3170  if ( !is_array( $insertOptions ) ) {
3171  $insertOptions = [ $insertOptions ];
3172  }
3173 
3174  $insertOptions = $this->makeInsertOptions( $insertOptions );
3175 
3176  $selectSql = $this->selectSQLText(
3177  $srcTable,
3178  array_values( $varMap ),
3179  $conds,
3180  $fname,
3181  $selectOptions,
3182  $selectJoinConds
3183  );
3184 
3185  $sql = "INSERT $insertOptions" .
3186  " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3187  $selectSql;
3188 
3189  $this->query( $sql, $fname );
3190  }
3191 
3192  public function limitResult( $sql, $limit, $offset = false ) {
3193  if ( !is_numeric( $limit ) ) {
3194  throw new DBUnexpectedError(
3195  $this,
3196  "Invalid non-numeric limit passed to " . __METHOD__
3197  );
3198  }
3199  // This version works in MySQL and SQLite. It will very likely need to be
3200  // overridden for most other RDBMS subclasses.
3201  return "$sql LIMIT "
3202  . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3203  . "{$limit} ";
3204  }
3205 
3206  public function unionSupportsOrderAndLimit() {
3207  return true; // True for almost every DB supported
3208  }
3209 
3210  public function unionQueries( $sqls, $all ) {
3211  $glue = $all ? ') UNION ALL (' : ') UNION (';
3212 
3213  return '(' . implode( $glue, $sqls ) . ')';
3214  }
3215 
3217  $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
3218  $options = [], $join_conds = []
3219  ) {
3220  // First, build the Cartesian product of $permute_conds
3221  $conds = [ [] ];
3222  foreach ( $permute_conds as $field => $values ) {
3223  if ( !$values ) {
3224  // Skip empty $values
3225  continue;
3226  }
3227  $values = array_unique( $values ); // For sanity
3228  $newConds = [];
3229  foreach ( $conds as $cond ) {
3230  foreach ( $values as $value ) {
3231  $cond[$field] = $value;
3232  $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3233  }
3234  }
3235  $conds = $newConds;
3236  }
3237 
3238  $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
3239 
3240  // If there's just one condition and no subordering, hand off to
3241  // selectSQLText directly.
3242  if ( count( $conds ) === 1 &&
3243  ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
3244  ) {
3245  return $this->selectSQLText(
3246  $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
3247  );
3248  }
3249 
3250  // Otherwise, we need to pull out the order and limit to apply after
3251  // the union. Then build the SQL queries for each set of conditions in
3252  // $conds. Then union them together (using UNION ALL, because the
3253  // product *should* already be distinct).
3254  $orderBy = $this->makeOrderBy( $options );
3255  $limit = $options['LIMIT'] ?? null;
3256  $offset = $options['OFFSET'] ?? false;
3257  $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3258  if ( !$this->unionSupportsOrderAndLimit() ) {
3259  unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3260  } else {
3261  if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3262  $options['ORDER BY'] = $options['INNER ORDER BY'];
3263  }
3264  if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3265  // We need to increase the limit by the offset rather than
3266  // using the offset directly, otherwise it'll skip incorrectly
3267  // in the subqueries.
3268  $options['LIMIT'] = $limit + $offset;
3269  unset( $options['OFFSET'] );
3270  }
3271  }
3272 
3273  $sqls = [];
3274  foreach ( $conds as $cond ) {
3275  $sqls[] = $this->selectSQLText(
3276  $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
3277  );
3278  }
3279  $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3280  if ( $limit !== null ) {
3281  $sql = $this->limitResult( $sql, $limit, $offset );
3282  }
3283 
3284  return $sql;
3285  }
3286 
3287  public function conditional( $cond, $trueVal, $falseVal ) {
3288  if ( is_array( $cond ) ) {
3289  $cond = $this->makeList( $cond, self::LIST_AND );
3290  }
3291 
3292  return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3293  }
3294 
3295  public function strreplace( $orig, $old, $new ) {
3296  return "REPLACE({$orig}, {$old}, {$new})";
3297  }
3298 
3299  public function getServerUptime() {
3300  return 0;
3301  }
3302 
3303  public function wasDeadlock() {
3304  return false;
3305  }
3306 
3307  public function wasLockTimeout() {
3308  return false;
3309  }
3310 
3311  public function wasConnectionLoss() {
3312  return $this->wasConnectionError( $this->lastErrno() );
3313  }
3314 
3315  public function wasReadOnlyError() {
3316  return false;
3317  }
3318 
3319  public function wasErrorReissuable() {
3320  return (
3321  $this->wasDeadlock() ||
3322  $this->wasLockTimeout() ||
3323  $this->wasConnectionLoss()
3324  );
3325  }
3326 
3333  public function wasConnectionError( $errno ) {
3334  return false;
3335  }
3336 
3343  protected function wasKnownStatementRollbackError() {
3344  return false; // don't know; it could have caused a transaction rollback
3345  }
3346 
3347  public function deadlockLoop() {
3348  $args = func_get_args();
3349  $function = array_shift( $args );
3350  $tries = self::$DEADLOCK_TRIES;
3351 
3352  $this->begin( __METHOD__ );
3353 
3354  $retVal = null;
3356  $e = null;
3357  do {
3358  try {
3359  $retVal = $function( ...$args );
3360  break;
3361  } catch ( DBQueryError $e ) {
3362  if ( $this->wasDeadlock() ) {
3363  // Retry after a randomized delay
3364  usleep( mt_rand( self::$DEADLOCK_DELAY_MIN, self::$DEADLOCK_DELAY_MAX ) );
3365  } else {
3366  // Throw the error back up
3367  throw $e;
3368  }
3369  }
3370  } while ( --$tries > 0 );
3371 
3372  if ( $tries <= 0 ) {
3373  // Too many deadlocks; give up
3374  $this->rollback( __METHOD__ );
3375  throw $e;
3376  } else {
3377  $this->commit( __METHOD__ );
3378 
3379  return $retVal;
3380  }
3381  }
3382 
3383  public function masterPosWait( DBMasterPos $pos, $timeout ) {
3384  # Real waits are implemented in the subclass.
3385  return 0;
3386  }
3387 
3388  public function getReplicaPos() {
3389  # Stub
3390  return false;
3391  }
3392 
3393  public function getMasterPos() {
3394  # Stub
3395  return false;
3396  }
3397 
3398  public function serverIsReadOnly() {
3399  return false;
3400  }
3401 
3402  final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3403  if ( !$this->trxLevel() ) {
3404  throw new DBUnexpectedError( $this, "No transaction is active" );
3405  }
3406  $this->trxEndCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3407  }
3408 
3409  final public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3410  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3411  // Start an implicit transaction similar to how query() does
3412  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3413  $this->trxAutomatic = true;
3414  }
3415 
3416  $this->trxIdleCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3417  if ( !$this->trxLevel() ) {
3418  $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3419  }
3420  }
3421 
3422  final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3423  $this->onTransactionCommitOrIdle( $callback, $fname );
3424  }
3425 
3426  final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3427  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3428  // Start an implicit transaction similar to how query() does
3429  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3430  $this->trxAutomatic = true;
3431  }
3432 
3433  if ( $this->trxLevel() ) {
3434  $this->trxPreCommitCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3435  } else {
3436  // No transaction is active nor will start implicitly, so make one for this callback
3437  $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3438  try {
3439  $callback( $this );
3440  $this->endAtomic( __METHOD__ );
3441  } catch ( Exception $e ) {
3442  $this->cancelAtomic( __METHOD__ );
3443  throw $e;
3444  }
3445  }
3446  }
3447 
3448  final public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ) {
3449  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3450  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3451  }
3452  $this->trxSectionCancelCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3453  }
3454 
3458  private function currentAtomicSectionId() {
3459  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
3460  $levelInfo = end( $this->trxAtomicLevels );
3461 
3462  return $levelInfo[1];
3463  }
3464 
3465  return null;
3466  }
3467 
3476  ) {
3477  foreach ( $this->trxPreCommitCallbacks as $key => $info ) {
3478  if ( $info[2] === $old ) {
3479  $this->trxPreCommitCallbacks[$key][2] = $new;
3480  }
3481  }
3482  foreach ( $this->trxIdleCallbacks as $key => $info ) {
3483  if ( $info[2] === $old ) {
3484  $this->trxIdleCallbacks[$key][2] = $new;
3485  }
3486  }
3487  foreach ( $this->trxEndCallbacks as $key => $info ) {
3488  if ( $info[2] === $old ) {
3489  $this->trxEndCallbacks[$key][2] = $new;
3490  }
3491  }
3492  foreach ( $this->trxSectionCancelCallbacks as $key => $info ) {
3493  if ( $info[2] === $old ) {
3494  $this->trxSectionCancelCallbacks[$key][2] = $new;
3495  }
3496  }
3497  }
3498 
3518  private function modifyCallbacksForCancel(
3519  array $sectionIds, AtomicSectionIdentifier $newSectionId = null
3520  ) {
3521  // Cancel the "on commit" callbacks owned by this savepoint
3522  $this->trxIdleCallbacks = array_filter(
3523  $this->trxIdleCallbacks,
3524  function ( $entry ) use ( $sectionIds ) {
3525  return !in_array( $entry[2], $sectionIds, true );
3526  }
3527  );
3528  $this->trxPreCommitCallbacks = array_filter(
3529  $this->trxPreCommitCallbacks,
3530  function ( $entry ) use ( $sectionIds ) {
3531  return !in_array( $entry[2], $sectionIds, true );
3532  }
3533  );
3534  // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3535  foreach ( $this->trxEndCallbacks as $key => $entry ) {
3536  if ( in_array( $entry[2], $sectionIds, true ) ) {
3537  $callback = $entry[0];
3538  $this->trxEndCallbacks[$key][0] = function () use ( $callback ) {
3539  // @phan-suppress-next-line PhanInfiniteRecursion, PhanUndeclaredInvokeInCallable
3540  return $callback( self::TRIGGER_ROLLBACK, $this );
3541  };
3542  // This "on resolution" callback no longer belongs to a section.
3543  $this->trxEndCallbacks[$key][2] = null;
3544  }
3545  }
3546  // Hoist callback ownership for section cancel callbacks to the new top section
3547  foreach ( $this->trxSectionCancelCallbacks as $key => $entry ) {
3548  if ( in_array( $entry[2], $sectionIds, true ) ) {
3549  $this->trxSectionCancelCallbacks[$key][2] = $newSectionId;
3550  }
3551  }
3552  }
3553 
3554  final public function setTransactionListener( $name, callable $callback = null ) {
3555  if ( $callback ) {
3556  $this->trxRecurringCallbacks[$name] = $callback;
3557  } else {
3558  unset( $this->trxRecurringCallbacks[$name] );
3559  }
3560  }
3561 
3570  final public function setTrxEndCallbackSuppression( $suppress ) {
3571  $this->trxEndCallbacksSuppressed = $suppress;
3572  }
3573 
3584  public function runOnTransactionIdleCallbacks( $trigger ) {
3585  if ( $this->trxLevel() ) { // sanity
3586  throw new DBUnexpectedError( $this, __METHOD__ . ': a transaction is still open' );
3587  }
3588 
3589  if ( $this->trxEndCallbacksSuppressed ) {
3590  return 0;
3591  }
3592 
3593  $count = 0;
3594  $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
3596  $e = null; // first exception
3597  do { // callbacks may add callbacks :)
3598  $callbacks = array_merge(
3599  $this->trxIdleCallbacks,
3600  $this->trxEndCallbacks // include "transaction resolution" callbacks
3601  );
3602  $this->trxIdleCallbacks = []; // consumed (and recursion guard)
3603  $this->trxEndCallbacks = []; // consumed (recursion guard)
3604 
3605  // Only run trxSectionCancelCallbacks on rollback, not commit.
3606  // But always consume them.
3607  if ( $trigger === self::TRIGGER_ROLLBACK ) {
3608  $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks );
3609  }
3610  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
3611 
3612  foreach ( $callbacks as $callback ) {
3613  ++$count;
3614  list( $phpCallback ) = $callback;
3615  $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
3616  try {
3617  // @phan-suppress-next-line PhanParamTooManyCallable
3618  call_user_func( $phpCallback, $trigger, $this );
3619  } catch ( Exception $ex ) {
3620  call_user_func( $this->errorLogger, $ex );
3621  $e = $e ?: $ex;
3622  // Some callbacks may use startAtomic/endAtomic, so make sure
3623  // their transactions are ended so other callbacks don't fail
3624  if ( $this->trxLevel() ) {
3625  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
3626  }
3627  } finally {
3628  if ( $autoTrx ) {
3629  $this->setFlag( self::DBO_TRX ); // restore automatic begin()
3630  } else {
3631  $this->clearFlag( self::DBO_TRX ); // restore auto-commit
3632  }
3633  }
3634  }
3635  } while ( count( $this->trxIdleCallbacks ) );
3636 
3637  if ( $e instanceof Exception ) {
3638  throw $e; // re-throw any first exception
3639  }
3640 
3641  return $count;
3642  }
3643 
3654  $count = 0;
3655 
3656  $e = null; // first exception
3657  do { // callbacks may add callbacks :)
3658  $callbacks = $this->trxPreCommitCallbacks;
3659  $this->trxPreCommitCallbacks = []; // consumed (and recursion guard)
3660  foreach ( $callbacks as $callback ) {
3661  try {
3662  ++$count;
3663  list( $phpCallback ) = $callback;
3664  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
3665  $phpCallback( $this );
3666  } catch ( Exception $ex ) {
3667  ( $this->errorLogger )( $ex );
3668  $e = $e ?: $ex;
3669  }
3670  }
3671  } while ( count( $this->trxPreCommitCallbacks ) );
3672 
3673  if ( $e instanceof Exception ) {
3674  throw $e; // re-throw any first exception
3675  }
3676 
3677  return $count;
3678  }
3679 
3688  $trigger, array $sectionIds = null
3689  ) {
3691  $e = null; // first exception
3692 
3693  $notCancelled = [];
3694  do {
3695  $callbacks = $this->trxSectionCancelCallbacks;
3696  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
3697  foreach ( $callbacks as $entry ) {
3698  if ( $sectionIds === null || in_array( $entry[2], $sectionIds, true ) ) {
3699  try {
3700  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
3701  $entry[0]( $trigger, $this );
3702  } catch ( Exception $ex ) {
3703  ( $this->errorLogger )( $ex );
3704  $e = $e ?: $ex;
3705  } catch ( Throwable $ex ) {
3706  // @todo: Log?
3707  $e = $e ?: $ex;
3708  }
3709  } else {
3710  $notCancelled[] = $entry;
3711  }
3712  }
3713  } while ( count( $this->trxSectionCancelCallbacks ) );
3714  $this->trxSectionCancelCallbacks = $notCancelled;
3715 
3716  if ( $e !== null ) {
3717  throw $e; // re-throw any first Exception/Throwable
3718  }
3719  }
3720 
3730  public function runTransactionListenerCallbacks( $trigger ) {
3731  if ( $this->trxEndCallbacksSuppressed ) {
3732  return;
3733  }
3734 
3736  $e = null; // first exception
3737 
3738  foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
3739  try {
3740  $phpCallback( $trigger, $this );
3741  } catch ( Exception $ex ) {
3742  ( $this->errorLogger )( $ex );
3743  $e = $e ?: $ex;
3744  }
3745  }
3746 
3747  if ( $e instanceof Exception ) {
3748  throw $e; // re-throw any first exception
3749  }
3750  }
3751 
3762  protected function doSavepoint( $identifier, $fname ) {
3763  $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3764  }
3765 
3776  protected function doReleaseSavepoint( $identifier, $fname ) {
3777  $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3778  }
3779 
3790  protected function doRollbackToSavepoint( $identifier, $fname ) {
3791  $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3792  }
3793 
3798  private function nextSavepointId( $fname ) {
3799  $savepointId = self::$SAVEPOINT_PREFIX . ++$this->trxAtomicCounter;
3800  if ( strlen( $savepointId ) > 30 ) {
3801  // 30 == Oracle's identifier length limit (pre 12c)
3802  // With a 22 character prefix, that puts the highest number at 99999999.
3803  throw new DBUnexpectedError(
3804  $this,
3805  'There have been an excessively large number of atomic sections in a transaction'
3806  . " started by $this->trxFname (at $fname)"
3807  );
3808  }
3809 
3810  return $savepointId;
3811  }
3812 
3813  final public function startAtomic(
3814  $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE
3815  ) {
3816  $savepointId = $cancelable === self::ATOMIC_CANCELABLE ? self::$NOT_APPLICABLE : null;
3817 
3818  if ( !$this->trxLevel() ) {
3819  $this->begin( $fname, self::TRANSACTION_INTERNAL ); // sets trxAutomatic
3820  // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3821  // in all changes being in one transaction to keep requests transactional.
3822  if ( $this->getFlag( self::DBO_TRX ) ) {
3823  // Since writes could happen in between the topmost atomic sections as part
3824  // of the transaction, those sections will need savepoints.
3825  $savepointId = $this->nextSavepointId( $fname );
3826  $this->doSavepoint( $savepointId, $fname );
3827  } else {
3828  $this->trxAutomaticAtomic = true;
3829  }
3830  } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
3831  $savepointId = $this->nextSavepointId( $fname );
3832  $this->doSavepoint( $savepointId, $fname );
3833  }
3834 
3835  $sectionId = new AtomicSectionIdentifier;
3836  $this->trxAtomicLevels[] = [ $fname, $sectionId, $savepointId ];
3837  $this->queryLogger->debug( 'startAtomic: entering level ' .
3838  ( count( $this->trxAtomicLevels ) - 1 ) . " ($fname)" );
3839 
3840  return $sectionId;
3841  }
3842 
3843  final public function endAtomic( $fname = __METHOD__ ) {
3844  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3845  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3846  }
3847 
3848  // Check if the current section matches $fname
3849  $pos = count( $this->trxAtomicLevels ) - 1;
3850  list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3851  $this->queryLogger->debug( "endAtomic: leaving level $pos ($fname)" );
3852 
3853  if ( $savedFname !== $fname ) {
3854  throw new DBUnexpectedError(
3855  $this,
3856  "Invalid atomic section ended (got $fname but expected $savedFname)"
3857  );
3858  }
3859 
3860  // Remove the last section (no need to re-index the array)
3861  array_pop( $this->trxAtomicLevels );
3862 
3863  if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3864  $this->commit( $fname, self::FLUSHING_INTERNAL );
3865  } elseif ( $savepointId !== null && $savepointId !== self::$NOT_APPLICABLE ) {
3866  $this->doReleaseSavepoint( $savepointId, $fname );
3867  }
3868 
3869  // Hoist callback ownership for callbacks in the section that just ended;
3870  // all callbacks should have an owner that is present in trxAtomicLevels.
3871  $currentSectionId = $this->currentAtomicSectionId();
3872  if ( $currentSectionId ) {
3873  $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3874  }
3875  }
3876 
3877  final public function cancelAtomic(
3878  $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null
3879  ) {
3880  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3881  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3882  }
3883 
3884  $excisedIds = [];
3885  $newTopSection = $this->currentAtomicSectionId();
3886  try {
3887  $excisedFnames = [];
3888  if ( $sectionId !== null ) {
3889  // Find the (last) section with the given $sectionId
3890  $pos = -1;
3891  foreach ( $this->trxAtomicLevels as $i => list( $asFname, $asId, $spId ) ) {
3892  if ( $asId === $sectionId ) {
3893  $pos = $i;
3894  }
3895  }
3896  if ( $pos < 0 ) {
3897  throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3898  }
3899  // Remove all descendant sections and re-index the array
3900  $len = count( $this->trxAtomicLevels );
3901  for ( $i = $pos + 1; $i < $len; ++$i ) {
3902  $excisedFnames[] = $this->trxAtomicLevels[$i][0];
3903  $excisedIds[] = $this->trxAtomicLevels[$i][1];
3904  }
3905  $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
3906  $newTopSection = $this->currentAtomicSectionId();
3907  }
3908 
3909  // Check if the current section matches $fname
3910  $pos = count( $this->trxAtomicLevels ) - 1;
3911  list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3912 
3913  if ( $excisedFnames ) {
3914  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3915  "and descendants " . implode( ', ', $excisedFnames ) );
3916  } else {
3917  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3918  }
3919 
3920  if ( $savedFname !== $fname ) {
3921  throw new DBUnexpectedError(
3922  $this,
3923  "Invalid atomic section ended (got $fname but expected $savedFname)"
3924  );
3925  }
3926 
3927  // Remove the last section (no need to re-index the array)
3928  array_pop( $this->trxAtomicLevels );
3929  $excisedIds[] = $savedSectionId;
3930  $newTopSection = $this->currentAtomicSectionId();
3931 
3932  if ( $savepointId !== null ) {
3933  // Rollback the transaction to the state just before this atomic section
3934  if ( $savepointId === self::$NOT_APPLICABLE ) {
3935  $this->rollback( $fname, self::FLUSHING_INTERNAL );
3936  // Note: rollback() will run trxSectionCancelCallbacks
3937  } else {
3938  $this->doRollbackToSavepoint( $savepointId, $fname );
3939  $this->trxStatus = self::STATUS_TRX_OK; // no exception; recovered
3940  $this->trxStatusIgnoredCause = null;
3941 
3942  // Run trxSectionCancelCallbacks now.
3943  $this->runOnAtomicSectionCancelCallbacks( self::TRIGGER_CANCEL, $excisedIds );
3944  }
3945  } elseif ( $this->trxStatus > self::STATUS_TRX_ERROR ) {
3946  // Put the transaction into an error state if it's not already in one
3947  $this->trxStatus = self::STATUS_TRX_ERROR;
3948  $this->trxStatusCause = new DBUnexpectedError(
3949  $this,
3950  "Uncancelable atomic section canceled (got $fname)"
3951  );
3952  }
3953  } finally {
3954  // Fix up callbacks owned by the sections that were just cancelled.
3955  // All callbacks should have an owner that is present in trxAtomicLevels.
3956  $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3957  }
3958 
3959  $this->affectedRowCount = 0; // for the sake of consistency
3960  }
3961 
3962  final public function doAtomicSection(
3963  $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
3964  ) {
3965  $sectionId = $this->startAtomic( $fname, $cancelable );
3966  try {
3967  $res = $callback( $this, $fname );
3968  } catch ( Exception $e ) {
3969  $this->cancelAtomic( $fname, $sectionId );
3970 
3971  throw $e;
3972  }
3973  $this->endAtomic( $fname );
3974 
3975  return $res;
3976  }
3977 
3978  final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
3979  static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
3980  if ( !in_array( $mode, $modes, true ) ) {
3981  throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
3982  }
3983 
3984  // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3985  if ( $this->trxLevel() ) {
3986  if ( $this->trxAtomicLevels ) {
3987  $levels = $this->flatAtomicSectionList();
3988  $msg = "$fname: got explicit BEGIN while atomic section(s) $levels are open";
3989  throw new DBUnexpectedError( $this, $msg );
3990  } elseif ( !$this->trxAutomatic ) {
3991  $msg = "$fname: explicit transaction already active (from {$this->trxFname})";
3992  throw new DBUnexpectedError( $this, $msg );
3993  } else {
3994  $msg = "$fname: implicit transaction already active (from {$this->trxFname})";
3995  throw new DBUnexpectedError( $this, $msg );
3996  }
3997  } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
3998  $msg = "$fname: implicit transaction expected (DBO_TRX set)";
3999  throw new DBUnexpectedError( $this, $msg );
4000  }
4001 
4002  $this->assertHasConnectionHandle();
4003 
4004  $this->doBegin( $fname );
4005  $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4006  $this->trxStatus = self::STATUS_TRX_OK;
4007  $this->trxStatusIgnoredCause = null;
4008  $this->trxAtomicCounter = 0;
4009  $this->trxTimestamp = microtime( true );
4010  $this->trxFname = $fname;
4011  $this->trxDoneWrites = false;
4012  $this->trxAutomaticAtomic = false;
4013  $this->trxAtomicLevels = [];
4014  $this->trxWriteDuration = 0.0;
4015  $this->trxWriteQueryCount = 0;
4016  $this->trxWriteAffectedRows = 0;
4017  $this->trxWriteAdjDuration = 0.0;
4018  $this->trxWriteAdjQueryCount = 0;
4019  $this->trxWriteCallers = [];
4020  // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4021  // Get an estimate of the replication lag before any such queries.
4022  $this->trxReplicaLag = null; // clear cached value first
4023  $this->trxReplicaLag = $this->getApproximateLagStatus()['lag'];
4024  // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4025  // caller will think its OK to muck around with the transaction just because startAtomic()
4026  // has not yet completed (e.g. setting trxAtomicLevels).
4027  $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
4028  }
4029 
4037  protected function doBegin( $fname ) {
4038  $this->query( 'BEGIN', $fname );
4039  }
4040 
4041  final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4042  static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
4043  if ( !in_array( $flush, $modes, true ) ) {
4044  throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4045  }
4046 
4047  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
4048  // There are still atomic sections open; this cannot be ignored
4049  $levels = $this->flatAtomicSectionList();
4050  throw new DBUnexpectedError(
4051  $this,
4052  "$fname: got COMMIT while atomic sections $levels are still open"
4053  );
4054  }
4055 
4056  if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
4057  if ( !$this->trxLevel() ) {
4058  return; // nothing to do
4059  } elseif ( !$this->trxAutomatic ) {
4060  throw new DBUnexpectedError(
4061  $this,
4062  "$fname: flushing an explicit transaction, getting out of sync"
4063  );
4064  }
4065  } elseif ( !$this->trxLevel() ) {
4066  $this->queryLogger->error(
4067  "$fname: no transaction to commit, something got out of sync" );
4068  return; // nothing to do
4069  } elseif ( $this->trxAutomatic ) {
4070  throw new DBUnexpectedError(
4071  $this,
4072  "$fname: expected mass commit of all peer transactions (DBO_TRX set)"
4073  );
4074  }
4075 
4076  $this->assertHasConnectionHandle();
4077 
4079 
4080  $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
4081  $this->doCommit( $fname );
4082  $oldTrxShortId = $this->consumeTrxShortId();
4083  $this->trxStatus = self::STATUS_TRX_NONE;
4084 
4085  if ( $this->trxDoneWrites ) {
4086  $this->lastWriteTime = microtime( true );
4087  $this->trxProfiler->transactionWritingOut(
4088  $this->server,
4089  $this->getDomainID(),
4090  $oldTrxShortId,
4091  $writeTime,
4092  $this->trxWriteAffectedRows
4093  );
4094  }
4095 
4096  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4097  if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4098  $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
4099  $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
4100  }
4101  }
4102 
4110  protected function doCommit( $fname ) {
4111  if ( $this->trxLevel() ) {
4112  $this->query( 'COMMIT', $fname );
4113  }
4114  }
4115 
4116  final public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4117  $trxActive = $this->trxLevel();
4118 
4119  if ( $flush !== self::FLUSHING_INTERNAL
4120  && $flush !== self::FLUSHING_ALL_PEERS
4121  && $this->getFlag( self::DBO_TRX )
4122  ) {
4123  throw new DBUnexpectedError(
4124  $this,
4125  "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4126  );
4127  }
4128 
4129  if ( $trxActive ) {
4130  $this->assertHasConnectionHandle();
4131 
4132  $this->doRollback( $fname );
4133  $oldTrxShortId = $this->consumeTrxShortId();
4134  $this->trxStatus = self::STATUS_TRX_NONE;
4135  $this->trxAtomicLevels = [];
4136  // Estimate the RTT via a query now that trxStatus is OK
4137  $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4138 
4139  if ( $this->trxDoneWrites ) {
4140  $this->trxProfiler->transactionWritingOut(
4141  $this->server,
4142  $this->getDomainID(),
4143  $oldTrxShortId,
4144  $writeTime,
4145  $this->trxWriteAffectedRows
4146  );
4147  }
4148  }
4149 
4150  // Clear any commit-dependant callbacks. They might even be present
4151  // only due to transaction rounds, with no SQL transaction being active
4152  $this->trxIdleCallbacks = [];
4153  $this->trxPreCommitCallbacks = [];
4154 
4155  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4156  if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4157  try {
4158  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
4159  } catch ( Exception $e ) {
4160  // already logged; finish and let LoadBalancer move on during mass-rollback
4161  }
4162  try {
4163  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
4164  } catch ( Exception $e ) {
4165  // already logged; let LoadBalancer move on during mass-rollback
4166  }
4167 
4168  $this->affectedRowCount = 0; // for the sake of consistency
4169  }
4170  }
4171 
4179  protected function doRollback( $fname ) {
4180  if ( $this->trxLevel() ) {
4181  # Disconnects cause rollback anyway, so ignore those errors
4182  $ignoreErrors = true;
4183  $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4184  }
4185  }
4186 
4187  public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4188  if ( $this->explicitTrxActive() ) {
4189  // Committing this transaction would break callers that assume it is still open
4190  throw new DBUnexpectedError(
4191  $this,
4192  "$fname: Cannot flush snapshot; " .
4193  "explicit transaction '{$this->trxFname}' is still open"
4194  );
4195  } elseif ( $this->writesOrCallbacksPending() ) {
4196  // This only flushes transactions to clear snapshots, not to write data
4197  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4198  throw new DBUnexpectedError(
4199  $this,
4200  "$fname: Cannot flush snapshot; " .
4201  "writes from transaction {$this->trxFname} are still pending ($fnames)"
4202  );
4203  } elseif (
4204  $this->trxLevel() &&
4205  $this->getTransactionRoundId() &&
4206  $flush !== self::FLUSHING_INTERNAL &&
4207  $flush !== self::FLUSHING_ALL_PEERS
4208  ) {
4209  $this->queryLogger->warning(
4210  "$fname: Expected mass snapshot flush of all peer transactions " .
4211  "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4212  [ 'exception' => new RuntimeException() ]
4213  );
4214  }
4215 
4216  $this->commit( $fname, self::FLUSHING_INTERNAL );
4217  }
4218 
4219  public function explicitTrxActive() {
4220  return $this->trxLevel() && ( $this->trxAtomicLevels || !$this->trxAutomatic );
4221  }
4222 
4223  public function duplicateTableStructure(
4224  $oldName, $newName, $temporary = false, $fname = __METHOD__
4225  ) {
4226  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4227  }
4228 
4229  public function listTables( $prefix = null, $fname = __METHOD__ ) {
4230  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4231  }
4232 
4233  public function listViews( $prefix = null, $fname = __METHOD__ ) {
4234  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4235  }
4236 
4237  public function timestamp( $ts = 0 ) {
4238  $t = new ConvertibleTimestamp( $ts );
4239  // Let errors bubble up to avoid putting garbage in the DB
4240  return $t->getTimestamp( TS_MW );
4241  }
4242 
4243  public function timestampOrNull( $ts = null ) {
4244  if ( is_null( $ts ) ) {
4245  return null;
4246  } else {
4247  return $this->timestamp( $ts );
4248  }
4249  }
4250 
4251  public function affectedRows() {
4252  return ( $this->affectedRowCount === null )
4253  ? $this->fetchAffectedRowCount() // default to driver value
4255  }
4256 
4260  abstract protected function fetchAffectedRowCount();
4261 
4274  protected function resultObject( $result ) {
4275  if ( !$result ) {
4276  return false; // failed query
4277  } elseif ( $result instanceof IResultWrapper ) {
4278  return $result;
4279  } elseif ( $result === true ) {
4280  return $result; // succesful write query
4281  } else {
4282  return new ResultWrapper( $this, $result );
4283  }
4284  }
4285 
4286  public function ping( &$rtt = null ) {
4287  // Avoid hitting the server if it was hit recently
4288  if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::$PING_TTL ) {
4289  if ( !func_num_args() || $this->lastRoundTripEstimate > 0 ) {
4291  return true; // don't care about $rtt
4292  }
4293  }
4294 
4295  // This will reconnect if possible or return false if not
4296  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
4297  $ok = ( $this->query( self::$PING_QUERY, __METHOD__, $flags ) !== false );
4298  if ( $ok ) {
4300  }
4301 
4302  return $ok;
4303  }
4304 
4311  protected function replaceLostConnection( $fname ) {
4312  $this->closeConnection();
4313  $this->conn = null;
4314 
4315  $this->handleSessionLossPreconnect();
4316 
4317  try {
4318  $this->open(
4319  $this->server,
4320  $this->user,
4321  $this->password,
4322  $this->currentDomain->getDatabase(),
4323  $this->currentDomain->getSchema(),
4324  $this->tablePrefix()
4325  );
4326  $this->lastPing = microtime( true );
4327  $ok = true;
4328 
4329  $this->connLogger->warning(
4330  $fname . ': lost connection to {dbserver}; reconnected',
4331  [
4332  'dbserver' => $this->getServer(),
4333  'exception' => new RuntimeException()
4334  ]
4335  );
4336  } catch ( DBConnectionError $e ) {
4337  $ok = false;
4338 
4339  $this->connLogger->error(
4340  $fname . ': lost connection to {dbserver} permanently',
4341  [ 'dbserver' => $this->getServer() ]
4342  );
4343  }
4344 
4346 
4347  return $ok;
4348  }
4349 
4350  public function getSessionLagStatus() {
4351  return $this->getRecordedTransactionLagStatus() ?: $this->getApproximateLagStatus();
4352  }
4353 
4367  final protected function getRecordedTransactionLagStatus() {
4368  return ( $this->trxLevel() && $this->trxReplicaLag !== null )
4369  ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
4370  : null;
4371  }
4372 
4379  protected function getApproximateLagStatus() {
4380  return [
4381  'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
4382  'since' => microtime( true )
4383  ];
4384  }
4385 
4405  public static function getCacheSetOptions( IDatabase $db1, IDatabase $db2 = null ) {
4406  $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
4407  foreach ( func_get_args() as $db ) {
4409  $status = $db->getSessionLagStatus();
4410  if ( $status['lag'] === false ) {
4411  $res['lag'] = false;
4412  } elseif ( $res['lag'] !== false ) {
4413  $res['lag'] = max( $res['lag'], $status['lag'] );
4414  }
4415  $res['since'] = min( $res['since'], $status['since'] );
4416  $res['pending'] = $res['pending'] ?: $db->writesPending();
4417  }
4418 
4419  return $res;
4420  }
4421 
4422  public function getLag() {
4423  if ( $this->getLBInfo( 'master' ) ) {
4424  return 0; // this is the master
4425  } elseif ( $this->getLBInfo( 'is static' ) ) {
4426  return 0; // static dataset
4427  }
4428 
4429  return $this->doGetLag();
4430  }
4431 
4432  protected function doGetLag() {
4433  return 0;
4434  }
4435 
4436  public function maxListLen() {
4437  return 0;
4438  }
4439 
4440  public function encodeBlob( $b ) {
4441  return $b;
4442  }
4443 
4444  public function decodeBlob( $b ) {
4445  if ( $b instanceof Blob ) {
4446  $b = $b->fetch();
4447  }
4448  return $b;
4449  }
4450 
4451  public function setSessionOptions( array $options ) {
4452  }
4453 
4454  public function sourceFile(
4455  $filename,
4456  callable $lineCallback = null,
4457  callable $resultCallback = null,
4458  $fname = false,
4459  callable $inputCallback = null
4460  ) {
4461  AtEase::suppressWarnings();
4462  $fp = fopen( $filename, 'r' );
4463  AtEase::restoreWarnings();
4464 
4465  if ( $fp === false ) {
4466  throw new RuntimeException( "Could not open \"{$filename}\"" );
4467  }
4468 
4469  if ( !$fname ) {
4470  $fname = __METHOD__ . "( $filename )";
4471  }
4472 
4473  try {
4474  $error = $this->sourceStream(
4475  $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4476  } catch ( Exception $e ) {
4477  fclose( $fp );
4478  throw $e;
4479  }
4480 
4481  fclose( $fp );
4482 
4483  return $error;
4484  }
4485 
4486  public function setSchemaVars( $vars ) {
4487  $this->schemaVars = is_array( $vars ) ? $vars : null;
4488  }
4489 
4490  public function sourceStream(
4491  $fp,
4492  callable $lineCallback = null,
4493  callable $resultCallback = null,
4494  $fname = __METHOD__,
4495  callable $inputCallback = null
4496  ) {
4497  $delimiterReset = new ScopedCallback(
4498  function ( $delimiter ) {
4499  $this->delimiter = $delimiter;
4500  },
4501  [ $this->delimiter ]
4502  );
4503  $cmd = '';
4504 
4505  while ( !feof( $fp ) ) {
4506  if ( $lineCallback ) {
4507  call_user_func( $lineCallback );
4508  }
4509 
4510  $line = trim( fgets( $fp ) );
4511 
4512  if ( $line == '' ) {
4513  continue;
4514  }
4515 
4516  if ( $line[0] == '-' && $line[1] == '-' ) {
4517  continue;
4518  }
4519 
4520  if ( $cmd != '' ) {
4521  $cmd .= ' ';
4522  }
4523 
4524  $done = $this->streamStatementEnd( $cmd, $line );
4525 
4526  $cmd .= "$line\n";
4527 
4528  if ( $done || feof( $fp ) ) {
4529  $cmd = $this->replaceVars( $cmd );
4530 
4531  if ( $inputCallback ) {
4532  $callbackResult = $inputCallback( $cmd );
4533 
4534  if ( is_string( $callbackResult ) || !$callbackResult ) {
4535  $cmd = $callbackResult;
4536  }
4537  }
4538 
4539  if ( $cmd ) {
4540  $res = $this->query( $cmd, $fname );
4541 
4542  if ( $resultCallback ) {
4543  $resultCallback( $res, $this );
4544  }
4545 
4546  if ( $res === false ) {
4547  $err = $this->lastError();
4548 
4549  return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4550  }
4551  }
4552  $cmd = '';
4553  }
4554  }
4555 
4556  ScopedCallback::consume( $delimiterReset );
4557  return true;
4558  }
4559 
4567  public function streamStatementEnd( &$sql, &$newLine ) {
4568  if ( $this->delimiter ) {
4569  $prev = $newLine;
4570  $newLine = preg_replace(
4571  '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4572  if ( $newLine != $prev ) {
4573  return true;
4574  }
4575  }
4576 
4577  return false;
4578  }
4579 
4600  protected function replaceVars( $ins ) {
4601  $vars = $this->getSchemaVars();
4602  return preg_replace_callback(
4603  '!
4604  /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4605  \'\{\$ (\w+) }\' | # 3. addQuotes
4606  `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4607  /\*\$ (\w+) \*/ # 5. leave unencoded
4608  !x',
4609  function ( $m ) use ( $vars ) {
4610  // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4611  // check for both nonexistent keys *and* the empty string.
4612  if ( isset( $m[1] ) && $m[1] !== '' ) {
4613  if ( $m[1] === 'i' ) {
4614  return $this->indexName( $m[2] );
4615  } else {
4616  return $this->tableName( $m[2] );
4617  }
4618  } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4619  return $this->addQuotes( $vars[$m[3]] );
4620  } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4621  return $this->addIdentifierQuotes( $vars[$m[4]] );
4622  } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4623  return $vars[$m[5]];
4624  } else {
4625  return $m[0];
4626  }
4627  },
4628  $ins
4629  );
4630  }
4631 
4638  protected function getSchemaVars() {
4639  return $this->schemaVars ?? $this->getDefaultSchemaVars();
4640  }
4641 
4650  protected function getDefaultSchemaVars() {
4651  return [];
4652  }
4653 
4654  public function lockIsFree( $lockName, $method ) {
4655  // RDBMs methods for checking named locks may or may not count this thread itself.
4656  // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4657  // the behavior choosen by the interface for this method.
4658  return !isset( $this->sessionNamedLocks[$lockName] );
4659  }
4660 
4661  public function lock( $lockName, $method, $timeout = 5 ) {
4662  $this->sessionNamedLocks[$lockName] = 1;
4663 
4664  return true;
4665  }
4666 
4667  public function unlock( $lockName, $method ) {
4668  unset( $this->sessionNamedLocks[$lockName] );
4669 
4670  return true;
4671  }
4672 
4673  public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4674  if ( $this->writesOrCallbacksPending() ) {
4675  // This only flushes transactions to clear snapshots, not to write data
4676  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4677  throw new DBUnexpectedError(
4678  $this,
4679  "$fname: Cannot flush pre-lock snapshot; " .
4680  "writes from transaction {$this->trxFname} are still pending ($fnames)"
4681  );
4682  }
4683 
4684  if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4685  return null;
4686  }
4687 
4688  $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4689  if ( $this->trxLevel() ) {
4690  // There is a good chance an exception was thrown, causing any early return
4691  // from the caller. Let any error handler get a chance to issue rollback().
4692  // If there isn't one, let the error bubble up and trigger server-side rollback.
4693  $this->onTransactionResolution(
4694  function () use ( $lockKey, $fname ) {
4695  $this->unlock( $lockKey, $fname );
4696  },
4697  $fname
4698  );
4699  } else {
4700  $this->unlock( $lockKey, $fname );
4701  }
4702  } );
4703 
4704  $this->commit( $fname, self::FLUSHING_INTERNAL );
4705 
4706  return $unlocker;
4707  }
4708 
4709  public function namedLocksEnqueue() {
4710  return false;
4711  }
4712 
4714  return true;
4715  }
4716 
4717  final public function lockTables( array $read, array $write, $method ) {
4718  if ( $this->writesOrCallbacksPending() ) {
4719  throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4720  }
4721 
4722  if ( $this->tableLocksHaveTransactionScope() ) {
4723  $this->startAtomic( $method );
4724  }
4725 
4726  return $this->doLockTables( $read, $write, $method );
4727  }
4728 
4737  protected function doLockTables( array $read, array $write, $method ) {
4738  return true;
4739  }
4740 
4741  final public function unlockTables( $method ) {
4742  if ( $this->tableLocksHaveTransactionScope() ) {
4743  $this->endAtomic( $method );
4744 
4745  return true; // locks released on COMMIT/ROLLBACK
4746  }
4747 
4748  return $this->doUnlockTables( $method );
4749  }
4750 
4757  protected function doUnlockTables( $method ) {
4758  return true;
4759  }
4760 
4768  public function dropTable( $tableName, $fName = __METHOD__ ) {
4769  if ( !$this->tableExists( $tableName, $fName ) ) {
4770  return false;
4771  }
4772  $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4773 
4774  return $this->query( $sql, $fName );
4775  }
4776 
4777  public function getInfinity() {
4778  return 'infinity';
4779  }
4780 
4781  public function encodeExpiry( $expiry ) {
4782  return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4783  ? $this->getInfinity()
4784  : $this->timestamp( $expiry );
4785  }
4786 
4787  public function decodeExpiry( $expiry, $format = TS_MW ) {
4788  if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
4789  return 'infinity';
4790  }
4791 
4792  return ConvertibleTimestamp::convert( $format, $expiry );
4793  }
4794 
4795  public function setBigSelects( $value = true ) {
4796  // no-op
4797  }
4798 
4799  public function isReadOnly() {
4800  return ( $this->getReadOnlyReason() !== false );
4801  }
4802 
4806  protected function getReadOnlyReason() {
4807  $reason = $this->getLBInfo( 'readOnlyReason' );
4808  if ( is_string( $reason ) ) {
4809  return $reason;
4810  } elseif ( $this->getLBInfo( 'replica' ) ) {
4811  return "Server is configured in the role of a read-only replica database.";
4812  }
4813 
4814  return false;
4815  }
4816 
4817  public function setTableAliases( array $aliases ) {
4818  $this->tableAliases = $aliases;
4819  }
4820 
4821  public function setIndexAliases( array $aliases ) {
4822  $this->indexAliases = $aliases;
4823  }
4824 
4831  final protected function fieldHasBit( $field, $flags ) {
4832  return ( ( $field & $flags ) === $flags );
4833  }
4834 
4846  protected function getBindingHandle() {
4847  if ( !$this->conn ) {
4848  throw new DBUnexpectedError(
4849  $this,
4850  'DB connection was already closed or the connection dropped'
4851  );
4852  }
4853 
4854  return $this->conn;
4855  }
4856 
4857  public function __toString() {
4858  // spl_object_id is PHP >= 7.2
4859  $id = function_exists( 'spl_object_id' )
4860  ? spl_object_id( $this )
4861  : spl_object_hash( $this );
4862 
4863  $description = $this->getType() . ' object #' . $id;
4864  if ( is_resource( $this->conn ) ) {
4865  $description .= ' (' . (string)$this->conn . ')'; // "resource id #<ID>"
4866  } elseif ( is_object( $this->conn ) ) {
4867  // spl_object_id is PHP >= 7.2
4868  $handleId = function_exists( 'spl_object_id' )
4869  ? spl_object_id( $this->conn )
4870  : spl_object_hash( $this->conn );
4871  $description .= " (handle id #$handleId)";
4872  }
4873 
4874  return $description;
4875  }
4876 
4881  public function __clone() {
4882  $this->connLogger->warning(
4883  "Cloning " . static::class . " is not recommended; forking connection",
4884  [ 'exception' => new RuntimeException() ]
4885  );
4886 
4887  if ( $this->isOpen() ) {
4888  // Open a new connection resource without messing with the old one
4889  $this->conn = null;
4890  $this->trxEndCallbacks = []; // don't copy
4891  $this->trxSectionCancelCallbacks = []; // don't copy
4892  $this->handleSessionLossPreconnect(); // no trx or locks anymore
4893  $this->open(
4894  $this->server,
4895  $this->user,
4896  $this->password,
4897  $this->currentDomain->getDatabase(),
4898  $this->currentDomain->getSchema(),
4899  $this->tablePrefix()
4900  );
4901  $this->lastPing = microtime( true );
4902  }
4903  }
4904 
4910  public function __sleep() {
4911  throw new RuntimeException( 'Database serialization may cause problems, since ' .
4912  'the connection is not restored on wakeup' );
4913  }
4914 
4918  public function __destruct() {
4919  if ( $this->trxLevel() && $this->trxDoneWrites ) {
4920  trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4921  }
4922 
4923  $danglingWriters = $this->pendingWriteAndCallbackCallers();
4924  if ( $danglingWriters ) {
4925  $fnames = implode( ', ', $danglingWriters );
4926  trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4927  }
4928 
4929  if ( $this->conn ) {
4930  // Avoid connection leaks for sanity. Normally, resources close at script completion.
4931  // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4932  AtEase::suppressWarnings();
4933  $this->closeConnection();
4934  AtEase::restoreWarnings();
4935  $this->conn = null;
4936  }
4937  }
4938 }
4939 
4943 class_alias( Database::class, 'DatabaseBase' );
4944 
4948 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:624
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:215
Wikimedia\Rdbms\Database\$schemaVars
array null $schemaVars
Current variables use for schema element placeholders.
Definition: Database.php:102
Wikimedia\Rdbms\Database\tablePrefix
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition: Database.php:547
Wikimedia\Rdbms\Database\$trxFname
string $trxFname
Name of the function that start the last transaction.
Definition: Database.php:127
Wikimedia\Rdbms\Database\getLastPHPError
getLastPHPError()
Definition: Database.php:837
Wikimedia\Rdbms\Database\insert
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
Definition: Database.php:2101
Wikimedia\Rdbms\Database\setSessionOptions
setSessionOptions(array $options)
Override database's default behavior.
Definition: Database.php:4451
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:49
Wikimedia\Rdbms\Database\limitResult
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
Definition: Database.php:3192
Wikimedia\Rdbms\Database\$trxDoneWrites
bool $trxDoneWrites
Whether possible write queries were done in the last transaction started.
Definition: Database.php:129
Wikimedia\Rdbms\Database\$trxEndCallbacksSuppressed
bool $trxEndCallbacksSuppressed
Whether to suppress triggering of transaction end callbacks.
Definition: Database.php:161
Wikimedia\Rdbms\Database\$DBO_MUTABLE
static int $DBO_MUTABLE
Bit field of all DBO_* flags that can be changed after connection.
Definition: Database.php:234
Wikimedia\Rdbms\Database\makeUpdateOptionsArray
makeUpdateOptionsArray( $options)
Make UPDATE options array for Database::makeUpdateOptions.
Definition: Database.php:2151
Wikimedia\Rdbms\Database\replaceLostConnection
replaceLostConnection( $fname)
Close any existing (dead) database connection and open a new connection.
Definition: Database.php:4311
Wikimedia\Rdbms\Database\$trxWriteAdjQueryCount
int $trxWriteAdjQueryCount
Number of write queries counted in trxWriteAdjDuration.
Definition: Database.php:149
Wikimedia\Rdbms\Database\getBindingHandle
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:4846
Wikimedia\Rdbms\Database\$lastPhpError
string bool $lastPhpError
Definition: Database.php:173
Wikimedia\Rdbms\Database\canRecoverFromDisconnect
canRecoverFromDisconnect( $sql, $priorWritesPending)
Determine whether it is safe to retry queries after a database connection is lost.
Definition: Database.php:1455
Wikimedia\Rdbms\Database\buildGroupConcatField
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
Definition: Database.php:2311
Wikimedia\Rdbms\Database\doInitConnection
doInitConnection()
Actually connect to the database over the wire (or to local files)
Definition: Database.php:300
Wikimedia\Rdbms\Database\$trxReplicaLag
float $trxReplicaLag
Replication lag estimate at the time of BEGIN for the last transaction.
Definition: Database.php:125
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:2761
Wikimedia\Rdbms\IDatabase\getServerVersion
getServerVersion()
A string describing the current software version, like from mysql_get_server_info()
Wikimedia\Rdbms\Database\fieldExists
fieldExists( $table, $field, $fname=__METHOD__)
Determines whether a field exists in a table.
Definition: Database.php:2060
Wikimedia\Rdbms\Database\bitOr
bitOr( $fieldLeft, $fieldRight)
Definition: Database.php:2303
Wikimedia\Rdbms\Database\selectRowCount
selectRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
Definition: Database.php:1928
Wikimedia\Rdbms\Database\ignoreIndexClause
ignoreIndexClause( $index)
IGNORE INDEX clause.
Definition: Database.php:2839
Wikimedia\Rdbms\Database\trxStatus
trxStatus()
Definition: Database.php:543
Wikimedia\Rdbms\Database\estimateRowCount
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate the number of rows in dataset.
Definition: Database.php:1911
Wikimedia\Rdbms\Database\listTables
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
Definition: Database.php:4229
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:31
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:1380
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:2272
Wikimedia\Rdbms\Database\$queryLogger
LoggerInterface $queryLogger
Definition: Database.php:55
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:4440
Wikimedia\Rdbms\Database\getDomainID
getDomainID()
Return the currently selected domain ID.
Definition: Database.php:790
Wikimedia\Rdbms\Database\getClass
static getClass( $dbType, $driver=null)
Definition: Database.php:450
Wikimedia\Rdbms\Database\pingAndCalculateLastTrxApplyTime
pingAndCalculateLastTrxApplyTime()
Definition: Database.php:686
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:954
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:3426
Wikimedia\Rdbms\Database\tableLocksHaveTransactionScope
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
Definition: Database.php:4713
Wikimedia\Rdbms\Database\wasErrorReissuable
wasErrorReissuable()
Determines if the last query error was due to something outside of the query itself.
Definition: Database.php:3319
Wikimedia\Rdbms\Database\deleteJoin
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
Definition: Database.php:2978
Wikimedia\Rdbms\Database\setIndexAliases
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.
Definition: Database.php:4821
Wikimedia\Rdbms\Database\$password
string $password
Password used to establish the current connection.
Definition: Database.php:79
Wikimedia\Rdbms\Database\nativeReplace
nativeReplace( $table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
Definition: Database.php:2904
Wikimedia\Rdbms\Database\decodeBlob
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
Definition: Database.php:4444
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:3216
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:370
Wikimedia\Rdbms\Database\maxListLen
maxListLen()
Return the maximum number of items allowed in a list, or 0 for unlimited.
Definition: Database.php:4436
Wikimedia\Rdbms\Database\selectDomain
selectDomain( $domain)
Set the current domain (database, schema, and table prefix)
Definition: Database.php:2386
Wikimedia\Rdbms\Database\buildIntegerCast
buildIntegerCast( $field)
Definition: Database.php:2359
Wikimedia\Rdbms\Database\getServerUptime
getServerUptime()
Determines how long the server has been up.
Definition: Database.php:3299
Wikimedia\Rdbms\Database\tableNames
tableNames()
Fetch a number of table names into an array This is handy when you need to construct SQL for joins.
Definition: Database.php:2517
Wikimedia\Rdbms\Database\prependDatabaseOrSchema
prependDatabaseOrSchema( $namespace, $relation, $format)
Definition: Database.php:2506
Wikimedia\Rdbms\Database\$delimiter
string $delimiter
Current SQL query delimiter.
Definition: Database.php:96
Wikimedia\Rdbms\Database\__destruct
__destruct()
Run a few simple sanity checks and close dangling connections.
Definition: Database.php:4918
Wikimedia\Rdbms\Database\endAtomic
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
Definition: Database.php:3843
Wikimedia\Rdbms\Database\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:2727
Wikimedia\Rdbms\Database\executeQuery
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
Definition: Database.php:1178
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.
Definition: Database.php:4795
Wikimedia\Rdbms\DBReadOnlyRoleError
Exception class for attempted DB write access to a DBConnRef with the DB_REPLICA role.
Definition: DBReadOnlyRoleError.php:29
Wikimedia\Rdbms\DBTransactionStateError
Definition: DBTransactionStateError.php:27
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:4243
Wikimedia\Rdbms\Database\decodeExpiry
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
Definition: Database.php:4787
Wikimedia\Rdbms\Database\$trxAutomaticAtomic
bool $trxAutomaticAtomic
Whether the current transaction was started implicitly by startAtomic()
Definition: Database.php:137
Wikimedia\Rdbms\Database\initConnection
initConnection()
Initialize the connection to the database over the wire (or to local files)
Definition: Database.php:286
Wikimedia\Rdbms\Database\normalizeConditions
normalizeConditions( $conds, $fname)
Definition: Database.php:2005
Wikimedia\Rdbms\Database\anyString
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
Definition: Database.php:2807
Wikimedia\Rdbms\Database\unionSupportsOrderAndLimit
unionSupportsOrderAndLimit()
Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION.
Definition: Database.php:3206
Wikimedia\Rdbms\DBMasterPos
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:12
Wikimedia\Rdbms\Database\isInsertSelectSafe
isInsertSelectSafe(array $insertOptions, array $selectOptions)
Definition: Database.php:3077
Wikimedia\Rdbms\Database\fieldNameWithAlias
fieldNameWithAlias( $name, $alias=false)
Get an aliased field name e.g.
Definition: Database.php:2596
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:966
Wikimedia\Rdbms\Database\getDefaultSchemaVars
getDefaultSchemaVars()
Get schema variables to use if none have been set via setSchemaVars().
Definition: Database.php:4650
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:63
Wikimedia\Rdbms\GeneralizedSql
Lazy-loaded wrapper for simplification and scrubbing of SQL queries for profiling.
Definition: GeneralizedSql.php:29
$s
$s
Definition: mergeMessageFileList.php:185
Wikimedia\Rdbms\Database\extractSingleFieldFromList
extractSingleFieldFromList( $var)
Definition: Database.php:2028
Wikimedia\Rdbms\Database\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.
Definition: Database.php:4223
Wikimedia\Rdbms\Database\$trxSectionCancelCallbacks
array[] $trxSectionCancelCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:157
Wikimedia\Rdbms\Database\onTransactionCommitOrIdle
onTransactionCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback as soon as there is no transaction pending.
Definition: Database.php:3409
Wikimedia\Rdbms\Database\upsert
upsert( $table, array $rows, $uniqueIndexes, array $set, $fname=__METHOD__)
INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
Definition: Database.php:2928
Wikimedia\Rdbms\Database\isWriteQuery
isWriteQuery( $sql)
Determine whether a query writes to the DB.
Definition: Database.php:1033
Wikimedia\Rdbms\Database\namedLocksEnqueue
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
Definition: Database.php:4709
Wikimedia\Rdbms\Database\buildSubstring
buildSubstring( $input, $startPosition, $length=null)
Definition: Database.php:2319
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:23
Wikimedia\Rdbms\Database\setLazyMasterHandle
setLazyMasterHandle(IDatabase $conn)
Set a lazy-connecting DB handle to the master DB (for replication status purposes)
Definition: Database.php:611
Wikimedia\Rdbms\IDatabase\getSessionLagStatus
getSessionLagStatus()
Get the replica DB lag when the current transaction started or a general lag estimate if not transact...
Wikimedia\Rdbms\Database\tableNamesWithIndexClauseOrJOIN
tableNamesWithIndexClauseOrJOIN( $tables, $use_index=[], $ignore_index=[], $join_conds=[])
Get the aliased table name clause for a FROM clause which might have a JOIN and/or USE INDEX or IGNOR...
Definition: Database.php:2632
Wikimedia\Rdbms\Database\getReplicaPos
getReplicaPos()
Get the replication position of this replica DB.
Definition: Database.php:3388
Wikimedia\Rdbms\Database\getSchemaVars
getSchemaVars()
Get schema variables.
Definition: Database.php:4638
Wikimedia\Rdbms\Database\setLogger
setLogger(LoggerInterface $logger)
Set the PSR-3 logger interface to use for query logging.
Definition: Database.php:512
Wikimedia\Rdbms\Database\__clone
__clone()
Make sure that copies do not share the same client binding handle.
Definition: Database.php:4881
$res
$res
Definition: testCompression.php:52
Wikimedia\Rdbms\Database\cancelAtomic
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
Definition: Database.php:3877
$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:786
Wikimedia\Rdbms\Database\conditional
conditional( $cond, $trueVal, $falseVal)
Returns an SQL expression for a simple conditional.
Definition: Database.php:3287
Wikimedia\Rdbms\Database\$trxAtomicLevels
array $trxAtomicLevels
List of (name, unique ID, savepoint ID) for each active atomic section level.
Definition: Database.php:135
Wikimedia\Rdbms\Database\$PING_QUERY
static string $PING_QUERY
Dummy SQL query.
Definition: Database.php:217
Wikimedia\Rdbms\Database\handleSessionLossPostconnect
handleSessionLossPostconnect()
Clean things up after session (and thus transaction) loss after reconnect.
Definition: Database.php:1517
Wikimedia\Rdbms\Database\$connectionVariables
string[] int[] float[] $connectionVariables
SQL variables values to use for all new connections.
Definition: Database.php:87
Wikimedia\Rdbms\Database\$lastQuery
string $lastQuery
The last SQL query attempted.
Definition: Database.php:169
Wikimedia\Rdbms\Database\$trxStatusIgnoredCause
array null $trxStatusIgnoredCause
Error details of the last statement-only rollback.
Definition: Database.php:121
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".
Definition: Database.php:2996
Wikimedia\Rdbms\Database\buildConcat
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
Definition: Database.php:2307
Wikimedia\Rdbms\Database\deadlockLoop
deadlockLoop()
Perform a deadlock-prone transaction.
Definition: Database.php:3347
Wikimedia\Rdbms\Database\bitNot
bitNot( $field)
Definition: Database.php:2295
Wikimedia\Rdbms\Database\nextSavepointId
nextSavepointId( $fname)
Definition: Database.php:3798
LIST_AND
const LIST_AND
Definition: Defines.php:48
Wikimedia\Rdbms\Database\$agent
string $agent
Agent name for query profiling.
Definition: Database.php:83
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:4910
DBO_NOBUFFER
const DBO_NOBUFFER
Definition: defines.php:10
Wikimedia\Rdbms\Database\doBegin
doBegin( $fname)
Issues the BEGIN command to the database server.
Definition: Database.php:4037
Wikimedia\Rdbms\Database\$trxIdleCallbacks
array[] $trxIdleCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:151
Wikimedia\Rdbms\Database\clearFlag
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
Definition: Database.php:758
Wikimedia\Rdbms\Database\getQueryExceptionAndLog
getQueryExceptionAndLog( $error, $errno, $sql, $fname)
Definition: Database.php:1585
Wikimedia\Rdbms\Database\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Definition: Database.php:3978
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:4274
Wikimedia\Rdbms\Database\doHandleSessionLossPreconnect
doHandleSessionLossPreconnect()
Reset any additional subclass trx* and session* fields.
Definition: Database.php:1510
Wikimedia\Rdbms\Database\$lastWriteTime
float bool $lastWriteTime
UNIX timestamp of last write query.
Definition: Database.php:171
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:3584
Wikimedia\Rdbms\Database\$trxStatusCause
Exception null $trxStatusCause
The last error that caused the status to become STATUS_TRX_ERROR.
Definition: Database.php:119
Wikimedia\Rdbms\Database\close
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition: Database.php:876
Wikimedia\Rdbms\Database\replaceVars
replaceVars( $ins)
Database independent variable replacement.
Definition: Database.php:4600
Wikimedia\Rdbms\Database\handleSessionLossPreconnect
handleSessionLossPreconnect()
Clean things up after session (and thus transaction) loss before reconnect.
Definition: Database.php:1480
Wikimedia\Rdbms\Database\$NOT_APPLICABLE
static string $NOT_APPLICABLE
Idiom used when a cancelable atomic section started the transaction.
Definition: Database.php:198
Wikimedia\Rdbms\Database\$trxStatus
int $trxStatus
Transaction status.
Definition: Database.php:117
Wikimedia\Rdbms\Database\runOnTransactionPreCommitCallbacks
runOnTransactionPreCommitCallbacks()
Actually consume and run any "on transaction pre-commit" callbacks.
Definition: Database.php:3653
Wikimedia\Rdbms\Database\wasLockTimeout
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
Definition: Database.php:3307
Wikimedia\Rdbms\Database\$affectedRowCount
integer null $affectedRowCount
Rows affected by the last query to query() or its CRUD wrappers.
Definition: Database.php:164
Wikimedia\Rdbms\Database\$currentDomain
DatabaseDomain $currentDomain
Definition: Database.php:66
LIST_OR
const LIST_OR
Definition: Defines.php:51
Wikimedia\Rdbms\Database\getLag
getLag()
Get the amount of replication lag for this database server.
Definition: Database.php:4422
Wikimedia\Rdbms\Database\$sessionTempTables
array $sessionTempTables
Map of (table name => 1) for TEMPORARY tables.
Definition: Database.php:112
Wikimedia\Rdbms\Database\buildSelectSubquery
buildSelectSubquery( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Equivalent to IDatabase::selectSQLText() except wraps the result in Subqyery.
Definition: Database.php:2363
Wikimedia\Rdbms\Database\$TEMP_PSEUDO_PERMANENT
static int $TEMP_PSEUDO_PERMANENT
Writes to this temporary table effect lastDoneWrites()
Definition: Database.php:205
Wikimedia\Rdbms\Database\assertBuildSubstringParams
assertBuildSubstringParams( $startPosition, $length)
Check type and bounds for parameters to self::buildSubstring()
Definition: Database.php:2340
Wikimedia\Rdbms\Database\isReadOnly
isReadOnly()
Definition: Database.php:4799
Wikimedia\Rdbms\Database\buildStringCast
buildStringCast( $field)
Definition: Database.php:2353
Wikimedia\Rdbms\Database\$lazyMasterHandle
IDatabase null $lazyMasterHandle
Lazy handle to the master DB this server replicates from.
Definition: Database.php:72
Wikimedia\Rdbms\Database\unlockTables
unlockTables( $method)
Unlock all tables locked via lockTables()
Definition: Database.php:4741
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:4350
Wikimedia\Rdbms\Database\nonNativeInsertSelect
nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
Implementation of insertSelect() based on select() and insert()
Definition: Database.php:3095
Wikimedia\Rdbms\Database\$trxWriteDuration
float $trxWriteDuration
Seconds spent in write queries for the current transaction.
Definition: Database.php:141
Wikimedia\Rdbms\Database\doRollbackToSavepoint
doRollbackToSavepoint( $identifier, $fname)
Rollback to a savepoint.
Definition: Database.php:3790
Wikimedia\Rdbms\Database\startAtomic
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Definition: Database.php:3813
Wikimedia\Rdbms\DBQueryTimeoutError
Error thrown when a query times out.
Definition: DBQueryTimeoutError.php:29
Wikimedia\Rdbms\Database\selectOptionsIncludeLocking
selectOptionsIncludeLocking( $options)
Definition: Database.php:1961
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
Wikimedia\Rdbms\Database\getCacheSetOptions
static getCacheSetOptions(IDatabase $db1, IDatabase $db2=null)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Definition: Database.php:4405
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\getTempWrites
getTempWrites( $sql, $pseudoPermanent)
Definition: Database.php:1090
Wikimedia\Rdbms\Database\lock
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
Definition: Database.php:4661
Wikimedia\Rdbms\Database\getTransactionRoundId
getTransactionRoundId()
Definition: Database.php:657
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:531
Wikimedia\Rdbms\Database\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Definition: Database.php:743
Wikimedia\Rdbms\Database\rollback
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
Definition: Database.php:4116
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:1409
$matches
$matches
Definition: NoLocalSettings.php:24
Wikimedia\Rdbms\Database\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Run a callback after each time any transaction commits or rolls back.
Definition: Database.php:3554
Wikimedia\Rdbms\Database\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
Definition: Database.php:2770
Wikimedia\Rdbms\Database\$tableAliases
array[] $tableAliases
Current map of (table => (dbname, schema, prefix) map)
Definition: Database.php:98
Wikimedia\Rdbms\Database\reportQueryError
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
Definition: Database.php:1570
Wikimedia\Rdbms\Database\$cliMode
bool $cliMode
Whether this PHP instance is for a CLI script.
Definition: Database.php:81
Wikimedia\Rdbms\Database\$trxShortId
string $trxShortId
ID of the active transaction or the empty string otherwise.
Definition: Database.php:115
Wikimedia\Rdbms\Database\isTransactableQuery
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
Definition: Database.php:1074
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:2044
LIST_SET
const LIST_SET
Definition: Defines.php:49
Wikimedia\Rdbms\Database\indexExists
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists.
Definition: Database.php:2066
Wikimedia\Rdbms\Database\writesOrCallbacksPending
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...
Definition: Database.php:640
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:4490
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.
Definition: Database.php:1810
Wikimedia\Rdbms\Database\$TEMP_NORMAL
static int $TEMP_NORMAL
Writes to this temporary table do not affect lastDoneWrites()
Definition: Database.php:203
Wikimedia\Rdbms\Database\$trxWriteCallers
string[] $trxWriteCallers
Write query callers of the current transaction.
Definition: Database.php:139
Wikimedia\Rdbms\Database\$lastPing
float $lastPing
UNIX timestamp.
Definition: Database.php:167
Wikimedia\Rdbms\Database\bitAnd
bitAnd( $fieldLeft, $fieldRight)
Definition: Database.php:2299
Wikimedia\Rdbms\Database\buildLike
buildLike( $param,... $params)
Definition: Database.php:2776
$t
$t
Definition: make-normalization-table.php:143
Wikimedia\Rdbms\Database\$trxProfiler
TransactionProfiler $trxProfiler
Definition: Database.php:63
Wikimedia\Rdbms\Database\$user
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:77
Wikimedia\Rdbms\Database\assertNoOpenTransactions
assertNoOpenTransactions()
Assert that all explicit transactions or atomic sections have been closed.
Definition: Database.php:1436
Wikimedia\Rdbms\Database\selectDB
selectDB( $db)
Change the current database.
Definition: Database.php:2376
Wikimedia\Rdbms\Database\wasQueryTimeout
wasQueryTimeout( $error, $errno)
Checks whether the cause of the error is detected to be a timeout.
Definition: Database.php:1555
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:632
Wikimedia\Rdbms\Database\dropTable
dropTable( $tableName, $fName=__METHOD__)
Delete a table.
Definition: Database.php:4768
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:222
Wikimedia\Rdbms\Database\wasReadOnlyError
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
Definition: Database.php:3315
Wikimedia\Rdbms\Database\beginIfImplied
beginIfImplied( $sql, $fname)
Start an implicit transaction if DBO_TRX is enabled and no transaction is active.
Definition: Database.php:1357
Wikimedia\Rdbms\Database\getServerInfo
getServerInfo()
Get a human-readable string describing the current software version.
Definition: Database.php:516
Wikimedia\Rdbms\Database\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Definition: Database.php:4041
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:773
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:855
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:597
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:4673
Wikimedia\Rdbms\Database\fieldNamesWithAlias
fieldNamesWithAlias( $fields)
Gets an array of aliased field names.
Definition: Database.php:2610
Wikimedia\Rdbms\Database\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:585
Wikimedia\Rdbms\DBReadOnlyError
Definition: DBReadOnlyError.php:27
Wikimedia\Rdbms\Database\$trxWriteAffectedRows
int $trxWriteAffectedRows
Number of rows affected by write queries for the current transaction.
Definition: Database.php:145
Wikimedia\Rdbms\Database\$trxWriteAdjDuration
float $trxWriteAdjDuration
Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries.
Definition: Database.php:147
Wikimedia\Rdbms\Database\insertSelect
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper.
Definition: Database.php:3033
Wikimedia\Rdbms\Database\makeInsertOptions
makeInsertOptions( $options)
Helper for Database::insert().
Definition: Database.php:2097
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:1893
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
Wikimedia\Rdbms\Database\useIndexClause
useIndexClause( $index)
USE INDEX clause.
Definition: Database.php:2825
Wikimedia\Rdbms\Database\makeUpdateOptions
makeUpdateOptions( $options)
Make UPDATE options for the Database::update function.
Definition: Database.php:2171
LIST_COMMA
const LIST_COMMA
Definition: Defines.php:47
Wikimedia\Rdbms\Database\getReadOnlyReason
getReadOnlyReason()
Definition: Database.php:4806
Wikimedia\Rdbms\DBQueryDisconnectedError
Definition: DBQueryDisconnectedError.php:28
Wikimedia\Rdbms\Database\$priorFlags
int[] $priorFlags
Prior flags member variable values.
Definition: Database.php:107
Wikimedia\Rdbms\Database\doGetLag
doGetLag()
Definition: Database.php:4432
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:814
Wikimedia\Rdbms\Database\aggregateValue
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
Definition: Database.php:2291
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:825
Wikimedia\Rdbms\Database\preCommitCallbacksPending
preCommitCallbacksPending()
Definition: Database.php:650
$line
$line
Definition: cdb.php:59
Wikimedia\Rdbms\Database\replace
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
REPLACE query wrapper.
Definition: Database.php:2843
Wikimedia\Rdbms\Database\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Definition: Database.php:3343
Wikimedia\Rdbms\Database\pendingWriteAndCallbackCallers
pendingWriteAndCallbackCallers()
List the methods that have write queries or callbacks for the current transaction.
Definition: Database.php:714
Wikimedia\Rdbms\Database\$trxPreCommitCallbacks
array[] $trxPreCommitCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:153
Wikimedia\Rdbms\Database\$htmlErrors
string bool null $htmlErrors
Stashed value of html_errors INI setting.
Definition: Database.php:105
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:200
Wikimedia\Rdbms\Database\pendingWriteCallers
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
Definition: Database.php:698
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MAX
static int $DEADLOCK_DELAY_MAX
Maximum time to wait before retry.
Definition: Database.php:212
Wikimedia\Rdbms\Database\$trxEndCallbacks
array[] $trxEndCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:155
Wikimedia\Rdbms\Database\tableNamesN
tableNamesN()
Fetch a number of table names into an zero-indexed numerical array This is handy when you need to con...
Definition: Database.php:2528
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:4857
Wikimedia\Rdbms\Database\$lastRoundTripEstimate
float $lastRoundTripEstimate
Query rount trip time estimate.
Definition: Database.php:175
Wikimedia\Rdbms\Database\getLogContext
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: Database.php:865
Wikimedia\Rdbms\Database\$connectionParams
array $connectionParams
Parameters used by initConnection() to establish a connection.
Definition: Database.php:85
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:131
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:4187
Wikimedia\Rdbms\Database\pendingWriteRowsAffected
pendingWriteRowsAffected()
Get the number of affected rows from pending write queries.
Definition: Database.php:702
Wikimedia\Rdbms\Database\$trxWriteQueryCount
int $trxWriteQueryCount
Number of write queries for the current transaction.
Definition: Database.php:143
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:3776
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:1269
Wikimedia\Rdbms\Database\currentAtomicSectionId
currentAtomicSectionId()
Definition: Database.php:3458
Wikimedia\Rdbms\Database\modifyCallbacksForCancel
modifyCallbacksForCancel(array $sectionIds, AtomicSectionIdentifier $newSectionId=null)
Update callbacks that were owned by cancelled atomic sections.
Definition: Database.php:3518
Wikimedia\Rdbms\Database\setTrxEndCallbackSuppression
setTrxEndCallbackSuppression( $suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
Definition: Database.php:3570
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.
Definition: Database.php:3393
Wikimedia\Rdbms\Database\pendingWriteQueryDuration
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
Definition: Database.php:668
Wikimedia\Rdbms\Database\$indexAliases
string[] $indexAliases
Current map of (index alias => index)
Definition: Database.php:100
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.
Definition: Database.php:2408
Wikimedia\Rdbms\Database\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: Database.php:3333
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:3962
Wikimedia\Rdbms\Database\getRecordedTransactionLagStatus
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
Definition: Database.php:4367
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:3687
Wikimedia\Rdbms\Database\getServer
getServer()
Get the server hostname or IP address.
Definition: Database.php:2404
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:27
Wikimedia\Rdbms\Database\doLockTables
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
Definition: Database.php:4737
Wikimedia\Rdbms\Database\doUnlockTables
doUnlockTables( $method)
Helper function for unlockTables() that handles the actual table unlocking.
Definition: Database.php:4757
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:4237
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:1631
Wikimedia\Rdbms\Database\bufferResults
bufferResults( $buffer=null)
Backwards-compatibility no-op method for disabling query buffering.
Definition: Database.php:527
Wikimedia\Rdbms\Database\makeList
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2192
Wikimedia\Rdbms\Database\registerTempWrites
registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel)
Definition: Database.php:1130
Wikimedia\Rdbms\Database\anyChar
anyChar()
Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
Definition: Database.php:2803
Wikimedia\Rdbms\Database\onTransactionIdle
onTransactionIdle(callable $callback, $fname=__METHOD__)
Alias for onTransactionCommitOrIdle() for backwards-compatibility.
Definition: Database.php:3422
Wikimedia\Rdbms\Database\unlock
unlock( $lockName, $method)
Release a lock.
Definition: Database.php:4667
Wikimedia\Rdbms\Database\$profiler
callable null $profiler
Definition: Database.php:61
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:224
Wikimedia\Rdbms\Database\addIdentifierQuotes
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.
Definition: Database.php:2748
Wikimedia\Rdbms\Database\getLazyMasterHandle
getLazyMasterHandle()
Definition: Database.php:620
Wikimedia\Rdbms\Database\consumeTrxShortId
consumeTrxShortId()
Reset the transaction ID and return the old one.
Definition: Database.php:1538
Wikimedia\Rdbms\Database\indexUnique
indexUnique( $table, $index)
Determines if a given index is unique.
Definition: Database.php:2081
$args
if( $line===false) $args
Definition: cdb.php:64
Wikimedia\Rdbms\Database\dbSchema
dbSchema( $schema=null)
Get/set the db schema.
Definition: Database.php:560
Wikimedia\Rdbms\Database\$trxRecurringCallbacks
callable[] $trxRecurringCallbacks
Map of (name => callable)
Definition: Database.php:159
Wikimedia\Rdbms\Database\getQueryVerb
getQueryVerb( $sql)
Definition: Database.php:1057
Wikimedia\Rdbms\Database\unionQueries
unionQueries( $sqls, $all)
Construct a UNION query.
Definition: Database.php:3210
Wikimedia\Rdbms\DBTransactionError
Definition: DBTransactionError.php:27
Wikimedia\Rdbms\Database\reassignCallbacksForSection
reassignCallbacksForSection(AtomicSectionIdentifier $old, AtomicSectionIdentifier $new)
Hoist callback ownership for callbacks in a section to a parent section.
Definition: Database.php:3474
Wikimedia\Rdbms\IDatabase\lastErrno
lastErrno()
Get the last error number.
Wikimedia\Rdbms\Database\relationSchemaQualifier
relationSchemaQualifier()
Definition: Database.php:581
Wikimedia\Rdbms\Database\$DEADLOCK_TRIES
static int $DEADLOCK_TRIES
Number of times to re-try an operation in case of deadlock.
Definition: Database.php:208
Wikimedia\Rdbms\Database\newExceptionAfterConnectError
newExceptionAfterConnectError( $error)
Definition: Database.php:1613
Wikimedia\Rdbms\Database\lockTables
lockTables(array $read, array $write, $method)
Lock specific tables.
Definition: Database.php:4717
Wikimedia\Rdbms\Database\$trxAtomicCounter
int $trxAtomicCounter
Counter for atomic savepoint identifiers (reset with each transaction)
Definition: Database.php:133
Wikimedia\Rdbms\Database\encodeExpiry
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
Definition: Database.php:4781
Wikimedia\Rdbms\Database\$srvCache
BagOStuff $srvCache
APC cache.
Definition: Database.php:51
Wikimedia\Rdbms\Database\doSavepoint
doSavepoint( $identifier, $fname)
Create a savepoint.
Definition: Database.php:3762
Wikimedia\Rdbms\Database\setSchemaVars
setSchemaVars( $vars)
Set variables to be used in sourceFile/sourceStream, in preference to the ones in $GLOBALS.
Definition: Database.php:4486
Wikimedia\Rdbms\Database\__construct
__construct(array $params)
Definition: Database.php:242
Wikimedia\Rdbms\Database\trxTimestamp
trxTimestamp()
Get the UNIX timestamp of the time that the transaction was established.
Definition: Database.php:535
Wikimedia\Rdbms\Database\$trxTimestamp
float null $trxTimestamp
UNIX timestamp at the time of BEGIN for the last transaction.
Definition: Database.php:123
Wikimedia\Rdbms\Database\makeGroupByWithHaving
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1764
Wikimedia\Rdbms\Database\tableNameWithAlias
tableNameWithAlias( $table, $alias=false)
Get an aliased table name.
Definition: Database.php:2550
Wikimedia\Rdbms\Database\getAttributes
static getAttributes()
Definition: Database.php:501
Wikimedia\Rdbms\Database\writesPending
writesPending()
Definition: Database.php:636
Wikimedia\Rdbms\Database\selectFieldsOrOptionsAggregate
selectFieldsOrOptionsAggregate( $fields, $options)
Definition: Database.php:1977
Wikimedia\Rdbms\Database\lockIsFree
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)
Definition: Database.php:4654
Wikimedia\Rdbms\Database\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Definition: Database.php:4286
Wikimedia\Rdbms\Database\$nonNativeInsertSelectBatchSize
int $nonNativeInsertSelectBatchSize
Row batch size to use for emulated INSERT SELECT queries.
Definition: Database.php:89
Wikimedia\Rdbms\Database\runTransactionListenerCallbacks
runTransactionListenerCallbacks( $trigger)
Actually run any "transaction listener" callbacks.
Definition: Database.php:3730
Wikimedia\Rdbms\Database\onAtomicSectionCancel
onAtomicSectionCancel(callable $callback, $fname=__METHOD__)
Run a callback when the atomic section is cancelled.
Definition: Database.php:3448
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
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:4817
Wikimedia\Rdbms\Database\$MUTABLE_FLAGS
static string[] $MUTABLE_FLAGS
List of DBO_* flags that can be changed after connection.
Definition: Database.php:227
Wikimedia\Rdbms\Database\masterPosWait
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
Definition: Database.php:3383
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:3402
Wikimedia\Rdbms\IDatabase\getType
getType()
Get the type of the DBMS (e.g.
Wikimedia\Rdbms\Database\explicitTrxActive
explicitTrxActive()
Definition: Database.php:4219
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:75
$keys
$keys
Definition: testCompression.php:67
Wikimedia\Rdbms\Database\freeResult
freeResult( $res)
Free a result object returned by query() or select()
Definition: Database.php:1628
Wikimedia\Rdbms\Database\isOpen
isOpen()
Definition: Database.php:739
Wikimedia\Rdbms\Database\doCommit
doCommit( $fname)
Issues the COMMIT command to the database server.
Definition: Database.php:4110
Wikimedia\Rdbms\IMaintainableDatabase\fieldInfo
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
Wikimedia\Rdbms\Database\makeOrderBy
makeOrderBy( $options)
Returns an optional ORDER BY.
Definition: Database.php:1790
Wikimedia\Rdbms\Database\$flags
int $flags
Current bit field of class DBO_* constants.
Definition: Database.php:92
Wikimedia\Rdbms\Database\serverIsReadOnly
serverIsReadOnly()
Definition: Database.php:3398
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:1693
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:1802
Wikimedia\Rdbms\Database\attributesFromType
static attributesFromType( $dbType, $driver=null)
Definition: Database.php:433
Wikimedia\Rdbms\Database\lastQuery
lastQuery()
Get the last query that sent on account of IDatabase::query()
Definition: Database.php:628
Wikimedia\Rdbms\Database\wasConnectionLoss
wasConnectionLoss()
Determines if the last query error was due to a dropped connection.
Definition: Database.php:3311
Wikimedia\Rdbms\Database\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.
Definition: Database.php:3303
Wikimedia\Rdbms\Database\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Definition: Database.php:2396
Wikimedia\Rdbms\Database\$connLogger
LoggerInterface $connLogger
Definition: Database.php:53
Wikimedia\Rdbms\Database\update
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
Definition: Database.php:2177
Wikimedia\Rdbms\Database\addQuotes
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
Definition: Database.php:2731
LIST_NAMES
const LIST_NAMES
Definition: Defines.php:50
Wikimedia\Rdbms\Database\getApproximateLagStatus
getApproximateLagStatus()
Get a replica DB lag estimate for this server.
Definition: Database.php:4379
Wikimedia\Rdbms\Database\qualifiedTableComponents
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
Definition: Database.php:2466
Wikimedia\Rdbms\Database\affectedRows
affectedRows()
Get the number of rows affected by the last write query.
Definition: Database.php:4251
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MIN
static int $DEADLOCK_DELAY_MIN
Minimum time to wait before retry, in microseconds.
Definition: Database.php:210
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.
Definition: Database.php:2372
Wikimedia\Rdbms\TransactionProfiler
Helper class that detects 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.
Definition: Database.php:3295
Wikimedia\Rdbms\Database\$ownerId
int null $ownerId
Integer ID of the managing LBFactory instance or null if none.
Definition: Database.php:178
Wikimedia\Rdbms\Database\fieldHasBit
fieldHasBit( $field, $flags)
Definition: Database.php:4831
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:4454
DBO_DEFAULT
const DBO_DEFAULT
Definition: defines.php:13
Wikimedia\Rdbms\Database\listViews
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.
Definition: Database.php:4233
Wikimedia\Rdbms\Database\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
Definition: Database.php:4567
Wikimedia\Rdbms\Database\nativeInsertSelect
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
Native server-side implementation of insertSelect() for situations where we don't want to select ever...
Definition: Database.php:3164
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query and return the result.
Definition: Database.php:1141
Wikimedia\Rdbms\Database\tableNamesWithAlias
tableNamesWithAlias( $tables)
Gets an array of aliased table names.
Definition: Database.php:2576
Wikimedia\Rdbms\Database\nextSequenceValue
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
Definition: Database.php:2811
Wikimedia\Rdbms\Subquery
Definition: Subquery.php:27
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:1657
Wikimedia\Rdbms\Database\flatAtomicSectionList
flatAtomicSectionList()
Definition: Database.php:733
Wikimedia\Rdbms\Database\$deprecationLogger
callable $deprecationLogger
Deprecation logging callback.
Definition: Database.php:59
Wikimedia\Rdbms\Database\$errorLogger
callable $errorLogger
Error logging callback.
Definition: Database.php:57
Wikimedia\Rdbms\Database\$conn
object resource null $conn
Database connection.
Definition: Database.php:69
Wikimedia\Rdbms\Database\doRollback
doRollback( $fname)
Issues the ROLLBACK command to the database server.
Definition: Database.php:4179
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:220
Wikimedia\Rdbms\Database\$lbInfo
array $lbInfo
Current LoadBalancer tracking information.
Definition: Database.php:94
Wikimedia\Rdbms\Database\getDBname
getDBname()
Get the current DB name.
Definition: Database.php:2400
Wikimedia\Rdbms\Blob
Definition: Blob.php:5
Wikimedia\Rdbms\Database\getInfinity
getInfinity()
Find out when 'infinity' is.
Definition: Database.php:4777
$type
$type
Definition: testCompression.php:48
Wikimedia\Rdbms\Database\$sessionNamedLocks
array $sessionNamedLocks
Map of (name => 1) for locks obtained via lock()
Definition: Database.php:110