MediaWiki  master
Database.php
Go to the documentation of this file.
1 <?php
26 namespace Wikimedia\Rdbms;
27 
28 use BagOStuff;
29 use Exception;
30 use HashBagOStuff;
31 use InvalidArgumentException;
32 use LogicException;
33 use Psr\Log\LoggerAwareInterface;
34 use Psr\Log\LoggerInterface;
35 use Psr\Log\NullLogger;
36 use RuntimeException;
37 use Throwable;
38 use UnexpectedValueException;
39 use Wikimedia\AtEase\AtEase;
40 use Wikimedia\ScopedCallback;
41 use Wikimedia\Timestamp\ConvertibleTimestamp;
42 
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 $topologyRole;
89  protected $connectionParams;
94 
96  protected $flags;
98  protected $lbInfo = [];
100  protected $delimiter = ';';
102  protected $tableAliases = [];
104  protected $indexAliases = [];
106  protected $schemaVars;
107 
109  private $htmlErrors;
111  private $priorFlags = [];
112 
114  protected $sessionNamedLocks = [];
116  protected $sessionTempTables = [];
117 
119  private $trxShortId = '';
121  private $trxStatus = self::STATUS_TRX_NONE;
127  private $trxTimestamp = null;
129  private $trxReplicaLag = null;
131  private $trxFname = null;
133  private $trxDoneWrites = false;
135  private $trxAutomatic = false;
137  private $trxAtomicCounter = 0;
139  private $trxAtomicLevels = [];
141  private $trxAutomaticAtomic = false;
143  private $trxWriteCallers = [];
145  private $trxWriteDuration = 0.0;
147  private $trxWriteQueryCount = 0;
151  private $trxWriteAdjDuration = 0.0;
155  private $trxIdleCallbacks = [];
162  private $trxEndCallbacks = [];
168  private $trxEndCallbacksSuppressed = false;
169 
171  protected $affectedRowCount;
172 
174  private $lastPing = 0.0;
176  private $lastQuery = '';
178  private $lastWriteTime = false;
180  private $lastPhpError = false;
182  private $lastRoundTripEstimate = 0.0;
183 
185  private $ownerId;
186 
188  const ATTR_DB_IS_FILE = 'db-is-file';
190  const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
192  const ATTR_SCHEMAS_AS_TABLE_GROUPS = 'supports-schemas';
193 
195  const NEW_UNCONNECTED = 0;
197  const NEW_CONNECTED = 1;
198 
200  const STATUS_TRX_ERROR = 1;
202  const STATUS_TRX_OK = 2;
204  const STATUS_TRX_NONE = 3;
205 
207  private static $NOT_APPLICABLE = 'n/a';
209  private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
210 
212  private static $TEMP_NORMAL = 1;
214  private static $TEMP_PSEUDO_PERMANENT = 2;
215 
217  private static $DEADLOCK_TRIES = 4;
219  private static $DEADLOCK_DELAY_MIN = 500000;
221  private static $DEADLOCK_DELAY_MAX = 1500000;
222 
224  private static $PING_TTL = 1.0;
226  private static $PING_QUERY = 'SELECT 1 AS ping';
227 
229  private static $TINY_WRITE_SEC = 0.010;
231  private static $SLOW_WRITE_SEC = 0.500;
233  private static $SMALL_WRITE_ROWS = 100;
234 
236  protected static $MUTABLE_FLAGS = [
237  'DBO_DEBUG',
238  'DBO_NOBUFFER',
239  'DBO_TRX',
240  'DBO_DDLMODE',
241  ];
243  protected static $DBO_MUTABLE = (
245  );
246 
251  public function __construct( array $params ) {
252  $this->connectionParams = [
253  'host' => strlen( $params['host'] ) ? $params['host'] : null,
254  'user' => strlen( $params['user'] ) ? $params['user'] : null,
255  'dbname' => strlen( $params['dbname'] ) ? $params['dbname'] : null,
256  'schema' => strlen( $params['schema'] ) ? $params['schema'] : null,
257  'password' => is_string( $params['password'] ) ? $params['password'] : null,
258  'tablePrefix' => (string)$params['tablePrefix']
259  ];
260 
261  $this->lbInfo = $params['lbInfo'] ?? [];
262  $this->lazyMasterHandle = $params['lazyMasterHandle'] ?? null;
263  $this->connectionVariables = $params['variables'] ?? [];
264 
265  $this->flags = (int)$params['flags'];
266  $this->cliMode = (bool)$params['cliMode'];
267  $this->agent = (string)$params['agent'];
268  $this->topologyRole = (string)$params['topologyRole'];
269  $this->topologyRootMaster = (string)$params['topologicalMaster'];
270  $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'] ?? 10000;
271 
272  $this->srvCache = $params['srvCache'];
273  $this->profiler = is_callable( $params['profiler'] ) ? $params['profiler'] : null;
274  $this->trxProfiler = $params['trxProfiler'];
275  $this->connLogger = $params['connLogger'];
276  $this->queryLogger = $params['queryLogger'];
277  $this->errorLogger = $params['errorLogger'];
278  $this->deprecationLogger = $params['deprecationLogger'];
279 
280  // Set initial dummy domain until open() sets the final DB/prefix
281  $this->currentDomain = new DatabaseDomain(
282  $params['dbname'] != '' ? $params['dbname'] : null,
283  $params['schema'] != '' ? $params['schema'] : null,
284  $params['tablePrefix']
285  );
286 
287  $this->ownerId = $params['ownerId'] ?? null;
288  }
289 
298  final public function initConnection() {
299  if ( $this->isOpen() ) {
300  throw new LogicException( __METHOD__ . ': already connected' );
301  }
302  // Establish the connection
303  $this->doInitConnection();
304  }
305 
312  protected function doInitConnection() {
313  $this->open(
314  $this->connectionParams['host'],
315  $this->connectionParams['user'],
316  $this->connectionParams['password'],
317  $this->connectionParams['dbname'],
318  $this->connectionParams['schema'],
319  $this->connectionParams['tablePrefix']
320  );
321  }
322 
334  abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
335 
389  final public static function factory( $type, $params = [], $connect = self::NEW_CONNECTED ) {
390  $class = self::getClass( $type, $params['driver'] ?? null );
391 
392  if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
393  $params += [
394  // Default configuration
395  'host' => null,
396  'user' => null,
397  'password' => null,
398  'dbname' => null,
399  'schema' => null,
400  'tablePrefix' => '',
401  'flags' => 0,
402  'variables' => [],
403  'lbInfo' => [],
404  'cliMode' => ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ),
405  'agent' => basename( $_SERVER['SCRIPT_NAME'] ) . '@' . gethostname(),
406  'ownerId' => null,
407  'topologyRole' => null,
408  'topologicalMaster' => null,
409  // Objects and callbacks
410  'lazyMasterHandle' => $params['lazyMasterHandle'] ?? null,
411  'srvCache' => $params['srvCache'] ?? new HashBagOStuff(),
412  'profiler' => $params['profiler'] ?? null,
413  'trxProfiler' => $params['trxProfiler'] ?? new TransactionProfiler(),
414  'connLogger' => $params['connLogger'] ?? new NullLogger(),
415  'queryLogger' => $params['queryLogger'] ?? new NullLogger(),
416  'errorLogger' => $params['errorLogger'] ?? function ( Exception $e ) {
417  trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
418  },
419  'deprecationLogger' => $params['deprecationLogger'] ?? function ( $msg ) {
420  trigger_error( $msg, E_USER_DEPRECATED );
421  }
422  ];
423 
425  $conn = new $class( $params );
426  if ( $connect === self::NEW_CONNECTED ) {
427  $conn->initConnection();
428  }
429  } else {
430  $conn = null;
431  }
432 
433  return $conn;
434  }
435 
443  final public static function attributesFromType( $dbType, $driver = null ) {
444  static $defaults = [
445  self::ATTR_DB_IS_FILE => false,
446  self::ATTR_DB_LEVEL_LOCKING => false,
447  self::ATTR_SCHEMAS_AS_TABLE_GROUPS => false
448  ];
449 
450  $class = self::getClass( $dbType, $driver );
451 
452  return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
453  }
454 
461  private static function getClass( $dbType, $driver = null ) {
462  // For database types with built-in support, the below maps type to IDatabase
463  // implementations. For types with multiple driver implementations (PHP extensions),
464  // an array can be used, keyed by extension name. In case of an array, the
465  // optional 'driver' parameter can be used to force a specific driver. Otherwise,
466  // we auto-detect the first available driver. For types without built-in support,
467  // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
468  static $builtinTypes = [
469  'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
470  'sqlite' => DatabaseSqlite::class,
471  'postgres' => DatabasePostgres::class,
472  ];
473 
474  $dbType = strtolower( $dbType );
475  $class = false;
476 
477  if ( isset( $builtinTypes[$dbType] ) ) {
478  $possibleDrivers = $builtinTypes[$dbType];
479  if ( is_string( $possibleDrivers ) ) {
480  $class = $possibleDrivers;
481  } elseif ( (string)$driver !== '' ) {
482  if ( !isset( $possibleDrivers[$driver] ) ) {
483  throw new InvalidArgumentException( __METHOD__ .
484  " type '$dbType' does not support driver '{$driver}'" );
485  }
486 
487  $class = $possibleDrivers[$driver];
488  } else {
489  foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
490  if ( extension_loaded( $posDriver ) ) {
491  $class = $possibleClass;
492  break;
493  }
494  }
495  }
496  } else {
497  $class = 'Database' . ucfirst( $dbType );
498  }
499 
500  if ( $class === false ) {
501  throw new InvalidArgumentException( __METHOD__ .
502  " no viable database extension found for type '$dbType'" );
503  }
504 
505  return $class;
506  }
507 
512  protected static function getAttributes() {
513  return [];
514  }
515 
523  public function setLogger( LoggerInterface $logger ) {
524  $this->queryLogger = $logger;
525  }
526 
527  public function getServerInfo() {
528  return $this->getServerVersion();
529  }
530 
531  public function getTopologyRole() {
532  return $this->topologyRole;
533  }
534 
535  public function getTopologyRootMaster() {
537  }
538 
546  public function bufferResults( $buffer = null ) {
547  return true;
548  }
549 
550  final public function trxLevel() {
551  return ( $this->trxShortId != '' ) ? 1 : 0;
552  }
553 
554  public function trxTimestamp() {
555  return $this->trxLevel() ? $this->trxTimestamp : null;
556  }
557 
562  public function trxStatus() {
563  return $this->trxStatus;
564  }
565 
566  public function tablePrefix( $prefix = null ) {
567  $old = $this->currentDomain->getTablePrefix();
568  if ( $prefix !== null ) {
569  $this->currentDomain = new DatabaseDomain(
570  $this->currentDomain->getDatabase(),
571  $this->currentDomain->getSchema(),
572  $prefix
573  );
574  }
575 
576  return $old;
577  }
578 
579  public function dbSchema( $schema = null ) {
580  if ( strlen( $schema ) && $this->getDBname() === null ) {
581  throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
582  }
583 
584  $old = $this->currentDomain->getSchema();
585  if ( $schema !== null ) {
586  $this->currentDomain = new DatabaseDomain(
587  $this->currentDomain->getDatabase(),
588  // DatabaseDomain uses null for unspecified schemas
589  strlen( $schema ) ? $schema : null,
590  $this->currentDomain->getTablePrefix()
591  );
592  }
593 
594  return (string)$old;
595  }
596 
600  protected function relationSchemaQualifier() {
601  return $this->dbSchema();
602  }
603 
604  public function getLBInfo( $name = null ) {
605  if ( $name === null ) {
606  return $this->lbInfo;
607  }
608 
609  if ( array_key_exists( $name, $this->lbInfo ) ) {
610  return $this->lbInfo[$name];
611  }
612 
613  return null;
614  }
615 
616  public function setLBInfo( $nameOrArray, $value = null ) {
617  if ( is_array( $nameOrArray ) ) {
618  $this->lbInfo = $nameOrArray;
619  } elseif ( is_string( $nameOrArray ) ) {
620  if ( $value !== null ) {
621  $this->lbInfo[$nameOrArray] = $value;
622  } else {
623  unset( $this->lbInfo[$nameOrArray] );
624  }
625  } else {
626  throw new InvalidArgumentException( "Got non-string key" );
627  }
628  }
629 
636  protected function getLazyMasterHandle() {
638  }
639 
640  public function implicitOrderby() {
641  return true;
642  }
643 
644  public function lastQuery() {
645  return $this->lastQuery;
646  }
647 
648  public function lastDoneWrites() {
649  return $this->lastWriteTime ?: false;
650  }
651 
652  public function writesPending() {
653  return $this->trxLevel() && $this->trxDoneWrites;
654  }
655 
656  public function writesOrCallbacksPending() {
657  return $this->trxLevel() && (
658  $this->trxDoneWrites ||
659  $this->trxIdleCallbacks ||
660  $this->trxPreCommitCallbacks ||
661  $this->trxEndCallbacks ||
663  );
664  }
665 
666  public function preCommitCallbacksPending() {
667  return $this->trxLevel() && $this->trxPreCommitCallbacks;
668  }
669 
673  final protected function getTransactionRoundId() {
674  // If transaction round participation is enabled, see if one is active
675  if ( $this->getFlag( self::DBO_TRX ) ) {
676  $id = $this->getLBInfo( self::LB_TRX_ROUND_ID );
677 
678  return is_string( $id ) ? $id : null;
679  }
680 
681  return null;
682  }
683 
684  public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
685  if ( !$this->trxLevel() ) {
686  return false;
687  } elseif ( !$this->trxDoneWrites ) {
688  return 0.0;
689  }
690 
691  switch ( $type ) {
692  case self::ESTIMATE_DB_APPLY:
693  return $this->pingAndCalculateLastTrxApplyTime();
694  default: // everything
696  }
697  }
698 
702  private function pingAndCalculateLastTrxApplyTime() {
703  $this->ping( $rtt );
704 
705  $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
706  $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
707  // For omitted queries, make them count as something at least
708  $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
709  $applyTime += self::$TINY_WRITE_SEC * $omitted;
710 
711  return $applyTime;
712  }
713 
714  public function pendingWriteCallers() {
715  return $this->trxLevel() ? $this->trxWriteCallers : [];
716  }
717 
718  public function pendingWriteRowsAffected() {
720  }
721 
730  public function pendingWriteAndCallbackCallers() {
731  $fnames = $this->pendingWriteCallers();
732  foreach ( [
733  $this->trxIdleCallbacks,
734  $this->trxPreCommitCallbacks,
735  $this->trxEndCallbacks,
736  $this->trxSectionCancelCallbacks
737  ] as $callbacks ) {
738  foreach ( $callbacks as $callback ) {
739  $fnames[] = $callback[1];
740  }
741  }
742 
743  return $fnames;
744  }
745 
749  private function flatAtomicSectionList() {
750  return array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
751  return $accum === null ? $v[0] : "$accum, " . $v[0];
752  } );
753  }
754 
755  public function isOpen() {
756  return (bool)$this->conn;
757  }
758 
759  public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
760  if ( $flag & ~static::$DBO_MUTABLE ) {
761  throw new DBUnexpectedError(
762  $this,
763  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
764  );
765  }
766 
767  if ( $remember === self::REMEMBER_PRIOR ) {
768  array_push( $this->priorFlags, $this->flags );
769  }
770 
771  $this->flags |= $flag;
772  }
773 
774  public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
775  if ( $flag & ~static::$DBO_MUTABLE ) {
776  throw new DBUnexpectedError(
777  $this,
778  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
779  );
780  }
781 
782  if ( $remember === self::REMEMBER_PRIOR ) {
783  array_push( $this->priorFlags, $this->flags );
784  }
785 
786  $this->flags &= ~$flag;
787  }
788 
789  public function restoreFlags( $state = self::RESTORE_PRIOR ) {
790  if ( !$this->priorFlags ) {
791  return;
792  }
793 
794  if ( $state === self::RESTORE_INITIAL ) {
795  $this->flags = reset( $this->priorFlags );
796  $this->priorFlags = [];
797  } else {
798  $this->flags = array_pop( $this->priorFlags );
799  }
800  }
801 
802  public function getFlag( $flag ) {
803  return ( ( $this->flags & $flag ) === $flag );
804  }
805 
806  public function getDomainID() {
807  return $this->currentDomain->getId();
808  }
809 
817  abstract function indexInfo( $table, $index, $fname = __METHOD__ );
818 
825  abstract function strencode( $s );
826 
830  protected function installErrorHandler() {
831  $this->lastPhpError = false;
832  $this->htmlErrors = ini_set( 'html_errors', '0' );
833  set_error_handler( [ $this, 'connectionErrorLogger' ] );
834  }
835 
841  protected function restoreErrorHandler() {
842  restore_error_handler();
843  if ( $this->htmlErrors !== false ) {
844  ini_set( 'html_errors', $this->htmlErrors );
845  }
846 
847  return $this->getLastPHPError();
848  }
849 
853  protected function getLastPHPError() {
854  if ( $this->lastPhpError ) {
855  $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
856  $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
857 
858  return $error;
859  }
860 
861  return false;
862  }
863 
871  public function connectionErrorLogger( $errno, $errstr ) {
872  $this->lastPhpError = $errstr;
873  }
874 
881  protected function getLogContext( array $extras = [] ) {
882  return array_merge(
883  [
884  'db_server' => $this->server,
885  'db_name' => $this->getDBname(),
886  'db_user' => $this->user,
887  ],
888  $extras
889  );
890  }
891 
892  final public function close( $fname = __METHOD__, $owner = null ) {
893  $error = null; // error to throw after disconnecting
894 
895  $wasOpen = (bool)$this->conn;
896  // This should mostly do nothing if the connection is already closed
897  if ( $this->conn ) {
898  // Roll back any dangling transaction first
899  if ( $this->trxLevel() ) {
900  if ( $this->trxAtomicLevels ) {
901  // Cannot let incomplete atomic sections be committed
902  $levels = $this->flatAtomicSectionList();
903  $error = "$fname: atomic sections $levels are still open";
904  } elseif ( $this->trxAutomatic ) {
905  // Only the connection manager can commit non-empty DBO_TRX transactions
906  // (empty ones we can silently roll back)
907  if ( $this->writesOrCallbacksPending() ) {
908  $error = "$fname: " .
909  "expected mass rollback of all peer transactions (DBO_TRX set)";
910  }
911  } else {
912  // Manual transactions should have been committed or rolled
913  // back, even if empty.
914  $error = "$fname: transaction is still open (from {$this->trxFname})";
915  }
916 
917  if ( $this->trxEndCallbacksSuppressed && $error === null ) {
918  $error = "$fname: callbacks are suppressed; cannot properly commit";
919  }
920 
921  // Rollback the changes and run any callbacks as needed
922  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
923  }
924 
925  // Close the actual connection in the binding handle
926  $closed = $this->closeConnection();
927  } else {
928  $closed = true; // already closed; nothing to do
929  }
930 
931  $this->conn = null;
932 
933  // Log or throw any unexpected errors after having disconnected
934  if ( $error !== null ) {
935  // T217819, T231443: if this is probably just LoadBalancer trying to recover from
936  // errors and shutdown, then log any problems and move on since the request has to
937  // end one way or another. Throwing errors is not very useful at some point.
938  if ( $this->ownerId !== null && $owner === $this->ownerId ) {
939  $this->queryLogger->error( $error );
940  } else {
941  throw new DBUnexpectedError( $this, $error );
942  }
943  }
944 
945  // Note that various subclasses call close() at the start of open(), which itself is
946  // called by replaceLostConnection(). In that case, just because onTransactionResolution()
947  // callbacks are pending does not mean that an exception should be thrown. Rather, they
948  // will be executed after the reconnection step.
949  if ( $wasOpen ) {
950  // Sanity check that no callbacks are dangling
951  $fnames = $this->pendingWriteAndCallbackCallers();
952  if ( $fnames ) {
953  throw new RuntimeException(
954  "Transaction callbacks are still pending: " . implode( ', ', $fnames )
955  );
956  }
957  }
958 
959  return $closed;
960  }
961 
970  final protected function assertHasConnectionHandle() {
971  if ( !$this->isOpen() ) {
972  throw new DBUnexpectedError( $this, "DB connection was already closed" );
973  }
974  }
975 
981  protected function assertIsWritableMaster() {
982  $info = $this->getReadOnlyReason();
983  if ( $info ) {
984  list( $reason, $source ) = $info;
985  if ( $source === 'role' ) {
986  throw new DBReadOnlyRoleError( $this, "Database is read-only: $reason" );
987  } else {
988  throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
989  }
990  }
991  }
992 
998  abstract protected function closeConnection();
999 
1029  abstract protected function doQuery( $sql );
1030 
1047  protected function isWriteQuery( $sql ) {
1048  // BEGIN and COMMIT queries are considered read queries here.
1049  // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1050  // treat these as write queries, in that their results have "affected rows"
1051  // as meta data as from writes, instead of "num rows" as from reads.
1052  // But, we treat them as read queries because when reading data (from
1053  // either replica or master) we use transactions to enable repeatable-read
1054  // snapshots, which ensures we get consistent results from the same snapshot
1055  // for all queries within a request. Use cases:
1056  // - Treating these as writes would trigger ChronologyProtector (see method doc).
1057  // - We use this method to reject writes to replicas, but we need to allow
1058  // use of transactions on replicas for read snapshots. This is fine given
1059  // that transactions by themselves don't make changes, only actual writes
1060  // within the transaction matter, which we still detect.
1061  return !preg_match(
1062  '/^\s*(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1063  $sql
1064  );
1065  }
1066 
1071  protected function getQueryVerb( $sql ) {
1072  return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
1073  }
1074 
1088  protected function isTransactableQuery( $sql ) {
1089  return !in_array(
1090  $this->getQueryVerb( $sql ),
1091  [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1092  true
1093  );
1094  }
1095 
1104  protected function getTempWrites( $sql, $pseudoPermanent ) {
1105  static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1106 
1107  if ( preg_match(
1108  '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1109  $sql,
1110  $matches
1111  ) ) {
1112  $type = $pseudoPermanent ? self::$TEMP_PSEUDO_PERMANENT : self::$TEMP_NORMAL;
1113 
1114  return [ $type, $matches[1], null ];
1115  } elseif ( preg_match(
1116  '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1117  $sql,
1118  $matches
1119  ) ) {
1120  return [ $this->sessionTempTables[$matches[1]] ?? null, null, $matches[1] ];
1121  } elseif ( preg_match(
1122  '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1123  $sql,
1124  $matches
1125  ) ) {
1126  return [ $this->sessionTempTables[$matches[1]] ?? null, null, null ];
1127  } elseif ( preg_match(
1128  '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1129  $sql,
1130  $matches
1131  ) ) {
1132  return [ $this->sessionTempTables[$matches[1]] ?? null, null, null ];
1133  }
1134 
1135  return [ null, null, null ];
1136  }
1137 
1144  protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1145  if ( $ret !== false ) {
1146  if ( $tmpNew !== null ) {
1147  $this->sessionTempTables[$tmpNew] = $tmpType;
1148  }
1149  if ( $tmpDel !== null ) {
1150  unset( $this->sessionTempTables[$tmpDel] );
1151  }
1152  }
1153  }
1154 
1155  public function query( $sql, $fname = __METHOD__, $flags = 0 ) {
1156  $flags = (int)$flags; // b/c; this field used to be a bool
1157  // Sanity check that the SQL query is appropriate in the current context and is
1158  // allowed for an outside caller (e.g. does not break transaction/session tracking).
1159  $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1160 
1161  // Send the query to the server and fetch any corresponding errors
1162  list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1163  if ( $ret === false ) {
1164  $ignoreErrors = $this->fieldHasBit( $flags, self::QUERY_SILENCE_ERRORS );
1165  // Throw an error unless both the ignore flag was set and a rollback is not needed
1166  $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1167  }
1168 
1169  return $this->resultObject( $ret );
1170  }
1171 
1192  final protected function executeQuery( $sql, $fname, $flags ) {
1193  $this->assertHasConnectionHandle();
1194 
1195  $priorTransaction = $this->trxLevel();
1196 
1197  if ( $this->isWriteQuery( $sql ) ) {
1198  // In theory, non-persistent writes are allowed in read-only mode, but due to things
1199  // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1200  $this->assertIsWritableMaster();
1201  // Do not treat temporary table writes as "meaningful writes" since they are only
1202  // visible to one session and are not permanent. Profile them as reads. Integration
1203  // tests can override this behavior via $flags.
1204  $pseudoPermanent = $this->fieldHasBit( $flags, self::QUERY_PSEUDO_PERMANENT );
1205  list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1206  $isPermWrite = ( $tmpType !== self::$TEMP_NORMAL );
1207  // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1208  if ( $isPermWrite && $this->fieldHasBit( $flags, self::QUERY_REPLICA_ROLE ) ) {
1209  throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1210  }
1211  } else {
1212  // No permanent writes in this query
1213  $isPermWrite = false;
1214  // No temporary tables written to either
1215  list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1216  }
1217 
1218  // Add trace comment to the begin of the sql string, right after the operator.
1219  // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1220  $encAgent = str_replace( '/', '-', $this->agent );
1221  $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1222 
1223  // Send the query to the server and fetch any corresponding errors.
1224  // This also doubles as a "ping" to see if the connection was dropped.
1225  list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1226  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1227 
1228  // Check if the query failed due to a recoverable connection loss
1229  $allowRetry = !$this->fieldHasBit( $flags, self::QUERY_NO_RETRY );
1230  if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1231  // Silently resend the query to the server since it is safe and possible
1232  list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1233  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1234  }
1235 
1236  // Register creation and dropping of temporary tables
1237  $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1238 
1239  $corruptedTrx = false;
1240 
1241  if ( $ret === false ) {
1242  if ( $priorTransaction ) {
1243  if ( $recoverableSR ) {
1244  # We're ignoring an error that caused just the current query to be aborted.
1245  # But log the cause so we can log a deprecation notice if a caller actually
1246  # does ignore it.
1247  $this->trxStatusIgnoredCause = [ $err, $errno, $fname ];
1248  } elseif ( !$recoverableCL ) {
1249  # Either the query was aborted or all queries after BEGIN where aborted.
1250  # In the first case, the only options going forward are (a) ROLLBACK, or
1251  # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1252  # option is ROLLBACK, since the snapshots would have been released.
1253  $corruptedTrx = true; // cannot recover
1254  $this->trxStatus = self::STATUS_TRX_ERROR;
1255  $this->trxStatusCause = $this->getQueryException( $err, $errno, $sql, $fname );
1256  $this->trxStatusIgnoredCause = null;
1257  }
1258  }
1259  }
1260 
1261  return [ $ret, $err, $errno, $corruptedTrx ];
1262  }
1263 
1282  private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1283  $priorWritesPending = $this->writesOrCallbacksPending();
1284 
1285  if ( ( $flags & self::QUERY_IGNORE_DBO_TRX ) == 0 ) {
1286  $this->beginIfImplied( $sql, $fname );
1287  }
1288 
1289  // Keep track of whether the transaction has write queries pending
1290  if ( $isPermWrite ) {
1291  $this->lastWriteTime = microtime( true );
1292  if ( $this->trxLevel() && !$this->trxDoneWrites ) {
1293  $this->trxDoneWrites = true;
1294  $this->trxProfiler->transactionWritingIn(
1295  $this->server, $this->getDomainID(), $this->trxShortId );
1296  }
1297  }
1298 
1299  $prefix = $this->topologyRole ? 'query-m: ' : 'query: ';
1300  $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId, $prefix );
1301 
1302  $startTime = microtime( true );
1303  $ps = $this->profiler
1304  ? ( $this->profiler )( $generalizedSql->stringify() )
1305  : null;
1306  $this->affectedRowCount = null;
1307  $this->lastQuery = $sql;
1308  $ret = $this->doQuery( $commentedSql );
1309  $lastError = $this->lastError();
1310  $lastErrno = $this->lastErrno();
1311 
1312  $this->affectedRowCount = $this->affectedRows();
1313  unset( $ps ); // profile out (if set)
1314  $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1315 
1316  $recoverableSR = false; // recoverable statement rollback?
1317  $recoverableCL = false; // recoverable connection loss?
1318  $reconnected = false; // reconnection both attempted and succeeded?
1319 
1320  if ( $ret !== false ) {
1321  $this->lastPing = $startTime;
1322  if ( $isPermWrite && $this->trxLevel() ) {
1323  $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1324  $this->trxWriteCallers[] = $fname;
1325  }
1326  } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1327  # Check if no meaningful session state was lost
1328  $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1329  # Update session state tracking and try to restore the connection
1330  $reconnected = $this->replaceLostConnection( __METHOD__ );
1331  } else {
1332  # Check if only the last query was rolled back
1333  $recoverableSR = $this->wasKnownStatementRollbackError();
1334  }
1335 
1336  if ( $sql === self::$PING_QUERY ) {
1337  $this->lastRoundTripEstimate = $queryRuntime;
1338  }
1339 
1340  $this->trxProfiler->recordQueryCompletion(
1341  $generalizedSql,
1342  $startTime,
1343  $isPermWrite,
1344  $isPermWrite ? $this->affectedRows() : $this->numRows( $ret )
1345  );
1346 
1347  // Avoid the overhead of logging calls unless debug mode is enabled
1348  if ( $this->getFlag( self::DBO_DEBUG ) ) {
1349  $this->queryLogger->debug(
1350  "{method} [{runtime}s] {db_host}: {sql}",
1351  [
1352  'method' => $fname,
1353  'db_host' => $this->getServer(),
1354  'sql' => $sql,
1355  'domain' => $this->getDomainID(),
1356  'runtime' => round( $queryRuntime, 3 )
1357  ]
1358  );
1359  }
1360 
1361  return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1362  }
1363 
1370  private function beginIfImplied( $sql, $fname ) {
1371  if (
1372  !$this->trxLevel() &&
1373  $this->getFlag( self::DBO_TRX ) &&
1374  $this->isTransactableQuery( $sql )
1375  ) {
1376  $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1377  $this->trxAutomatic = true;
1378  }
1379  }
1380 
1393  private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1394  // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1395  $indicativeOfReplicaRuntime = true;
1396  if ( $runtime > self::$SLOW_WRITE_SEC ) {
1397  $verb = $this->getQueryVerb( $sql );
1398  // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1399  if ( $verb === 'INSERT' ) {
1400  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS;
1401  } elseif ( $verb === 'REPLACE' ) {
1402  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS / 2;
1403  }
1404  }
1405 
1406  $this->trxWriteDuration += $runtime;
1407  $this->trxWriteQueryCount += 1;
1408  $this->trxWriteAffectedRows += $affected;
1409  if ( $indicativeOfReplicaRuntime ) {
1410  $this->trxWriteAdjDuration += $runtime;
1411  $this->trxWriteAdjQueryCount += 1;
1412  }
1413  }
1414 
1422  private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1423  $verb = $this->getQueryVerb( $sql );
1424  if ( $verb === 'USE' ) {
1425  throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1426  }
1427 
1428  if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1429  return;
1430  }
1431 
1432  if ( $this->trxStatus < self::STATUS_TRX_OK ) {
1433  throw new DBTransactionStateError(
1434  $this,
1435  "Cannot execute query from $fname while transaction status is ERROR",
1436  [],
1437  $this->trxStatusCause
1438  );
1439  } elseif ( $this->trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1440  list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause;
1441  call_user_func( $this->deprecationLogger,
1442  "Caller from $fname ignored an error originally raised from $iFname: " .
1443  "[$iLastErrno] $iLastError"
1444  );
1445  $this->trxStatusIgnoredCause = null;
1446  }
1447  }
1448 
1449  public function assertNoOpenTransactions() {
1450  if ( $this->explicitTrxActive() ) {
1451  throw new DBTransactionError(
1452  $this,
1453  "Explicit transaction still active. A caller may have caught an error. "
1454  . "Open transactions: " . $this->flatAtomicSectionList()
1455  );
1456  }
1457  }
1458 
1468  private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1469  # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1470  # Dropped connections also mean that named locks are automatically released.
1471  # Only allow error suppression in autocommit mode or when the lost transaction
1472  # didn't matter anyway (aside from DBO_TRX snapshot loss).
1473  if ( $this->sessionNamedLocks ) {
1474  return false; // possible critical section violation
1475  } elseif ( $this->sessionTempTables ) {
1476  return false; // tables might be queried latter
1477  } elseif ( $sql === 'COMMIT' ) {
1478  return !$priorWritesPending; // nothing written anyway? (T127428)
1479  } elseif ( $sql === 'ROLLBACK' ) {
1480  return true; // transaction lost...which is also what was requested :)
1481  } elseif ( $this->explicitTrxActive() ) {
1482  return false; // don't drop atomicity and explicit snapshots
1483  } elseif ( $priorWritesPending ) {
1484  return false; // prior writes lost from implicit transaction
1485  }
1486 
1487  return true;
1488  }
1489 
1493  private function handleSessionLossPreconnect() {
1494  // Clean up tracking of session-level things...
1495  // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1496  // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1497  $this->sessionTempTables = [];
1498  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1499  // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1500  $this->sessionNamedLocks = [];
1501  // Session loss implies transaction loss
1502  $oldTrxShortId = $this->consumeTrxShortId();
1503  $this->trxAtomicCounter = 0;
1504  $this->trxIdleCallbacks = []; // T67263; transaction already lost
1505  $this->trxPreCommitCallbacks = []; // T67263; transaction already lost
1506  // Clear additional subclass fields
1508  // @note: leave trxRecurringCallbacks in place
1509  if ( $this->trxDoneWrites ) {
1510  $this->trxProfiler->transactionWritingOut(
1511  $this->server,
1512  $this->getDomainID(),
1513  $oldTrxShortId,
1514  $this->pendingWriteQueryDuration( self::ESTIMATE_TOTAL ),
1515  $this->trxWriteAffectedRows
1516  );
1517  }
1518  }
1519 
1523  protected function doHandleSessionLossPreconnect() {
1524  // no-op
1525  }
1526 
1530  private function handleSessionLossPostconnect() {
1531  try {
1532  // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1533  // If callback suppression is set then the array will remain unhandled.
1534  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1535  } catch ( Exception $ex ) {
1536  // Already logged; move on...
1537  }
1538  try {
1539  // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1540  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1541  } catch ( Exception $ex ) {
1542  // Already logged; move on...
1543  }
1544  }
1545 
1551  private function consumeTrxShortId() {
1552  $old = $this->trxShortId;
1553  $this->trxShortId = '';
1554 
1555  return $old;
1556  }
1557 
1568  protected function wasQueryTimeout( $error, $errno ) {
1569  return false;
1570  }
1571 
1583  public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1584  if ( $ignore ) {
1585  $this->queryLogger->debug( "SQL ERROR (ignored): $error" );
1586  } else {
1587  throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1588  }
1589  }
1590 
1598  private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1599  $this->queryLogger->error(
1600  "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1601  $this->getLogContext( [
1602  'method' => __METHOD__,
1603  'errno' => $errno,
1604  'error' => $error,
1605  'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1606  'fname' => $fname,
1607  'exception' => new RuntimeException()
1608  ] )
1609  );
1610  return $this->getQueryException( $error, $errno, $sql, $fname );
1611  }
1612 
1620  private function getQueryException( $error, $errno, $sql, $fname ) {
1621  if ( $this->wasQueryTimeout( $error, $errno ) ) {
1622  return new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1623  } elseif ( $this->wasConnectionError( $errno ) ) {
1624  return new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1625  } else {
1626  return new DBQueryError( $this, $error, $errno, $sql, $fname );
1627  }
1628  }
1629 
1634  final protected function newExceptionAfterConnectError( $error ) {
1635  // Connection was not fully initialized and is not safe for use
1636  $this->conn = null;
1637 
1638  $this->connLogger->error(
1639  "Error connecting to {db_server} as user {db_user}: {error}",
1640  $this->getLogContext( [
1641  'error' => $error,
1642  'exception' => new RuntimeException()
1643  ] )
1644  );
1645 
1646  return new DBConnectionError( $this, $error );
1647  }
1648 
1649  public function freeResult( $res ) {
1650  }
1651 
1652  public function selectField(
1653  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1654  ) {
1655  if ( $var === '*' ) { // sanity
1656  throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1657  }
1658 
1659  if ( !is_array( $options ) ) {
1660  $options = [ $options ];
1661  }
1662 
1663  $options['LIMIT'] = 1;
1664 
1665  $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1666  if ( $res === false ) {
1667  throw new DBUnexpectedError( $this, "Got false from select()" );
1668  }
1669 
1670  $row = $this->fetchRow( $res );
1671  if ( $row === false ) {
1672  return false;
1673  }
1674 
1675  return reset( $row );
1676  }
1677 
1678  public function selectFieldValues(
1679  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1680  ) {
1681  if ( $var === '*' ) { // sanity
1682  throw new DBUnexpectedError( $this, "Cannot use a * field" );
1683  } elseif ( !is_string( $var ) ) { // sanity
1684  throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1685  }
1686 
1687  if ( !is_array( $options ) ) {
1688  $options = [ $options ];
1689  }
1690 
1691  $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1692  if ( $res === false ) {
1693  throw new DBUnexpectedError( $this, "Got false from select()" );
1694  }
1695 
1696  $values = [];
1697  foreach ( $res as $row ) {
1698  $values[] = $row->value;
1699  }
1700 
1701  return $values;
1702  }
1703 
1714  protected function makeSelectOptions( array $options ) {
1715  $preLimitTail = $postLimitTail = '';
1716  $startOpts = '';
1717 
1718  $noKeyOptions = [];
1719 
1720  foreach ( $options as $key => $option ) {
1721  if ( is_numeric( $key ) ) {
1722  $noKeyOptions[$option] = true;
1723  }
1724  }
1725 
1726  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1727 
1728  $preLimitTail .= $this->makeOrderBy( $options );
1729 
1730  if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1731  $postLimitTail .= ' FOR UPDATE';
1732  }
1733 
1734  if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1735  $postLimitTail .= ' LOCK IN SHARE MODE';
1736  }
1737 
1738  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1739  $startOpts .= 'DISTINCT';
1740  }
1741 
1742  # Various MySQL extensions
1743  if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1744  $startOpts .= ' /*! STRAIGHT_JOIN */';
1745  }
1746 
1747  if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1748  $startOpts .= ' SQL_BIG_RESULT';
1749  }
1750 
1751  if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1752  $startOpts .= ' SQL_BUFFER_RESULT';
1753  }
1754 
1755  if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1756  $startOpts .= ' SQL_SMALL_RESULT';
1757  }
1758 
1759  if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1760  $startOpts .= ' SQL_CALC_FOUND_ROWS';
1761  }
1762 
1763  if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1764  $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1765  } else {
1766  $useIndex = '';
1767  }
1768  if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1769  $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1770  } else {
1771  $ignoreIndex = '';
1772  }
1773 
1774  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1775  }
1776 
1785  protected function makeGroupByWithHaving( $options ) {
1786  $sql = '';
1787  if ( isset( $options['GROUP BY'] ) ) {
1788  $gb = is_array( $options['GROUP BY'] )
1789  ? implode( ',', $options['GROUP BY'] )
1790  : $options['GROUP BY'];
1791  $sql .= ' GROUP BY ' . $gb;
1792  }
1793  if ( isset( $options['HAVING'] ) ) {
1794  $having = is_array( $options['HAVING'] )
1795  ? $this->makeList( $options['HAVING'], self::LIST_AND )
1796  : $options['HAVING'];
1797  $sql .= ' HAVING ' . $having;
1798  }
1799 
1800  return $sql;
1801  }
1802 
1811  protected function makeOrderBy( $options ) {
1812  if ( isset( $options['ORDER BY'] ) ) {
1813  $ob = is_array( $options['ORDER BY'] )
1814  ? implode( ',', $options['ORDER BY'] )
1815  : $options['ORDER BY'];
1816 
1817  return ' ORDER BY ' . $ob;
1818  }
1819 
1820  return '';
1821  }
1822 
1823  public function select(
1824  $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1825  ) {
1826  $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1827 
1828  return $this->query( $sql, $fname );
1829  }
1830 
1831  public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1832  $options = [], $join_conds = []
1833  ) {
1834  if ( is_array( $vars ) ) {
1835  $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1836  } else {
1837  $fields = $vars;
1838  }
1839 
1840  $options = (array)$options;
1841  $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1842  ? $options['USE INDEX']
1843  : [];
1844  $ignoreIndexes = (
1845  isset( $options['IGNORE INDEX'] ) &&
1846  is_array( $options['IGNORE INDEX'] )
1847  )
1848  ? $options['IGNORE INDEX']
1849  : [];
1850 
1851  if (
1852  $this->selectOptionsIncludeLocking( $options ) &&
1853  $this->selectFieldsOrOptionsAggregate( $vars, $options )
1854  ) {
1855  // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
1856  // functions. Discourage use of such queries to encourage compatibility.
1857  call_user_func(
1858  $this->deprecationLogger,
1859  __METHOD__ . ": aggregation used with a locking SELECT ($fname)"
1860  );
1861  }
1862 
1863  if ( is_array( $table ) ) {
1864  $from = ' FROM ' .
1866  $table, $useIndexes, $ignoreIndexes, $join_conds );
1867  } elseif ( $table != '' ) {
1868  $from = ' FROM ' .
1870  [ $table ], $useIndexes, $ignoreIndexes, [] );
1871  } else {
1872  $from = '';
1873  }
1874 
1875  list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1876  $this->makeSelectOptions( $options );
1877 
1878  if ( is_array( $conds ) ) {
1879  $conds = $this->makeList( $conds, self::LIST_AND );
1880  }
1881 
1882  if ( $conds === null || $conds === false ) {
1883  $this->queryLogger->warning(
1884  __METHOD__
1885  . ' called from '
1886  . $fname
1887  . ' with incorrect parameters: $conds must be a string or an array'
1888  );
1889  $conds = '';
1890  }
1891 
1892  if ( $conds === '' || $conds === '*' ) {
1893  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1894  } elseif ( is_string( $conds ) ) {
1895  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1896  "WHERE $conds $preLimitTail";
1897  } else {
1898  throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1899  }
1900 
1901  if ( isset( $options['LIMIT'] ) ) {
1902  $sql = $this->limitResult( $sql, $options['LIMIT'],
1903  $options['OFFSET'] ?? false );
1904  }
1905  $sql = "$sql $postLimitTail";
1906 
1907  if ( isset( $options['EXPLAIN'] ) ) {
1908  $sql = 'EXPLAIN ' . $sql;
1909  }
1910 
1911  return $sql;
1912  }
1913 
1914  public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1915  $options = [], $join_conds = []
1916  ) {
1917  $options = (array)$options;
1918  $options['LIMIT'] = 1;
1919 
1920  $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1921  if ( $res === false ) {
1922  throw new DBUnexpectedError( $this, "Got false from select()" );
1923  }
1924 
1925  if ( !$this->numRows( $res ) ) {
1926  return false;
1927  }
1928 
1929  return $this->fetchObject( $res );
1930  }
1931 
1932  public function estimateRowCount(
1933  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1934  ) {
1935  $conds = $this->normalizeConditions( $conds, $fname );
1936  $column = $this->extractSingleFieldFromList( $var );
1937  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1938  $conds[] = "$column IS NOT NULL";
1939  }
1940 
1941  $res = $this->select(
1942  $tables, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1943  );
1944  $row = $res ? $this->fetchRow( $res ) : [];
1945 
1946  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1947  }
1948 
1949  public function selectRowCount(
1950  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1951  ) {
1952  $conds = $this->normalizeConditions( $conds, $fname );
1953  $column = $this->extractSingleFieldFromList( $var );
1954  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1955  $conds[] = "$column IS NOT NULL";
1956  }
1957 
1958  $res = $this->select(
1959  [
1960  'tmp_count' => $this->buildSelectSubquery(
1961  $tables,
1962  '1',
1963  $conds,
1964  $fname,
1965  $options,
1966  $join_conds
1967  )
1968  ],
1969  [ 'rowcount' => 'COUNT(*)' ],
1970  [],
1971  $fname
1972  );
1973  $row = $res ? $this->fetchRow( $res ) : [];
1974 
1975  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1976  }
1977 
1982  private function selectOptionsIncludeLocking( $options ) {
1983  $options = (array)$options;
1984  foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1985  if ( in_array( $lock, $options, true ) ) {
1986  return true;
1987  }
1988  }
1989 
1990  return false;
1991  }
1992 
1998  private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1999  foreach ( (array)$options as $key => $value ) {
2000  if ( is_string( $key ) ) {
2001  if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
2002  return true;
2003  }
2004  } elseif ( is_string( $value ) ) {
2005  if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
2006  return true;
2007  }
2008  }
2009  }
2010 
2011  $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
2012  foreach ( (array)$fields as $field ) {
2013  if ( is_string( $field ) && preg_match( $regex, $field ) ) {
2014  return true;
2015  }
2016  }
2017 
2018  return false;
2019  }
2020 
2026  final protected function normalizeConditions( $conds, $fname ) {
2027  if ( $conds === null || $conds === false ) {
2028  $this->queryLogger->warning(
2029  __METHOD__
2030  . ' called from '
2031  . $fname
2032  . ' with incorrect parameters: $conds must be a string or an array'
2033  );
2034  $conds = '';
2035  }
2036 
2037  if ( !is_array( $conds ) ) {
2038  $conds = ( $conds === '' ) ? [] : [ $conds ];
2039  }
2040 
2041  return $conds;
2042  }
2043 
2049  final protected function extractSingleFieldFromList( $var ) {
2050  if ( is_array( $var ) ) {
2051  if ( !$var ) {
2052  $column = null;
2053  } elseif ( count( $var ) == 1 ) {
2054  $column = $var[0] ?? reset( $var );
2055  } else {
2056  throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns' );
2057  }
2058  } else {
2059  $column = $var;
2060  }
2061 
2062  return $column;
2063  }
2064 
2065  public function lockForUpdate(
2066  $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2067  ) {
2068  if ( !$this->trxLevel() && !$this->getFlag( self::DBO_TRX ) ) {
2069  throw new DBUnexpectedError(
2070  $this,
2071  __METHOD__ . ': no transaction is active nor is DBO_TRX set'
2072  );
2073  }
2074 
2075  $options = (array)$options;
2076  $options[] = 'FOR UPDATE';
2077 
2078  return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2079  }
2080 
2081  public function fieldExists( $table, $field, $fname = __METHOD__ ) {
2082  $info = $this->fieldInfo( $table, $field );
2083 
2084  return (bool)$info;
2085  }
2086 
2087  public function indexExists( $table, $index, $fname = __METHOD__ ) {
2088  if ( !$this->tableExists( $table ) ) {
2089  return null;
2090  }
2091 
2092  $info = $this->indexInfo( $table, $index, $fname );
2093  if ( $info === null ) {
2094  return null;
2095  } else {
2096  return $info !== false;
2097  }
2098  }
2099 
2100  abstract public function tableExists( $table, $fname = __METHOD__ );
2101 
2102  public function indexUnique( $table, $index ) {
2103  $indexInfo = $this->indexInfo( $table, $index );
2104 
2105  if ( !$indexInfo ) {
2106  return null;
2107  }
2108 
2109  return !$indexInfo[0]->Non_unique;
2110  }
2111 
2118  protected function makeInsertOptions( $options ) {
2119  return implode( ' ', $options );
2120  }
2121 
2126  final protected function isMultiRowArray( array $a ) {
2127  return ( isset( $a[0] ) && is_array( $a[0] ) );
2128  }
2129 
2130  public function insert( $table, $rows, $fname = __METHOD__, $options = [] ) {
2131  # No rows to insert, easy just return now
2132  if ( !count( $rows ) ) {
2133  return true;
2134  }
2135 
2136  $table = $this->tableName( $table );
2137 
2138  if ( !is_array( $options ) ) {
2139  $options = [ $options ];
2140  }
2141 
2142  $options = $this->makeInsertOptions( $options );
2143 
2144  $multi = $this->isMultiRowArray( $rows );
2145  if ( $multi ) {
2146  $multi = true;
2147  $keys = array_keys( $rows[0] );
2148  } else {
2149  $multi = false;
2150  $keys = array_keys( $rows );
2151  }
2152 
2153  $sql = 'INSERT ' . $options .
2154  " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2155 
2156  if ( $multi ) {
2157  $first = true;
2158  foreach ( $rows as $row ) {
2159  if ( $first ) {
2160  $first = false;
2161  } else {
2162  $sql .= ',';
2163  }
2164  $sql .= '(' . $this->makeList( $row ) . ')';
2165  }
2166  } else {
2167  $sql .= '(' . $this->makeList( $rows ) . ')';
2168  }
2169 
2170  $this->query( $sql, $fname );
2171 
2172  return true;
2173  }
2174 
2181  protected function makeUpdateOptionsArray( $options ) {
2182  if ( !is_array( $options ) ) {
2183  $options = [ $options ];
2184  }
2185 
2186  $opts = [];
2187 
2188  if ( in_array( 'IGNORE', $options ) ) {
2189  $opts[] = 'IGNORE';
2190  }
2191 
2192  return $opts;
2193  }
2194 
2201  protected function makeUpdateOptions( $options ) {
2202  $opts = $this->makeUpdateOptionsArray( $options );
2203 
2204  return implode( ' ', $opts );
2205  }
2206 
2207  public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
2208  $table = $this->tableName( $table );
2209  $opts = $this->makeUpdateOptions( $options );
2210  $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
2211 
2212  // @phan-suppress-next-line PhanTypeComparisonFromArray
2213  if ( $conds !== [] && $conds !== '*' ) {
2214  $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
2215  }
2216 
2217  $this->query( $sql, $fname );
2218 
2219  return true;
2220  }
2221 
2222  public function makeList( array $a, $mode = self::LIST_COMMA ) {
2223  $first = true;
2224  $list = '';
2225 
2226  foreach ( $a as $field => $value ) {
2227  if ( !$first ) {
2228  if ( $mode == self::LIST_AND ) {
2229  $list .= ' AND ';
2230  } elseif ( $mode == self::LIST_OR ) {
2231  $list .= ' OR ';
2232  } else {
2233  $list .= ',';
2234  }
2235  } else {
2236  $first = false;
2237  }
2238 
2239  if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
2240  $list .= "($value)";
2241  } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
2242  $list .= "$value";
2243  } elseif (
2244  ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
2245  ) {
2246  // Remove null from array to be handled separately if found
2247  $includeNull = false;
2248  foreach ( array_keys( $value, null, true ) as $nullKey ) {
2249  $includeNull = true;
2250  unset( $value[$nullKey] );
2251  }
2252  if ( count( $value ) == 0 && !$includeNull ) {
2253  throw new InvalidArgumentException(
2254  __METHOD__ . ": empty input for field $field" );
2255  } elseif ( count( $value ) == 0 ) {
2256  // only check if $field is null
2257  $list .= "$field IS NULL";
2258  } else {
2259  // IN clause contains at least one valid element
2260  if ( $includeNull ) {
2261  // Group subconditions to ensure correct precedence
2262  $list .= '(';
2263  }
2264  if ( count( $value ) == 1 ) {
2265  // Special-case single values, as IN isn't terribly efficient
2266  // Don't necessarily assume the single key is 0; we don't
2267  // enforce linear numeric ordering on other arrays here.
2268  $value = array_values( $value )[0];
2269  $list .= $field . " = " . $this->addQuotes( $value );
2270  } else {
2271  $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2272  }
2273  // if null present in array, append IS NULL
2274  if ( $includeNull ) {
2275  $list .= " OR $field IS NULL)";
2276  }
2277  }
2278  } elseif ( $value === null ) {
2279  if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2280  $list .= "$field IS ";
2281  } elseif ( $mode == self::LIST_SET ) {
2282  $list .= "$field = ";
2283  }
2284  $list .= 'NULL';
2285  } else {
2286  if (
2287  $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2288  ) {
2289  $list .= "$field = ";
2290  }
2291  $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
2292  }
2293  }
2294 
2295  return $list;
2296  }
2297 
2298  public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2299  $conds = [];
2300 
2301  foreach ( $data as $base => $sub ) {
2302  if ( count( $sub ) ) {
2303  $conds[] = $this->makeList(
2304  [ $baseKey => $base, $subKey => array_map( 'strval', array_keys( $sub ) ) ],
2305  self::LIST_AND );
2306  }
2307  }
2308 
2309  if ( $conds ) {
2310  return $this->makeList( $conds, self::LIST_OR );
2311  } else {
2312  // Nothing to search for...
2313  return false;
2314  }
2315  }
2316 
2317  public function aggregateValue( $valuedata, $valuename = 'value' ) {
2318  return $valuename;
2319  }
2320 
2321  public function bitNot( $field ) {
2322  return "(~$field)";
2323  }
2324 
2325  public function bitAnd( $fieldLeft, $fieldRight ) {
2326  return "($fieldLeft & $fieldRight)";
2327  }
2328 
2329  public function bitOr( $fieldLeft, $fieldRight ) {
2330  return "($fieldLeft | $fieldRight)";
2331  }
2332 
2333  public function buildConcat( $stringList ) {
2334  return 'CONCAT(' . implode( ',', $stringList ) . ')';
2335  }
2336 
2337  public function buildGroupConcatField(
2338  $delim, $table, $field, $conds = '', $join_conds = []
2339  ) {
2340  $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2341 
2342  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2343  }
2344 
2345  public function buildSubstring( $input, $startPosition, $length = null ) {
2346  $this->assertBuildSubstringParams( $startPosition, $length );
2347  $functionBody = "$input FROM $startPosition";
2348  if ( $length !== null ) {
2349  $functionBody .= " FOR $length";
2350  }
2351  return 'SUBSTRING(' . $functionBody . ')';
2352  }
2353 
2366  protected function assertBuildSubstringParams( $startPosition, $length ) {
2367  if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2368  throw new InvalidArgumentException(
2369  '$startPosition must be a positive integer'
2370  );
2371  }
2372  if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2373  throw new InvalidArgumentException(
2374  '$length must be null or an integer greater than or equal to 0'
2375  );
2376  }
2377  }
2378 
2379  public function buildStringCast( $field ) {
2380  // In theory this should work for any standards-compliant
2381  // SQL implementation, although it may not be the best way to do it.
2382  return "CAST( $field AS CHARACTER )";
2383  }
2384 
2385  public function buildIntegerCast( $field ) {
2386  return 'CAST( ' . $field . ' AS INTEGER )';
2387  }
2388 
2389  public function buildSelectSubquery(
2390  $table, $vars, $conds = '', $fname = __METHOD__,
2391  $options = [], $join_conds = []
2392  ) {
2393  return new Subquery(
2394  $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2395  );
2396  }
2397 
2398  public function databasesAreIndependent() {
2399  return false;
2400  }
2401 
2402  final public function selectDB( $db ) {
2403  $this->selectDomain( new DatabaseDomain(
2404  $db,
2405  $this->currentDomain->getSchema(),
2406  $this->currentDomain->getTablePrefix()
2407  ) );
2408 
2409  return true;
2410  }
2411 
2412  final public function selectDomain( $domain ) {
2413  $this->doSelectDomain( DatabaseDomain::newFromId( $domain ) );
2414  }
2415 
2422  protected function doSelectDomain( DatabaseDomain $domain ) {
2423  $this->currentDomain = $domain;
2424  }
2425 
2426  public function getDBname() {
2427  return $this->currentDomain->getDatabase();
2428  }
2429 
2430  public function getServer() {
2431  return $this->server;
2432  }
2433 
2434  public function tableName( $name, $format = 'quoted' ) {
2435  if ( $name instanceof Subquery ) {
2436  throw new DBUnexpectedError(
2437  $this,
2438  __METHOD__ . ': got Subquery instance when expecting a string'
2439  );
2440  }
2441 
2442  # Skip the entire process when we have a string quoted on both ends.
2443  # Note that we check the end so that we will still quote any use of
2444  # use of `database`.table. But won't break things if someone wants
2445  # to query a database table with a dot in the name.
2446  if ( $this->isQuotedIdentifier( $name ) ) {
2447  return $name;
2448  }
2449 
2450  # Lets test for any bits of text that should never show up in a table
2451  # name. Basically anything like JOIN or ON which are actually part of
2452  # SQL queries, but may end up inside of the table value to combine
2453  # sql. Such as how the API is doing.
2454  # Note that we use a whitespace test rather than a \b test to avoid
2455  # any remote case where a word like on may be inside of a table name
2456  # surrounded by symbols which may be considered word breaks.
2457  if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2458  $this->queryLogger->warning(
2459  __METHOD__ . ": use of subqueries is not supported this way",
2460  [ 'exception' => new RuntimeException() ]
2461  );
2462 
2463  return $name;
2464  }
2465 
2466  # Split database and table into proper variables.
2467  list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2468 
2469  # Quote $table and apply the prefix if not quoted.
2470  # $tableName might be empty if this is called from Database::replaceVars()
2471  $tableName = "{$prefix}{$table}";
2472  if ( $format === 'quoted'
2473  && !$this->isQuotedIdentifier( $tableName )
2474  && $tableName !== ''
2475  ) {
2476  $tableName = $this->addIdentifierQuotes( $tableName );
2477  }
2478 
2479  # Quote $schema and $database and merge them with the table name if needed
2480  $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2481  $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2482 
2483  return $tableName;
2484  }
2485 
2492  protected function qualifiedTableComponents( $name ) {
2493  # We reverse the explode so that database.table and table both output the correct table.
2494  $dbDetails = explode( '.', $name, 3 );
2495  if ( count( $dbDetails ) == 3 ) {
2496  list( $database, $schema, $table ) = $dbDetails;
2497  # We don't want any prefix added in this case
2498  $prefix = '';
2499  } elseif ( count( $dbDetails ) == 2 ) {
2500  list( $database, $table ) = $dbDetails;
2501  # We don't want any prefix added in this case
2502  $prefix = '';
2503  # In dbs that support it, $database may actually be the schema
2504  # but that doesn't affect any of the functionality here
2505  $schema = '';
2506  } else {
2507  list( $table ) = $dbDetails;
2508  if ( isset( $this->tableAliases[$table] ) ) {
2509  $database = $this->tableAliases[$table]['dbname'];
2510  $schema = is_string( $this->tableAliases[$table]['schema'] )
2511  ? $this->tableAliases[$table]['schema']
2512  : $this->relationSchemaQualifier();
2513  $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2514  ? $this->tableAliases[$table]['prefix']
2515  : $this->tablePrefix();
2516  } else {
2517  $database = '';
2518  $schema = $this->relationSchemaQualifier(); # Default schema
2519  $prefix = $this->tablePrefix(); # Default prefix
2520  }
2521  }
2522 
2523  return [ $database, $schema, $prefix, $table ];
2524  }
2525 
2532  private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2533  if ( strlen( $namespace ) ) {
2534  if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2535  $namespace = $this->addIdentifierQuotes( $namespace );
2536  }
2537  $relation = $namespace . '.' . $relation;
2538  }
2539 
2540  return $relation;
2541  }
2542 
2543  public function tableNames( ...$tables ) {
2544  $retVal = [];
2545 
2546  foreach ( $tables as $name ) {
2547  $retVal[$name] = $this->tableName( $name );
2548  }
2549 
2550  return $retVal;
2551  }
2552 
2553  public function tableNamesN( ...$tables ) {
2554  $retVal = [];
2555 
2556  foreach ( $tables as $name ) {
2557  $retVal[] = $this->tableName( $name );
2558  }
2559 
2560  return $retVal;
2561  }
2562 
2574  protected function tableNameWithAlias( $table, $alias = false ) {
2575  if ( is_string( $table ) ) {
2576  $quotedTable = $this->tableName( $table );
2577  } elseif ( $table instanceof Subquery ) {
2578  $quotedTable = (string)$table;
2579  } else {
2580  throw new InvalidArgumentException( "Table must be a string or Subquery" );
2581  }
2582 
2583  if ( $alias === false || $alias === $table ) {
2584  if ( $table instanceof Subquery ) {
2585  throw new InvalidArgumentException( "Subquery table missing alias" );
2586  }
2587 
2588  return $quotedTable;
2589  } else {
2590  return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2591  }
2592  }
2593 
2600  protected function tableNamesWithAlias( $tables ) {
2601  $retval = [];
2602  foreach ( $tables as $alias => $table ) {
2603  if ( is_numeric( $alias ) ) {
2604  $alias = $table;
2605  }
2606  $retval[] = $this->tableNameWithAlias( $table, $alias );
2607  }
2608 
2609  return $retval;
2610  }
2611 
2620  protected function fieldNameWithAlias( $name, $alias = false ) {
2621  if ( !$alias || (string)$alias === (string)$name ) {
2622  return $name;
2623  } else {
2624  return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2625  }
2626  }
2627 
2634  protected function fieldNamesWithAlias( $fields ) {
2635  $retval = [];
2636  foreach ( $fields as $alias => $field ) {
2637  if ( is_numeric( $alias ) ) {
2638  $alias = $field;
2639  }
2640  $retval[] = $this->fieldNameWithAlias( $field, $alias );
2641  }
2642 
2643  return $retval;
2644  }
2645 
2657  $tables, $use_index = [], $ignore_index = [], $join_conds = []
2658  ) {
2659  $ret = [];
2660  $retJOIN = [];
2661  $use_index = (array)$use_index;
2662  $ignore_index = (array)$ignore_index;
2663  $join_conds = (array)$join_conds;
2664 
2665  foreach ( $tables as $alias => $table ) {
2666  if ( !is_string( $alias ) ) {
2667  // No alias? Set it equal to the table name
2668  $alias = $table;
2669  }
2670 
2671  if ( is_array( $table ) ) {
2672  // A parenthesized group
2673  if ( count( $table ) > 1 ) {
2674  $joinedTable = '(' .
2676  $table, $use_index, $ignore_index, $join_conds ) . ')';
2677  } else {
2678  // Degenerate case
2679  $innerTable = reset( $table );
2680  $innerAlias = key( $table );
2681  $joinedTable = $this->tableNameWithAlias(
2682  $innerTable,
2683  is_string( $innerAlias ) ? $innerAlias : $innerTable
2684  );
2685  }
2686  } else {
2687  $joinedTable = $this->tableNameWithAlias( $table, $alias );
2688  }
2689 
2690  // Is there a JOIN clause for this table?
2691  if ( isset( $join_conds[$alias] ) ) {
2692  list( $joinType, $conds ) = $join_conds[$alias];
2693  $tableClause = $joinType;
2694  $tableClause .= ' ' . $joinedTable;
2695  if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2696  $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2697  if ( $use != '' ) {
2698  $tableClause .= ' ' . $use;
2699  }
2700  }
2701  if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2702  $ignore = $this->ignoreIndexClause(
2703  implode( ',', (array)$ignore_index[$alias] ) );
2704  if ( $ignore != '' ) {
2705  $tableClause .= ' ' . $ignore;
2706  }
2707  }
2708  $on = $this->makeList( (array)$conds, self::LIST_AND );
2709  if ( $on != '' ) {
2710  $tableClause .= ' ON (' . $on . ')';
2711  }
2712 
2713  $retJOIN[] = $tableClause;
2714  } elseif ( isset( $use_index[$alias] ) ) {
2715  // Is there an INDEX clause for this table?
2716  $tableClause = $joinedTable;
2717  $tableClause .= ' ' . $this->useIndexClause(
2718  implode( ',', (array)$use_index[$alias] )
2719  );
2720 
2721  $ret[] = $tableClause;
2722  } elseif ( isset( $ignore_index[$alias] ) ) {
2723  // Is there an INDEX clause for this table?
2724  $tableClause = $joinedTable;
2725  $tableClause .= ' ' . $this->ignoreIndexClause(
2726  implode( ',', (array)$ignore_index[$alias] )
2727  );
2728 
2729  $ret[] = $tableClause;
2730  } else {
2731  $tableClause = $joinedTable;
2732 
2733  $ret[] = $tableClause;
2734  }
2735  }
2736 
2737  // We can't separate explicit JOIN clauses with ',', use ' ' for those
2738  $implicitJoins = implode( ',', $ret );
2739  $explicitJoins = implode( ' ', $retJOIN );
2740 
2741  // Compile our final table clause
2742  return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2743  }
2744 
2751  protected function indexName( $index ) {
2752  return $this->indexAliases[$index] ?? $index;
2753  }
2754 
2755  public function addQuotes( $s ) {
2756  if ( $s instanceof Blob ) {
2757  $s = $s->fetch();
2758  }
2759  if ( $s === null ) {
2760  return 'NULL';
2761  } elseif ( is_bool( $s ) ) {
2762  return (string)(int)$s;
2763  } elseif ( is_int( $s ) ) {
2764  return (string)$s;
2765  } else {
2766  return "'" . $this->strencode( $s ) . "'";
2767  }
2768  }
2769 
2770  public function addIdentifierQuotes( $s ) {
2771  return '"' . str_replace( '"', '""', $s ) . '"';
2772  }
2773 
2783  public function isQuotedIdentifier( $name ) {
2784  return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2785  }
2786 
2792  protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2793  return str_replace( [ $escapeChar, '%', '_' ],
2794  [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2795  $s );
2796  }
2797 
2798  public function buildLike( $param, ...$params ) {
2799  if ( is_array( $param ) ) {
2800  $params = $param;
2801  } else {
2802  $params = func_get_args();
2803  }
2804 
2805  $s = '';
2806 
2807  // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2808  // may escape backslashes, creating problems of double escaping. The `
2809  // character has good cross-DBMS compatibility, avoiding special operators
2810  // in MS SQL like ^ and %
2811  $escapeChar = '`';
2812 
2813  foreach ( $params as $value ) {
2814  if ( $value instanceof LikeMatch ) {
2815  $s .= $value->toString();
2816  } else {
2817  $s .= $this->escapeLikeInternal( $value, $escapeChar );
2818  }
2819  }
2820 
2821  return ' LIKE ' .
2822  $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2823  }
2824 
2825  public function anyChar() {
2826  return new LikeMatch( '_' );
2827  }
2828 
2829  public function anyString() {
2830  return new LikeMatch( '%' );
2831  }
2832 
2833  public function nextSequenceValue( $seqName ) {
2834  return null;
2835  }
2836 
2847  public function useIndexClause( $index ) {
2848  return '';
2849  }
2850 
2861  public function ignoreIndexClause( $index ) {
2862  return '';
2863  }
2864 
2865  public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2866  if ( count( $rows ) == 0 ) {
2867  return;
2868  }
2869 
2870  $uniqueIndexes = (array)$uniqueIndexes;
2871  // Single row case
2872  if ( !is_array( reset( $rows ) ) ) {
2873  $rows = [ $rows ];
2874  }
2875 
2876  try {
2877  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2878  $affectedRowCount = 0;
2879  foreach ( $rows as $row ) {
2880  // Delete rows which collide with this one
2881  $indexWhereClauses = [];
2882  foreach ( $uniqueIndexes as $index ) {
2883  $indexColumns = (array)$index;
2884  $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2885  if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2886  throw new DBUnexpectedError(
2887  $this,
2888  'New record does not provide all values for unique key (' .
2889  implode( ', ', $indexColumns ) . ')'
2890  );
2891  } elseif ( in_array( null, $indexRowValues, true ) ) {
2892  throw new DBUnexpectedError(
2893  $this,
2894  'New record has a null value for unique key (' .
2895  implode( ', ', $indexColumns ) . ')'
2896  );
2897  }
2898  $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND );
2899  }
2900 
2901  if ( $indexWhereClauses ) {
2902  $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR ), $fname );
2903  $affectedRowCount += $this->affectedRows();
2904  }
2905 
2906  // Now insert the row
2907  $this->insert( $table, $row, $fname );
2908  $affectedRowCount += $this->affectedRows();
2909  }
2910  $this->endAtomic( $fname );
2911  $this->affectedRowCount = $affectedRowCount;
2912  } catch ( Exception $e ) {
2913  $this->cancelAtomic( $fname );
2914  throw $e;
2915  }
2916  }
2917 
2926  protected function nativeReplace( $table, $rows, $fname ) {
2927  $table = $this->tableName( $table );
2928 
2929  # Single row case
2930  if ( !is_array( reset( $rows ) ) ) {
2931  $rows = [ $rows ];
2932  }
2933 
2934  $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2935  $first = true;
2936 
2937  foreach ( $rows as $row ) {
2938  if ( $first ) {
2939  $first = false;
2940  } else {
2941  $sql .= ',';
2942  }
2943 
2944  $sql .= '(' . $this->makeList( $row ) . ')';
2945  }
2946 
2947  $this->query( $sql, $fname );
2948  }
2949 
2950  public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2951  $fname = __METHOD__
2952  ) {
2953  if ( $rows === [] ) {
2954  return true; // nothing to do
2955  }
2956 
2957  $uniqueIndexes = (array)$uniqueIndexes;
2958  if ( !is_array( reset( $rows ) ) ) {
2959  $rows = [ $rows ];
2960  }
2961  '@phan-var array[] $rows';
2962 
2963  if ( count( $uniqueIndexes ) ) {
2964  $clauses = []; // list WHERE clauses that each identify a single row
2965  foreach ( $rows as $row ) {
2966  foreach ( $uniqueIndexes as $index ) {
2967  $index = is_array( $index ) ? $index : [ $index ]; // columns
2968  $rowKey = []; // unique key to this row
2969  foreach ( $index as $column ) {
2970  $rowKey[$column] = $row[$column];
2971  }
2972  $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2973  }
2974  }
2975  $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2976  } else {
2977  $where = false;
2978  }
2979 
2980  $affectedRowCount = 0;
2981  try {
2982  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2983  # Update any existing conflicting row(s)
2984  if ( $where !== false ) {
2985  $this->update( $table, $set, $where, $fname );
2986  $affectedRowCount += $this->affectedRows();
2987  }
2988  # Now insert any non-conflicting row(s)
2989  $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2990  $affectedRowCount += $this->affectedRows();
2991  $this->endAtomic( $fname );
2992  $this->affectedRowCount = $affectedRowCount;
2993  } catch ( Exception $e ) {
2994  $this->cancelAtomic( $fname );
2995  throw $e;
2996  }
2997 
2998  return true;
2999  }
3000 
3001  public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3002  $fname = __METHOD__
3003  ) {
3004  if ( !$conds ) {
3005  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
3006  }
3007 
3008  $delTable = $this->tableName( $delTable );
3009  $joinTable = $this->tableName( $joinTable );
3010  $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3011  if ( $conds != '*' ) {
3012  $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
3013  }
3014  $sql .= ')';
3015 
3016  $this->query( $sql, $fname );
3017  }
3018 
3019  public function textFieldSize( $table, $field ) {
3020  $table = $this->tableName( $table );
3021  $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
3022  $res = $this->query( $sql, __METHOD__ );
3023  $row = $this->fetchObject( $res );
3024 
3025  $m = [];
3026 
3027  if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
3028  $size = $m[1];
3029  } else {
3030  $size = -1;
3031  }
3032 
3033  return $size;
3034  }
3035 
3036  public function delete( $table, $conds, $fname = __METHOD__ ) {
3037  if ( !$conds ) {
3038  throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
3039  }
3040 
3041  $table = $this->tableName( $table );
3042  $sql = "DELETE FROM $table";
3043 
3044  if ( $conds != '*' ) {
3045  if ( is_array( $conds ) ) {
3046  $conds = $this->makeList( $conds, self::LIST_AND );
3047  }
3048  $sql .= ' WHERE ' . $conds;
3049  }
3050 
3051  $this->query( $sql, $fname );
3052 
3053  return true;
3054  }
3055 
3056  final public function insertSelect(
3057  $destTable, $srcTable, $varMap, $conds,
3058  $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3059  ) {
3060  static $hints = [ 'NO_AUTO_COLUMNS' ];
3061 
3062  $insertOptions = (array)$insertOptions;
3063  $selectOptions = (array)$selectOptions;
3064 
3065  if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3066  // For massive migrations with downtime, we don't want to select everything
3067  // into memory and OOM, so do all this native on the server side if possible.
3068  $this->nativeInsertSelect(
3069  $destTable,
3070  $srcTable,
3071  $varMap,
3072  $conds,
3073  $fname,
3074  array_diff( $insertOptions, $hints ),
3075  $selectOptions,
3076  $selectJoinConds
3077  );
3078  } else {
3079  $this->nonNativeInsertSelect(
3080  $destTable,
3081  $srcTable,
3082  $varMap,
3083  $conds,
3084  $fname,
3085  array_diff( $insertOptions, $hints ),
3086  $selectOptions,
3087  $selectJoinConds
3088  );
3089  }
3090 
3091  return true;
3092  }
3093 
3100  protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3101  return true;
3102  }
3103 
3118  protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3119  $fname = __METHOD__,
3120  $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3121  ) {
3122  // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3123  // on only the master (without needing row-based-replication). It also makes it easy to
3124  // know how big the INSERT is going to be.
3125  $fields = [];
3126  foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3127  $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3128  }
3129  $selectOptions[] = 'FOR UPDATE';
3130  $res = $this->select(
3131  $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3132  );
3133  if ( !$res ) {
3134  return;
3135  }
3136 
3137  try {
3138  $affectedRowCount = 0;
3139  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3140  $rows = [];
3141  $ok = true;
3142  foreach ( $res as $row ) {
3143  $rows[] = (array)$row;
3144 
3145  // Avoid inserts that are too huge
3146  if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize ) {
3147  $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3148  if ( !$ok ) {
3149  break;
3150  }
3151  $affectedRowCount += $this->affectedRows();
3152  $rows = [];
3153  }
3154  }
3155  if ( $rows && $ok ) {
3156  $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3157  if ( $ok ) {
3158  $affectedRowCount += $this->affectedRows();
3159  }
3160  }
3161  if ( $ok ) {
3162  $this->endAtomic( $fname );
3163  $this->affectedRowCount = $affectedRowCount;
3164  } else {
3165  $this->cancelAtomic( $fname );
3166  }
3167  } catch ( Exception $e ) {
3168  $this->cancelAtomic( $fname );
3169  throw $e;
3170  }
3171  }
3172 
3187  protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3188  $fname = __METHOD__,
3189  $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3190  ) {
3191  $destTable = $this->tableName( $destTable );
3192 
3193  if ( !is_array( $insertOptions ) ) {
3194  $insertOptions = [ $insertOptions ];
3195  }
3196 
3197  $insertOptions = $this->makeInsertOptions( $insertOptions );
3198 
3199  $selectSql = $this->selectSQLText(
3200  $srcTable,
3201  array_values( $varMap ),
3202  $conds,
3203  $fname,
3204  $selectOptions,
3205  $selectJoinConds
3206  );
3207 
3208  $sql = "INSERT $insertOptions" .
3209  " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3210  $selectSql;
3211 
3212  $this->query( $sql, $fname );
3213  }
3214 
3215  public function limitResult( $sql, $limit, $offset = false ) {
3216  if ( !is_numeric( $limit ) ) {
3217  throw new DBUnexpectedError(
3218  $this,
3219  "Invalid non-numeric limit passed to " . __METHOD__
3220  );
3221  }
3222  // This version works in MySQL and SQLite. It will very likely need to be
3223  // overridden for most other RDBMS subclasses.
3224  return "$sql LIMIT "
3225  . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3226  . "{$limit} ";
3227  }
3228 
3229  public function unionSupportsOrderAndLimit() {
3230  return true; // True for almost every DB supported
3231  }
3232 
3233  public function unionQueries( $sqls, $all ) {
3234  $glue = $all ? ') UNION ALL (' : ') UNION (';
3235 
3236  return '(' . implode( $glue, $sqls ) . ')';
3237  }
3238 
3240  $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
3241  $options = [], $join_conds = []
3242  ) {
3243  // First, build the Cartesian product of $permute_conds
3244  $conds = [ [] ];
3245  foreach ( $permute_conds as $field => $values ) {
3246  if ( !$values ) {
3247  // Skip empty $values
3248  continue;
3249  }
3250  $values = array_unique( $values ); // For sanity
3251  $newConds = [];
3252  foreach ( $conds as $cond ) {
3253  foreach ( $values as $value ) {
3254  $cond[$field] = $value;
3255  $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3256  }
3257  }
3258  $conds = $newConds;
3259  }
3260 
3261  $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
3262 
3263  // If there's just one condition and no subordering, hand off to
3264  // selectSQLText directly.
3265  if ( count( $conds ) === 1 &&
3266  ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
3267  ) {
3268  return $this->selectSQLText(
3269  $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
3270  );
3271  }
3272 
3273  // Otherwise, we need to pull out the order and limit to apply after
3274  // the union. Then build the SQL queries for each set of conditions in
3275  // $conds. Then union them together (using UNION ALL, because the
3276  // product *should* already be distinct).
3277  $orderBy = $this->makeOrderBy( $options );
3278  $limit = $options['LIMIT'] ?? null;
3279  $offset = $options['OFFSET'] ?? false;
3280  $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3281  if ( !$this->unionSupportsOrderAndLimit() ) {
3282  unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3283  } else {
3284  if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3285  $options['ORDER BY'] = $options['INNER ORDER BY'];
3286  }
3287  if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3288  // We need to increase the limit by the offset rather than
3289  // using the offset directly, otherwise it'll skip incorrectly
3290  // in the subqueries.
3291  $options['LIMIT'] = $limit + $offset;
3292  unset( $options['OFFSET'] );
3293  }
3294  }
3295 
3296  $sqls = [];
3297  foreach ( $conds as $cond ) {
3298  $sqls[] = $this->selectSQLText(
3299  $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
3300  );
3301  }
3302  $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3303  if ( $limit !== null ) {
3304  $sql = $this->limitResult( $sql, $limit, $offset );
3305  }
3306 
3307  return $sql;
3308  }
3309 
3310  public function conditional( $cond, $trueVal, $falseVal ) {
3311  if ( is_array( $cond ) ) {
3312  $cond = $this->makeList( $cond, self::LIST_AND );
3313  }
3314 
3315  return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3316  }
3317 
3318  public function strreplace( $orig, $old, $new ) {
3319  return "REPLACE({$orig}, {$old}, {$new})";
3320  }
3321 
3322  public function getServerUptime() {
3323  return 0;
3324  }
3325 
3326  public function wasDeadlock() {
3327  return false;
3328  }
3329 
3330  public function wasLockTimeout() {
3331  return false;
3332  }
3333 
3334  public function wasConnectionLoss() {
3335  return $this->wasConnectionError( $this->lastErrno() );
3336  }
3337 
3338  public function wasReadOnlyError() {
3339  return false;
3340  }
3341 
3342  public function wasErrorReissuable() {
3343  return (
3344  $this->wasDeadlock() ||
3345  $this->wasLockTimeout() ||
3346  $this->wasConnectionLoss()
3347  );
3348  }
3349 
3356  public function wasConnectionError( $errno ) {
3357  return false;
3358  }
3359 
3366  protected function wasKnownStatementRollbackError() {
3367  return false; // don't know; it could have caused a transaction rollback
3368  }
3369 
3370  public function deadlockLoop( ...$args ) {
3371  $function = array_shift( $args );
3372  $tries = self::$DEADLOCK_TRIES;
3373 
3374  $this->begin( __METHOD__ );
3375 
3376  $retVal = null;
3378  $e = null;
3379  do {
3380  try {
3381  $retVal = $function( ...$args );
3382  break;
3383  } catch ( DBQueryError $e ) {
3384  if ( $this->wasDeadlock() ) {
3385  // Retry after a randomized delay
3386  usleep( mt_rand( self::$DEADLOCK_DELAY_MIN, self::$DEADLOCK_DELAY_MAX ) );
3387  } else {
3388  // Throw the error back up
3389  throw $e;
3390  }
3391  }
3392  } while ( --$tries > 0 );
3393 
3394  if ( $tries <= 0 ) {
3395  // Too many deadlocks; give up
3396  $this->rollback( __METHOD__ );
3397  throw $e;
3398  } else {
3399  $this->commit( __METHOD__ );
3400 
3401  return $retVal;
3402  }
3403  }
3404 
3405  public function masterPosWait( DBMasterPos $pos, $timeout ) {
3406  # Real waits are implemented in the subclass.
3407  return 0;
3408  }
3409 
3410  public function getReplicaPos() {
3411  # Stub
3412  return false;
3413  }
3414 
3415  public function getMasterPos() {
3416  # Stub
3417  return false;
3418  }
3419 
3420  public function serverIsReadOnly() {
3421  return false;
3422  }
3423 
3424  final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3425  if ( !$this->trxLevel() ) {
3426  throw new DBUnexpectedError( $this, "No transaction is active" );
3427  }
3428  $this->trxEndCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3429  }
3430 
3431  final public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3432  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3433  // Start an implicit transaction similar to how query() does
3434  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3435  $this->trxAutomatic = true;
3436  }
3437 
3438  $this->trxIdleCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3439  if ( !$this->trxLevel() ) {
3440  $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3441  }
3442  }
3443 
3444  final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3445  $this->onTransactionCommitOrIdle( $callback, $fname );
3446  }
3447 
3448  final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3449  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3450  // Start an implicit transaction similar to how query() does
3451  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3452  $this->trxAutomatic = true;
3453  }
3454 
3455  if ( $this->trxLevel() ) {
3456  $this->trxPreCommitCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3457  } else {
3458  // No transaction is active nor will start implicitly, so make one for this callback
3459  $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3460  try {
3461  $callback( $this );
3462  $this->endAtomic( __METHOD__ );
3463  } catch ( Exception $e ) {
3464  $this->cancelAtomic( __METHOD__ );
3465  throw $e;
3466  }
3467  }
3468  }
3469 
3470  final public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ) {
3471  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3472  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3473  }
3474  $this->trxSectionCancelCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3475  }
3476 
3480  private function currentAtomicSectionId() {
3481  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
3482  $levelInfo = end( $this->trxAtomicLevels );
3483 
3484  return $levelInfo[1];
3485  }
3486 
3487  return null;
3488  }
3489 
3498  ) {
3499  foreach ( $this->trxPreCommitCallbacks as $key => $info ) {
3500  if ( $info[2] === $old ) {
3501  $this->trxPreCommitCallbacks[$key][2] = $new;
3502  }
3503  }
3504  foreach ( $this->trxIdleCallbacks as $key => $info ) {
3505  if ( $info[2] === $old ) {
3506  $this->trxIdleCallbacks[$key][2] = $new;
3507  }
3508  }
3509  foreach ( $this->trxEndCallbacks as $key => $info ) {
3510  if ( $info[2] === $old ) {
3511  $this->trxEndCallbacks[$key][2] = $new;
3512  }
3513  }
3514  foreach ( $this->trxSectionCancelCallbacks as $key => $info ) {
3515  if ( $info[2] === $old ) {
3516  $this->trxSectionCancelCallbacks[$key][2] = $new;
3517  }
3518  }
3519  }
3520 
3540  private function modifyCallbacksForCancel(
3541  array $sectionIds, AtomicSectionIdentifier $newSectionId = null
3542  ) {
3543  // Cancel the "on commit" callbacks owned by this savepoint
3544  $this->trxIdleCallbacks = array_filter(
3545  $this->trxIdleCallbacks,
3546  function ( $entry ) use ( $sectionIds ) {
3547  return !in_array( $entry[2], $sectionIds, true );
3548  }
3549  );
3550  $this->trxPreCommitCallbacks = array_filter(
3551  $this->trxPreCommitCallbacks,
3552  function ( $entry ) use ( $sectionIds ) {
3553  return !in_array( $entry[2], $sectionIds, true );
3554  }
3555  );
3556  // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3557  foreach ( $this->trxEndCallbacks as $key => $entry ) {
3558  if ( in_array( $entry[2], $sectionIds, true ) ) {
3559  $callback = $entry[0];
3560  $this->trxEndCallbacks[$key][0] = function () use ( $callback ) {
3561  return $callback( self::TRIGGER_ROLLBACK, $this );
3562  };
3563  // This "on resolution" callback no longer belongs to a section.
3564  $this->trxEndCallbacks[$key][2] = null;
3565  }
3566  }
3567  // Hoist callback ownership for section cancel callbacks to the new top section
3568  foreach ( $this->trxSectionCancelCallbacks as $key => $entry ) {
3569  if ( in_array( $entry[2], $sectionIds, true ) ) {
3570  $this->trxSectionCancelCallbacks[$key][2] = $newSectionId;
3571  }
3572  }
3573  }
3574 
3575  final public function setTransactionListener( $name, callable $callback = null ) {
3576  if ( $callback ) {
3577  $this->trxRecurringCallbacks[$name] = $callback;
3578  } else {
3579  unset( $this->trxRecurringCallbacks[$name] );
3580  }
3581  }
3582 
3591  final public function setTrxEndCallbackSuppression( $suppress ) {
3592  $this->trxEndCallbacksSuppressed = $suppress;
3593  }
3594 
3605  public function runOnTransactionIdleCallbacks( $trigger ) {
3606  if ( $this->trxLevel() ) { // sanity
3607  throw new DBUnexpectedError( $this, __METHOD__ . ': a transaction is still open' );
3608  }
3609 
3610  if ( $this->trxEndCallbacksSuppressed ) {
3611  return 0;
3612  }
3613 
3614  $count = 0;
3615  $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
3617  $e = null; // first exception
3618  do { // callbacks may add callbacks :)
3619  $callbacks = array_merge(
3620  $this->trxIdleCallbacks,
3621  $this->trxEndCallbacks // include "transaction resolution" callbacks
3622  );
3623  $this->trxIdleCallbacks = []; // consumed (and recursion guard)
3624  $this->trxEndCallbacks = []; // consumed (recursion guard)
3625 
3626  // Only run trxSectionCancelCallbacks on rollback, not commit.
3627  // But always consume them.
3628  if ( $trigger === self::TRIGGER_ROLLBACK ) {
3629  $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks );
3630  }
3631  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
3632 
3633  foreach ( $callbacks as $callback ) {
3634  ++$count;
3635  list( $phpCallback ) = $callback;
3636  $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
3637  try {
3638  call_user_func( $phpCallback, $trigger, $this );
3639  } catch ( Exception $ex ) {
3640  call_user_func( $this->errorLogger, $ex );
3641  $e = $e ?: $ex;
3642  // Some callbacks may use startAtomic/endAtomic, so make sure
3643  // their transactions are ended so other callbacks don't fail
3644  if ( $this->trxLevel() ) {
3645  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
3646  }
3647  } finally {
3648  if ( $autoTrx ) {
3649  $this->setFlag( self::DBO_TRX ); // restore automatic begin()
3650  } else {
3651  $this->clearFlag( self::DBO_TRX ); // restore auto-commit
3652  }
3653  }
3654  }
3655  } while ( count( $this->trxIdleCallbacks ) );
3656 
3657  if ( $e instanceof Exception ) {
3658  throw $e; // re-throw any first exception
3659  }
3660 
3661  return $count;
3662  }
3663 
3674  $count = 0;
3675 
3676  $e = null; // first exception
3677  do { // callbacks may add callbacks :)
3678  $callbacks = $this->trxPreCommitCallbacks;
3679  $this->trxPreCommitCallbacks = []; // consumed (and recursion guard)
3680  foreach ( $callbacks as $callback ) {
3681  try {
3682  ++$count;
3683  list( $phpCallback ) = $callback;
3684  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
3685  $phpCallback( $this );
3686  } catch ( Exception $ex ) {
3687  ( $this->errorLogger )( $ex );
3688  $e = $e ?: $ex;
3689  }
3690  }
3691  } while ( count( $this->trxPreCommitCallbacks ) );
3692 
3693  if ( $e instanceof Exception ) {
3694  throw $e; // re-throw any first exception
3695  }
3696 
3697  return $count;
3698  }
3699 
3708  $trigger, array $sectionIds = null
3709  ) {
3711  $e = null; // first exception
3712 
3713  $notCancelled = [];
3714  do {
3715  $callbacks = $this->trxSectionCancelCallbacks;
3716  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
3717  foreach ( $callbacks as $entry ) {
3718  if ( $sectionIds === null || in_array( $entry[2], $sectionIds, true ) ) {
3719  try {
3720  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
3721  $entry[0]( $trigger, $this );
3722  } catch ( Exception $ex ) {
3723  ( $this->errorLogger )( $ex );
3724  $e = $e ?: $ex;
3725  } catch ( Throwable $ex ) {
3726  // @todo: Log?
3727  $e = $e ?: $ex;
3728  }
3729  } else {
3730  $notCancelled[] = $entry;
3731  }
3732  }
3733  } while ( count( $this->trxSectionCancelCallbacks ) );
3734  $this->trxSectionCancelCallbacks = $notCancelled;
3735 
3736  if ( $e !== null ) {
3737  throw $e; // re-throw any first Exception/Throwable
3738  }
3739  }
3740 
3750  public function runTransactionListenerCallbacks( $trigger ) {
3751  if ( $this->trxEndCallbacksSuppressed ) {
3752  return;
3753  }
3754 
3756  $e = null; // first exception
3757 
3758  foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
3759  try {
3760  $phpCallback( $trigger, $this );
3761  } catch ( Exception $ex ) {
3762  ( $this->errorLogger )( $ex );
3763  $e = $e ?: $ex;
3764  }
3765  }
3766 
3767  if ( $e instanceof Exception ) {
3768  throw $e; // re-throw any first exception
3769  }
3770  }
3771 
3782  protected function doSavepoint( $identifier, $fname ) {
3783  $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3784  }
3785 
3796  protected function doReleaseSavepoint( $identifier, $fname ) {
3797  $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3798  }
3799 
3810  protected function doRollbackToSavepoint( $identifier, $fname ) {
3811  $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3812  }
3813 
3818  private function nextSavepointId( $fname ) {
3819  $savepointId = self::$SAVEPOINT_PREFIX . ++$this->trxAtomicCounter;
3820  if ( strlen( $savepointId ) > 30 ) {
3821  // 30 == Oracle's identifier length limit (pre 12c)
3822  // With a 22 character prefix, that puts the highest number at 99999999.
3823  throw new DBUnexpectedError(
3824  $this,
3825  'There have been an excessively large number of atomic sections in a transaction'
3826  . " started by $this->trxFname (at $fname)"
3827  );
3828  }
3829 
3830  return $savepointId;
3831  }
3832 
3833  final public function startAtomic(
3834  $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE
3835  ) {
3836  $savepointId = $cancelable === self::ATOMIC_CANCELABLE ? self::$NOT_APPLICABLE : null;
3837 
3838  if ( !$this->trxLevel() ) {
3839  $this->begin( $fname, self::TRANSACTION_INTERNAL ); // sets trxAutomatic
3840  // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3841  // in all changes being in one transaction to keep requests transactional.
3842  if ( $this->getFlag( self::DBO_TRX ) ) {
3843  // Since writes could happen in between the topmost atomic sections as part
3844  // of the transaction, those sections will need savepoints.
3845  $savepointId = $this->nextSavepointId( $fname );
3846  $this->doSavepoint( $savepointId, $fname );
3847  } else {
3848  $this->trxAutomaticAtomic = true;
3849  }
3850  } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
3851  $savepointId = $this->nextSavepointId( $fname );
3852  $this->doSavepoint( $savepointId, $fname );
3853  }
3854 
3855  $sectionId = new AtomicSectionIdentifier;
3856  $this->trxAtomicLevels[] = [ $fname, $sectionId, $savepointId ];
3857  $this->queryLogger->debug( 'startAtomic: entering level ' .
3858  ( count( $this->trxAtomicLevels ) - 1 ) . " ($fname)" );
3859 
3860  return $sectionId;
3861  }
3862 
3863  final public function endAtomic( $fname = __METHOD__ ) {
3864  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3865  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3866  }
3867 
3868  // Check if the current section matches $fname
3869  $pos = count( $this->trxAtomicLevels ) - 1;
3870  list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3871  $this->queryLogger->debug( "endAtomic: leaving level $pos ($fname)" );
3872 
3873  if ( $savedFname !== $fname ) {
3874  throw new DBUnexpectedError(
3875  $this,
3876  "Invalid atomic section ended (got $fname but expected $savedFname)"
3877  );
3878  }
3879 
3880  // Remove the last section (no need to re-index the array)
3881  array_pop( $this->trxAtomicLevels );
3882 
3883  if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3884  $this->commit( $fname, self::FLUSHING_INTERNAL );
3885  } elseif ( $savepointId !== null && $savepointId !== self::$NOT_APPLICABLE ) {
3886  $this->doReleaseSavepoint( $savepointId, $fname );
3887  }
3888 
3889  // Hoist callback ownership for callbacks in the section that just ended;
3890  // all callbacks should have an owner that is present in trxAtomicLevels.
3891  $currentSectionId = $this->currentAtomicSectionId();
3892  if ( $currentSectionId ) {
3893  $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3894  }
3895  }
3896 
3897  final public function cancelAtomic(
3898  $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null
3899  ) {
3900  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3901  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3902  }
3903 
3904  $excisedIds = [];
3905  $newTopSection = $this->currentAtomicSectionId();
3906  try {
3907  $excisedFnames = [];
3908  if ( $sectionId !== null ) {
3909  // Find the (last) section with the given $sectionId
3910  $pos = -1;
3911  foreach ( $this->trxAtomicLevels as $i => list( $asFname, $asId, $spId ) ) {
3912  if ( $asId === $sectionId ) {
3913  $pos = $i;
3914  }
3915  }
3916  if ( $pos < 0 ) {
3917  throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3918  }
3919  // Remove all descendant sections and re-index the array
3920  $len = count( $this->trxAtomicLevels );
3921  for ( $i = $pos + 1; $i < $len; ++$i ) {
3922  $excisedFnames[] = $this->trxAtomicLevels[$i][0];
3923  $excisedIds[] = $this->trxAtomicLevels[$i][1];
3924  }
3925  $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
3926  $newTopSection = $this->currentAtomicSectionId();
3927  }
3928 
3929  // Check if the current section matches $fname
3930  $pos = count( $this->trxAtomicLevels ) - 1;
3931  list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
3932 
3933  if ( $excisedFnames ) {
3934  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3935  "and descendants " . implode( ', ', $excisedFnames ) );
3936  } else {
3937  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3938  }
3939 
3940  if ( $savedFname !== $fname ) {
3941  throw new DBUnexpectedError(
3942  $this,
3943  "Invalid atomic section ended (got $fname but expected $savedFname)"
3944  );
3945  }
3946 
3947  // Remove the last section (no need to re-index the array)
3948  array_pop( $this->trxAtomicLevels );
3949  $excisedIds[] = $savedSectionId;
3950  $newTopSection = $this->currentAtomicSectionId();
3951 
3952  if ( $savepointId !== null ) {
3953  // Rollback the transaction to the state just before this atomic section
3954  if ( $savepointId === self::$NOT_APPLICABLE ) {
3955  $this->rollback( $fname, self::FLUSHING_INTERNAL );
3956  // Note: rollback() will run trxSectionCancelCallbacks
3957  } else {
3958  $this->doRollbackToSavepoint( $savepointId, $fname );
3959  $this->trxStatus = self::STATUS_TRX_OK; // no exception; recovered
3960  $this->trxStatusIgnoredCause = null;
3961 
3962  // Run trxSectionCancelCallbacks now.
3963  $this->runOnAtomicSectionCancelCallbacks( self::TRIGGER_CANCEL, $excisedIds );
3964  }
3965  } elseif ( $this->trxStatus > self::STATUS_TRX_ERROR ) {
3966  // Put the transaction into an error state if it's not already in one
3967  $this->trxStatus = self::STATUS_TRX_ERROR;
3968  $this->trxStatusCause = new DBUnexpectedError(
3969  $this,
3970  "Uncancelable atomic section canceled (got $fname)"
3971  );
3972  }
3973  } finally {
3974  // Fix up callbacks owned by the sections that were just cancelled.
3975  // All callbacks should have an owner that is present in trxAtomicLevels.
3976  $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3977  }
3978 
3979  $this->affectedRowCount = 0; // for the sake of consistency
3980  }
3981 
3982  final public function doAtomicSection(
3983  $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
3984  ) {
3985  $sectionId = $this->startAtomic( $fname, $cancelable );
3986  try {
3987  $res = $callback( $this, $fname );
3988  } catch ( Exception $e ) {
3989  $this->cancelAtomic( $fname, $sectionId );
3990 
3991  throw $e;
3992  }
3993  $this->endAtomic( $fname );
3994 
3995  return $res;
3996  }
3997 
3998  final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
3999  static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
4000  if ( !in_array( $mode, $modes, true ) ) {
4001  throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
4002  }
4003 
4004  // Protect against mismatched atomic section, transaction nesting, and snapshot loss
4005  if ( $this->trxLevel() ) {
4006  if ( $this->trxAtomicLevels ) {
4007  $levels = $this->flatAtomicSectionList();
4008  $msg = "$fname: got explicit BEGIN while atomic section(s) $levels are open";
4009  throw new DBUnexpectedError( $this, $msg );
4010  } elseif ( !$this->trxAutomatic ) {
4011  $msg = "$fname: explicit transaction already active (from {$this->trxFname})";
4012  throw new DBUnexpectedError( $this, $msg );
4013  } else {
4014  $msg = "$fname: implicit transaction already active (from {$this->trxFname})";
4015  throw new DBUnexpectedError( $this, $msg );
4016  }
4017  } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
4018  $msg = "$fname: implicit transaction expected (DBO_TRX set)";
4019  throw new DBUnexpectedError( $this, $msg );
4020  }
4021 
4022  $this->assertHasConnectionHandle();
4023 
4024  $this->doBegin( $fname );
4025  $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4026  $this->trxStatus = self::STATUS_TRX_OK;
4027  $this->trxStatusIgnoredCause = null;
4028  $this->trxAtomicCounter = 0;
4029  $this->trxTimestamp = microtime( true );
4030  $this->trxFname = $fname;
4031  $this->trxDoneWrites = false;
4032  $this->trxAutomaticAtomic = false;
4033  $this->trxAtomicLevels = [];
4034  $this->trxWriteDuration = 0.0;
4035  $this->trxWriteQueryCount = 0;
4036  $this->trxWriteAffectedRows = 0;
4037  $this->trxWriteAdjDuration = 0.0;
4038  $this->trxWriteAdjQueryCount = 0;
4039  $this->trxWriteCallers = [];
4040  // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4041  // Get an estimate of the replication lag before any such queries.
4042  $this->trxReplicaLag = null; // clear cached value first
4043  $this->trxReplicaLag = $this->getApproximateLagStatus()['lag'];
4044  // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4045  // caller will think its OK to muck around with the transaction just because startAtomic()
4046  // has not yet completed (e.g. setting trxAtomicLevels).
4047  $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
4048  }
4049 
4057  protected function doBegin( $fname ) {
4058  $this->query( 'BEGIN', $fname );
4059  }
4060 
4061  final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4062  static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
4063  if ( !in_array( $flush, $modes, true ) ) {
4064  throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4065  }
4066 
4067  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
4068  // There are still atomic sections open; this cannot be ignored
4069  $levels = $this->flatAtomicSectionList();
4070  throw new DBUnexpectedError(
4071  $this,
4072  "$fname: got COMMIT while atomic sections $levels are still open"
4073  );
4074  }
4075 
4076  if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
4077  if ( !$this->trxLevel() ) {
4078  return; // nothing to do
4079  } elseif ( !$this->trxAutomatic ) {
4080  throw new DBUnexpectedError(
4081  $this,
4082  "$fname: flushing an explicit transaction, getting out of sync"
4083  );
4084  }
4085  } elseif ( !$this->trxLevel() ) {
4086  $this->queryLogger->error(
4087  "$fname: no transaction to commit, something got out of sync" );
4088  return; // nothing to do
4089  } elseif ( $this->trxAutomatic ) {
4090  throw new DBUnexpectedError(
4091  $this,
4092  "$fname: expected mass commit of all peer transactions (DBO_TRX set)"
4093  );
4094  }
4095 
4096  $this->assertHasConnectionHandle();
4097 
4099 
4100  $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
4101  $this->doCommit( $fname );
4102  $oldTrxShortId = $this->consumeTrxShortId();
4103  $this->trxStatus = self::STATUS_TRX_NONE;
4104 
4105  if ( $this->trxDoneWrites ) {
4106  $this->lastWriteTime = microtime( true );
4107  $this->trxProfiler->transactionWritingOut(
4108  $this->server,
4109  $this->getDomainID(),
4110  $oldTrxShortId,
4111  $writeTime,
4112  $this->trxWriteAffectedRows
4113  );
4114  }
4115 
4116  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4117  if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4118  $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
4119  $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
4120  }
4121  }
4122 
4130  protected function doCommit( $fname ) {
4131  if ( $this->trxLevel() ) {
4132  $this->query( 'COMMIT', $fname );
4133  }
4134  }
4135 
4136  final public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4137  $trxActive = $this->trxLevel();
4138 
4139  if ( $flush !== self::FLUSHING_INTERNAL
4140  && $flush !== self::FLUSHING_ALL_PEERS
4141  && $this->getFlag( self::DBO_TRX )
4142  ) {
4143  throw new DBUnexpectedError(
4144  $this,
4145  "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4146  );
4147  }
4148 
4149  if ( $trxActive ) {
4150  $this->assertHasConnectionHandle();
4151 
4152  $this->doRollback( $fname );
4153  $oldTrxShortId = $this->consumeTrxShortId();
4154  $this->trxStatus = self::STATUS_TRX_NONE;
4155  $this->trxAtomicLevels = [];
4156  // Estimate the RTT via a query now that trxStatus is OK
4157  $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4158 
4159  if ( $this->trxDoneWrites ) {
4160  $this->trxProfiler->transactionWritingOut(
4161  $this->server,
4162  $this->getDomainID(),
4163  $oldTrxShortId,
4164  $writeTime,
4165  $this->trxWriteAffectedRows
4166  );
4167  }
4168  }
4169 
4170  // Clear any commit-dependant callbacks. They might even be present
4171  // only due to transaction rounds, with no SQL transaction being active
4172  $this->trxIdleCallbacks = [];
4173  $this->trxPreCommitCallbacks = [];
4174 
4175  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4176  if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4177  try {
4178  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
4179  } catch ( Exception $e ) {
4180  // already logged; finish and let LoadBalancer move on during mass-rollback
4181  }
4182  try {
4183  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
4184  } catch ( Exception $e ) {
4185  // already logged; let LoadBalancer move on during mass-rollback
4186  }
4187 
4188  $this->affectedRowCount = 0; // for the sake of consistency
4189  }
4190  }
4191 
4199  protected function doRollback( $fname ) {
4200  if ( $this->trxLevel() ) {
4201  # Disconnects cause rollback anyway, so ignore those errors
4202  $this->query( 'ROLLBACK', $fname, IDatabase::QUERY_SILENCE_ERRORS );
4203  }
4204  }
4205 
4206  public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4207  if ( $this->explicitTrxActive() ) {
4208  // Committing this transaction would break callers that assume it is still open
4209  throw new DBUnexpectedError(
4210  $this,
4211  "$fname: Cannot flush snapshot; " .
4212  "explicit transaction '{$this->trxFname}' is still open"
4213  );
4214  } elseif ( $this->writesOrCallbacksPending() ) {
4215  // This only flushes transactions to clear snapshots, not to write data
4216  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4217  throw new DBUnexpectedError(
4218  $this,
4219  "$fname: Cannot flush snapshot; " .
4220  "writes from transaction {$this->trxFname} are still pending ($fnames)"
4221  );
4222  } elseif (
4223  $this->trxLevel() &&
4224  $this->getTransactionRoundId() &&
4225  $flush !== self::FLUSHING_INTERNAL &&
4226  $flush !== self::FLUSHING_ALL_PEERS
4227  ) {
4228  $this->queryLogger->warning(
4229  "$fname: Expected mass snapshot flush of all peer transactions " .
4230  "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4231  [ 'exception' => new RuntimeException() ]
4232  );
4233  }
4234 
4235  $this->commit( $fname, self::FLUSHING_INTERNAL );
4236  }
4237 
4238  public function explicitTrxActive() {
4239  return $this->trxLevel() && ( $this->trxAtomicLevels || !$this->trxAutomatic );
4240  }
4241 
4242  public function duplicateTableStructure(
4243  $oldName, $newName, $temporary = false, $fname = __METHOD__
4244  ) {
4245  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4246  }
4247 
4248  public function listTables( $prefix = null, $fname = __METHOD__ ) {
4249  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4250  }
4251 
4252  public function listViews( $prefix = null, $fname = __METHOD__ ) {
4253  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4254  }
4255 
4256  public function timestamp( $ts = 0 ) {
4257  $t = new ConvertibleTimestamp( $ts );
4258  // Let errors bubble up to avoid putting garbage in the DB
4259  return $t->getTimestamp( TS_MW );
4260  }
4261 
4262  public function timestampOrNull( $ts = null ) {
4263  if ( $ts === null ) {
4264  return null;
4265  } else {
4266  return $this->timestamp( $ts );
4267  }
4268  }
4269 
4270  public function affectedRows() {
4271  return ( $this->affectedRowCount === null )
4272  ? $this->fetchAffectedRowCount() // default to driver value
4274  }
4275 
4279  abstract protected function fetchAffectedRowCount();
4280 
4293  protected function resultObject( $result ) {
4294  if ( !$result ) {
4295  return false; // failed query
4296  } elseif ( $result instanceof IResultWrapper ) {
4297  return $result;
4298  } elseif ( $result === true ) {
4299  return $result; // successful write query
4300  } else {
4301  return new ResultWrapper( $this, $result );
4302  }
4303  }
4304 
4305  public function ping( &$rtt = null ) {
4306  // Avoid hitting the server if it was hit recently
4307  if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::$PING_TTL ) {
4308  if ( !func_num_args() || $this->lastRoundTripEstimate > 0 ) {
4310  return true; // don't care about $rtt
4311  }
4312  }
4313 
4314  // This will reconnect if possible or return false if not
4315  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
4316  $ok = ( $this->query( self::$PING_QUERY, __METHOD__, $flags ) !== false );
4317  if ( $ok ) {
4319  }
4320 
4321  return $ok;
4322  }
4323 
4330  protected function replaceLostConnection( $fname ) {
4331  $this->closeConnection();
4332  $this->conn = null;
4333 
4334  $this->handleSessionLossPreconnect();
4335 
4336  try {
4337  $this->open(
4338  $this->server,
4339  $this->user,
4340  $this->password,
4341  $this->currentDomain->getDatabase(),
4342  $this->currentDomain->getSchema(),
4343  $this->tablePrefix()
4344  );
4345  $this->lastPing = microtime( true );
4346  $ok = true;
4347 
4348  $this->connLogger->warning(
4349  $fname . ': lost connection to {dbserver}; reconnected',
4350  [
4351  'dbserver' => $this->getServer(),
4352  'exception' => new RuntimeException()
4353  ]
4354  );
4355  } catch ( DBConnectionError $e ) {
4356  $ok = false;
4357 
4358  $this->connLogger->error(
4359  $fname . ': lost connection to {dbserver} permanently',
4360  [ 'dbserver' => $this->getServer() ]
4361  );
4362  }
4363 
4365 
4366  return $ok;
4367  }
4368 
4369  public function getSessionLagStatus() {
4370  return $this->getRecordedTransactionLagStatus() ?: $this->getApproximateLagStatus();
4371  }
4372 
4386  final protected function getRecordedTransactionLagStatus() {
4387  return ( $this->trxLevel() && $this->trxReplicaLag !== null )
4388  ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
4389  : null;
4390  }
4391 
4400  protected function getApproximateLagStatus() {
4401  return [
4402  'lag' => ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) ? $this->getLag() : 0,
4403  'since' => microtime( true )
4404  ];
4405  }
4406 
4426  public static function getCacheSetOptions( IDatabase $db1, IDatabase $db2 = null ) {
4427  $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
4428  foreach ( func_get_args() as $db ) {
4430  $status = $db->getSessionLagStatus();
4431  if ( $status['lag'] === false ) {
4432  $res['lag'] = false;
4433  } elseif ( $res['lag'] !== false ) {
4434  $res['lag'] = max( $res['lag'], $status['lag'] );
4435  }
4436  $res['since'] = min( $res['since'], $status['since'] );
4437  $res['pending'] = $res['pending'] ?: $db->writesPending();
4438  }
4439 
4440  return $res;
4441  }
4442 
4443  public function getLag() {
4444  if ( $this->topologyRole === self::ROLE_STREAMING_MASTER ) {
4445  return 0; // this is the master
4446  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
4447  return 0; // static dataset
4448  }
4449 
4450  return $this->doGetLag();
4451  }
4452 
4453  protected function doGetLag() {
4454  return 0;
4455  }
4456 
4457  public function maxListLen() {
4458  return 0;
4459  }
4460 
4461  public function encodeBlob( $b ) {
4462  return $b;
4463  }
4464 
4465  public function decodeBlob( $b ) {
4466  if ( $b instanceof Blob ) {
4467  $b = $b->fetch();
4468  }
4469  return $b;
4470  }
4471 
4472  public function setSessionOptions( array $options ) {
4473  }
4474 
4475  public function sourceFile(
4476  $filename,
4477  callable $lineCallback = null,
4478  callable $resultCallback = null,
4479  $fname = false,
4480  callable $inputCallback = null
4481  ) {
4482  AtEase::suppressWarnings();
4483  $fp = fopen( $filename, 'r' );
4484  AtEase::restoreWarnings();
4485 
4486  if ( $fp === false ) {
4487  throw new RuntimeException( "Could not open \"{$filename}\"" );
4488  }
4489 
4490  if ( !$fname ) {
4491  $fname = __METHOD__ . "( $filename )";
4492  }
4493 
4494  try {
4495  $error = $this->sourceStream(
4496  $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4497  } catch ( Exception $e ) {
4498  fclose( $fp );
4499  throw $e;
4500  }
4501 
4502  fclose( $fp );
4503 
4504  return $error;
4505  }
4506 
4507  public function setSchemaVars( $vars ) {
4508  $this->schemaVars = is_array( $vars ) ? $vars : null;
4509  }
4510 
4511  public function sourceStream(
4512  $fp,
4513  callable $lineCallback = null,
4514  callable $resultCallback = null,
4515  $fname = __METHOD__,
4516  callable $inputCallback = null
4517  ) {
4518  $delimiterReset = new ScopedCallback(
4519  function ( $delimiter ) {
4520  $this->delimiter = $delimiter;
4521  },
4522  [ $this->delimiter ]
4523  );
4524  $cmd = '';
4525 
4526  while ( !feof( $fp ) ) {
4527  if ( $lineCallback ) {
4528  call_user_func( $lineCallback );
4529  }
4530 
4531  $line = trim( fgets( $fp ) );
4532 
4533  if ( $line == '' ) {
4534  continue;
4535  }
4536 
4537  if ( $line[0] == '-' && $line[1] == '-' ) {
4538  continue;
4539  }
4540 
4541  if ( $cmd != '' ) {
4542  $cmd .= ' ';
4543  }
4544 
4545  $done = $this->streamStatementEnd( $cmd, $line );
4546 
4547  $cmd .= "$line\n";
4548 
4549  if ( $done || feof( $fp ) ) {
4550  $cmd = $this->replaceVars( $cmd );
4551 
4552  if ( $inputCallback ) {
4553  $callbackResult = $inputCallback( $cmd );
4554 
4555  if ( is_string( $callbackResult ) || !$callbackResult ) {
4556  $cmd = $callbackResult;
4557  }
4558  }
4559 
4560  if ( $cmd ) {
4561  $res = $this->query( $cmd, $fname );
4562 
4563  if ( $resultCallback ) {
4564  $resultCallback( $res, $this );
4565  }
4566 
4567  if ( $res === false ) {
4568  $err = $this->lastError();
4569 
4570  return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4571  }
4572  }
4573  $cmd = '';
4574  }
4575  }
4576 
4577  ScopedCallback::consume( $delimiterReset );
4578  return true;
4579  }
4580 
4588  public function streamStatementEnd( &$sql, &$newLine ) {
4589  if ( $this->delimiter ) {
4590  $prev = $newLine;
4591  $newLine = preg_replace(
4592  '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4593  if ( $newLine != $prev ) {
4594  return true;
4595  }
4596  }
4597 
4598  return false;
4599  }
4600 
4621  protected function replaceVars( $ins ) {
4622  $vars = $this->getSchemaVars();
4623  return preg_replace_callback(
4624  '!
4625  /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4626  \'\{\$ (\w+) }\' | # 3. addQuotes
4627  `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4628  /\*\$ (\w+) \*/ # 5. leave unencoded
4629  !x',
4630  function ( $m ) use ( $vars ) {
4631  // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4632  // check for both nonexistent keys *and* the empty string.
4633  if ( isset( $m[1] ) && $m[1] !== '' ) {
4634  if ( $m[1] === 'i' ) {
4635  return $this->indexName( $m[2] );
4636  } else {
4637  return $this->tableName( $m[2] );
4638  }
4639  } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4640  return $this->addQuotes( $vars[$m[3]] );
4641  } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4642  return $this->addIdentifierQuotes( $vars[$m[4]] );
4643  } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4644  return $vars[$m[5]];
4645  } else {
4646  return $m[0];
4647  }
4648  },
4649  $ins
4650  );
4651  }
4652 
4659  protected function getSchemaVars() {
4660  return $this->schemaVars ?? $this->getDefaultSchemaVars();
4661  }
4662 
4671  protected function getDefaultSchemaVars() {
4672  return [];
4673  }
4674 
4675  public function lockIsFree( $lockName, $method ) {
4676  // RDBMs methods for checking named locks may or may not count this thread itself.
4677  // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4678  // the behavior chosen by the interface for this method.
4679  return !isset( $this->sessionNamedLocks[$lockName] );
4680  }
4681 
4682  public function lock( $lockName, $method, $timeout = 5 ) {
4683  $this->sessionNamedLocks[$lockName] = 1;
4684 
4685  return true;
4686  }
4687 
4688  public function unlock( $lockName, $method ) {
4689  unset( $this->sessionNamedLocks[$lockName] );
4690 
4691  return true;
4692  }
4693 
4694  public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4695  if ( $this->writesOrCallbacksPending() ) {
4696  // This only flushes transactions to clear snapshots, not to write data
4697  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4698  throw new DBUnexpectedError(
4699  $this,
4700  "$fname: Cannot flush pre-lock snapshot; " .
4701  "writes from transaction {$this->trxFname} are still pending ($fnames)"
4702  );
4703  }
4704 
4705  if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4706  return null;
4707  }
4708 
4709  $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4710  if ( $this->trxLevel() ) {
4711  // There is a good chance an exception was thrown, causing any early return
4712  // from the caller. Let any error handler get a chance to issue rollback().
4713  // If there isn't one, let the error bubble up and trigger server-side rollback.
4714  $this->onTransactionResolution(
4715  function () use ( $lockKey, $fname ) {
4716  $this->unlock( $lockKey, $fname );
4717  },
4718  $fname
4719  );
4720  } else {
4721  $this->unlock( $lockKey, $fname );
4722  }
4723  } );
4724 
4725  $this->commit( $fname, self::FLUSHING_INTERNAL );
4726 
4727  return $unlocker;
4728  }
4729 
4730  public function namedLocksEnqueue() {
4731  return false;
4732  }
4733 
4735  return true;
4736  }
4737 
4738  final public function lockTables( array $read, array $write, $method ) {
4739  if ( $this->writesOrCallbacksPending() ) {
4740  throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4741  }
4742 
4743  if ( $this->tableLocksHaveTransactionScope() ) {
4744  $this->startAtomic( $method );
4745  }
4746 
4747  return $this->doLockTables( $read, $write, $method );
4748  }
4749 
4758  protected function doLockTables( array $read, array $write, $method ) {
4759  return true;
4760  }
4761 
4762  final public function unlockTables( $method ) {
4763  if ( $this->tableLocksHaveTransactionScope() ) {
4764  $this->endAtomic( $method );
4765 
4766  return true; // locks released on COMMIT/ROLLBACK
4767  }
4768 
4769  return $this->doUnlockTables( $method );
4770  }
4771 
4778  protected function doUnlockTables( $method ) {
4779  return true;
4780  }
4781 
4789  public function dropTable( $tableName, $fName = __METHOD__ ) {
4790  if ( !$this->tableExists( $tableName, $fName ) ) {
4791  return false;
4792  }
4793  $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4794 
4795  return $this->query( $sql, $fName );
4796  }
4797 
4798  public function getInfinity() {
4799  return 'infinity';
4800  }
4801 
4802  public function encodeExpiry( $expiry ) {
4803  return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4804  ? $this->getInfinity()
4805  : $this->timestamp( $expiry );
4806  }
4807 
4808  public function decodeExpiry( $expiry, $format = TS_MW ) {
4809  if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
4810  return 'infinity';
4811  }
4812 
4813  return ConvertibleTimestamp::convert( $format, $expiry );
4814  }
4815 
4816  public function setBigSelects( $value = true ) {
4817  // no-op
4818  }
4819 
4820  public function isReadOnly() {
4821  return ( $this->getReadOnlyReason() !== false );
4822  }
4823 
4827  protected function getReadOnlyReason() {
4828  if ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) {
4829  return [ 'Server is configured as a read-only replica database.', 'role' ];
4830  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
4831  return [ 'Server is configured as a read-only static clone database.', 'role' ];
4832  }
4833 
4834  $reason = $this->getLBInfo( self::LB_READ_ONLY_REASON );
4835  if ( is_string( $reason ) ) {
4836  return [ $reason, 'lb' ];
4837  }
4838 
4839  return false;
4840  }
4841 
4842  public function setTableAliases( array $aliases ) {
4843  $this->tableAliases = $aliases;
4844  }
4845 
4846  public function setIndexAliases( array $aliases ) {
4847  $this->indexAliases = $aliases;
4848  }
4849 
4856  final protected function fieldHasBit( $field, $flags ) {
4857  return ( ( $field & $flags ) === $flags );
4858  }
4859 
4871  protected function getBindingHandle() {
4872  if ( !$this->conn ) {
4873  throw new DBUnexpectedError(
4874  $this,
4875  'DB connection was already closed or the connection dropped'
4876  );
4877  }
4878 
4879  return $this->conn;
4880  }
4881 
4882  public function __toString() {
4883  // spl_object_id is PHP >= 7.2
4884  $id = function_exists( 'spl_object_id' )
4885  ? spl_object_id( $this )
4886  : spl_object_hash( $this );
4887 
4888  $description = $this->getType() . ' object #' . $id;
4889  if ( is_resource( $this->conn ) ) {
4890  $description .= ' (' . (string)$this->conn . ')'; // "resource id #<ID>"
4891  } elseif ( is_object( $this->conn ) ) {
4892  // spl_object_id is PHP >= 7.2
4893  $handleId = function_exists( 'spl_object_id' )
4894  ? spl_object_id( $this->conn )
4895  : spl_object_hash( $this->conn );
4896  $description .= " (handle id #$handleId)";
4897  }
4898 
4899  return $description;
4900  }
4901 
4906  public function __clone() {
4907  $this->connLogger->warning(
4908  "Cloning " . static::class . " is not recommended; forking connection",
4909  [ 'exception' => new RuntimeException() ]
4910  );
4911 
4912  if ( $this->isOpen() ) {
4913  // Open a new connection resource without messing with the old one
4914  $this->conn = null;
4915  $this->trxEndCallbacks = []; // don't copy
4916  $this->trxSectionCancelCallbacks = []; // don't copy
4917  $this->handleSessionLossPreconnect(); // no trx or locks anymore
4918  $this->open(
4919  $this->server,
4920  $this->user,
4921  $this->password,
4922  $this->currentDomain->getDatabase(),
4923  $this->currentDomain->getSchema(),
4924  $this->tablePrefix()
4925  );
4926  $this->lastPing = microtime( true );
4927  }
4928  }
4929 
4935  public function __sleep() {
4936  throw new RuntimeException( 'Database serialization may cause problems, since ' .
4937  'the connection is not restored on wakeup' );
4938  }
4939 
4943  public function __destruct() {
4944  if ( $this->trxLevel() && $this->trxDoneWrites ) {
4945  trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4946  }
4947 
4948  $danglingWriters = $this->pendingWriteAndCallbackCallers();
4949  if ( $danglingWriters ) {
4950  $fnames = implode( ', ', $danglingWriters );
4951  trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4952  }
4953 
4954  if ( $this->conn ) {
4955  // Avoid connection leaks for sanity. Normally, resources close at script completion.
4956  // The connection might already be closed in PHP by now, so suppress warnings.
4957  AtEase::suppressWarnings();
4958  $this->closeConnection();
4959  AtEase::restoreWarnings();
4960  $this->conn = null;
4961  }
4962  }
4963 }
4964 
4968 class_alias( Database::class, 'DatabaseBase' );
4969 
4973 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:640
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:224
Wikimedia\Rdbms\Database\$schemaVars
array null $schemaVars
Current variables use for schema element placeholders.
Definition: Database.php:106
Wikimedia\Rdbms\Database\tablePrefix
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition: Database.php:566
Wikimedia\Rdbms\Database\$trxFname
string $trxFname
Name of the function that start the last transaction.
Definition: Database.php:131
Wikimedia\Rdbms\Database\getLastPHPError
getLastPHPError()
Definition: Database.php:853
Wikimedia\Rdbms\Database\setSessionOptions
setSessionOptions(array $options)
Override database's default behavior.
Definition: Database.php:4472
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:3215
Wikimedia\Rdbms\Database\$trxDoneWrites
bool $trxDoneWrites
Whether possible write queries were done in the last transaction started.
Definition: Database.php:133
Wikimedia\Rdbms\Database\$trxEndCallbacksSuppressed
bool $trxEndCallbacksSuppressed
Whether to suppress triggering of transaction end callbacks.
Definition: Database.php:168
Wikimedia\Rdbms\Database\$DBO_MUTABLE
static int $DBO_MUTABLE
Bit field of all DBO_* flags that can be changed after connection.
Definition: Database.php:243
Wikimedia\Rdbms\Database\makeUpdateOptionsArray
makeUpdateOptionsArray( $options)
Make UPDATE options array for Database::makeUpdateOptions.
Definition: Database.php:2181
Wikimedia\Rdbms\Database\replaceLostConnection
replaceLostConnection( $fname)
Close any existing (dead) database connection and open a new connection.
Definition: Database.php:4330
Wikimedia\Rdbms\Database\$trxWriteAdjQueryCount
int $trxWriteAdjQueryCount
Number of write queries counted in trxWriteAdjDuration.
Definition: Database.php:153
Wikimedia\Rdbms\Database\getBindingHandle
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:4871
Wikimedia\Rdbms\Database\$lastPhpError
string bool $lastPhpError
Definition: Database.php:180
Wikimedia\Rdbms\Database\canRecoverFromDisconnect
canRecoverFromDisconnect( $sql, $priorWritesPending)
Determine whether it is safe to retry queries after a database connection is lost.
Definition: Database.php:1468
Wikimedia\Rdbms\Database\buildGroupConcatField
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
Definition: Database.php:2337
Wikimedia\Rdbms\Database\doInitConnection
doInitConnection()
Actually connect to the database over the wire (or to local files)
Definition: Database.php:312
Wikimedia\Rdbms\Database\$trxReplicaLag
float $trxReplicaLag
Replication lag estimate at the time of BEGIN for the last transaction.
Definition: Database.php:129
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:2783
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:2081
Wikimedia\Rdbms\Database\deadlockLoop
deadlockLoop(... $args)
Perform a deadlock-prone transaction.
Definition: Database.php:3370
Wikimedia\Rdbms\Database\bitOr
bitOr( $fieldLeft, $fieldRight)
Definition: Database.php:2329
Wikimedia\Rdbms\Database\selectRowCount
selectRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
Definition: Database.php:1949
Wikimedia\Rdbms\Database\ignoreIndexClause
ignoreIndexClause( $index)
IGNORE INDEX clause.
Definition: Database.php:2861
Wikimedia\Rdbms\Database\trxStatus
trxStatus()
Definition: Database.php:562
Wikimedia\Rdbms\Database\listTables
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
Definition: Database.php:4248
Wikimedia\Rdbms\Database\isMultiRowArray
isMultiRowArray(array $a)
Definition: Database.php:2126
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:1393
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:2298
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:4461
Wikimedia\Rdbms\Database\tableNamesN
tableNamesN(... $tables)
Fetch a number of table names into an zero-indexed numerical array This is handy when you need to con...
Definition: Database.php:2553
Wikimedia\Rdbms\Database\getDomainID
getDomainID()
Return the currently selected domain ID.
Definition: Database.php:806
Wikimedia\Rdbms\Database\getClass
static getClass( $dbType, $driver=null)
Definition: Database.php:461
Wikimedia\Rdbms\Database\pingAndCalculateLastTrxApplyTime
pingAndCalculateLastTrxApplyTime()
Definition: Database.php:702
Wikimedia\Rdbms\Database\$topologyRole
string $topologyRole
Replication topology role of the server; one of the class ROLE_* constants.
Definition: Database.php:85
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:970
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:3448
Wikimedia\Rdbms\Database\tableLocksHaveTransactionScope
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
Definition: Database.php:4734
Wikimedia\Rdbms\Database\wasErrorReissuable
wasErrorReissuable()
Determines if the last query error was due to something outside of the query itself.
Definition: Database.php:3342
Wikimedia\Rdbms\Database\deleteJoin
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
Definition: Database.php:3001
Wikimedia\Rdbms\Database\setIndexAliases
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.
Definition: Database.php:4846
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:2926
Wikimedia\Rdbms\Database\decodeBlob
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
Definition: Database.php:4465
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:3239
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:389
Wikimedia\Rdbms\Database\maxListLen
maxListLen()
Return the maximum number of items allowed in a list, or 0 for unlimited.
Definition: Database.php:4457
Wikimedia\Rdbms\Database\selectDomain
selectDomain( $domain)
Set the current domain (database, schema, and table prefix)
Definition: Database.php:2412
Wikimedia\Rdbms\Database\buildIntegerCast
buildIntegerCast( $field)
Definition: Database.php:2385
Wikimedia\Rdbms\Database\getServerUptime
getServerUptime()
Determines how long the server has been up.
Definition: Database.php:3322
Wikimedia\Rdbms\Database\prependDatabaseOrSchema
prependDatabaseOrSchema( $namespace, $relation, $format)
Definition: Database.php:2532
Wikimedia\Rdbms\Database\$delimiter
string $delimiter
Current SQL query delimiter.
Definition: Database.php:100
Wikimedia\Rdbms\Database\__destruct
__destruct()
Run a few simple sanity checks and close dangling connections.
Definition: Database.php:4943
Wikimedia\Rdbms\Database\endAtomic
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
Definition: Database.php:3863
Wikimedia\Rdbms\Database\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:2751
Wikimedia\Rdbms\Database\executeQuery
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
Definition: Database.php:1192
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:4816
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:4262
Wikimedia\Rdbms\Database\decodeExpiry
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
Definition: Database.php:4808
Wikimedia\Rdbms\Database\$trxAutomaticAtomic
bool $trxAutomaticAtomic
Whether the current transaction was started implicitly by startAtomic()
Definition: Database.php:141
Wikimedia\Rdbms\Database\initConnection
initConnection()
Initialize the connection to the database over the wire (or to local files)
Definition: Database.php:298
Wikimedia\Rdbms\Database\normalizeConditions
normalizeConditions( $conds, $fname)
Definition: Database.php:2026
Wikimedia\Rdbms\Database\anyString
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
Definition: Database.php:2829
Wikimedia\Rdbms\Database\unionSupportsOrderAndLimit
unionSupportsOrderAndLimit()
Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION.
Definition: Database.php:3229
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:3100
Wikimedia\Rdbms\Database\fieldNameWithAlias
fieldNameWithAlias( $name, $alias=false)
Get an aliased field name e.g.
Definition: Database.php:2620
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:981
Wikimedia\Rdbms\Database\getDefaultSchemaVars
getDefaultSchemaVars()
Get schema variables to use if none have been set via setSchemaVars().
Definition: Database.php:4671
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:2049
Wikimedia\Rdbms\Database\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.
Definition: Database.php:4242
Wikimedia\Rdbms\Database\$trxSectionCancelCallbacks
array[] $trxSectionCancelCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:164
Wikimedia\Rdbms\Database\onTransactionCommitOrIdle
onTransactionCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback as soon as there is no transaction pending.
Definition: Database.php:3431
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:2950
Wikimedia\Rdbms\Database\isWriteQuery
isWriteQuery( $sql)
Determine whether a query writes to the DB.
Definition: Database.php:1047
Wikimedia\Rdbms\Database\namedLocksEnqueue
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
Definition: Database.php:4730
Wikimedia\Rdbms\Database\buildSubstring
buildSubstring( $input, $startPosition, $length=null)
Definition: Database.php:2345
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:23
Wikimedia\Rdbms\IDatabase\getSessionLagStatus
getSessionLagStatus()
Get the replica DB lag when the current transaction started or a general lag estimate if not transact...
Wikimedia\Rdbms\Database\tableNamesWithIndexClauseOrJOIN
tableNamesWithIndexClauseOrJOIN( $tables, $use_index=[], $ignore_index=[], $join_conds=[])
Get the aliased table name clause for a FROM clause which might have a JOIN and/or USE INDEX or IGNOR...
Definition: Database.php:2656
Wikimedia\Rdbms\Database\getReplicaPos
getReplicaPos()
Get the replication position of this replica DB.
Definition: Database.php:3410
Wikimedia\Rdbms\Database\getSchemaVars
getSchemaVars()
Get schema variables.
Definition: Database.php:4659
Wikimedia\Rdbms\Database\setLogger
setLogger(LoggerInterface $logger)
Set the PSR-3 logger interface to use for query logging.
Definition: Database.php:523
Wikimedia\Rdbms\Database\__clone
__clone()
Make sure that copies do not share the same client binding handle.
Definition: Database.php:4906
$res
$res
Definition: testCompression.php:54
Wikimedia\Rdbms\Database\cancelAtomic
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
Definition: Database.php:3897
$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:802
Wikimedia\Rdbms\Database\conditional
conditional( $cond, $trueVal, $falseVal)
Returns an SQL expression for a simple conditional.
Definition: Database.php:3310
Wikimedia\Rdbms\Database\$trxAtomicLevels
array $trxAtomicLevels
List of (name, unique ID, savepoint ID) for each active atomic section level.
Definition: Database.php:139
Wikimedia\Rdbms\Database\$PING_QUERY
static string $PING_QUERY
Dummy SQL query.
Definition: Database.php:226
Wikimedia\Rdbms\Database\handleSessionLossPostconnect
handleSessionLossPostconnect()
Clean things up after session (and thus transaction) loss after reconnect.
Definition: Database.php:1530
Wikimedia\Rdbms\Database\$connectionVariables
string[] int[] float[] $connectionVariables
SQL variables values to use for all new connections.
Definition: Database.php:91
Wikimedia\Rdbms\Database\$lastQuery
string $lastQuery
The last SQL query attempted.
Definition: Database.php:176
Wikimedia\Rdbms\Database\$trxStatusIgnoredCause
array null $trxStatusIgnoredCause
Error details of the last statement-only rollback.
Definition: Database.php:125
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:3019
Wikimedia\Rdbms\Database\buildConcat
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
Definition: Database.php:2333
Wikimedia\Rdbms\Database\bitNot
bitNot( $field)
Definition: Database.php:2321
Wikimedia\Rdbms\Database\nextSavepointId
nextSavepointId( $fname)
Definition: Database.php:3818
LIST_AND
const LIST_AND
Definition: Defines.php:39
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:4935
DBO_NOBUFFER
const DBO_NOBUFFER
Definition: defines.php:10
Wikimedia\Rdbms\Database\getTopologyRole
getTopologyRole()
Get the replication topology role of this server.
Definition: Database.php:531
Wikimedia\Rdbms\Database\doBegin
doBegin( $fname)
Issues the BEGIN command to the database server.
Definition: Database.php:4057
Wikimedia\Rdbms\Database\$trxIdleCallbacks
array[] $trxIdleCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:155
Wikimedia\Rdbms\Database\clearFlag
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
Definition: Database.php:774
Wikimedia\Rdbms\Database\getQueryExceptionAndLog
getQueryExceptionAndLog( $error, $errno, $sql, $fname)
Definition: Database.php:1598
Wikimedia\Rdbms\Database\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Definition: Database.php:3998
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:4293
Wikimedia\Rdbms\Database\doHandleSessionLossPreconnect
doHandleSessionLossPreconnect()
Reset any additional subclass trx* and session* fields.
Definition: Database.php:1523
Wikimedia\Rdbms\Database\$lastWriteTime
float bool $lastWriteTime
UNIX timestamp of last write query.
Definition: Database.php:178
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:3605
Wikimedia\Rdbms\Database\$trxStatusCause
Exception null $trxStatusCause
The last error that caused the status to become STATUS_TRX_ERROR.
Definition: Database.php:123
Wikimedia\Rdbms\Database\close
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition: Database.php:892
Wikimedia\Rdbms\Database\replaceVars
replaceVars( $ins)
Database independent variable replacement.
Definition: Database.php:4621
Wikimedia\Rdbms\Database\handleSessionLossPreconnect
handleSessionLossPreconnect()
Clean things up after session (and thus transaction) loss before reconnect.
Definition: Database.php:1493
Wikimedia\Rdbms\Database\$NOT_APPLICABLE
static string $NOT_APPLICABLE
Idiom used when a cancelable atomic section started the transaction.
Definition: Database.php:207
Wikimedia\Rdbms\Database\$trxStatus
int $trxStatus
Transaction status.
Definition: Database.php:121
Wikimedia\Rdbms\Database\runOnTransactionPreCommitCallbacks
runOnTransactionPreCommitCallbacks()
Actually consume and run any "on transaction pre-commit" callbacks.
Definition: Database.php:3673
Wikimedia\Rdbms\Database\wasLockTimeout
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
Definition: Database.php:3330
Wikimedia\Rdbms\Database\$affectedRowCount
integer null $affectedRowCount
Rows affected by the last query to query() or its CRUD wrappers.
Definition: Database.php:171
Wikimedia\Rdbms\Database\$currentDomain
DatabaseDomain $currentDomain
Definition: Database.php:66
LIST_OR
const LIST_OR
Definition: Defines.php:42
Wikimedia\Rdbms\Database\getLag
getLag()
Get the amount of replication lag for this database server.
Definition: Database.php:4443
Wikimedia\Rdbms\Database\$sessionTempTables
array $sessionTempTables
Map of (table name => 1) for TEMPORARY tables.
Definition: Database.php:116
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:2389
Wikimedia\Rdbms\Database\$TEMP_PSEUDO_PERMANENT
static int $TEMP_PSEUDO_PERMANENT
Writes to this temporary table effect lastDoneWrites()
Definition: Database.php:214
Wikimedia\Rdbms\Database\assertBuildSubstringParams
assertBuildSubstringParams( $startPosition, $length)
Check type and bounds for parameters to self::buildSubstring()
Definition: Database.php:2366
Wikimedia\Rdbms\Database\isReadOnly
isReadOnly()
Definition: Database.php:4820
Wikimedia\Rdbms\Database\buildStringCast
buildStringCast( $field)
Definition: Database.php:2379
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:4762
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:4369
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:3118
Wikimedia\Rdbms\Database\$trxWriteDuration
float $trxWriteDuration
Seconds spent in write queries for the current transaction.
Definition: Database.php:145
Wikimedia\Rdbms\Database\doRollbackToSavepoint
doRollbackToSavepoint( $identifier, $fname)
Rollback to a savepoint.
Definition: Database.php:3810
Wikimedia\Rdbms\Database\startAtomic
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Definition: Database.php:3833
Wikimedia\Rdbms\DBQueryTimeoutError
Error thrown when a query times out.
Definition: DBQueryTimeoutError.php:29
Wikimedia\Rdbms\Database\selectOptionsIncludeLocking
selectOptionsIncludeLocking( $options)
Definition: Database.php:1982
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:4426
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:1104
Wikimedia\Rdbms\Database\lock
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
Definition: Database.php:4682
Wikimedia\Rdbms\Database\getTransactionRoundId
getTransactionRoundId()
Definition: Database.php:673
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:550
Wikimedia\Rdbms\Database\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Definition: Database.php:759
Wikimedia\Rdbms\Database\rollback
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
Definition: Database.php:4136
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:1422
$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:3575
Wikimedia\Rdbms\Database\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
Definition: Database.php:2792
Wikimedia\Rdbms\Database\$tableAliases
array[] $tableAliases
Current map of (table => (dbname, schema, prefix) map)
Definition: Database.php:102
Wikimedia\Rdbms\Database\reportQueryError
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
Definition: Database.php:1583
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:119
Wikimedia\Rdbms\Database\isTransactableQuery
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
Definition: Database.php:1088
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:2065
LIST_SET
const LIST_SET
Definition: Defines.php:40
Wikimedia\Rdbms\Database\indexExists
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists.
Definition: Database.php:2087
Wikimedia\Rdbms\Database\writesOrCallbacksPending
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...
Definition: Database.php:656
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:4511
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:1831
$args
if( $line===false) $args
Definition: mcc.php:124
Wikimedia\Rdbms\Database\$TEMP_NORMAL
static int $TEMP_NORMAL
Writes to this temporary table do not affect lastDoneWrites()
Definition: Database.php:212
Wikimedia\Rdbms\Database\$trxWriteCallers
string[] $trxWriteCallers
Write query callers of the current transaction.
Definition: Database.php:143
Wikimedia\Rdbms\Database\$lastPing
float $lastPing
UNIX timestamp.
Definition: Database.php:174
Wikimedia\Rdbms\Database\bitAnd
bitAnd( $fieldLeft, $fieldRight)
Definition: Database.php:2325
Wikimedia\Rdbms\Database\buildLike
buildLike( $param,... $params)
LIKE statement wrapper.
Definition: Database.php:2798
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:1449
Wikimedia\Rdbms\Database\selectDB
selectDB( $db)
Change the current database.
Definition: Database.php:2402
Wikimedia\Rdbms\Database\wasQueryTimeout
wasQueryTimeout( $error, $errno)
Checks whether the cause of the error is detected to be a timeout.
Definition: Database.php:1568
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:648
Wikimedia\Rdbms\Database\dropTable
dropTable( $tableName, $fName=__METHOD__)
Delete a table.
Definition: Database.php:4789
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:231
Wikimedia\Rdbms\Database\wasReadOnlyError
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
Definition: Database.php:3338
Wikimedia\Rdbms\Database\beginIfImplied
beginIfImplied( $sql, $fname)
Start an implicit transaction if DBO_TRX is enabled and no transaction is active.
Definition: Database.php:1370
Wikimedia\Rdbms\Database\getQueryException
getQueryException( $error, $errno, $sql, $fname)
Definition: Database.php:1620
Wikimedia\Rdbms\Database\getServerInfo
getServerInfo()
Get a human-readable string describing the current software version.
Definition: Database.php:527
Wikimedia\Rdbms\Database\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Definition: Database.php:4061
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:789
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:871
Wikimedia\Rdbms\Database\setLBInfo
setLBInfo( $nameOrArray, $value=null)
Set the entire array or a particular key of the managing load balancer info array.
Definition: Database.php:616
Wikimedia\Rdbms\Database\getScopedLockAndFlush
getScopedLockAndFlush( $lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
Definition: Database.php:4694
Wikimedia\Rdbms\Database\fieldNamesWithAlias
fieldNamesWithAlias( $fields)
Gets an array of aliased field names.
Definition: Database.php:2634
Wikimedia\Rdbms\Database\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:604
Wikimedia\Rdbms\DBReadOnlyError
Definition: DBReadOnlyError.php:27
Wikimedia\Rdbms\Database\$trxWriteAffectedRows
int $trxWriteAffectedRows
Number of rows affected by write queries for the current transaction.
Definition: Database.php:149
Wikimedia\Rdbms\Database\$trxWriteAdjDuration
float $trxWriteAdjDuration
Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries.
Definition: Database.php:151
Wikimedia\Rdbms\Database\insertSelect
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper.
Definition: Database.php:3056
Wikimedia\Rdbms\Database\makeInsertOptions
makeInsertOptions( $options)
Helper for Database::insert().
Definition: Database.php:2118
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:1914
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
Wikimedia\Rdbms\Database\useIndexClause
useIndexClause( $index)
USE INDEX clause.
Definition: Database.php:2847
Wikimedia\Rdbms\Database\makeUpdateOptions
makeUpdateOptions( $options)
Make UPDATE options for the Database::update function.
Definition: Database.php:2201
LIST_COMMA
const LIST_COMMA
Definition: Defines.php:38
Wikimedia\Rdbms\Database\getReadOnlyReason
getReadOnlyReason()
Definition: Database.php:4827
Wikimedia\Rdbms\DBQueryDisconnectedError
Definition: DBQueryDisconnectedError.php:28
Wikimedia\Rdbms\Database\$priorFlags
int[] $priorFlags
Prior flags member variable values.
Definition: Database.php:111
Wikimedia\Rdbms\Database\doGetLag
doGetLag()
Definition: Database.php:4453
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:830
Wikimedia\Rdbms\Database\aggregateValue
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
Definition: Database.php:2317
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:841
Wikimedia\Rdbms\Database\preCommitCallbacksPending
preCommitCallbacksPending()
Definition: Database.php:666
Wikimedia\Rdbms\Database\replace
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
REPLACE query wrapper.
Definition: Database.php:2865
Wikimedia\Rdbms\Database\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Definition: Database.php:3366
Wikimedia\Rdbms\Database\pendingWriteAndCallbackCallers
pendingWriteAndCallbackCallers()
List the methods that have write queries or callbacks for the current transaction.
Definition: Database.php:730
Wikimedia\Rdbms\Database\$trxPreCommitCallbacks
array[] $trxPreCommitCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:157
Wikimedia\Rdbms\Database\$htmlErrors
string bool null $htmlErrors
Stashed value of html_errors INI setting.
Definition: Database.php:109
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:209
Wikimedia\Rdbms\Database\pendingWriteCallers
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
Definition: Database.php:714
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MAX
static int $DEADLOCK_DELAY_MAX
Maximum time to wait before retry.
Definition: Database.php:221
Wikimedia\Rdbms\Database\$trxEndCallbacks
array[] $trxEndCallbacks
List of (callable, method name, atomic section id) @phan-var array<array{0:callable,...
Definition: Database.php:162
Wikimedia\Rdbms\Database\tableNames
tableNames(... $tables)
Fetch a number of table names into an array This is handy when you need to construct SQL for joins.
Definition: Database.php:2543
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:4882
Wikimedia\Rdbms\Database\$lastRoundTripEstimate
float $lastRoundTripEstimate
Query round trip time estimate.
Definition: Database.php:182
Wikimedia\Rdbms\Database\getLogContext
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: Database.php:881
Wikimedia\Rdbms\Database\$connectionParams
array $connectionParams
Parameters used by initConnection() to establish a connection.
Definition: Database.php:89
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:135
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:4206
Wikimedia\Rdbms\Database\pendingWriteRowsAffected
pendingWriteRowsAffected()
Get the number of affected rows from pending write queries.
Definition: Database.php:718
Wikimedia\Rdbms\Database\$trxWriteQueryCount
int $trxWriteQueryCount
Number of write queries for the current transaction.
Definition: Database.php:147
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:3796
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:1282
$line
$line
Definition: mcc.php:119
Wikimedia\Rdbms\Database\currentAtomicSectionId
currentAtomicSectionId()
Definition: Database.php:3480
Wikimedia\Rdbms\Database\modifyCallbacksForCancel
modifyCallbacksForCancel(array $sectionIds, AtomicSectionIdentifier $newSectionId=null)
Update callbacks that were owned by cancelled atomic sections.
Definition: Database.php:3540
Wikimedia\Rdbms\Database\setTrxEndCallbackSuppression
setTrxEndCallbackSuppression( $suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
Definition: Database.php:3591
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:3415
Wikimedia\Rdbms\Database\pendingWriteQueryDuration
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
Definition: Database.php:684
Wikimedia\Rdbms\Database\$indexAliases
string[] $indexAliases
Current map of (index alias => index)
Definition: Database.php:104
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:2434
Wikimedia\Rdbms\Database\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: Database.php:3356
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:3982
Wikimedia\Rdbms\Database\getRecordedTransactionLagStatus
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
Definition: Database.php:4386
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:3707
Wikimedia\Rdbms\Database\getServer
getServer()
Get the server hostname or IP address.
Definition: Database.php:2430
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:4758
Wikimedia\Rdbms\Database\doUnlockTables
doUnlockTables( $method)
Helper function for unlockTables() that handles the actual table unlocking.
Definition: Database.php:4778
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:4256
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:1652
Wikimedia\Rdbms\Database\bufferResults
bufferResults( $buffer=null)
Backwards-compatibility no-op method for disabling query buffering.
Definition: Database.php:546
Wikimedia\Rdbms\Database\registerTempWrites
registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel)
Definition: Database.php:1144
Wikimedia\Rdbms\Database\anyChar
anyChar()
Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
Definition: Database.php:2825
Wikimedia\Rdbms\Database\onTransactionIdle
onTransactionIdle(callable $callback, $fname=__METHOD__)
Alias for onTransactionCommitOrIdle() for backwards-compatibility.
Definition: Database.php:3444
Wikimedia\Rdbms\Database\unlock
unlock( $lockName, $method)
Release a lock.
Definition: Database.php:4688
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:233
Wikimedia\Rdbms\Database\addIdentifierQuotes
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.
Definition: Database.php:2770
Wikimedia\Rdbms\Database\getLazyMasterHandle
getLazyMasterHandle()
Get a handle to the master server of the cluster to which this server belongs.
Definition: Database.php:636
Wikimedia\Rdbms\Database\consumeTrxShortId
consumeTrxShortId()
Reset the transaction ID and return the old one.
Definition: Database.php:1551
Wikimedia\Rdbms\Database\estimateRowCount
estimateRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate the number of rows in dataset.
Definition: Database.php:1932
Wikimedia\Rdbms\Database\indexUnique
indexUnique( $table, $index)
Determines if a given index is unique.
Definition: Database.php:2102
Wikimedia\Rdbms\Database\dbSchema
dbSchema( $schema=null)
Get/set the db schema.
Definition: Database.php:579
Wikimedia\Rdbms\Database\$trxRecurringCallbacks
callable[] $trxRecurringCallbacks
Map of (name => callable)
Definition: Database.php:166
Wikimedia\Rdbms\Database\getQueryVerb
getQueryVerb( $sql)
Definition: Database.php:1071
Wikimedia\Rdbms\Database\unionQueries
unionQueries( $sqls, $all)
Construct a UNION query.
Definition: Database.php:3233
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:3496
Wikimedia\Rdbms\Database\insert
insert( $table, $rows, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
Definition: Database.php:2130
Wikimedia\Rdbms\IDatabase\lastErrno
lastErrno()
Get the last error number.
Wikimedia\Rdbms\Database\relationSchemaQualifier
relationSchemaQualifier()
Definition: Database.php:600
Wikimedia\Rdbms\Database\$DEADLOCK_TRIES
static int $DEADLOCK_TRIES
Number of times to re-try an operation in case of deadlock.
Definition: Database.php:217
Wikimedia\Rdbms\Database\newExceptionAfterConnectError
newExceptionAfterConnectError( $error)
Definition: Database.php:1634
Wikimedia\Rdbms\Database\lockTables
lockTables(array $read, array $write, $method)
Lock specific tables.
Definition: Database.php:4738
Wikimedia\Rdbms\Database\$trxAtomicCounter
int $trxAtomicCounter
Counter for atomic savepoint identifiers (reset with each transaction)
Definition: Database.php:137
Wikimedia\Rdbms\Database\encodeExpiry
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
Definition: Database.php:4802
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:3782
Wikimedia\Rdbms\Database\setSchemaVars
setSchemaVars( $vars)
Set schema variables to be used when streaming commands from SQL files or stdin.
Definition: Database.php:4507
Wikimedia\Rdbms\Database\__construct
__construct(array $params)
Definition: Database.php:251
Wikimedia\Rdbms\Database\trxTimestamp
trxTimestamp()
Get the UNIX timestamp of the time that the transaction was established.
Definition: Database.php:554
Wikimedia\Rdbms\Database\$trxTimestamp
float null $trxTimestamp
UNIX timestamp at the time of BEGIN for the last transaction.
Definition: Database.php:127
Wikimedia\Rdbms\Database\makeGroupByWithHaving
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1785
Wikimedia\Rdbms\Database\tableNameWithAlias
tableNameWithAlias( $table, $alias=false)
Get an aliased table name.
Definition: Database.php:2574
Wikimedia\Rdbms\Database\getAttributes
static getAttributes()
Definition: Database.php:512
Wikimedia\Rdbms\Database\writesPending
writesPending()
Definition: Database.php:652
Wikimedia\Rdbms\Database\selectFieldsOrOptionsAggregate
selectFieldsOrOptionsAggregate( $fields, $options)
Definition: Database.php:1998
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:4675
Wikimedia\Rdbms\Database\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Definition: Database.php:4305
Wikimedia\Rdbms\Database\$nonNativeInsertSelectBatchSize
int $nonNativeInsertSelectBatchSize
Row batch size to use for emulated INSERT SELECT queries.
Definition: Database.php:93
Wikimedia\Rdbms\Database\runTransactionListenerCallbacks
runTransactionListenerCallbacks( $trigger)
Actually run any "transaction listener" callbacks.
Definition: Database.php:3750
Wikimedia\Rdbms\Database\onAtomicSectionCancel
onAtomicSectionCancel(callable $callback, $fname=__METHOD__)
Run a callback when the atomic section is cancelled.
Definition: Database.php:3470
Wikimedia\Rdbms\Database\getTopologyRootMaster
getTopologyRootMaster()
Get the host (or address) of the root master server for the replication topology.
Definition: Database.php:535
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:4842
Wikimedia\Rdbms\Database\$MUTABLE_FLAGS
static string[] $MUTABLE_FLAGS
List of DBO_* flags that can be changed after connection.
Definition: Database.php:236
Wikimedia\Rdbms\Database\masterPosWait
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
Definition: Database.php:3405
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:3424
Wikimedia\Rdbms\IDatabase\getType
getType()
Get the type of the DBMS (e.g.
Wikimedia\Rdbms\Database\explicitTrxActive
explicitTrxActive()
Definition: Database.php:4238
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:75
$keys
$keys
Definition: testCompression.php:69
Wikimedia\Rdbms\Database\freeResult
freeResult( $res)
Free a result object returned by query() or select()
Definition: Database.php:1649
Wikimedia\Rdbms\Database\isOpen
isOpen()
Definition: Database.php:755
Wikimedia\Rdbms\Database\doCommit
doCommit( $fname)
Issues the COMMIT command to the database server.
Definition: Database.php:4130
$source
$source
Definition: mwdoc-filter.php:34
Wikimedia\Rdbms\IMaintainableDatabase\fieldInfo
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
Wikimedia\Rdbms\Database\$topologyRootMaster
string null $topologyRootMaster
Host (or address) of the root master server for the replication topology.
Definition: Database.php:87
Wikimedia\Rdbms\Database\makeOrderBy
makeOrderBy( $options)
Returns an optional ORDER BY.
Definition: Database.php:1811
Wikimedia\Rdbms\Database\$flags
int $flags
Current bit field of class DBO_* constants.
Definition: Database.php:96
Wikimedia\Rdbms\Database\serverIsReadOnly
serverIsReadOnly()
Definition: Database.php:3420
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:1714
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:1823
Wikimedia\Rdbms\Database\attributesFromType
static attributesFromType( $dbType, $driver=null)
Definition: Database.php:443
Wikimedia\Rdbms\Database\lastQuery
lastQuery()
Get the last query that sent on account of IDatabase::query()
Definition: Database.php:644
Wikimedia\Rdbms\Database\wasConnectionLoss
wasConnectionLoss()
Determines if the last query error was due to a dropped connection.
Definition: Database.php:3334
Wikimedia\Rdbms\Database\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.
Definition: Database.php:3326
$t
$t
Definition: testCompression.php:71
Wikimedia\Rdbms\Database\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Definition: Database.php:2422
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:2207
Wikimedia\Rdbms\Database\addQuotes
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
Definition: Database.php:2755
LIST_NAMES
const LIST_NAMES
Definition: Defines.php:41
Wikimedia\Rdbms\Database\getApproximateLagStatus
getApproximateLagStatus()
Get a replica DB lag estimate for this server at the start of a transaction.
Definition: Database.php:4400
Wikimedia\Rdbms\Database\qualifiedTableComponents
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
Definition: Database.php:2492
Wikimedia\Rdbms\Database\affectedRows
affectedRows()
Get the number of rows affected by the last write query.
Definition: Database.php:4270
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MIN
static int $DEADLOCK_DELAY_MIN
Minimum time to wait before retry, in microseconds.
Definition: Database.php:219
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:2398
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:3318
Wikimedia\Rdbms\Database\$ownerId
int null $ownerId
Integer ID of the managing LBFactory instance or null if none.
Definition: Database.php:185
Wikimedia\Rdbms\Database\fieldHasBit
fieldHasBit( $field, $flags)
Definition: Database.php:4856
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:4475
Wikimedia\Rdbms\Database\listViews
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.
Definition: Database.php:4252
Wikimedia\Rdbms\Database\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
Definition: Database.php:4588
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:3187
Wikimedia\Rdbms\Database\makeList
makeList(array $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2222
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:1155
Wikimedia\Rdbms\Database\tableNamesWithAlias
tableNamesWithAlias( $tables)
Gets an array of aliased table names.
Definition: Database.php:2600
Wikimedia\Rdbms\Database\nextSequenceValue
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
Definition: Database.php:2833
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:1678
Wikimedia\Rdbms\Database\flatAtomicSectionList
flatAtomicSectionList()
Definition: Database.php:749
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:4199
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:229
Wikimedia\Rdbms\Database\$lbInfo
array $lbInfo
Current LoadBalancer tracking information.
Definition: Database.php:98
Wikimedia\Rdbms\Database\getDBname
getDBname()
Get the current DB name.
Definition: Database.php:2426
Wikimedia\Rdbms\Blob
Definition: Blob.php:5
Wikimedia\Rdbms\Database\getInfinity
getInfinity()
Find out when 'infinity' is.
Definition: Database.php:4798
$type
$type
Definition: testCompression.php:50
Wikimedia\Rdbms\Database\$sessionNamedLocks
array $sessionNamedLocks
Map of (name => 1) for locks obtained via lock()
Definition: Database.php:114