MediaWiki  master
Database.php
Go to the documentation of this file.
1 <?php
26 namespace Wikimedia\Rdbms;
27 
28 use BagOStuff;
29 use Exception;
30 use HashBagOStuff;
31 use InvalidArgumentException;
32 use LogicException;
33 use Psr\Log\LoggerAwareInterface;
34 use Psr\Log\LoggerInterface;
35 use Psr\Log\NullLogger;
36 use RuntimeException;
37 use Throwable;
38 use UnexpectedValueException;
39 use Wikimedia\AtEase\AtEase;
40 use Wikimedia\ScopedCallback;
41 use Wikimedia\Timestamp\ConvertibleTimestamp;
42 
50 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
52  protected $srvCache;
54  protected $connLogger;
56  protected $queryLogger;
58  protected $replLogger;
60  protected $errorLogger;
62  protected $deprecationLogger;
64  protected $profiler;
66  protected $trxProfiler;
67 
69  protected $currentDomain;
70 
71  // phpcs:ignore MediaWiki.Commenting.PropertyDocumentation.ObjectTypeHintVar
73  protected $conn;
74 
77 
79  protected $server;
81  protected $user;
83  protected $password;
85  protected $cliMode;
87  protected $agent;
89  protected $topologyRole;
93  protected $connectionParams;
98 
100  protected $flags;
102  protected $lbInfo = [];
104  protected $delimiter = ';';
106  protected $tableAliases = [];
108  protected $indexAliases = [];
110  protected $schemaVars;
111 
113  private $htmlErrors;
115  private $priorFlags = [];
116 
118  protected $sessionNamedLocks = [];
120  protected $sessionTempTables = [];
122  protected $sessionDirtyTempTables = [];
123 
125  private $trxShortId = '';
127  private $trxStatus = self::STATUS_TRX_NONE;
133  private $trxTimestamp = null;
135  private $trxReplicaLag = null;
137  private $trxFname = null;
139  private $trxDoneWrites = false;
141  private $trxAutomatic = false;
143  private $trxAtomicCounter = 0;
145  private $trxAtomicLevels = [];
147  private $trxAutomaticAtomic = false;
149  private $trxWriteCallers = [];
151  private $trxWriteDuration = 0.0;
153  private $trxWriteQueryCount = 0;
157  private $trxWriteAdjDuration = 0.0;
168  private $trxEndCallbacks = [];
174  private $trxEndCallbacksSuppressed = false;
175 
177  protected $affectedRowCount;
178 
180  private $lastPing = 0.0;
182  private $lastQuery = '';
184  private $lastWriteTime = false;
186  private $lastPhpError = false;
188  private $lastRoundTripEstimate = 0.0;
189 
191  private $ownerId;
192 
194  public const ATTR_DB_IS_FILE = 'db-is-file';
196  public const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
198  public const ATTR_SCHEMAS_AS_TABLE_GROUPS = 'supports-schemas';
199 
201  public const NEW_UNCONNECTED = 0;
203  public const NEW_CONNECTED = 1;
204 
206  public const STATUS_TRX_ERROR = 1;
208  public const STATUS_TRX_OK = 2;
210  public const STATUS_TRX_NONE = 3;
211 
213  private static $NOT_APPLICABLE = 'n/a';
215  private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
216 
218  private static $TEMP_NORMAL = 1;
220  private static $TEMP_PSEUDO_PERMANENT = 2;
221 
223  private static $DEADLOCK_TRIES = 4;
225  private static $DEADLOCK_DELAY_MIN = 500000;
227  private static $DEADLOCK_DELAY_MAX = 1500000;
228 
230  private static $PING_TTL = 1.0;
232  private static $PING_QUERY = 'SELECT 1 AS ping';
233 
235  private static $TINY_WRITE_SEC = 0.010;
237  private static $SLOW_WRITE_SEC = 0.500;
239  private static $SMALL_WRITE_ROWS = 100;
240 
242  protected static $MUTABLE_FLAGS = [
243  'DBO_DEBUG',
244  'DBO_NOBUFFER',
245  'DBO_TRX',
246  'DBO_DDLMODE',
247  ];
249  protected static $DBO_MUTABLE = (
251  );
252 
258  public function __construct( array $params ) {
259  $this->connectionParams = [
260  'host' => ( isset( $params['host'] ) && $params['host'] !== '' )
261  ? $params['host']
262  : null,
263  'user' => ( isset( $params['user'] ) && $params['user'] !== '' )
264  ? $params['user']
265  : null,
266  'dbname' => ( isset( $params['dbname'] ) && $params['dbname'] !== '' )
267  ? $params['dbname']
268  : null,
269  'schema' => ( isset( $params['schema'] ) && $params['schema'] !== '' )
270  ? $params['schema']
271  : null,
272  'password' => is_string( $params['password'] ) ? $params['password'] : null,
273  'tablePrefix' => (string)$params['tablePrefix']
274  ];
275 
276  $this->lbInfo = $params['lbInfo'] ?? [];
277  $this->lazyMasterHandle = $params['lazyMasterHandle'] ?? null;
278  $this->connectionVariables = $params['variables'] ?? [];
279 
280  $this->flags = (int)$params['flags'];
281  $this->cliMode = (bool)$params['cliMode'];
282  $this->agent = (string)$params['agent'];
283  $this->topologyRole = (string)$params['topologyRole'];
284  $this->topologyRootMaster = (string)$params['topologicalMaster'];
285  $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'] ?? 10000;
286 
287  $this->srvCache = $params['srvCache'];
288  $this->profiler = is_callable( $params['profiler'] ) ? $params['profiler'] : null;
289  $this->trxProfiler = $params['trxProfiler'];
290  $this->connLogger = $params['connLogger'];
291  $this->queryLogger = $params['queryLogger'];
292  $this->replLogger = $params['replLogger'];
293  $this->errorLogger = $params['errorLogger'];
294  $this->deprecationLogger = $params['deprecationLogger'];
295 
296  // Set initial dummy domain until open() sets the final DB/prefix
297  $this->currentDomain = new DatabaseDomain(
298  $params['dbname'] != '' ? $params['dbname'] : null,
299  $params['schema'] != '' ? $params['schema'] : null,
300  $params['tablePrefix']
301  );
302 
303  $this->ownerId = $params['ownerId'] ?? null;
304  }
305 
314  final public function initConnection() {
315  if ( $this->isOpen() ) {
316  throw new LogicException( __METHOD__ . ': already connected' );
317  }
318  // Establish the connection
319  $this->doInitConnection();
320  }
321 
328  protected function doInitConnection() {
329  $this->open(
330  $this->connectionParams['host'],
331  $this->connectionParams['user'],
332  $this->connectionParams['password'],
333  $this->connectionParams['dbname'],
334  $this->connectionParams['schema'],
335  $this->connectionParams['tablePrefix']
336  );
337  }
338 
350  abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
351 
405  final public static function factory( $type, $params = [], $connect = self::NEW_CONNECTED ) {
406  $class = self::getClass( $type, $params['driver'] ?? null );
407 
408  if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
409  $params += [
410  // Default configuration
411  'host' => null,
412  'user' => null,
413  'password' => null,
414  'dbname' => null,
415  'schema' => null,
416  'tablePrefix' => '',
417  'flags' => 0,
418  'variables' => [],
419  'lbInfo' => [],
420  'cliMode' => ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ),
421  'agent' => '',
422  'ownerId' => null,
423  'topologyRole' => null,
424  'topologicalMaster' => null,
425  // Objects and callbacks
426  'lazyMasterHandle' => $params['lazyMasterHandle'] ?? null,
427  'srvCache' => $params['srvCache'] ?? new HashBagOStuff(),
428  'profiler' => $params['profiler'] ?? null,
429  'trxProfiler' => $params['trxProfiler'] ?? new TransactionProfiler(),
430  'connLogger' => $params['connLogger'] ?? new NullLogger(),
431  'queryLogger' => $params['queryLogger'] ?? new NullLogger(),
432  'replLogger' => $params['replLogger'] ?? new NullLogger(),
433  'errorLogger' => $params['errorLogger'] ?? static function ( Throwable $e ) {
434  trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
435  },
436  'deprecationLogger' => $params['deprecationLogger'] ?? static function ( $msg ) {
437  trigger_error( $msg, E_USER_DEPRECATED );
438  }
439  ];
440 
442  $conn = new $class( $params );
443  if ( $connect === self::NEW_CONNECTED ) {
444  $conn->initConnection();
445  }
446  } else {
447  $conn = null;
448  }
449 
450  return $conn;
451  }
452 
460  final public static function attributesFromType( $dbType, $driver = null ) {
461  static $defaults = [
462  self::ATTR_DB_IS_FILE => false,
463  self::ATTR_DB_LEVEL_LOCKING => false,
464  self::ATTR_SCHEMAS_AS_TABLE_GROUPS => false
465  ];
466 
467  $class = self::getClass( $dbType, $driver );
468 
469  return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
470  }
471 
478  private static function getClass( $dbType, $driver = null ) {
479  // For database types with built-in support, the below maps type to IDatabase
480  // implementations. For types with multiple driver implementations (PHP extensions),
481  // an array can be used, keyed by extension name. In case of an array, the
482  // optional 'driver' parameter can be used to force a specific driver. Otherwise,
483  // we auto-detect the first available driver. For types without built-in support,
484  // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
485  static $builtinTypes = [
486  'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
487  'sqlite' => DatabaseSqlite::class,
488  'postgres' => DatabasePostgres::class,
489  ];
490 
491  $dbType = strtolower( $dbType );
492 
493  if ( !isset( $builtinTypes[$dbType] ) ) {
494  // Not a built in type, assume standard naming scheme
495  return 'Database' . ucfirst( $dbType );
496  }
497 
498  $class = false;
499  $possibleDrivers = $builtinTypes[$dbType];
500  if ( is_string( $possibleDrivers ) ) {
501  $class = $possibleDrivers;
502  } elseif ( (string)$driver !== '' ) {
503  if ( !isset( $possibleDrivers[$driver] ) ) {
504  throw new InvalidArgumentException( __METHOD__ .
505  " type '$dbType' does not support driver '{$driver}'" );
506  }
507 
508  $class = $possibleDrivers[$driver];
509  } else {
510  foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
511  if ( extension_loaded( $posDriver ) ) {
512  $class = $possibleClass;
513  break;
514  }
515  }
516  }
517 
518  if ( $class === false ) {
519  throw new InvalidArgumentException( __METHOD__ .
520  " no viable database extension found for type '$dbType'" );
521  }
522 
523  return $class;
524  }
525 
531  protected static function getAttributes() {
532  return [];
533  }
534 
542  public function setLogger( LoggerInterface $logger ) {
543  $this->queryLogger = $logger;
544  }
545 
546  public function getServerInfo() {
547  return $this->getServerVersion();
548  }
549 
550  public function getTopologyRole() {
551  return $this->topologyRole;
552  }
553 
554  public function getTopologyRootMaster() {
556  }
557 
558  final public function trxLevel() {
559  return ( $this->trxShortId != '' ) ? 1 : 0;
560  }
561 
562  public function trxTimestamp() {
563  return $this->trxLevel() ? $this->trxTimestamp : null;
564  }
565 
570  public function trxStatus() {
571  return $this->trxStatus;
572  }
573 
574  public function tablePrefix( $prefix = null ) {
575  $old = $this->currentDomain->getTablePrefix();
576 
577  if ( $prefix !== null ) {
578  $this->currentDomain = new DatabaseDomain(
579  $this->currentDomain->getDatabase(),
580  $this->currentDomain->getSchema(),
581  $prefix
582  );
583  }
584 
585  return $old;
586  }
587 
588  public function dbSchema( $schema = null ) {
589  $old = $this->currentDomain->getSchema();
590 
591  if ( $schema !== null ) {
592  if ( $schema !== '' && $this->getDBname() === null ) {
593  throw new DBUnexpectedError(
594  $this,
595  "Cannot set schema to '$schema'; no database set"
596  );
597  }
598 
599  $this->currentDomain = new DatabaseDomain(
600  $this->currentDomain->getDatabase(),
601  // DatabaseDomain uses null for unspecified schemas
602  ( $schema !== '' ) ? $schema : null,
603  $this->currentDomain->getTablePrefix()
604  );
605  }
606 
607  return (string)$old;
608  }
609 
614  protected function relationSchemaQualifier() {
615  return $this->dbSchema();
616  }
617 
618  public function getLBInfo( $name = null ) {
619  if ( $name === null ) {
620  return $this->lbInfo;
621  }
622 
623  if ( array_key_exists( $name, $this->lbInfo ) ) {
624  return $this->lbInfo[$name];
625  }
626 
627  return null;
628  }
629 
630  public function setLBInfo( $nameOrArray, $value = null ) {
631  if ( is_array( $nameOrArray ) ) {
632  $this->lbInfo = $nameOrArray;
633  } elseif ( is_string( $nameOrArray ) ) {
634  if ( $value !== null ) {
635  $this->lbInfo[$nameOrArray] = $value;
636  } else {
637  unset( $this->lbInfo[$nameOrArray] );
638  }
639  } else {
640  throw new InvalidArgumentException( "Got non-string key" );
641  }
642  }
643 
650  protected function getLazyMasterHandle() {
652  }
653 
658  public function implicitOrderby() {
659  return true;
660  }
661 
662  public function lastQuery() {
663  return $this->lastQuery;
664  }
665 
666  public function lastDoneWrites() {
667  return $this->lastWriteTime ?: false;
668  }
669 
670  public function writesPending() {
671  return $this->trxLevel() && $this->trxDoneWrites;
672  }
673 
674  public function writesOrCallbacksPending() {
675  return $this->trxLevel() && (
676  $this->trxDoneWrites ||
677  $this->trxPostCommitOrIdleCallbacks ||
678  $this->trxPreCommitOrIdleCallbacks ||
679  $this->trxEndCallbacks ||
681  );
682  }
683 
684  public function preCommitCallbacksPending() {
685  return $this->trxLevel() && $this->trxPreCommitOrIdleCallbacks;
686  }
687 
691  final protected function getTransactionRoundId() {
692  // If transaction round participation is enabled, see if one is active
693  if ( $this->getFlag( self::DBO_TRX ) ) {
694  $id = $this->getLBInfo( self::LB_TRX_ROUND_ID );
695 
696  return is_string( $id ) ? $id : null;
697  }
698 
699  return null;
700  }
701 
702  public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
703  if ( !$this->trxLevel() ) {
704  return false;
705  } elseif ( !$this->trxDoneWrites ) {
706  return 0.0;
707  }
708 
709  switch ( $type ) {
710  case self::ESTIMATE_DB_APPLY:
711  return $this->pingAndCalculateLastTrxApplyTime();
712  default: // everything
714  }
715  }
716 
720  private function pingAndCalculateLastTrxApplyTime() {
721  // passed by reference
722  $rtt = null;
723  $this->ping( $rtt );
724 
725  $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
726  $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
727  // For omitted queries, make them count as something at least
728  $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
729  $applyTime += self::$TINY_WRITE_SEC * $omitted;
730 
731  return $applyTime;
732  }
733 
734  public function pendingWriteCallers() {
735  return $this->trxLevel() ? $this->trxWriteCallers : [];
736  }
737 
738  public function pendingWriteRowsAffected() {
740  }
741 
750  public function pendingWriteAndCallbackCallers() {
751  $fnames = $this->pendingWriteCallers();
752  foreach ( [
753  $this->trxPostCommitOrIdleCallbacks,
754  $this->trxPreCommitOrIdleCallbacks,
755  $this->trxEndCallbacks,
756  $this->trxSectionCancelCallbacks
757  ] as $callbacks ) {
758  foreach ( $callbacks as $callback ) {
759  $fnames[] = $callback[1];
760  }
761  }
762 
763  return $fnames;
764  }
765 
769  private function flatAtomicSectionList() {
770  return array_reduce( $this->trxAtomicLevels, static function ( $accum, $v ) {
771  return $accum === null ? $v[0] : "$accum, " . $v[0];
772  } );
773  }
774 
775  public function isOpen() {
776  return (bool)$this->conn;
777  }
778 
779  public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
780  if ( $flag & ~static::$DBO_MUTABLE ) {
781  throw new DBUnexpectedError(
782  $this,
783  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
784  );
785  }
786 
787  if ( $remember === self::REMEMBER_PRIOR ) {
788  $this->priorFlags[] = $this->flags;
789  }
790 
791  $this->flags |= $flag;
792  }
793 
794  public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
795  if ( $flag & ~static::$DBO_MUTABLE ) {
796  throw new DBUnexpectedError(
797  $this,
798  "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
799  );
800  }
801 
802  if ( $remember === self::REMEMBER_PRIOR ) {
803  $this->priorFlags[] = $this->flags;
804  }
805 
806  $this->flags &= ~$flag;
807  }
808 
809  public function restoreFlags( $state = self::RESTORE_PRIOR ) {
810  if ( !$this->priorFlags ) {
811  return;
812  }
813 
814  if ( $state === self::RESTORE_INITIAL ) {
815  $this->flags = reset( $this->priorFlags );
816  $this->priorFlags = [];
817  } else {
818  $this->flags = array_pop( $this->priorFlags );
819  }
820  }
821 
822  public function getFlag( $flag ) {
823  return ( ( $this->flags & $flag ) === $flag );
824  }
825 
826  public function getDomainID() {
827  return $this->currentDomain->getId();
828  }
829 
839  abstract public function indexInfo( $table, $index, $fname = __METHOD__ );
840 
848  abstract public function strencode( $s );
849 
853  protected function installErrorHandler() {
854  $this->lastPhpError = false;
855  $this->htmlErrors = ini_set( 'html_errors', '0' );
856  set_error_handler( [ $this, 'connectionErrorLogger' ] );
857  }
858 
864  protected function restoreErrorHandler() {
865  restore_error_handler();
866  if ( $this->htmlErrors !== false ) {
867  ini_set( 'html_errors', $this->htmlErrors );
868  }
869 
870  return $this->getLastPHPError();
871  }
872 
876  protected function getLastPHPError() {
877  if ( $this->lastPhpError ) {
878  $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
879  $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
880 
881  return $error;
882  }
883 
884  return false;
885  }
886 
894  public function connectionErrorLogger( $errno, $errstr ) {
895  $this->lastPhpError = $errstr;
896  }
897 
904  protected function getLogContext( array $extras = [] ) {
905  return array_merge(
906  [
907  'db_server' => $this->server,
908  'db_name' => $this->getDBname(),
909  'db_user' => $this->user,
910  ],
911  $extras
912  );
913  }
914 
915  final public function close( $fname = __METHOD__, $owner = null ) {
916  $error = null; // error to throw after disconnecting
917 
918  $wasOpen = (bool)$this->conn;
919  // This should mostly do nothing if the connection is already closed
920  if ( $this->conn ) {
921  // Roll back any dangling transaction first
922  if ( $this->trxLevel() ) {
923  if ( $this->trxAtomicLevels ) {
924  // Cannot let incomplete atomic sections be committed
925  $levels = $this->flatAtomicSectionList();
926  $error = "$fname: atomic sections $levels are still open";
927  } elseif ( $this->trxAutomatic ) {
928  // Only the connection manager can commit non-empty DBO_TRX transactions
929  // (empty ones we can silently roll back)
930  if ( $this->writesOrCallbacksPending() ) {
931  $error = "$fname: " .
932  "expected mass rollback of all peer transactions (DBO_TRX set)";
933  }
934  } else {
935  // Manual transactions should have been committed or rolled
936  // back, even if empty.
937  $error = "$fname: transaction is still open (from {$this->trxFname})";
938  }
939 
940  if ( $this->trxEndCallbacksSuppressed && $error === null ) {
941  $error = "$fname: callbacks are suppressed; cannot properly commit";
942  }
943 
944  // Rollback the changes and run any callbacks as needed
945  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
946  }
947 
948  // Close the actual connection in the binding handle
949  $closed = $this->closeConnection();
950  } else {
951  $closed = true; // already closed; nothing to do
952  }
953 
954  $this->conn = null;
955 
956  // Log or throw any unexpected errors after having disconnected
957  if ( $error !== null ) {
958  // T217819, T231443: if this is probably just LoadBalancer trying to recover from
959  // errors and shutdown, then log any problems and move on since the request has to
960  // end one way or another. Throwing errors is not very useful at some point.
961  if ( $this->ownerId !== null && $owner === $this->ownerId ) {
962  $this->queryLogger->error( $error );
963  } else {
964  throw new DBUnexpectedError( $this, $error );
965  }
966  }
967 
968  // Note that various subclasses call close() at the start of open(), which itself is
969  // called by replaceLostConnection(). In that case, just because onTransactionResolution()
970  // callbacks are pending does not mean that an exception should be thrown. Rather, they
971  // will be executed after the reconnection step.
972  if ( $wasOpen ) {
973  // Sanity check that no callbacks are dangling
974  $fnames = $this->pendingWriteAndCallbackCallers();
975  if ( $fnames ) {
976  throw new RuntimeException(
977  "Transaction callbacks are still pending: " . implode( ', ', $fnames )
978  );
979  }
980  }
981 
982  return $closed;
983  }
984 
993  final protected function assertHasConnectionHandle() {
994  if ( !$this->isOpen() ) {
995  throw new DBUnexpectedError( $this, "DB connection was already closed" );
996  }
997  }
998 
1004  protected function assertIsWritableMaster() {
1005  $info = $this->getReadOnlyReason();
1006  if ( $info ) {
1007  list( $reason, $source ) = $info;
1008  if ( $source === 'role' ) {
1009  throw new DBReadOnlyRoleError( $this, "Database is read-only: $reason" );
1010  } else {
1011  throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1012  }
1013  }
1014  }
1015 
1021  abstract protected function closeConnection();
1022 
1052  abstract protected function doQuery( $sql );
1053 
1071  protected function isWriteQuery( $sql, $flags ) {
1072  if (
1073  $this->fieldHasBit( $flags, self::QUERY_CHANGE_ROWS ) ||
1074  $this->fieldHasBit( $flags, self::QUERY_CHANGE_SCHEMA )
1075  ) {
1076  return true;
1077  } elseif ( $this->fieldHasBit( $flags, self::QUERY_CHANGE_NONE ) ) {
1078  return false;
1079  }
1080  // BEGIN and COMMIT queries are considered read queries here.
1081  // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1082  // treat these as write queries, in that their results have "affected rows"
1083  // as meta data as from writes, instead of "num rows" as from reads.
1084  // But, we treat them as read queries because when reading data (from
1085  // either replica or master) we use transactions to enable repeatable-read
1086  // snapshots, which ensures we get consistent results from the same snapshot
1087  // for all queries within a request. Use cases:
1088  // - Treating these as writes would trigger ChronologyProtector (see method doc).
1089  // - We use this method to reject writes to replicas, but we need to allow
1090  // use of transactions on replicas for read snapshots. This is fine given
1091  // that transactions by themselves don't make changes, only actual writes
1092  // within the transaction matter, which we still detect.
1093  return !preg_match(
1094  '/^\s*(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\‍(SELECT)\b/i',
1095  $sql
1096  );
1097  }
1098 
1103  protected function getQueryVerb( $sql ) {
1104  return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
1105  }
1106 
1121  protected function isTransactableQuery( $sql ) {
1122  return !in_array(
1123  $this->getQueryVerb( $sql ),
1124  [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1125  true
1126  );
1127  }
1128 
1137  protected function getTempTableWrites( $sql, $pseudoPermanent ) {
1138  // Regexes for basic queries that can create/change/drop temporary tables.
1139  // For simplicity, this only looks for tables with sane, alphanumeric, names;
1140  // temporary tables only need simple programming names anyway.
1141  static $regexes = null;
1142  if ( $regexes === null ) {
1143  // Regex with a group for quoted table 0 and a group for quoted tables 1..N
1144  $qts = '((?:\w+|`\w+`|\'\w+\'|"\w+")(?:\s*,\s*(?:\w+|`\w+`|\'\w+\'|"\w+"))*)';
1145  // Regex to get query verb, table 0, and tables 1..N
1146  $regexes = [
1147  // DML write queries
1148  "/^(INSERT|REPLACE)\s+(?:\w+\s+)*?INTO\s+$qts/i",
1149  "/^(UPDATE)(?:\s+OR\s+\w+|\s+IGNORE|\s+ONLY)?\s+$qts/i",
1150  "/^(DELETE)\s+(?:\w+\s+)*?FROM(?:\s+ONLY)?\s+$qts/i",
1151  // DDL write queries
1152  "/^(CREATE)\s+TEMPORARY\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+$qts/i",
1153  "/^(DROP)\s+(?:TEMPORARY\s+)?TABLE(?:\s+IF\s+EXISTS)?\s+$qts/i",
1154  "/^(TRUNCATE)\s+(?:TEMPORARY\s+)?TABLE\s+$qts/i",
1155  "/^(ALTER)\s+TABLE\s+$qts/i"
1156  ];
1157  }
1158 
1159  $queryVerb = null;
1160  $queryTables = [];
1161  foreach ( $regexes as $regex ) {
1162  if ( preg_match( $regex, $sql, $m, PREG_UNMATCHED_AS_NULL ) ) {
1163  $queryVerb = $m[1];
1164  $allTables = preg_split( '/\s*,\s*/', $m[2] );
1165  foreach ( $allTables as $quotedTable ) {
1166  $queryTables[] = trim( $quotedTable, "\"'`" );
1167  }
1168  break;
1169  }
1170  }
1171 
1172  $tempTableChanges = [];
1173  foreach ( $queryTables as $table ) {
1174  if ( $queryVerb === 'CREATE' ) {
1175  // Record the type of temporary table being created
1176  $tableType = $pseudoPermanent ? self::$TEMP_PSEUDO_PERMANENT : self::$TEMP_NORMAL;
1177  } else {
1178  $tableType = $this->sessionTempTables[$table] ?? null;
1179  }
1180 
1181  if ( $tableType !== null ) {
1182  $tempTableChanges[] = [ $tableType, $queryVerb, $table ];
1183  }
1184  }
1185 
1186  return $tempTableChanges;
1187  }
1188 
1193  protected function registerTempWrites( $ret, array $changes ) {
1194  if ( $ret === false ) {
1195  return;
1196  }
1197 
1198  foreach ( $changes as list( $tmpTableType, $verb, $table ) ) {
1199  switch ( $verb ) {
1200  case 'CREATE':
1201  $this->sessionTempTables[$table] = $tmpTableType;
1202  break;
1203  case 'DROP':
1204  unset( $this->sessionTempTables[$table] );
1205  unset( $this->sessionDirtyTempTables[$table] );
1206  break;
1207  case 'TRUNCATE':
1208  unset( $this->sessionDirtyTempTables[$table] );
1209  break;
1210  default:
1211  $this->sessionDirtyTempTables[$table] = 1;
1212  break;
1213  }
1214  }
1215  }
1216 
1224  protected function isPristineTemporaryTable( $table ) {
1225  $rawTable = $this->tableName( $table, 'raw' );
1226 
1227  return (
1228  isset( $this->sessionTempTables[$rawTable] ) &&
1229  !isset( $this->sessionDirtyTempTables[$rawTable] )
1230  );
1231  }
1232 
1233  public function query( $sql, $fname = __METHOD__, $flags = self::QUERY_NORMAL ) {
1234  $flags = (int)$flags; // b/c; this field used to be a bool
1235  // Sanity check that the SQL query is appropriate in the current context and is
1236  // allowed for an outside caller (e.g. does not break transaction/session tracking).
1237  $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1238 
1239  // Send the query to the server and fetch any corresponding errors
1240  list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1241  if ( $ret === false ) {
1242  $ignoreErrors = $this->fieldHasBit( $flags, self::QUERY_SILENCE_ERRORS );
1243  // Throw an error unless both the ignore flag was set and a rollback is not needed
1244  $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1245  }
1246 
1247  return $this->resultObject( $ret );
1248  }
1249 
1270  final protected function executeQuery( $sql, $fname, $flags ) {
1271  $this->assertHasConnectionHandle();
1272 
1273  $priorTransaction = $this->trxLevel();
1274 
1275  if ( $this->isWriteQuery( $sql, $flags ) ) {
1276  // Do not treat temporary table writes as "meaningful writes" since they are only
1277  // visible to one session and are not permanent. Profile them as reads. Integration
1278  // tests can override this behavior via $flags.
1279  $pseudoPermanent = $this->fieldHasBit( $flags, self::QUERY_PSEUDO_PERMANENT );
1280  $tempTableChanges = $this->getTempTableWrites( $sql, $pseudoPermanent );
1281  $isPermWrite = !$tempTableChanges;
1282  foreach ( $tempTableChanges as list( $tmpType ) ) {
1283  $isPermWrite = $isPermWrite || ( $tmpType !== self::$TEMP_NORMAL );
1284  }
1285 
1286  // Permit temporary table writes on replica DB connections
1287  // but require a writable master connection for any persistent writes.
1288  if ( $isPermWrite ) {
1289  $this->assertIsWritableMaster();
1290 
1291  // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1292  if ( $this->fieldHasBit( $flags, self::QUERY_REPLICA_ROLE ) ) {
1293  throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1294  }
1295  }
1296  } else {
1297  // No permanent writes in this query
1298  $isPermWrite = false;
1299  // No temporary tables written to either
1300  $tempTableChanges = [];
1301  }
1302 
1303  // Add trace comment to the begin of the sql string, right after the operator.
1304  // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
1305  $encAgent = str_replace( '/', '-', $this->agent );
1306  $commentedSql = preg_replace( '/\s|$/', " /* $fname $encAgent */ ", $sql, 1 );
1307 
1308  // Send the query to the server and fetch any corresponding errors.
1309  // This also doubles as a "ping" to see if the connection was dropped.
1310  list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1311  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1312 
1313  // Check if the query failed due to a recoverable connection loss
1314  $allowRetry = !$this->fieldHasBit( $flags, self::QUERY_NO_RETRY );
1315  if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1316  // Silently resend the query to the server since it is safe and possible
1317  list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1318  $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1319  }
1320 
1321  // Register creation and dropping of temporary tables
1322  $this->registerTempWrites( $ret, $tempTableChanges );
1323 
1324  $corruptedTrx = false;
1325 
1326  if ( $ret === false ) {
1327  if ( $priorTransaction ) {
1328  if ( $recoverableSR ) {
1329  # We're ignoring an error that caused just the current query to be aborted.
1330  # But log the cause so we can log a deprecation notice if a caller actually
1331  # does ignore it.
1332  $this->trxStatusIgnoredCause = [ $err, $errno, $fname ];
1333  } elseif ( !$recoverableCL ) {
1334  # Either the query was aborted or all queries after BEGIN where aborted.
1335  # In the first case, the only options going forward are (a) ROLLBACK, or
1336  # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1337  # option is ROLLBACK, since the snapshots would have been released.
1338  $corruptedTrx = true; // cannot recover
1339  $this->trxStatus = self::STATUS_TRX_ERROR;
1340  $this->trxStatusCause = $this->getQueryException( $err, $errno, $sql, $fname );
1341  $this->trxStatusIgnoredCause = null;
1342  }
1343  }
1344  }
1345 
1346  return [ $ret, $err, $errno, $corruptedTrx ];
1347  }
1348 
1367  private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1368  $priorWritesPending = $this->writesOrCallbacksPending();
1369 
1370  if ( ( $flags & self::QUERY_IGNORE_DBO_TRX ) == 0 ) {
1371  $this->beginIfImplied( $sql, $fname );
1372  }
1373 
1374  // Keep track of whether the transaction has write queries pending
1375  if ( $isPermWrite ) {
1376  $this->lastWriteTime = microtime( true );
1377  if ( $this->trxLevel() && !$this->trxDoneWrites ) {
1378  $this->trxDoneWrites = true;
1379  $this->trxProfiler->transactionWritingIn(
1380  $this->getServer(),
1381  $this->getDomainID(),
1382  $this->trxShortId
1383  );
1384  }
1385  }
1386 
1387  $prefix = $this->topologyRole ? 'query-m: ' : 'query: ';
1388  $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId, $prefix );
1389 
1390  $startTime = microtime( true );
1391  $ps = $this->profiler
1392  ? ( $this->profiler )( $generalizedSql->stringify() )
1393  : null;
1394  $this->affectedRowCount = null;
1395  $this->lastQuery = $sql;
1396  $ret = $this->doQuery( $commentedSql );
1397  $lastError = $this->lastError();
1398  $lastErrno = $this->lastErrno();
1399 
1400  $this->affectedRowCount = $this->affectedRows();
1401  unset( $ps ); // profile out (if set)
1402  $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1403 
1404  $recoverableSR = false; // recoverable statement rollback?
1405  $recoverableCL = false; // recoverable connection loss?
1406  $reconnected = false; // reconnection both attempted and succeeded?
1407 
1408  if ( $ret !== false ) {
1409  $this->lastPing = $startTime;
1410  if ( $isPermWrite && $this->trxLevel() ) {
1411  $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1412  $this->trxWriteCallers[] = $fname;
1413  }
1414  } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1415  # Check if no meaningful session state was lost
1416  $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1417  # Update session state tracking and try to restore the connection
1418  $reconnected = $this->replaceLostConnection( __METHOD__ );
1419  } else {
1420  # Check if only the last query was rolled back
1421  $recoverableSR = $this->wasKnownStatementRollbackError();
1422  }
1423 
1424  if ( $sql === self::$PING_QUERY ) {
1425  $this->lastRoundTripEstimate = $queryRuntime;
1426  }
1427 
1428  $this->trxProfiler->recordQueryCompletion(
1429  $generalizedSql,
1430  $startTime,
1431  $isPermWrite,
1432  $isPermWrite ? $this->affectedRows() : $this->numRows( $ret )
1433  );
1434 
1435  // Avoid the overhead of logging calls unless debug mode is enabled
1436  if ( $this->getFlag( self::DBO_DEBUG ) ) {
1437  $this->queryLogger->debug(
1438  "{method} [{runtime}s] {db_host}: {sql}",
1439  [
1440  'method' => $fname,
1441  'db_host' => $this->getServer(),
1442  'sql' => $sql,
1443  'domain' => $this->getDomainID(),
1444  'runtime' => round( $queryRuntime, 3 )
1445  ]
1446  );
1447  }
1448 
1449  return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1450  }
1451 
1458  private function beginIfImplied( $sql, $fname ) {
1459  if (
1460  !$this->trxLevel() &&
1461  $this->getFlag( self::DBO_TRX ) &&
1462  $this->isTransactableQuery( $sql )
1463  ) {
1464  $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1465  $this->trxAutomatic = true;
1466  }
1467  }
1468 
1481  private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1482  // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1483  $indicativeOfReplicaRuntime = true;
1484  if ( $runtime > self::$SLOW_WRITE_SEC ) {
1485  $verb = $this->getQueryVerb( $sql );
1486  // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1487  if ( $verb === 'INSERT' ) {
1488  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS;
1489  } elseif ( $verb === 'REPLACE' ) {
1490  $indicativeOfReplicaRuntime = $this->affectedRows() > self::$SMALL_WRITE_ROWS / 2;
1491  }
1492  }
1493 
1494  $this->trxWriteDuration += $runtime;
1495  $this->trxWriteQueryCount += 1;
1496  $this->trxWriteAffectedRows += $affected;
1497  if ( $indicativeOfReplicaRuntime ) {
1498  $this->trxWriteAdjDuration += $runtime;
1499  $this->trxWriteAdjQueryCount += 1;
1500  }
1501  }
1502 
1510  private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1511  $verb = $this->getQueryVerb( $sql );
1512  if ( $verb === 'USE' ) {
1513  throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1514  }
1515 
1516  if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1517  return;
1518  }
1519 
1520  if ( $this->trxStatus < self::STATUS_TRX_OK ) {
1521  throw new DBTransactionStateError(
1522  $this,
1523  "Cannot execute query from $fname while transaction status is ERROR",
1524  [],
1525  $this->trxStatusCause
1526  );
1527  } elseif ( $this->trxStatus === self::STATUS_TRX_OK && $this->trxStatusIgnoredCause ) {
1528  list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause;
1529  call_user_func( $this->deprecationLogger,
1530  "Caller from $fname ignored an error originally raised from $iFname: " .
1531  "[$iLastErrno] $iLastError"
1532  );
1533  $this->trxStatusIgnoredCause = null;
1534  }
1535  }
1536 
1537  public function assertNoOpenTransactions() {
1538  if ( $this->explicitTrxActive() ) {
1539  throw new DBTransactionError(
1540  $this,
1541  "Explicit transaction still active. A caller may have caught an error. "
1542  . "Open transactions: " . $this->flatAtomicSectionList()
1543  );
1544  }
1545  }
1546 
1556  private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1557  # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1558  # Dropped connections also mean that named locks are automatically released.
1559  # Only allow error suppression in autocommit mode or when the lost transaction
1560  # didn't matter anyway (aside from DBO_TRX snapshot loss).
1561  if ( $this->sessionNamedLocks ) {
1562  return false; // possible critical section violation
1563  } elseif ( $this->sessionTempTables ) {
1564  return false; // tables might be queried latter
1565  } elseif ( $sql === 'COMMIT' ) {
1566  return !$priorWritesPending; // nothing written anyway? (T127428)
1567  } elseif ( $sql === 'ROLLBACK' ) {
1568  return true; // transaction lost...which is also what was requested :)
1569  } elseif ( $this->explicitTrxActive() ) {
1570  return false; // don't drop atomicity and explicit snapshots
1571  } elseif ( $priorWritesPending ) {
1572  return false; // prior writes lost from implicit transaction
1573  }
1574 
1575  return true;
1576  }
1577 
1581  private function handleSessionLossPreconnect() {
1582  // Clean up tracking of session-level things...
1583  // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1584  // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1585  $this->sessionTempTables = [];
1586  $this->sessionDirtyTempTables = [];
1587  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1588  // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1589  $this->sessionNamedLocks = [];
1590  // Session loss implies transaction loss
1591  $oldTrxShortId = $this->consumeTrxShortId();
1592  $this->trxAtomicCounter = 0;
1593  $this->trxPostCommitOrIdleCallbacks = []; // T67263; transaction already lost
1594  $this->trxPreCommitOrIdleCallbacks = []; // T67263; transaction already lost
1595  // Clear additional subclass fields
1597  // @note: leave trxRecurringCallbacks in place
1598  if ( $this->trxDoneWrites ) {
1599  $this->trxProfiler->transactionWritingOut(
1600  $this->getServer(),
1601  $this->getDomainID(),
1602  $oldTrxShortId,
1603  $this->pendingWriteQueryDuration( self::ESTIMATE_TOTAL ),
1604  $this->trxWriteAffectedRows
1605  );
1606  }
1607  }
1608 
1613  protected function doHandleSessionLossPreconnect() {
1614  // no-op
1615  }
1616 
1620  private function handleSessionLossPostconnect() {
1621  try {
1622  // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1623  // If callback suppression is set then the array will remain unhandled.
1624  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1625  } catch ( Throwable $ex ) {
1626  // Already logged; move on...
1627  }
1628  try {
1629  // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1630  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1631  } catch ( Throwable $ex ) {
1632  // Already logged; move on...
1633  }
1634  }
1635 
1641  private function consumeTrxShortId() {
1642  $old = $this->trxShortId;
1643  $this->trxShortId = '';
1644 
1645  return $old;
1646  }
1647 
1659  protected function wasQueryTimeout( $error, $errno ) {
1660  return false;
1661  }
1662 
1674  public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1675  if ( $ignore ) {
1676  $this->queryLogger->debug( "SQL ERROR (ignored): $error" );
1677  } else {
1678  throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1679  }
1680  }
1681 
1689  private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1690  // Information that instances of the same problem have in common should
1691  // not be normalized (T255202).
1692  $this->queryLogger->error(
1693  "Error $errno from $fname, {error} {sql1line} {db_server}",
1694  $this->getLogContext( [
1695  'method' => __METHOD__,
1696  'errno' => $errno,
1697  'error' => $error,
1698  'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1699  'fname' => $fname,
1700  'exception' => new RuntimeException()
1701  ] )
1702  );
1703  return $this->getQueryException( $error, $errno, $sql, $fname );
1704  }
1705 
1713  private function getQueryException( $error, $errno, $sql, $fname ) {
1714  if ( $this->wasQueryTimeout( $error, $errno ) ) {
1715  return new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1716  } elseif ( $this->wasConnectionError( $errno ) ) {
1717  return new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1718  } else {
1719  return new DBQueryError( $this, $error, $errno, $sql, $fname );
1720  }
1721  }
1722 
1727  final protected function newExceptionAfterConnectError( $error ) {
1728  // Connection was not fully initialized and is not safe for use
1729  $this->conn = null;
1730 
1731  $this->connLogger->error(
1732  "Error connecting to {db_server} as user {db_user}: {error}",
1733  $this->getLogContext( [
1734  'error' => $error,
1735  'exception' => new RuntimeException()
1736  ] )
1737  );
1738 
1739  return new DBConnectionError( $this, $error );
1740  }
1741 
1746  public function freeResult( $res ) {
1747  }
1748 
1752  public function newSelectQueryBuilder() {
1753  return new SelectQueryBuilder( $this );
1754  }
1755 
1756  public function selectField(
1757  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1758  ) {
1759  if ( $var === '*' ) { // sanity
1760  throw new DBUnexpectedError( $this, "Cannot use a * field" );
1761  } elseif ( is_array( $var ) && count( $var ) !== 1 ) {
1762  throw new DBUnexpectedError( $this, 'Cannot use more than one field' );
1763  }
1764 
1765  $options = $this->normalizeOptions( $options );
1766  $options['LIMIT'] = 1;
1767 
1768  $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1769  if ( $res === false ) {
1770  throw new DBUnexpectedError( $this, "Got false from select()" );
1771  }
1772 
1773  $row = $this->fetchRow( $res );
1774  if ( $row === false ) {
1775  return false;
1776  }
1777 
1778  return reset( $row );
1779  }
1780 
1781  public function selectFieldValues(
1782  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1783  ) {
1784  if ( $var === '*' ) { // sanity
1785  throw new DBUnexpectedError( $this, "Cannot use a * field" );
1786  } elseif ( !is_string( $var ) ) { // sanity
1787  throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1788  }
1789 
1790  $options = $this->normalizeOptions( $options );
1791  $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1792  if ( $res === false ) {
1793  throw new DBUnexpectedError( $this, "Got false from select()" );
1794  }
1795 
1796  $values = [];
1797  foreach ( $res as $row ) {
1798  $values[] = $row->value;
1799  }
1800 
1801  return $values;
1802  }
1803 
1815  protected function makeSelectOptions( array $options ) {
1816  $preLimitTail = $postLimitTail = '';
1817  $startOpts = '';
1818 
1819  $noKeyOptions = [];
1820 
1821  foreach ( $options as $key => $option ) {
1822  if ( is_numeric( $key ) ) {
1823  $noKeyOptions[$option] = true;
1824  }
1825  }
1826 
1827  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1828 
1829  $preLimitTail .= $this->makeOrderBy( $options );
1830 
1831  if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1832  $postLimitTail .= ' FOR UPDATE';
1833  }
1834 
1835  if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1836  $postLimitTail .= ' LOCK IN SHARE MODE';
1837  }
1838 
1839  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1840  $startOpts .= 'DISTINCT';
1841  }
1842 
1843  # Various MySQL extensions
1844  if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1845  $startOpts .= ' /*! STRAIGHT_JOIN */';
1846  }
1847 
1848  if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1849  $startOpts .= ' SQL_BIG_RESULT';
1850  }
1851 
1852  if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1853  $startOpts .= ' SQL_BUFFER_RESULT';
1854  }
1855 
1856  if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1857  $startOpts .= ' SQL_SMALL_RESULT';
1858  }
1859 
1860  if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1861  $startOpts .= ' SQL_CALC_FOUND_ROWS';
1862  }
1863 
1864  if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1865  $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1866  } else {
1867  $useIndex = '';
1868  }
1869  if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1870  $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1871  } else {
1872  $ignoreIndex = '';
1873  }
1874 
1875  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1876  }
1877 
1886  protected function makeGroupByWithHaving( $options ) {
1887  $sql = '';
1888  if ( isset( $options['GROUP BY'] ) ) {
1889  $gb = is_array( $options['GROUP BY'] )
1890  ? implode( ',', $options['GROUP BY'] )
1891  : $options['GROUP BY'];
1892  $sql .= ' GROUP BY ' . $gb;
1893  }
1894  if ( isset( $options['HAVING'] ) ) {
1895  $having = is_array( $options['HAVING'] )
1896  ? $this->makeList( $options['HAVING'], self::LIST_AND )
1897  : $options['HAVING'];
1898  $sql .= ' HAVING ' . $having;
1899  }
1900 
1901  return $sql;
1902  }
1903 
1912  protected function makeOrderBy( $options ) {
1913  if ( isset( $options['ORDER BY'] ) ) {
1914  $ob = is_array( $options['ORDER BY'] )
1915  ? implode( ',', $options['ORDER BY'] )
1916  : $options['ORDER BY'];
1917 
1918  return ' ORDER BY ' . $ob;
1919  }
1920 
1921  return '';
1922  }
1923 
1924  public function select(
1925  $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1926  ) {
1927  $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1928 
1929  return $this->query( $sql, $fname, self::QUERY_CHANGE_NONE );
1930  }
1931 
1936  public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1937  $options = [], $join_conds = []
1938  ) {
1939  if ( is_array( $vars ) ) {
1940  $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1941  } else {
1942  $fields = $vars;
1943  }
1944 
1945  $options = (array)$options;
1946  $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1947  ? $options['USE INDEX']
1948  : [];
1949  $ignoreIndexes = (
1950  isset( $options['IGNORE INDEX'] ) &&
1951  is_array( $options['IGNORE INDEX'] )
1952  )
1953  ? $options['IGNORE INDEX']
1954  : [];
1955 
1956  if (
1957  $this->selectOptionsIncludeLocking( $options ) &&
1958  $this->selectFieldsOrOptionsAggregate( $vars, $options )
1959  ) {
1960  // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
1961  // functions. Discourage use of such queries to encourage compatibility.
1962  call_user_func(
1963  $this->deprecationLogger,
1964  __METHOD__ . ": aggregation used with a locking SELECT ($fname)"
1965  );
1966  }
1967 
1968  if ( is_array( $table ) ) {
1969  if ( count( $table ) === 0 ) {
1970  $from = '';
1971  } else {
1972  $from = ' FROM ' .
1974  $table, $useIndexes, $ignoreIndexes, $join_conds );
1975  }
1976  } elseif ( $table != '' ) {
1977  $from = ' FROM ' .
1979  [ $table ], $useIndexes, $ignoreIndexes, [] );
1980  } else {
1981  $from = '';
1982  }
1983 
1984  list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1985  $this->makeSelectOptions( $options );
1986 
1987  if ( is_array( $conds ) ) {
1988  $conds = $this->makeList( $conds, self::LIST_AND );
1989  }
1990 
1991  if ( $conds === null || $conds === false ) {
1992  $this->queryLogger->warning(
1993  __METHOD__
1994  . ' called from '
1995  . $fname
1996  . ' with incorrect parameters: $conds must be a string or an array'
1997  );
1998  $conds = '';
1999  }
2000 
2001  if ( $conds === '' || $conds === '*' ) {
2002  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
2003  } elseif ( is_string( $conds ) ) {
2004  $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
2005  "WHERE $conds $preLimitTail";
2006  } else {
2007  throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
2008  }
2009 
2010  if ( isset( $options['LIMIT'] ) ) {
2011  $sql = $this->limitResult( $sql, $options['LIMIT'],
2012  $options['OFFSET'] ?? false );
2013  }
2014  $sql = "$sql $postLimitTail";
2015 
2016  if ( isset( $options['EXPLAIN'] ) ) {
2017  $sql = 'EXPLAIN ' . $sql;
2018  }
2019 
2020  return $sql;
2021  }
2022 
2023  public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
2024  $options = [], $join_conds = []
2025  ) {
2026  $options = (array)$options;
2027  $options['LIMIT'] = 1;
2028 
2029  $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
2030  if ( $res === false ) {
2031  throw new DBUnexpectedError( $this, "Got false from select()" );
2032  }
2033 
2034  if ( !$this->numRows( $res ) ) {
2035  return false;
2036  }
2037 
2038  return $this->fetchObject( $res );
2039  }
2040 
2045  public function estimateRowCount(
2046  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2047  ) {
2048  $conds = $this->normalizeConditions( $conds, $fname );
2049  $column = $this->extractSingleFieldFromList( $var );
2050  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
2051  $conds[] = "$column IS NOT NULL";
2052  }
2053 
2054  $res = $this->select(
2055  $tables, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
2056  );
2057  $row = $res ? $this->fetchRow( $res ) : [];
2058 
2059  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
2060  }
2061 
2062  public function selectRowCount(
2063  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2064  ) {
2065  $conds = $this->normalizeConditions( $conds, $fname );
2066  $column = $this->extractSingleFieldFromList( $var );
2067  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
2068  $conds[] = "$column IS NOT NULL";
2069  }
2070 
2071  $res = $this->select(
2072  [
2073  'tmp_count' => $this->buildSelectSubquery(
2074  $tables,
2075  '1',
2076  $conds,
2077  $fname,
2078  $options,
2079  $join_conds
2080  )
2081  ],
2082  [ 'rowcount' => 'COUNT(*)' ],
2083  [],
2084  $fname
2085  );
2086  $row = $res ? $this->fetchRow( $res ) : [];
2087 
2088  return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
2089  }
2090 
2095  private function selectOptionsIncludeLocking( $options ) {
2096  $options = (array)$options;
2097  foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
2098  if ( in_array( $lock, $options, true ) ) {
2099  return true;
2100  }
2101  }
2102 
2103  return false;
2104  }
2105 
2111  private function selectFieldsOrOptionsAggregate( $fields, $options ) {
2112  foreach ( (array)$options as $key => $value ) {
2113  if ( is_string( $key ) ) {
2114  if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
2115  return true;
2116  }
2117  } elseif ( is_string( $value ) ) {
2118  if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
2119  return true;
2120  }
2121  }
2122  }
2123 
2124  $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
2125  foreach ( (array)$fields as $field ) {
2126  if ( is_string( $field ) && preg_match( $regex, $field ) ) {
2127  return true;
2128  }
2129  }
2130 
2131  return false;
2132  }
2133 
2139  final protected function normalizeRowArray( array $rowOrRows ) {
2140  if ( !$rowOrRows ) {
2141  $rows = [];
2142  } elseif ( isset( $rowOrRows[0] ) ) {
2143  $rows = $rowOrRows;
2144  } else {
2145  $rows = [ $rowOrRows ];
2146  }
2147 
2148  foreach ( $rows as $row ) {
2149  if ( !is_array( $row ) ) {
2150  throw new DBUnexpectedError( $this, "Got non-array in row array" );
2151  } elseif ( !$row ) {
2152  throw new DBUnexpectedError( $this, "Got empty array in row array" );
2153  }
2154  }
2155 
2156  return $rows;
2157  }
2158 
2165  final protected function normalizeConditions( $conds, $fname ) {
2166  if ( $conds === null || $conds === false ) {
2167  $this->queryLogger->warning(
2168  __METHOD__
2169  . ' called from '
2170  . $fname
2171  . ' with incorrect parameters: $conds must be a string or an array'
2172  );
2173  return [];
2174  } elseif ( $conds === '' ) {
2175  return [];
2176  }
2177 
2178  return is_array( $conds ) ? $conds : [ $conds ];
2179  }
2180 
2186  final protected function normalizeUpsertKeys( $uniqueKeys ) {
2187  if ( is_string( $uniqueKeys ) ) {
2188  return [ [ $uniqueKeys ] ];
2189  }
2190 
2191  if ( !is_array( $uniqueKeys ) || !$uniqueKeys ) {
2192  throw new DBUnexpectedError( $this, 'Invalid or empty unique key array' );
2193  }
2194 
2195  $oldStyle = false;
2196  $uniqueColumnSets = [];
2197  foreach ( $uniqueKeys as $i => $uniqueKey ) {
2198  if ( !is_int( $i ) ) {
2199  throw new DBUnexpectedError( $this, 'Unique key array should be a list' );
2200  } elseif ( is_string( $uniqueKey ) ) {
2201  $oldStyle = true;
2202  $uniqueColumnSets[] = [ $uniqueKey ];
2203  } elseif ( is_array( $uniqueKey ) && $uniqueKey ) {
2204  $uniqueColumnSets[] = $uniqueKey;
2205  } else {
2206  throw new DBUnexpectedError( $this, 'Invalid unique key array entry' );
2207  }
2208  }
2209 
2210  if ( count( $uniqueColumnSets ) > 1 ) {
2211  // If an existing row conflicts with new row X on key A and new row Y on key B,
2212  // it is not well defined how many UPDATEs should apply to the existing row and
2213  // in what order the new rows are checked
2214  $this->queryLogger->warning(
2215  __METHOD__ . " called with multiple unique keys",
2216  [ 'exception' => new RuntimeException() ]
2217  );
2218  }
2219 
2220  if ( $oldStyle ) {
2221  // Passing a list of strings for single-column unique keys is too
2222  // easily confused with passing the columns of composite unique key
2223  $this->queryLogger->warning(
2224  __METHOD__ . " called with deprecated parameter style: " .
2225  "the unique key array should be a string or array of string arrays",
2226  [ 'exception' => new RuntimeException() ]
2227  );
2228  }
2229 
2230  return $uniqueColumnSets;
2231  }
2232 
2238  final protected function normalizeOptions( $options ) {
2239  if ( is_array( $options ) ) {
2240  return $options;
2241  } elseif ( is_string( $options ) ) {
2242  return ( $options === '' ) ? [] : [ $options ];
2243  } else {
2244  throw new DBUnexpectedError( $this, __METHOD__ . ': expected string or array' );
2245  }
2246  }
2247 
2254  final protected function isFlagInOptions( $option, array $options ) {
2255  foreach ( array_keys( $options, $option, true ) as $k ) {
2256  if ( is_int( $k ) ) {
2257  return true;
2258  }
2259  }
2260 
2261  return false;
2262  }
2263 
2268  final protected function extractSingleFieldFromList( $var ) {
2269  if ( is_array( $var ) ) {
2270  if ( !$var ) {
2271  $column = null;
2272  } elseif ( count( $var ) == 1 ) {
2273  $column = $var[0] ?? reset( $var );
2274  } else {
2275  throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns' );
2276  }
2277  } else {
2278  $column = $var;
2279  }
2280 
2281  return $column;
2282  }
2283 
2284  public function lockForUpdate(
2285  $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
2286  ) {
2287  if ( !$this->trxLevel() && !$this->getFlag( self::DBO_TRX ) ) {
2288  throw new DBUnexpectedError(
2289  $this,
2290  __METHOD__ . ': no transaction is active nor is DBO_TRX set'
2291  );
2292  }
2293 
2294  $options = (array)$options;
2295  $options[] = 'FOR UPDATE';
2296 
2297  return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2298  }
2299 
2300  public function fieldExists( $table, $field, $fname = __METHOD__ ) {
2301  $info = $this->fieldInfo( $table, $field );
2302 
2303  return (bool)$info;
2304  }
2305 
2306  public function indexExists( $table, $index, $fname = __METHOD__ ) {
2307  if ( !$this->tableExists( $table, $fname ) ) {
2308  return null;
2309  }
2310 
2311  $info = $this->indexInfo( $table, $index, $fname );
2312  if ( $info === null ) {
2313  return null;
2314  } else {
2315  return $info !== false;
2316  }
2317  }
2318 
2319  abstract public function tableExists( $table, $fname = __METHOD__ );
2320 
2325  public function indexUnique( $table, $index, $fname = __METHOD__ ) {
2326  $indexInfo = $this->indexInfo( $table, $index, $fname );
2327 
2328  if ( !$indexInfo ) {
2329  return null;
2330  }
2331 
2332  return !$indexInfo[0]->Non_unique;
2333  }
2334 
2335  public function insert( $table, $rows, $fname = __METHOD__, $options = [] ) {
2336  $rows = $this->normalizeRowArray( $rows );
2337  if ( !$rows ) {
2338  return true;
2339  }
2340 
2341  $options = $this->normalizeOptions( $options );
2342  if ( $this->isFlagInOptions( 'IGNORE', $options ) ) {
2343  $this->doInsertNonConflicting( $table, $rows, $fname );
2344  } else {
2345  $this->doInsert( $table, $rows, $fname );
2346  }
2347 
2348  return true;
2349  }
2350 
2359  protected function doInsert( $table, array $rows, $fname ) {
2360  $encTable = $this->tableName( $table );
2361  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
2362 
2363  $sql = "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples";
2364 
2365  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2366  }
2367 
2376  protected function doInsertNonConflicting( $table, array $rows, $fname ) {
2377  $encTable = $this->tableName( $table );
2378  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
2379  list( $sqlVerb, $sqlOpts ) = $this->makeInsertNonConflictingVerbAndOptions();
2380 
2381  $sql = rtrim( "$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" );
2382 
2383  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2384  }
2385 
2392  return [ 'INSERT IGNORE INTO', '' ];
2393  }
2394 
2405  protected function makeInsertLists( array $rows ) {
2406  $firstRow = $rows[0];
2407  if ( !is_array( $firstRow ) || !$firstRow ) {
2408  throw new DBUnexpectedError( $this, 'Got an empty row list or empty row' );
2409  }
2410  // List of columns that define the value tuple ordering
2411  $tupleColumns = array_keys( $firstRow );
2412 
2413  $valueTuples = [];
2414  foreach ( $rows as $row ) {
2415  $rowColumns = array_keys( $row );
2416  // VALUES(...) requires a uniform correspondance of (column => value)
2417  if ( $rowColumns !== $tupleColumns ) {
2418  throw new DBUnexpectedError(
2419  $this,
2420  'Got row columns (' . implode( ', ', $rowColumns ) . ') ' .
2421  'instead of expected (' . implode( ', ', $tupleColumns ) . ')'
2422  );
2423  }
2424  // Make the value tuple that defines this row
2425  $valueTuples[] = '(' . $this->makeList( $row, self::LIST_COMMA ) . ')';
2426  }
2427 
2428  return [
2429  $this->makeList( $tupleColumns, self::LIST_NAMES ),
2430  implode( ',', $valueTuples )
2431  ];
2432  }
2433 
2441  protected function makeUpdateOptionsArray( $options ) {
2442  $options = $this->normalizeOptions( $options );
2443 
2444  $opts = [];
2445 
2446  if ( in_array( 'IGNORE', $options ) ) {
2447  $opts[] = 'IGNORE';
2448  }
2449 
2450  return $opts;
2451  }
2452 
2460  protected function makeUpdateOptions( $options ) {
2461  $opts = $this->makeUpdateOptionsArray( $options );
2462 
2463  return implode( ' ', $opts );
2464  }
2465 
2466  public function update( $table, $set, $conds, $fname = __METHOD__, $options = [] ) {
2467  $this->assertConditionIsNotEmpty( $conds, __METHOD__, true );
2468  $table = $this->tableName( $table );
2469  $opts = $this->makeUpdateOptions( $options );
2470  $sql = "UPDATE $opts $table SET " . $this->makeList( $set, self::LIST_SET );
2471 
2472  if ( $conds && $conds !== IDatabase::ALL_ROWS ) {
2473  if ( is_array( $conds ) ) {
2474  $conds = $this->makeList( $conds, self::LIST_AND );
2475  }
2476  $sql .= ' WHERE ' . $conds;
2477  }
2478 
2479  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
2480 
2481  return true;
2482  }
2483 
2484  public function makeList( array $a, $mode = self::LIST_COMMA ) {
2485  $first = true;
2486  $list = '';
2487 
2488  foreach ( $a as $field => $value ) {
2489  if ( $first ) {
2490  $first = false;
2491  } else {
2492  if ( $mode == self::LIST_AND ) {
2493  $list .= ' AND ';
2494  } elseif ( $mode == self::LIST_OR ) {
2495  $list .= ' OR ';
2496  } else {
2497  $list .= ',';
2498  }
2499  }
2500 
2501  if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
2502  $list .= "($value)";
2503  } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
2504  $list .= "$value";
2505  } elseif (
2506  ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
2507  ) {
2508  // Remove null from array to be handled separately if found
2509  $includeNull = false;
2510  foreach ( array_keys( $value, null, true ) as $nullKey ) {
2511  $includeNull = true;
2512  unset( $value[$nullKey] );
2513  }
2514  if ( count( $value ) == 0 && !$includeNull ) {
2515  throw new InvalidArgumentException(
2516  __METHOD__ . ": empty input for field $field" );
2517  } elseif ( count( $value ) == 0 ) {
2518  // only check if $field is null
2519  $list .= "$field IS NULL";
2520  } else {
2521  // IN clause contains at least one valid element
2522  if ( $includeNull ) {
2523  // Group subconditions to ensure correct precedence
2524  $list .= '(';
2525  }
2526  if ( count( $value ) == 1 ) {
2527  // Special-case single values, as IN isn't terribly efficient
2528  // Don't necessarily assume the single key is 0; we don't
2529  // enforce linear numeric ordering on other arrays here.
2530  $value = array_values( $value )[0];
2531  $list .= $field . " = " . $this->addQuotes( $value );
2532  } else {
2533  $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2534  }
2535  // if null present in array, append IS NULL
2536  if ( $includeNull ) {
2537  $list .= " OR $field IS NULL)";
2538  }
2539  }
2540  } elseif ( $value === null ) {
2541  if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2542  $list .= "$field IS ";
2543  } elseif ( $mode == self::LIST_SET ) {
2544  $list .= "$field = ";
2545  }
2546  $list .= 'NULL';
2547  } else {
2548  if (
2549  $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2550  ) {
2551  $list .= "$field = ";
2552  }
2553  $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
2554  }
2555  }
2556 
2557  return $list;
2558  }
2559 
2560  public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2561  $conds = [];
2562 
2563  foreach ( $data as $base => $sub ) {
2564  if ( count( $sub ) ) {
2565  $conds[] = $this->makeList(
2566  [ $baseKey => $base, $subKey => array_map( 'strval', array_keys( $sub ) ) ],
2568  );
2569  }
2570  }
2571 
2572  if ( $conds ) {
2573  return $this->makeList( $conds, self::LIST_OR );
2574  } else {
2575  // Nothing to search for...
2576  return false;
2577  }
2578  }
2579 
2584  public function aggregateValue( $valuedata, $valuename = 'value' ) {
2585  return $valuename;
2586  }
2587 
2592  public function bitNot( $field ) {
2593  return "(~$field)";
2594  }
2595 
2600  public function bitAnd( $fieldLeft, $fieldRight ) {
2601  return "($fieldLeft & $fieldRight)";
2602  }
2603 
2608  public function bitOr( $fieldLeft, $fieldRight ) {
2609  return "($fieldLeft | $fieldRight)";
2610  }
2611 
2616  public function buildConcat( $stringList ) {
2617  return 'CONCAT(' . implode( ',', $stringList ) . ')';
2618  }
2619 
2624  public function buildGroupConcatField(
2625  $delim, $table, $field, $conds = '', $join_conds = []
2626  ) {
2627  $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2628 
2629  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2630  }
2631 
2636  public function buildGreatest( $fields, $values ) {
2637  return $this->buildSuperlative( 'GREATEST', $fields, $values );
2638  }
2639 
2644  public function buildLeast( $fields, $values ) {
2645  return $this->buildSuperlative( 'LEAST', $fields, $values );
2646  }
2647 
2664  protected function buildSuperlative( $sqlfunc, $fields, $values ) {
2665  $fields = is_array( $fields ) ? $fields : [ $fields ];
2666  $values = is_array( $values ) ? $values : [ $values ];
2667 
2668  $encValues = [];
2669  foreach ( $fields as $alias => $field ) {
2670  if ( is_int( $alias ) ) {
2671  $encValues[] = $this->addIdentifierQuotes( $field );
2672  } else {
2673  $encValues[] = $field; // expression
2674  }
2675  }
2676  foreach ( $values as $value ) {
2677  if ( is_int( $value ) || is_float( $value ) ) {
2678  $encValues[] = $value;
2679  } elseif ( is_string( $value ) ) {
2680  $encValues[] = $this->addQuotes( $value );
2681  } elseif ( $value === null ) {
2682  throw new DBUnexpectedError( $this, 'Null value in superlative' );
2683  } else {
2684  throw new DBUnexpectedError( $this, 'Unexpected value type in superlative' );
2685  }
2686  }
2687 
2688  return $sqlfunc . '(' . implode( ',', $encValues ) . ')';
2689  }
2690 
2695  public function buildSubstring( $input, $startPosition, $length = null ) {
2696  $this->assertBuildSubstringParams( $startPosition, $length );
2697  $functionBody = "$input FROM $startPosition";
2698  if ( $length !== null ) {
2699  $functionBody .= " FOR $length";
2700  }
2701  return 'SUBSTRING(' . $functionBody . ')';
2702  }
2703 
2716  protected function assertBuildSubstringParams( $startPosition, $length ) {
2717  if ( $startPosition === 0 ) {
2718  // The DBMSs we support use 1-based indexing here.
2719  throw new InvalidArgumentException( 'Use 1 as $startPosition for the beginning of the string' );
2720  }
2721  if ( !is_int( $startPosition ) || $startPosition < 0 ) {
2722  throw new InvalidArgumentException(
2723  '$startPosition must be a positive integer'
2724  );
2725  }
2726  if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2727  throw new InvalidArgumentException(
2728  '$length must be null or an integer greater than or equal to 0'
2729  );
2730  }
2731  }
2732 
2746  protected function assertConditionIsNotEmpty( $conds, string $fname, bool $deprecate ) {
2747  $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
2748  if ( !$isCondValid ) {
2749  if ( $deprecate ) {
2750  wfDeprecated( $fname . ' called with empty $conds', '1.35', false, 3 );
2751  } else {
2752  throw new DBUnexpectedError( $this, $fname . ' called with empty conditions' );
2753  }
2754  }
2755  }
2756 
2761  public function buildStringCast( $field ) {
2762  // In theory this should work for any standards-compliant
2763  // SQL implementation, although it may not be the best way to do it.
2764  return "CAST( $field AS CHARACTER )";
2765  }
2766 
2771  public function buildIntegerCast( $field ) {
2772  return 'CAST( ' . $field . ' AS INTEGER )';
2773  }
2774 
2775  public function buildSelectSubquery(
2776  $table, $vars, $conds = '', $fname = __METHOD__,
2777  $options = [], $join_conds = []
2778  ) {
2779  return new Subquery(
2780  $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2781  );
2782  }
2783 
2788  public function databasesAreIndependent() {
2789  return false;
2790  }
2791 
2792  final public function selectDB( $db ) {
2793  $this->selectDomain( new DatabaseDomain(
2794  $db,
2795  $this->currentDomain->getSchema(),
2796  $this->currentDomain->getTablePrefix()
2797  ) );
2798 
2799  return true;
2800  }
2801 
2802  final public function selectDomain( $domain ) {
2803  $this->doSelectDomain( DatabaseDomain::newFromId( $domain ) );
2804  }
2805 
2813  protected function doSelectDomain( DatabaseDomain $domain ) {
2814  $this->currentDomain = $domain;
2815  }
2816 
2817  public function getDBname() {
2818  return $this->currentDomain->getDatabase();
2819  }
2820 
2821  public function getServer() {
2822  return $this->server;
2823  }
2824 
2829  public function tableName( $name, $format = 'quoted' ) {
2830  if ( $name instanceof Subquery ) {
2831  throw new DBUnexpectedError(
2832  $this,
2833  __METHOD__ . ': got Subquery instance when expecting a string'
2834  );
2835  }
2836 
2837  # Skip the entire process when we have a string quoted on both ends.
2838  # Note that we check the end so that we will still quote any use of
2839  # use of `database`.table. But won't break things if someone wants
2840  # to query a database table with a dot in the name.
2841  if ( $this->isQuotedIdentifier( $name ) ) {
2842  return $name;
2843  }
2844 
2845  # Lets test for any bits of text that should never show up in a table
2846  # name. Basically anything like JOIN or ON which are actually part of
2847  # SQL queries, but may end up inside of the table value to combine
2848  # sql. Such as how the API is doing.
2849  # Note that we use a whitespace test rather than a \b test to avoid
2850  # any remote case where a word like on may be inside of a table name
2851  # surrounded by symbols which may be considered word breaks.
2852  if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2853  $this->queryLogger->warning(
2854  __METHOD__ . ": use of subqueries is not supported this way",
2855  [ 'exception' => new RuntimeException() ]
2856  );
2857 
2858  return $name;
2859  }
2860 
2861  # Split database and table into proper variables.
2862  list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2863 
2864  # Quote $table and apply the prefix if not quoted.
2865  # $tableName might be empty if this is called from Database::replaceVars()
2866  $tableName = "{$prefix}{$table}";
2867  if ( $format === 'quoted'
2868  && !$this->isQuotedIdentifier( $tableName )
2869  && $tableName !== ''
2870  ) {
2871  $tableName = $this->addIdentifierQuotes( $tableName );
2872  }
2873 
2874  # Quote $schema and $database and merge them with the table name if needed
2875  $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2876  $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2877 
2878  return $tableName;
2879  }
2880 
2887  protected function qualifiedTableComponents( $name ) {
2888  # We reverse the explode so that database.table and table both output the correct table.
2889  $dbDetails = explode( '.', $name, 3 );
2890  if ( count( $dbDetails ) == 3 ) {
2891  list( $database, $schema, $table ) = $dbDetails;
2892  # We don't want any prefix added in this case
2893  $prefix = '';
2894  } elseif ( count( $dbDetails ) == 2 ) {
2895  list( $database, $table ) = $dbDetails;
2896  # We don't want any prefix added in this case
2897  $prefix = '';
2898  # In dbs that support it, $database may actually be the schema
2899  # but that doesn't affect any of the functionality here
2900  $schema = '';
2901  } else {
2902  list( $table ) = $dbDetails;
2903  if ( isset( $this->tableAliases[$table] ) ) {
2904  $database = $this->tableAliases[$table]['dbname'];
2905  $schema = is_string( $this->tableAliases[$table]['schema'] )
2906  ? $this->tableAliases[$table]['schema']
2907  : $this->relationSchemaQualifier();
2908  $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2909  ? $this->tableAliases[$table]['prefix']
2910  : $this->tablePrefix();
2911  } else {
2912  $database = '';
2913  $schema = $this->relationSchemaQualifier(); # Default schema
2914  $prefix = $this->tablePrefix(); # Default prefix
2915  }
2916  }
2917 
2918  return [ $database, $schema, $prefix, $table ];
2919  }
2920 
2927  private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2928  if ( $namespace !== null && $namespace !== '' ) {
2929  if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2930  $namespace = $this->addIdentifierQuotes( $namespace );
2931  }
2932  $relation = $namespace . '.' . $relation;
2933  }
2934 
2935  return $relation;
2936  }
2937 
2938  public function tableNames( ...$tables ) {
2939  $retVal = [];
2940 
2941  foreach ( $tables as $name ) {
2942  $retVal[$name] = $this->tableName( $name );
2943  }
2944 
2945  return $retVal;
2946  }
2947 
2948  public function tableNamesN( ...$tables ) {
2949  $retVal = [];
2950 
2951  foreach ( $tables as $name ) {
2952  $retVal[] = $this->tableName( $name );
2953  }
2954 
2955  return $retVal;
2956  }
2957 
2969  protected function tableNameWithAlias( $table, $alias = false ) {
2970  if ( is_string( $table ) ) {
2971  $quotedTable = $this->tableName( $table );
2972  } elseif ( $table instanceof Subquery ) {
2973  $quotedTable = (string)$table;
2974  } else {
2975  throw new InvalidArgumentException( "Table must be a string or Subquery" );
2976  }
2977 
2978  if ( $alias === false || $alias === $table ) {
2979  if ( $table instanceof Subquery ) {
2980  throw new InvalidArgumentException( "Subquery table missing alias" );
2981  }
2982 
2983  return $quotedTable;
2984  } else {
2985  return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2986  }
2987  }
2988 
2998  protected function fieldNameWithAlias( $name, $alias = false ) {
2999  if ( !$alias || (string)$alias === (string)$name ) {
3000  return $name;
3001  } else {
3002  return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
3003  }
3004  }
3005 
3012  protected function fieldNamesWithAlias( $fields ) {
3013  $retval = [];
3014  foreach ( $fields as $alias => $field ) {
3015  if ( is_numeric( $alias ) ) {
3016  $alias = $field;
3017  }
3018  $retval[] = $this->fieldNameWithAlias( $field, $alias );
3019  }
3020 
3021  return $retval;
3022  }
3023 
3035  $tables,
3036  $use_index = [],
3037  $ignore_index = [],
3038  $join_conds = []
3039  ) {
3040  $ret = [];
3041  $retJOIN = [];
3042  $use_index = (array)$use_index;
3043  $ignore_index = (array)$ignore_index;
3044  $join_conds = (array)$join_conds;
3045 
3046  foreach ( $tables as $alias => $table ) {
3047  if ( !is_string( $alias ) ) {
3048  // No alias? Set it equal to the table name
3049  $alias = $table;
3050  }
3051 
3052  if ( is_array( $table ) ) {
3053  // A parenthesized group
3054  if ( count( $table ) > 1 ) {
3055  $joinedTable = '(' .
3057  $table, $use_index, $ignore_index, $join_conds ) . ')';
3058  } else {
3059  // Degenerate case
3060  $innerTable = reset( $table );
3061  $innerAlias = key( $table );
3062  $joinedTable = $this->tableNameWithAlias(
3063  $innerTable,
3064  is_string( $innerAlias ) ? $innerAlias : $innerTable
3065  );
3066  }
3067  } else {
3068  $joinedTable = $this->tableNameWithAlias( $table, $alias );
3069  }
3070 
3071  // Is there a JOIN clause for this table?
3072  if ( isset( $join_conds[$alias] ) ) {
3073  list( $joinType, $conds ) = $join_conds[$alias];
3074  $tableClause = $joinType;
3075  $tableClause .= ' ' . $joinedTable;
3076  if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
3077  $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
3078  if ( $use != '' ) {
3079  $tableClause .= ' ' . $use;
3080  }
3081  }
3082  if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
3083  $ignore = $this->ignoreIndexClause(
3084  implode( ',', (array)$ignore_index[$alias] ) );
3085  if ( $ignore != '' ) {
3086  $tableClause .= ' ' . $ignore;
3087  }
3088  }
3089  $on = $this->makeList( (array)$conds, self::LIST_AND );
3090  if ( $on != '' ) {
3091  $tableClause .= ' ON (' . $on . ')';
3092  }
3093 
3094  $retJOIN[] = $tableClause;
3095  } elseif ( isset( $use_index[$alias] ) ) {
3096  // Is there an INDEX clause for this table?
3097  $tableClause = $joinedTable;
3098  $tableClause .= ' ' . $this->useIndexClause(
3099  implode( ',', (array)$use_index[$alias] )
3100  );
3101 
3102  $ret[] = $tableClause;
3103  } elseif ( isset( $ignore_index[$alias] ) ) {
3104  // Is there an INDEX clause for this table?
3105  $tableClause = $joinedTable;
3106  $tableClause .= ' ' . $this->ignoreIndexClause(
3107  implode( ',', (array)$ignore_index[$alias] )
3108  );
3109 
3110  $ret[] = $tableClause;
3111  } else {
3112  $tableClause = $joinedTable;
3113 
3114  $ret[] = $tableClause;
3115  }
3116  }
3117 
3118  // We can't separate explicit JOIN clauses with ',', use ' ' for those
3119  $implicitJoins = implode( ',', $ret );
3120  $explicitJoins = implode( ' ', $retJOIN );
3121 
3122  // Compile our final table clause
3123  return implode( ' ', [ $implicitJoins, $explicitJoins ] );
3124  }
3125 
3132  protected function indexName( $index ) {
3133  return $this->indexAliases[$index] ?? $index;
3134  }
3135 
3140  public function addQuotes( $s ) {
3141  if ( $s instanceof Blob ) {
3142  $s = $s->fetch();
3143  }
3144  if ( $s === null ) {
3145  return 'NULL';
3146  } elseif ( is_bool( $s ) ) {
3147  return (string)(int)$s;
3148  } elseif ( is_int( $s ) ) {
3149  return (string)$s;
3150  } else {
3151  return "'" . $this->strencode( $s ) . "'";
3152  }
3153  }
3154 
3159  public function addIdentifierQuotes( $s ) {
3160  return '"' . str_replace( '"', '""', $s ) . '"';
3161  }
3162 
3173  public function isQuotedIdentifier( $name ) {
3174  return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
3175  }
3176 
3183  protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
3184  return str_replace(
3185  [ $escapeChar, '%', '_' ],
3186  [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
3187  $s
3188  );
3189  }
3190 
3195  public function buildLike( $param, ...$params ) {
3196  if ( is_array( $param ) ) {
3197  $params = $param;
3198  } else {
3199  $params = func_get_args();
3200  }
3201 
3202  $s = '';
3203 
3204  // We use ` instead of \ as the default LIKE escape character, since addQuotes()
3205  // may escape backslashes, creating problems of double escaping. The `
3206  // character has good cross-DBMS compatibility, avoiding special operators
3207  // in MS SQL like ^ and %
3208  $escapeChar = '`';
3209 
3210  foreach ( $params as $value ) {
3211  if ( $value instanceof LikeMatch ) {
3212  $s .= $value->toString();
3213  } else {
3214  $s .= $this->escapeLikeInternal( $value, $escapeChar );
3215  }
3216  }
3217 
3218  return ' LIKE ' .
3219  $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
3220  }
3221 
3222  public function anyChar() {
3223  return new LikeMatch( '_' );
3224  }
3225 
3226  public function anyString() {
3227  return new LikeMatch( '%' );
3228  }
3229 
3230  public function nextSequenceValue( $seqName ) {
3231  return null;
3232  }
3233 
3247  public function useIndexClause( $index ) {
3248  return '';
3249  }
3250 
3260  public function ignoreIndexClause( $index ) {
3261  return '';
3262  }
3263 
3264  public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
3265  $rows = $this->normalizeRowArray( $rows );
3266  if ( !$rows ) {
3267  return;
3268  }
3269 
3270  if ( $uniqueKeys ) {
3271  $uniqueKeys = $this->normalizeUpsertKeys( $uniqueKeys );
3272  $this->doReplace( $table, $uniqueKeys, $rows, $fname );
3273  } else {
3274  $this->queryLogger->warning(
3275  __METHOD__ . " called with no unique keys",
3276  [ 'exception' => new RuntimeException() ]
3277  );
3278  $this->doInsert( $table, $rows, $fname );
3279  }
3280  }
3281 
3291  protected function doReplace( $table, array $uniqueKeys, array $rows, $fname ) {
3292  $affectedRowCount = 0;
3293  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3294  try {
3295  foreach ( $rows as $row ) {
3296  // Delete any conflicting rows (including ones inserted from $rows)
3297  $sqlCondition = $this->makeConditionCollidesUponKeys( [ $row ], $uniqueKeys );
3298  $this->delete( $table, [ $sqlCondition ], $fname );
3299  $affectedRowCount += $this->affectedRows();
3300  // Now insert the row
3301  $this->insert( $table, $row, $fname );
3302  $affectedRowCount += $this->affectedRows();
3303  }
3304  $this->endAtomic( $fname );
3305  } catch ( Throwable $e ) {
3306  $this->cancelAtomic( $fname );
3307  throw $e;
3308  }
3309  $this->affectedRowCount = $affectedRowCount;
3310  }
3311 
3317  private function makeConditionCollidesUponKey( array $rows, array $uniqueKey ) {
3318  if ( !$rows ) {
3319  throw new DBUnexpectedError( $this, "Empty row array" );
3320  } elseif ( !$uniqueKey ) {
3321  throw new DBUnexpectedError( $this, "Empty unique key array" );
3322  }
3323 
3324  if ( count( $uniqueKey ) == 1 ) {
3325  // Use a simple IN(...) clause
3326  $column = reset( $uniqueKey );
3327  $values = array_column( $rows, $column );
3328  if ( count( $values ) !== count( $rows ) ) {
3329  throw new DBUnexpectedError( $this, "Missing values for unique key ($column)" );
3330  }
3331 
3332  return $this->makeList( [ $column => $values ], self::LIST_AND );
3333  }
3334 
3335  $disjunctions = [];
3336  foreach ( $rows as $row ) {
3337  $rowKeyMap = array_intersect_key( $row, array_flip( $uniqueKey ) );
3338  if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
3339  throw new DBUnexpectedError(
3340  $this,
3341  "Missing values for unique key (" . implode( ',', $uniqueKey ) . ")"
3342  );
3343  }
3344  $disjunctions[] = $this->makeList( $rowKeyMap, self::LIST_AND );
3345  }
3346 
3347  return count( $disjunctions ) > 1
3348  ? $this->makeList( $disjunctions, self::LIST_OR )
3349  : $disjunctions[0];
3350  }
3351 
3358  final protected function makeConditionCollidesUponKeys( array $rows, array $uniqueKeys ) {
3359  if ( !$uniqueKeys ) {
3360  throw new DBUnexpectedError( $this, "Empty unique key array" );
3361  }
3362 
3363  $disjunctions = [];
3364  foreach ( $uniqueKeys as $uniqueKey ) {
3365  $disjunctions[] = $this->makeConditionCollidesUponKey( $rows, $uniqueKey );
3366  }
3367 
3368  return count( $disjunctions ) > 1
3369  ? $this->makeList( $disjunctions, self::LIST_OR )
3370  : $disjunctions[0];
3371  }
3372 
3373  public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
3374  $rows = $this->normalizeRowArray( $rows );
3375  if ( !$rows ) {
3376  return true;
3377  }
3378 
3379  if ( $uniqueKeys ) {
3380  $uniqueKeys = $this->normalizeUpsertKeys( $uniqueKeys );
3381  $this->doUpsert( $table, $rows, $uniqueKeys, $set, $fname );
3382  } else {
3383  $this->queryLogger->warning(
3384  __METHOD__ . " called with no unique keys",
3385  [ 'exception' => new RuntimeException() ]
3386  );
3387  $this->doInsert( $table, $rows, $fname );
3388  }
3389 
3390  return true;
3391  }
3392 
3403  protected function doUpsert( $table, array $rows, array $uniqueKeys, array $set, $fname ) {
3404  $affectedRowCount = 0;
3405  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3406  try {
3407  foreach ( $rows as $row ) {
3408  // Update any existing conflicting rows (including ones inserted from $rows)
3409  $sqlConditions = $this->makeConditionCollidesUponKeys( [ $row ], $uniqueKeys );
3410  $this->update( $table, $set, [ $sqlConditions ], $fname );
3411  $rowsUpdated = $this->affectedRows();
3412  $affectedRowCount += $rowsUpdated;
3413  if ( $rowsUpdated <= 0 ) {
3414  // Now insert the row if there are no conflicts
3415  $this->insert( $table, $row, $fname );
3416  $affectedRowCount += $this->affectedRows();
3417  }
3418  }
3419  $this->endAtomic( $fname );
3420  } catch ( Throwable $e ) {
3421  $this->cancelAtomic( $fname );
3422  throw $e;
3423  }
3424  $this->affectedRowCount = $affectedRowCount;
3425  }
3426 
3431  public function deleteJoin(
3432  $delTable,
3433  $joinTable,
3434  $delVar,
3435  $joinVar,
3436  $conds,
3437  $fname = __METHOD__
3438  ) {
3439  if ( !$conds ) {
3440  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
3441  }
3442 
3443  $delTable = $this->tableName( $delTable );
3444  $joinTable = $this->tableName( $joinTable );
3445  $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3446  if ( $conds != '*' ) {
3447  $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
3448  }
3449  $sql .= ')';
3450 
3451  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3452  }
3453 
3458  public function textFieldSize( $table, $field ) {
3459  $table = $this->tableName( $table );
3460  $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
3461  $res = $this->query( $sql, __METHOD__, self::QUERY_CHANGE_NONE );
3462  $row = $this->fetchObject( $res );
3463 
3464  $m = [];
3465 
3466  if ( preg_match( '/\‍((.*)\‍)/', $row->Type, $m ) ) {
3467  $size = $m[1];
3468  } else {
3469  $size = -1;
3470  }
3471 
3472  return $size;
3473  }
3474 
3475  public function delete( $table, $conds, $fname = __METHOD__ ) {
3476  $this->assertConditionIsNotEmpty( $conds, __METHOD__, false );
3477 
3478  $table = $this->tableName( $table );
3479  $sql = "DELETE FROM $table";
3480 
3481  if ( $conds !== IDatabase::ALL_ROWS ) {
3482  if ( is_array( $conds ) ) {
3483  $conds = $this->makeList( $conds, self::LIST_AND );
3484  }
3485  $sql .= ' WHERE ' . $conds;
3486  }
3487 
3488  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3489 
3490  return true;
3491  }
3492 
3493  final public function insertSelect(
3494  $destTable,
3495  $srcTable,
3496  $varMap,
3497  $conds,
3498  $fname = __METHOD__,
3499  $insertOptions = [],
3500  $selectOptions = [],
3501  $selectJoinConds = []
3502  ) {
3503  static $hints = [ 'NO_AUTO_COLUMNS' ];
3504 
3505  $insertOptions = $this->normalizeOptions( $insertOptions );
3506  $selectOptions = $this->normalizeOptions( $selectOptions );
3507 
3508  if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3509  // For massive migrations with downtime, we don't want to select everything
3510  // into memory and OOM, so do all this native on the server side if possible.
3511  $this->doInsertSelectNative(
3512  $destTable,
3513  $srcTable,
3514  $varMap,
3515  $conds,
3516  $fname,
3517  array_diff( $insertOptions, $hints ),
3518  $selectOptions,
3519  $selectJoinConds
3520  );
3521  } else {
3522  $this->doInsertSelectGeneric(
3523  $destTable,
3524  $srcTable,
3525  $varMap,
3526  $conds,
3527  $fname,
3528  array_diff( $insertOptions, $hints ),
3529  $selectOptions,
3530  $selectJoinConds
3531  );
3532  }
3533 
3534  return true;
3535  }
3536 
3544  protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3545  return true;
3546  }
3547 
3562  protected function doInsertSelectGeneric(
3563  $destTable,
3564  $srcTable,
3565  array $varMap,
3566  $conds,
3567  $fname,
3568  array $insertOptions,
3569  array $selectOptions,
3570  $selectJoinConds
3571  ) {
3572  // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3573  // on only the master (without needing row-based-replication). It also makes it easy to
3574  // know how big the INSERT is going to be.
3575  $fields = [];
3576  foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3577  $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3578  }
3579  $res = $this->select(
3580  $srcTable,
3581  implode( ',', $fields ),
3582  $conds,
3583  $fname,
3584  array_merge( $selectOptions, [ 'FOR UPDATE' ] ),
3585  $selectJoinConds
3586  );
3587  if ( !$res ) {
3588  return;
3589  }
3590 
3591  $affectedRowCount = 0;
3592  $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3593  try {
3594  $rows = [];
3595  foreach ( $res as $row ) {
3596  $rows[] = (array)$row;
3597  }
3598  // Avoid inserts that are too huge
3599  $rowBatches = array_chunk( $rows, $this->nonNativeInsertSelectBatchSize );
3600  foreach ( $rowBatches as $rows ) {
3601  $this->insert( $destTable, $rows, $fname, $insertOptions );
3602  $affectedRowCount += $this->affectedRows();
3603  }
3604  } catch ( Throwable $e ) {
3605  $this->cancelAtomic( $fname );
3606  throw $e;
3607  }
3608  $this->endAtomic( $fname );
3609  $this->affectedRowCount = $affectedRowCount;
3610  }
3611 
3627  protected function doInsertSelectNative(
3628  $destTable,
3629  $srcTable,
3630  array $varMap,
3631  $conds,
3632  $fname,
3633  array $insertOptions,
3634  array $selectOptions,
3635  $selectJoinConds
3636  ) {
3637  list( $sqlVerb, $sqlOpts ) = $this->isFlagInOptions( 'IGNORE', $insertOptions )
3639  : [ 'INSERT INTO', '' ];
3640  $encDstTable = $this->tableName( $destTable );
3641  $sqlDstColumns = implode( ',', array_keys( $varMap ) );
3642  $selectSql = $this->selectSQLText(
3643  $srcTable,
3644  array_values( $varMap ),
3645  $conds,
3646  $fname,
3647  $selectOptions,
3648  $selectJoinConds
3649  );
3650 
3651  $sql = rtrim( "$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
3652 
3653  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
3654  }
3655 
3660  public function limitResult( $sql, $limit, $offset = false ) {
3661  if ( !is_numeric( $limit ) ) {
3662  throw new DBUnexpectedError(
3663  $this,
3664  "Invalid non-numeric limit passed to " . __METHOD__
3665  );
3666  }
3667  // This version works in MySQL and SQLite. It will very likely need to be
3668  // overridden for most other RDBMS subclasses.
3669  return "$sql LIMIT "
3670  . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3671  . "{$limit} ";
3672  }
3673 
3678  public function unionSupportsOrderAndLimit() {
3679  return true; // True for almost every DB supported
3680  }
3681 
3686  public function unionQueries( $sqls, $all ) {
3687  $glue = $all ? ') UNION ALL (' : ') UNION (';
3688 
3689  return '(' . implode( $glue, $sqls ) . ')';
3690  }
3691 
3693  $table,
3694  $vars,
3695  array $permute_conds,
3696  $extra_conds = '',
3697  $fname = __METHOD__,
3698  $options = [],
3699  $join_conds = []
3700  ) {
3701  // First, build the Cartesian product of $permute_conds
3702  $conds = [ [] ];
3703  foreach ( $permute_conds as $field => $values ) {
3704  if ( !$values ) {
3705  // Skip empty $values
3706  continue;
3707  }
3708  $values = array_unique( $values ); // For sanity
3709  $newConds = [];
3710  foreach ( $conds as $cond ) {
3711  foreach ( $values as $value ) {
3712  $cond[$field] = $value;
3713  $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3714  }
3715  }
3716  $conds = $newConds;
3717  }
3718 
3719  $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
3720 
3721  // If there's just one condition and no subordering, hand off to
3722  // selectSQLText directly.
3723  if ( count( $conds ) === 1 &&
3724  ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
3725  ) {
3726  return $this->selectSQLText(
3727  $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
3728  );
3729  }
3730 
3731  // Otherwise, we need to pull out the order and limit to apply after
3732  // the union. Then build the SQL queries for each set of conditions in
3733  // $conds. Then union them together (using UNION ALL, because the
3734  // product *should* already be distinct).
3735  $orderBy = $this->makeOrderBy( $options );
3736  $limit = $options['LIMIT'] ?? null;
3737  $offset = $options['OFFSET'] ?? false;
3738  $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3739  if ( !$this->unionSupportsOrderAndLimit() ) {
3740  unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3741  } else {
3742  if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3743  $options['ORDER BY'] = $options['INNER ORDER BY'];
3744  }
3745  if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3746  // We need to increase the limit by the offset rather than
3747  // using the offset directly, otherwise it'll skip incorrectly
3748  // in the subqueries.
3749  $options['LIMIT'] = $limit + $offset;
3750  unset( $options['OFFSET'] );
3751  }
3752  }
3753 
3754  $sqls = [];
3755  foreach ( $conds as $cond ) {
3756  $sqls[] = $this->selectSQLText(
3757  $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
3758  );
3759  }
3760  $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3761  if ( $limit !== null ) {
3762  $sql = $this->limitResult( $sql, $limit, $offset );
3763  }
3764 
3765  return $sql;
3766  }
3767 
3772  public function conditional( $cond, $trueVal, $falseVal ) {
3773  if ( is_array( $cond ) ) {
3774  $cond = $this->makeList( $cond, self::LIST_AND );
3775  }
3776 
3777  return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3778  }
3779 
3784  public function strreplace( $orig, $old, $new ) {
3785  return "REPLACE({$orig}, {$old}, {$new})";
3786  }
3787 
3792  public function getServerUptime() {
3793  return 0;
3794  }
3795 
3800  public function wasDeadlock() {
3801  return false;
3802  }
3803 
3808  public function wasLockTimeout() {
3809  return false;
3810  }
3811 
3816  public function wasConnectionLoss() {
3817  return $this->wasConnectionError( $this->lastErrno() );
3818  }
3819 
3824  public function wasReadOnlyError() {
3825  return false;
3826  }
3827 
3828  public function wasErrorReissuable() {
3829  return (
3830  $this->wasDeadlock() ||
3831  $this->wasLockTimeout() ||
3832  $this->wasConnectionLoss()
3833  );
3834  }
3835 
3843  public function wasConnectionError( $errno ) {
3844  return false;
3845  }
3846 
3854  protected function wasKnownStatementRollbackError() {
3855  return false; // don't know; it could have caused a transaction rollback
3856  }
3857 
3862  public function deadlockLoop( ...$args ) {
3863  $function = array_shift( $args );
3864  $tries = self::$DEADLOCK_TRIES;
3865 
3866  $this->begin( __METHOD__ );
3867 
3868  $retVal = null;
3870  $e = null;
3871  do {
3872  try {
3873  $retVal = $function( ...$args );
3874  break;
3875  } catch ( DBQueryError $e ) {
3876  if ( $this->wasDeadlock() ) {
3877  // Retry after a randomized delay
3878  usleep( mt_rand( self::$DEADLOCK_DELAY_MIN, self::$DEADLOCK_DELAY_MAX ) );
3879  } else {
3880  // Throw the error back up
3881  throw $e;
3882  }
3883  }
3884  } while ( --$tries > 0 );
3885 
3886  if ( $tries <= 0 ) {
3887  // Too many deadlocks; give up
3888  $this->rollback( __METHOD__ );
3889  throw $e;
3890  } else {
3891  $this->commit( __METHOD__ );
3892 
3893  return $retVal;
3894  }
3895  }
3896 
3901  public function masterPosWait( DBMasterPos $pos, $timeout ) {
3902  # Real waits are implemented in the subclass.
3903  return 0;
3904  }
3905 
3910  public function getReplicaPos() {
3911  # Stub
3912  return false;
3913  }
3914 
3919  public function getMasterPos() {
3920  # Stub
3921  return false;
3922  }
3923 
3928  public function serverIsReadOnly() {
3929  return false;
3930  }
3931 
3932  final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3933  if ( !$this->trxLevel() ) {
3934  throw new DBUnexpectedError( $this, "No transaction is active" );
3935  }
3936  $this->trxEndCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3937  }
3938 
3939  final public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3940  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3941  // Start an implicit transaction similar to how query() does
3942  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3943  $this->trxAutomatic = true;
3944  }
3945 
3946  $this->trxPostCommitOrIdleCallbacks[] = [
3947  $callback,
3948  $fname,
3949  $this->currentAtomicSectionId()
3950  ];
3951 
3952  if ( !$this->trxLevel() ) {
3953  $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3954  }
3955  }
3956 
3957  final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3958  $this->onTransactionCommitOrIdle( $callback, $fname );
3959  }
3960 
3961  final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3962  if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3963  // Start an implicit transaction similar to how query() does
3964  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
3965  $this->trxAutomatic = true;
3966  }
3967 
3968  if ( $this->trxLevel() ) {
3969  $this->trxPreCommitOrIdleCallbacks[] = [
3970  $callback,
3971  $fname,
3972  $this->currentAtomicSectionId()
3973  ];
3974  } else {
3975  // No transaction is active nor will start implicitly, so make one for this callback
3976  $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3977  try {
3978  $callback( $this );
3979  $this->endAtomic( __METHOD__ );
3980  } catch ( Throwable $e ) {
3981  $this->cancelAtomic( __METHOD__ );
3982  throw $e;
3983  }
3984  }
3985  }
3986 
3987  final public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ) {
3988  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
3989  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3990  }
3991  $this->trxSectionCancelCallbacks[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3992  }
3993 
3997  private function currentAtomicSectionId() {
3998  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
3999  $levelInfo = end( $this->trxAtomicLevels );
4000 
4001  return $levelInfo[1];
4002  }
4003 
4004  return null;
4005  }
4006 
4016  ) {
4017  foreach ( $this->trxPreCommitOrIdleCallbacks as $key => $info ) {
4018  if ( $info[2] === $old ) {
4019  $this->trxPreCommitOrIdleCallbacks[$key][2] = $new;
4020  }
4021  }
4022  foreach ( $this->trxPostCommitOrIdleCallbacks as $key => $info ) {
4023  if ( $info[2] === $old ) {
4024  $this->trxPostCommitOrIdleCallbacks[$key][2] = $new;
4025  }
4026  }
4027  foreach ( $this->trxEndCallbacks as $key => $info ) {
4028  if ( $info[2] === $old ) {
4029  $this->trxEndCallbacks[$key][2] = $new;
4030  }
4031  }
4032  foreach ( $this->trxSectionCancelCallbacks as $key => $info ) {
4033  if ( $info[2] === $old ) {
4034  $this->trxSectionCancelCallbacks[$key][2] = $new;
4035  }
4036  }
4037  }
4038 
4058  private function modifyCallbacksForCancel(
4059  array $sectionIds,
4060  AtomicSectionIdentifier $newSectionId = null
4061  ) {
4062  // Cancel the "on commit" callbacks owned by this savepoint
4063  $this->trxPostCommitOrIdleCallbacks = array_filter(
4064  $this->trxPostCommitOrIdleCallbacks,
4065  static function ( $entry ) use ( $sectionIds ) {
4066  return !in_array( $entry[2], $sectionIds, true );
4067  }
4068  );
4069  $this->trxPreCommitOrIdleCallbacks = array_filter(
4070  $this->trxPreCommitOrIdleCallbacks,
4071  static function ( $entry ) use ( $sectionIds ) {
4072  return !in_array( $entry[2], $sectionIds, true );
4073  }
4074  );
4075  // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
4076  foreach ( $this->trxEndCallbacks as $key => $entry ) {
4077  if ( in_array( $entry[2], $sectionIds, true ) ) {
4078  $callback = $entry[0];
4079  $this->trxEndCallbacks[$key][0] = function () use ( $callback ) {
4080  return $callback( self::TRIGGER_ROLLBACK, $this );
4081  };
4082  // This "on resolution" callback no longer belongs to a section.
4083  $this->trxEndCallbacks[$key][2] = null;
4084  }
4085  }
4086  // Hoist callback ownership for section cancel callbacks to the new top section
4087  foreach ( $this->trxSectionCancelCallbacks as $key => $entry ) {
4088  if ( in_array( $entry[2], $sectionIds, true ) ) {
4089  $this->trxSectionCancelCallbacks[$key][2] = $newSectionId;
4090  }
4091  }
4092  }
4093 
4094  final public function setTransactionListener( $name, callable $callback = null ) {
4095  if ( $callback ) {
4096  $this->trxRecurringCallbacks[$name] = $callback;
4097  } else {
4098  unset( $this->trxRecurringCallbacks[$name] );
4099  }
4100  }
4101 
4110  final public function setTrxEndCallbackSuppression( $suppress ) {
4111  $this->trxEndCallbacksSuppressed = $suppress;
4112  }
4113 
4124  public function runOnTransactionIdleCallbacks( $trigger ) {
4125  if ( $this->trxLevel() ) { // sanity
4126  throw new DBUnexpectedError( $this, __METHOD__ . ': a transaction is still open' );
4127  }
4128 
4129  if ( $this->trxEndCallbacksSuppressed ) {
4130  return 0;
4131  }
4132 
4133  $count = 0;
4134  $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
4136  $e = null; // first exception
4137  do { // callbacks may add callbacks :)
4138  $callbacks = array_merge(
4139  $this->trxPostCommitOrIdleCallbacks,
4140  $this->trxEndCallbacks // include "transaction resolution" callbacks
4141  );
4142  $this->trxPostCommitOrIdleCallbacks = []; // consumed (and recursion guard)
4143  $this->trxEndCallbacks = []; // consumed (recursion guard)
4144 
4145  // Only run trxSectionCancelCallbacks on rollback, not commit.
4146  // But always consume them.
4147  if ( $trigger === self::TRIGGER_ROLLBACK ) {
4148  $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks );
4149  }
4150  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
4151 
4152  foreach ( $callbacks as $callback ) {
4153  ++$count;
4154  list( $phpCallback ) = $callback;
4155  $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
4156  try {
4157  call_user_func( $phpCallback, $trigger, $this );
4158  } catch ( Throwable $ex ) {
4159  call_user_func( $this->errorLogger, $ex );
4160  $e = $e ?: $ex;
4161  // Some callbacks may use startAtomic/endAtomic, so make sure
4162  // their transactions are ended so other callbacks don't fail
4163  if ( $this->trxLevel() ) {
4164  $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
4165  }
4166  } finally {
4167  if ( $autoTrx ) {
4168  $this->setFlag( self::DBO_TRX ); // restore automatic begin()
4169  } else {
4170  $this->clearFlag( self::DBO_TRX ); // restore auto-commit
4171  }
4172  }
4173  }
4174  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4175  } while ( count( $this->trxPostCommitOrIdleCallbacks ) );
4176 
4177  if ( $e instanceof Throwable ) {
4178  throw $e; // re-throw any first exception
4179  }
4180 
4181  return $count;
4182  }
4183 
4194  $count = 0;
4195 
4196  $e = null; // first exception
4197  do { // callbacks may add callbacks :)
4199  $this->trxPreCommitOrIdleCallbacks = []; // consumed (and recursion guard)
4200  foreach ( $callbacks as $callback ) {
4201  try {
4202  ++$count;
4203  list( $phpCallback ) = $callback;
4204  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
4205  $phpCallback( $this );
4206  } catch ( Throwable $ex ) {
4207  ( $this->errorLogger )( $ex );
4208  $e = $e ?: $ex;
4209  }
4210  }
4211  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4212  } while ( count( $this->trxPreCommitOrIdleCallbacks ) );
4213 
4214  if ( $e instanceof Throwable ) {
4215  throw $e; // re-throw any first exception
4216  }
4217 
4218  return $count;
4219  }
4220 
4229  $trigger, array $sectionIds = null
4230  ) {
4232  $e = null; // first exception
4233 
4234  $notCancelled = [];
4235  do {
4236  $callbacks = $this->trxSectionCancelCallbacks;
4237  $this->trxSectionCancelCallbacks = []; // consumed (recursion guard)
4238  foreach ( $callbacks as $entry ) {
4239  if ( $sectionIds === null || in_array( $entry[2], $sectionIds, true ) ) {
4240  try {
4241  // @phan-suppress-next-line PhanUndeclaredInvokeInCallable
4242  $entry[0]( $trigger, $this );
4243  } catch ( Throwable $ex ) {
4244  ( $this->errorLogger )( $ex );
4245  $e = $e ?: $ex;
4246  }
4247  } else {
4248  $notCancelled[] = $entry;
4249  }
4250  }
4251  // @phan-suppress-next-line PhanImpossibleConditionInLoop
4252  } while ( count( $this->trxSectionCancelCallbacks ) );
4253  $this->trxSectionCancelCallbacks = $notCancelled;
4254 
4255  if ( $e !== null ) {
4256  throw $e; // re-throw any first Throwable
4257  }
4258  }
4259 
4269  public function runTransactionListenerCallbacks( $trigger ) {
4270  if ( $this->trxEndCallbacksSuppressed ) {
4271  return;
4272  }
4273 
4275  $e = null; // first exception
4276 
4277  foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
4278  try {
4279  $phpCallback( $trigger, $this );
4280  } catch ( Throwable $ex ) {
4281  ( $this->errorLogger )( $ex );
4282  $e = $e ?: $ex;
4283  }
4284  }
4285 
4286  if ( $e instanceof Throwable ) {
4287  throw $e; // re-throw any first exception
4288  }
4289  }
4290 
4302  protected function doSavepoint( $identifier, $fname ) {
4303  $sql = 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4304  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4305  }
4306 
4318  protected function doReleaseSavepoint( $identifier, $fname ) {
4319  $sql = 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4320  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4321  }
4322 
4334  protected function doRollbackToSavepoint( $identifier, $fname ) {
4335  $sql = 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
4336  $this->query( $sql, $fname, self::QUERY_CHANGE_TRX );
4337  }
4338 
4343  private function nextSavepointId( $fname ) {
4344  $savepointId = self::$SAVEPOINT_PREFIX . ++$this->trxAtomicCounter;
4345  if ( strlen( $savepointId ) > 30 ) {
4346  // 30 == Oracle's identifier length limit (pre 12c)
4347  // With a 22 character prefix, that puts the highest number at 99999999.
4348  throw new DBUnexpectedError(
4349  $this,
4350  'There have been an excessively large number of atomic sections in a transaction'
4351  . " started by $this->trxFname (at $fname)"
4352  );
4353  }
4354 
4355  return $savepointId;
4356  }
4357 
4358  final public function startAtomic(
4359  $fname = __METHOD__,
4360  $cancelable = self::ATOMIC_NOT_CANCELABLE
4361  ) {
4362  $savepointId = $cancelable === self::ATOMIC_CANCELABLE ? self::$NOT_APPLICABLE : null;
4363 
4364  if ( !$this->trxLevel() ) {
4365  $this->begin( $fname, self::TRANSACTION_INTERNAL ); // sets trxAutomatic
4366  // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
4367  // in all changes being in one transaction to keep requests transactional.
4368  if ( $this->getFlag( self::DBO_TRX ) ) {
4369  // Since writes could happen in between the topmost atomic sections as part
4370  // of the transaction, those sections will need savepoints.
4371  $savepointId = $this->nextSavepointId( $fname );
4372  $this->doSavepoint( $savepointId, $fname );
4373  } else {
4374  $this->trxAutomaticAtomic = true;
4375  }
4376  } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
4377  $savepointId = $this->nextSavepointId( $fname );
4378  $this->doSavepoint( $savepointId, $fname );
4379  }
4380 
4381  $sectionId = new AtomicSectionIdentifier;
4382  $this->trxAtomicLevels[] = [ $fname, $sectionId, $savepointId ];
4383  $this->queryLogger->debug( 'startAtomic: entering level ' .
4384  ( count( $this->trxAtomicLevels ) - 1 ) . " ($fname)" );
4385 
4386  return $sectionId;
4387  }
4388 
4389  final public function endAtomic( $fname = __METHOD__ ) {
4390  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
4391  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
4392  }
4393 
4394  // Check if the current section matches $fname
4395  $pos = count( $this->trxAtomicLevels ) - 1;
4396  list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
4397  $this->queryLogger->debug( "endAtomic: leaving level $pos ($fname)" );
4398 
4399  if ( $savedFname !== $fname ) {
4400  throw new DBUnexpectedError(
4401  $this,
4402  "Invalid atomic section ended (got $fname but expected $savedFname)"
4403  );
4404  }
4405 
4406  // Remove the last section (no need to re-index the array)
4407  array_pop( $this->trxAtomicLevels );
4408 
4409  if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
4410  $this->commit( $fname, self::FLUSHING_INTERNAL );
4411  } elseif ( $savepointId !== null && $savepointId !== self::$NOT_APPLICABLE ) {
4412  $this->doReleaseSavepoint( $savepointId, $fname );
4413  }
4414 
4415  // Hoist callback ownership for callbacks in the section that just ended;
4416  // all callbacks should have an owner that is present in trxAtomicLevels.
4417  $currentSectionId = $this->currentAtomicSectionId();
4418  if ( $currentSectionId ) {
4419  $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
4420  }
4421  }
4422 
4423  final public function cancelAtomic(
4424  $fname = __METHOD__,
4425  AtomicSectionIdentifier $sectionId = null
4426  ) {
4427  if ( !$this->trxLevel() || !$this->trxAtomicLevels ) {
4428  throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
4429  }
4430 
4431  $excisedIds = [];
4432  $newTopSection = $this->currentAtomicSectionId();
4433  try {
4434  $excisedFnames = [];
4435  if ( $sectionId !== null ) {
4436  // Find the (last) section with the given $sectionId
4437  $pos = -1;
4438  foreach ( $this->trxAtomicLevels as $i => list( $asFname, $asId, $spId ) ) {
4439  if ( $asId === $sectionId ) {
4440  $pos = $i;
4441  }
4442  }
4443  if ( $pos < 0 ) {
4444  throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
4445  }
4446  // Remove all descendant sections and re-index the array
4447  $len = count( $this->trxAtomicLevels );
4448  for ( $i = $pos + 1; $i < $len; ++$i ) {
4449  $excisedFnames[] = $this->trxAtomicLevels[$i][0];
4450  $excisedIds[] = $this->trxAtomicLevels[$i][1];
4451  }
4452  $this->trxAtomicLevels = array_slice( $this->trxAtomicLevels, 0, $pos + 1 );
4453  $newTopSection = $this->currentAtomicSectionId();
4454  }
4455 
4456  // Check if the current section matches $fname
4457  $pos = count( $this->trxAtomicLevels ) - 1;
4458  list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels[$pos];
4459 
4460  if ( $excisedFnames ) {
4461  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
4462  "and descendants " . implode( ', ', $excisedFnames ) );
4463  } else {
4464  $this->queryLogger->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
4465  }
4466 
4467  if ( $savedFname !== $fname ) {
4468  throw new DBUnexpectedError(
4469  $this,
4470  "Invalid atomic section ended (got $fname but expected $savedFname)"
4471  );
4472  }
4473 
4474  // Remove the last section (no need to re-index the array)
4475  array_pop( $this->trxAtomicLevels );
4476  $excisedIds[] = $savedSectionId;
4477  $newTopSection = $this->currentAtomicSectionId();
4478 
4479  if ( $savepointId !== null ) {
4480  // Rollback the transaction to the state just before this atomic section
4481  if ( $savepointId === self::$NOT_APPLICABLE ) {
4482  $this->rollback( $fname, self::FLUSHING_INTERNAL );
4483  // Note: rollback() will run trxSectionCancelCallbacks
4484  } else {
4485  $this->doRollbackToSavepoint( $savepointId, $fname );
4486  $this->trxStatus = self::STATUS_TRX_OK; // no exception; recovered
4487  $this->trxStatusIgnoredCause = null;
4488 
4489  // Run trxSectionCancelCallbacks now.
4490  $this->runOnAtomicSectionCancelCallbacks( self::TRIGGER_CANCEL, $excisedIds );
4491  }
4492  } elseif ( $this->trxStatus > self::STATUS_TRX_ERROR ) {
4493  // Put the transaction into an error state if it's not already in one
4494  $this->trxStatus = self::STATUS_TRX_ERROR;
4495  $this->trxStatusCause = new DBUnexpectedError(
4496  $this,
4497  "Uncancelable atomic section canceled (got $fname)"
4498  );
4499  }
4500  } finally {
4501  // Fix up callbacks owned by the sections that were just cancelled.
4502  // All callbacks should have an owner that is present in trxAtomicLevels.
4503  $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
4504  }
4505 
4506  $this->affectedRowCount = 0; // for the sake of consistency
4507  }
4508 
4509  final public function doAtomicSection(
4510  $fname,
4511  callable $callback,
4512  $cancelable = self::ATOMIC_NOT_CANCELABLE
4513  ) {
4514  $sectionId = $this->startAtomic( $fname, $cancelable );
4515  try {
4516  $res = $callback( $this, $fname );
4517  } catch ( Throwable $e ) {
4518  $this->cancelAtomic( $fname, $sectionId );
4519 
4520  throw $e;
4521  }
4522  $this->endAtomic( $fname );
4523 
4524  return $res;
4525  }
4526 
4527  final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
4528  static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
4529  if ( !in_array( $mode, $modes, true ) ) {
4530  throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
4531  }
4532 
4533  // Protect against mismatched atomic section, transaction nesting, and snapshot loss
4534  if ( $this->trxLevel() ) {
4535  if ( $this->trxAtomicLevels ) {
4536  $levels = $this->flatAtomicSectionList();
4537  $msg = "$fname: got explicit BEGIN while atomic section(s) $levels are open";
4538  throw new DBUnexpectedError( $this, $msg );
4539  } elseif ( !$this->trxAutomatic ) {
4540  $msg = "$fname: explicit transaction already active (from {$this->trxFname})";
4541  throw new DBUnexpectedError( $this, $msg );
4542  } else {
4543  $msg = "$fname: implicit transaction already active (from {$this->trxFname})";
4544  throw new DBUnexpectedError( $this, $msg );
4545  }
4546  } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
4547  $msg = "$fname: implicit transaction expected (DBO_TRX set)";
4548  throw new DBUnexpectedError( $this, $msg );
4549  }
4550 
4551  $this->assertHasConnectionHandle();
4552 
4553  $this->doBegin( $fname );
4554  $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4555  $this->trxStatus = self::STATUS_TRX_OK;
4556  $this->trxStatusIgnoredCause = null;
4557  $this->trxAtomicCounter = 0;
4558  $this->trxTimestamp = microtime( true );
4559  $this->trxFname = $fname;
4560  $this->trxDoneWrites = false;
4561  $this->trxAutomaticAtomic = false;
4562  $this->trxAtomicLevels = [];
4563  $this->trxWriteDuration = 0.0;
4564  $this->trxWriteQueryCount = 0;
4565  $this->trxWriteAffectedRows = 0;
4566  $this->trxWriteAdjDuration = 0.0;
4567  $this->trxWriteAdjQueryCount = 0;
4568  $this->trxWriteCallers = [];
4569  // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4570  // Get an estimate of the replication lag before any such queries.
4571  $this->trxReplicaLag = null; // clear cached value first
4572  $this->trxReplicaLag = $this->getApproximateLagStatus()['lag'];
4573  // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4574  // caller will think its OK to muck around with the transaction just because startAtomic()
4575  // has not yet completed (e.g. setting trxAtomicLevels).
4576  $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
4577  }
4578 
4587  protected function doBegin( $fname ) {
4588  $this->query( 'BEGIN', $fname, self::QUERY_CHANGE_TRX );
4589  }
4590 
4591  final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4592  static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
4593  if ( !in_array( $flush, $modes, true ) ) {
4594  throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4595  }
4596 
4597  if ( $this->trxLevel() && $this->trxAtomicLevels ) {
4598  // There are still atomic sections open; this cannot be ignored
4599  $levels = $this->flatAtomicSectionList();
4600  throw new DBUnexpectedError(
4601  $this,
4602  "$fname: got COMMIT while atomic sections $levels are still open"
4603  );
4604  }
4605 
4606  if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
4607  if ( !$this->trxLevel() ) {
4608  return; // nothing to do
4609  } elseif ( !$this->trxAutomatic ) {
4610  throw new DBUnexpectedError(
4611  $this,
4612  "$fname: flushing an explicit transaction, getting out of sync"
4613  );
4614  }
4615  } elseif ( !$this->trxLevel() ) {
4616  $this->queryLogger->error(
4617  "$fname: no transaction to commit, something got out of sync",
4618  [ 'exception' => new RuntimeException() ]
4619  );
4620 
4621  return; // nothing to do
4622  } elseif ( $this->trxAutomatic ) {
4623  throw new DBUnexpectedError(
4624  $this,
4625  "$fname: expected mass commit of all peer transactions (DBO_TRX set)"
4626  );
4627  }
4628 
4629  $this->assertHasConnectionHandle();
4630 
4632 
4633  $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
4634  $this->doCommit( $fname );
4635  $oldTrxShortId = $this->consumeTrxShortId();
4636  $this->trxStatus = self::STATUS_TRX_NONE;
4637 
4638  if ( $this->trxDoneWrites ) {
4639  $this->lastWriteTime = microtime( true );
4640  $this->trxProfiler->transactionWritingOut(
4641  $this->getServer(),
4642  $this->getDomainID(),
4643  $oldTrxShortId,
4644  $writeTime,
4645  $this->trxWriteAffectedRows
4646  );
4647  }
4648 
4649  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4650  if ( $flush !== self::FLUSHING_ALL_PEERS ) {
4651  $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
4652  $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
4653  }
4654  }
4655 
4664  protected function doCommit( $fname ) {
4665  if ( $this->trxLevel() ) {
4666  $this->query( 'COMMIT', $fname, self::QUERY_CHANGE_TRX );
4667  }
4668  }
4669 
4670  final public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4671  $trxActive = $this->trxLevel();
4672 
4673  if ( $flush !== self::FLUSHING_INTERNAL
4674  && $flush !== self::FLUSHING_ALL_PEERS
4675  && $this->getFlag( self::DBO_TRX )
4676  ) {
4677  throw new DBUnexpectedError(
4678  $this,
4679  "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4680  );
4681  }
4682 
4683  if ( $trxActive ) {
4684  $this->assertHasConnectionHandle();
4685 
4686  $this->doRollback( $fname );
4687  $oldTrxShortId = $this->consumeTrxShortId();
4688  $this->trxStatus = self::STATUS_TRX_NONE;
4689  $this->trxAtomicLevels = [];
4690  // Estimate the RTT via a query now that trxStatus is OK
4691  $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4692 
4693  if ( $this->trxDoneWrites ) {
4694  $this->trxProfiler->transactionWritingOut(
4695  $this->getServer(),
4696  $this->getDomainID(),
4697  $oldTrxShortId,
4698  $writeTime,
4699  $this->trxWriteAffectedRows
4700  );
4701  }
4702  }
4703 
4704  // Clear any commit-dependent callbacks. They might even be present
4705  // only due to transaction rounds, with no SQL transaction being active
4706  $this->trxPostCommitOrIdleCallbacks = [];
4707  $this->trxPreCommitOrIdleCallbacks = [];
4708 
4709  // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4710  if ( $trxActive && $flush !== self::FLUSHING_ALL_PEERS ) {
4711  try {
4712  $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
4713  } catch ( Throwable $e ) {
4714  // already logged; finish and let LoadBalancer move on during mass-rollback
4715  }
4716  try {
4717  $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
4718  } catch ( Throwable $e ) {
4719  // already logged; let LoadBalancer move on during mass-rollback
4720  }
4721 
4722  $this->affectedRowCount = 0; // for the sake of consistency
4723  }
4724  }
4725 
4734  protected function doRollback( $fname ) {
4735  if ( $this->trxLevel() ) {
4736  # Disconnects cause rollback anyway, so ignore those errors
4737  $this->query( 'ROLLBACK', $fname, self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_TRX );
4738  }
4739  }
4740 
4741  public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
4742  if ( $this->explicitTrxActive() ) {
4743  // Committing this transaction would break callers that assume it is still open
4744  throw new DBUnexpectedError(
4745  $this,
4746  "$fname: Cannot flush snapshot; " .
4747  "explicit transaction '{$this->trxFname}' is still open"
4748  );
4749  } elseif ( $this->writesOrCallbacksPending() ) {
4750  // This only flushes transactions to clear snapshots, not to write data
4751  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4752  throw new DBUnexpectedError(
4753  $this,
4754  "$fname: Cannot flush snapshot; " .
4755  "writes from transaction {$this->trxFname} are still pending ($fnames)"
4756  );
4757  } elseif (
4758  $this->trxLevel() &&
4759  $this->getTransactionRoundId() &&
4760  $flush !== self::FLUSHING_INTERNAL &&
4761  $flush !== self::FLUSHING_ALL_PEERS
4762  ) {
4763  $this->queryLogger->warning(
4764  "$fname: Expected mass snapshot flush of all peer transactions " .
4765  "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4766  [ 'exception' => new RuntimeException() ]
4767  );
4768  }
4769 
4770  $this->commit( $fname, self::FLUSHING_INTERNAL );
4771  }
4772 
4773  public function explicitTrxActive() {
4774  return $this->trxLevel() && ( $this->trxAtomicLevels || !$this->trxAutomatic );
4775  }
4776 
4781  public function duplicateTableStructure(
4782  $oldName,
4783  $newName,
4784  $temporary = false,
4785  $fname = __METHOD__
4786  ) {
4787  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4788  }
4789 
4794  public function listTables( $prefix = null, $fname = __METHOD__ ) {
4795  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4796  }
4797 
4802  public function listViews( $prefix = null, $fname = __METHOD__ ) {
4803  throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
4804  }
4805 
4810  public function timestamp( $ts = 0 ) {
4811  $t = new ConvertibleTimestamp( $ts );
4812  // Let errors bubble up to avoid putting garbage in the DB
4813  return $t->getTimestamp( TS_MW );
4814  }
4815 
4816  public function timestampOrNull( $ts = null ) {
4817  if ( $ts === null ) {
4818  return null;
4819  } else {
4820  return $this->timestamp( $ts );
4821  }
4822  }
4823 
4824  public function affectedRows() {
4825  return ( $this->affectedRowCount === null )
4826  ? $this->fetchAffectedRowCount() // default to driver value
4828  }
4829 
4833  abstract protected function fetchAffectedRowCount();
4834 
4847  protected function resultObject( $result ) {
4848  if ( !$result ) {
4849  return false; // failed query
4850  } elseif ( $result instanceof IResultWrapper ) {
4851  return $result;
4852  } elseif ( $result === true ) {
4853  return $result; // successful write query
4854  } else {
4855  return new ResultWrapper( $this, $result );
4856  }
4857  }
4858 
4859  public function ping( &$rtt = null ) {
4860  // Avoid hitting the server if it was hit recently
4861  if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::$PING_TTL ) {
4862  if ( !func_num_args() || $this->lastRoundTripEstimate > 0 ) {
4864  return true; // don't care about $rtt
4865  }
4866  }
4867 
4868  // This will reconnect if possible or return false if not
4869  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_NONE;
4870  $ok = ( $this->query( self::$PING_QUERY, __METHOD__, $flags ) !== false );
4871  if ( $ok ) {
4873  }
4874 
4875  return $ok;
4876  }
4877 
4884  protected function replaceLostConnection( $fname ) {
4885  $this->closeConnection();
4886  $this->conn = null;
4887 
4888  $this->handleSessionLossPreconnect();
4889 
4890  try {
4891  $this->open(
4892  $this->server,
4893  $this->user,
4894  $this->password,
4895  $this->currentDomain->getDatabase(),
4896  $this->currentDomain->getSchema(),
4897  $this->tablePrefix()
4898  );
4899  $this->lastPing = microtime( true );
4900  $ok = true;
4901 
4902  $this->connLogger->warning(
4903  $fname . ': lost connection to {dbserver}; reconnected',
4904  [
4905  'dbserver' => $this->getServer(),
4906  'exception' => new RuntimeException()
4907  ]
4908  );
4909  } catch ( DBConnectionError $e ) {
4910  $ok = false;
4911 
4912  $this->connLogger->error(
4913  $fname . ': lost connection to {dbserver} permanently',
4914  [ 'dbserver' => $this->getServer() ]
4915  );
4916  }
4917 
4919 
4920  return $ok;
4921  }
4922 
4923  public function getSessionLagStatus() {
4924  return $this->getRecordedTransactionLagStatus() ?: $this->getApproximateLagStatus();
4925  }
4926 
4940  final protected function getRecordedTransactionLagStatus() {
4941  return ( $this->trxLevel() && $this->trxReplicaLag !== null )
4942  ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
4943  : null;
4944  }
4945 
4955  protected function getApproximateLagStatus() {
4956  return [
4957  'lag' => ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) ? $this->getLag() : 0,
4958  'since' => microtime( true )
4959  ];
4960  }
4961 
4984  public static function getCacheSetOptions( ?IDatabase ...$dbs ) {
4985  $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
4986 
4987  foreach ( func_get_args() as $db ) {
4988  if ( $db instanceof IDatabase ) {
4989  $status = $db->getSessionLagStatus();
4990 
4991  if ( $status['lag'] === false ) {
4992  $res['lag'] = false;
4993  } elseif ( $res['lag'] !== false ) {
4994  $res['lag'] = max( $res['lag'], $status['lag'] );
4995  }
4996  $res['since'] = min( $res['since'], $status['since'] );
4997  $res['pending'] = $res['pending'] ?: $db->writesPending();
4998  }
4999  }
5000 
5001  return $res;
5002  }
5003 
5004  public function getLag() {
5005  if ( $this->topologyRole === self::ROLE_STREAMING_MASTER ) {
5006  return 0; // this is the master
5007  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
5008  return 0; // static dataset
5009  }
5010 
5011  return $this->doGetLag();
5012  }
5013 
5018  protected function doGetLag() {
5019  return 0;
5020  }
5021 
5026  public function maxListLen() {
5027  return 0;
5028  }
5029 
5034  public function encodeBlob( $b ) {
5035  return $b;
5036  }
5037 
5042  public function decodeBlob( $b ) {
5043  if ( $b instanceof Blob ) {
5044  $b = $b->fetch();
5045  }
5046  return $b;
5047  }
5048 
5053  public function setSessionOptions( array $options ) {
5054  }
5055 
5056  public function sourceFile(
5057  $filename,
5058  callable $lineCallback = null,
5059  callable $resultCallback = null,
5060  $fname = false,
5061  callable $inputCallback = null
5062  ) {
5063  AtEase::suppressWarnings();
5064  $fp = fopen( $filename, 'r' );
5065  AtEase::restoreWarnings();
5066 
5067  if ( $fp === false ) {
5068  throw new RuntimeException( "Could not open \"{$filename}\"" );
5069  }
5070 
5071  if ( !$fname ) {
5072  $fname = __METHOD__ . "( $filename )";
5073  }
5074 
5075  try {
5076  $error = $this->sourceStream(
5077  $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
5078  } catch ( Throwable $e ) {
5079  fclose( $fp );
5080  throw $e;
5081  }
5082 
5083  fclose( $fp );
5084 
5085  return $error;
5086  }
5087 
5088  public function setSchemaVars( $vars ) {
5089  $this->schemaVars = is_array( $vars ) ? $vars : null;
5090  }
5091 
5092  public function sourceStream(
5093  $fp,
5094  callable $lineCallback = null,
5095  callable $resultCallback = null,
5096  $fname = __METHOD__,
5097  callable $inputCallback = null
5098  ) {
5099  $delimiterReset = new ScopedCallback(
5100  function ( $delimiter ) {
5101  $this->delimiter = $delimiter;
5102  },
5103  [ $this->delimiter ]
5104  );
5105  $cmd = '';
5106 
5107  while ( !feof( $fp ) ) {
5108  if ( $lineCallback ) {
5109  call_user_func( $lineCallback );
5110  }
5111 
5112  $line = trim( fgets( $fp ) );
5113 
5114  if ( $line == '' ) {
5115  continue;
5116  }
5117 
5118  if ( $line[0] == '-' && $line[1] == '-' ) {
5119  continue;
5120  }
5121 
5122  if ( $cmd != '' ) {
5123  $cmd .= ' ';
5124  }
5125 
5126  $done = $this->streamStatementEnd( $cmd, $line );
5127 
5128  $cmd .= "$line\n";
5129 
5130  if ( $done || feof( $fp ) ) {
5131  $cmd = $this->replaceVars( $cmd );
5132 
5133  if ( $inputCallback ) {
5134  $callbackResult = $inputCallback( $cmd );
5135 
5136  if ( is_string( $callbackResult ) || !$callbackResult ) {
5137  $cmd = $callbackResult;
5138  }
5139  }
5140 
5141  if ( $cmd ) {
5142  $res = $this->query( $cmd, $fname );
5143 
5144  if ( $resultCallback ) {
5145  $resultCallback( $res, $this );
5146  }
5147 
5148  if ( $res === false ) {
5149  $err = $this->lastError();
5150 
5151  return "Query \"{$cmd}\" failed with error code \"$err\".\n";
5152  }
5153  }
5154  $cmd = '';
5155  }
5156  }
5157 
5158  ScopedCallback::consume( $delimiterReset );
5159  return true;
5160  }
5161 
5170  public function streamStatementEnd( &$sql, &$newLine ) {
5171  if ( $this->delimiter ) {
5172  $prev = $newLine;
5173  $newLine = preg_replace(
5174  '/' . preg_quote( $this->delimiter, '/' ) . '$/',
5175  '',
5176  $newLine
5177  );
5178  if ( $newLine != $prev ) {
5179  return true;
5180  }
5181  }
5182 
5183  return false;
5184  }
5185 
5207  protected function replaceVars( $ins ) {
5208  $vars = $this->getSchemaVars();
5209  return preg_replace_callback(
5210  '!
5211  /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
5212  \'\{\$ (\w+) }\' | # 3. addQuotes
5213  `\{\$ (\w+) }` | # 4. addIdentifierQuotes
5214  /\*\$ (\w+) \*/ # 5. leave unencoded
5215  !x',
5216  function ( $m ) use ( $vars ) {
5217  // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
5218  // check for both nonexistent keys *and* the empty string.
5219  if ( isset( $m[1] ) && $m[1] !== '' ) {
5220  if ( $m[1] === 'i' ) {
5221  return $this->indexName( $m[2] );
5222  } else {
5223  return $this->tableName( $m[2] );
5224  }
5225  } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
5226  return $this->addQuotes( $vars[$m[3]] );
5227  } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
5228  return $this->addIdentifierQuotes( $vars[$m[4]] );
5229  } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
5230  return $vars[$m[5]];
5231  } else {
5232  return $m[0];
5233  }
5234  },
5235  $ins
5236  );
5237  }
5238 
5245  protected function getSchemaVars() {
5246  return $this->schemaVars ?? $this->getDefaultSchemaVars();
5247  }
5248 
5258  protected function getDefaultSchemaVars() {
5259  return [];
5260  }
5261 
5266  public function lockIsFree( $lockName, $method ) {
5267  // RDBMs methods for checking named locks may or may not count this thread itself.
5268  // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
5269  // the behavior chosen by the interface for this method.
5270  return !isset( $this->sessionNamedLocks[$lockName] );
5271  }
5272 
5277  public function lock( $lockName, $method, $timeout = 5 ) {
5278  $this->sessionNamedLocks[$lockName] = 1;
5279 
5280  return true;
5281  }
5282 
5287  public function unlock( $lockName, $method ) {
5288  unset( $this->sessionNamedLocks[$lockName] );
5289 
5290  return true;
5291  }
5292 
5293  public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
5294  if ( $this->writesOrCallbacksPending() ) {
5295  // This only flushes transactions to clear snapshots, not to write data
5296  $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
5297  throw new DBUnexpectedError(
5298  $this,
5299  "$fname: Cannot flush pre-lock snapshot; " .
5300  "writes from transaction {$this->trxFname} are still pending ($fnames)"
5301  );
5302  }
5303 
5304  if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
5305  return null;
5306  }
5307 
5308  $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
5309  if ( $this->trxLevel() ) {
5310  // There is a good chance an exception was thrown, causing any early return
5311  // from the caller. Let any error handler get a chance to issue rollback().
5312  // If there isn't one, let the error bubble up and trigger server-side rollback.
5313  $this->onTransactionResolution(
5314  function () use ( $lockKey, $fname ) {
5315  $this->unlock( $lockKey, $fname );
5316  },
5317  $fname
5318  );
5319  } else {
5320  $this->unlock( $lockKey, $fname );
5321  }
5322  } );
5323 
5324  $this->commit( $fname, self::FLUSHING_INTERNAL );
5325 
5326  return $unlocker;
5327  }
5328 
5333  public function namedLocksEnqueue() {
5334  return false;
5335  }
5336 
5338  return true;
5339  }
5340 
5341  final public function lockTables( array $read, array $write, $method ) {
5342  if ( $this->writesOrCallbacksPending() ) {
5343  throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
5344  }
5345 
5346  if ( $this->tableLocksHaveTransactionScope() ) {
5347  $this->startAtomic( $method );
5348  }
5349 
5350  return $this->doLockTables( $read, $write, $method );
5351  }
5352 
5362  protected function doLockTables( array $read, array $write, $method ) {
5363  return true;
5364  }
5365 
5366  final public function unlockTables( $method ) {
5367  if ( $this->tableLocksHaveTransactionScope() ) {
5368  $this->endAtomic( $method );
5369 
5370  return true; // locks released on COMMIT/ROLLBACK
5371  }
5372 
5373  return $this->doUnlockTables( $method );
5374  }
5375 
5383  protected function doUnlockTables( $method ) {
5384  return true;
5385  }
5386 
5387  public function dropTable( $table, $fname = __METHOD__ ) {
5388  if ( !$this->tableExists( $table, $fname ) ) {
5389  return false;
5390  }
5391 
5392  $this->doDropTable( $table, $fname );
5393 
5394  return true;
5395  }
5396 
5403  protected function doDropTable( $table, $fname ) {
5404  // https://mariadb.com/kb/en/drop-table/
5405  // https://dev.mysql.com/doc/refman/8.0/en/drop-table.html
5406  // https://www.postgresql.org/docs/9.2/sql-truncate.html
5407  $sql = "DROP TABLE " . $this->tableName( $table ) . " CASCADE";
5408  $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
5409  }
5410 
5411  public function truncate( $tables, $fname = __METHOD__ ) {
5412  $tables = is_array( $tables ) ? $tables : [ $tables ];
5413 
5414  $tablesTruncate = [];
5415  foreach ( $tables as $table ) {
5416  // Skip TEMPORARY tables with no writes nor sequence updates detected.
5417  // This mostly is an optimization for integration testing.
5418  if ( !$this->isPristineTemporaryTable( $table ) ) {
5419  $tablesTruncate[] = $table;
5420  }
5421  }
5422 
5423  if ( $tablesTruncate ) {
5424  $this->doTruncate( $tablesTruncate, $fname );
5425  }
5426  }
5427 
5434  protected function doTruncate( array $tables, $fname ) {
5435  foreach ( $tables as $table ) {
5436  $sql = "TRUNCATE TABLE " . $this->tableName( $table );
5437  $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
5438  }
5439  }
5440 
5445  public function getInfinity() {
5446  return 'infinity';
5447  }
5448 
5449  public function encodeExpiry( $expiry ) {
5450  return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
5451  ? $this->getInfinity()
5452  : $this->timestamp( $expiry );
5453  }
5454 
5455  public function decodeExpiry( $expiry, $format = TS_MW ) {
5456  if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
5457  return 'infinity';
5458  }
5459 
5460  return ConvertibleTimestamp::convert( $format, $expiry );
5461  }
5462 
5467  public function setBigSelects( $value = true ) {
5468  // no-op
5469  }
5470 
5471  public function isReadOnly() {
5472  return ( $this->getReadOnlyReason() !== false );
5473  }
5474 
5478  protected function getReadOnlyReason() {
5479  if ( $this->topologyRole === self::ROLE_STREAMING_REPLICA ) {
5480  return [ 'Server is configured as a read-only replica database.', 'role' ];
5481  } elseif ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
5482  return [ 'Server is configured as a read-only static clone database.', 'role' ];
5483  }
5484 
5485  $reason = $this->getLBInfo( self::LB_READ_ONLY_REASON );
5486  if ( is_string( $reason ) ) {
5487  return [ $reason, 'lb' ];
5488  }
5489 
5490  return false;
5491  }
5492 
5497  public function setTableAliases( array $aliases ) {
5498  $this->tableAliases = $aliases;
5499  }
5500 
5505  public function setIndexAliases( array $aliases ) {
5506  $this->indexAliases = $aliases;
5507  }
5508 
5515  final protected function fieldHasBit( int $flags, int $bit ) {
5516  return ( ( $flags & $bit ) === $bit );
5517  }
5518 
5531  protected function getBindingHandle() {
5532  if ( !$this->conn ) {
5533  throw new DBUnexpectedError(
5534  $this,
5535  'DB connection was already closed or the connection dropped'
5536  );
5537  }
5538 
5539  return $this->conn;
5540  }
5541 
5542  public function __toString() {
5543  // spl_object_id is PHP >= 7.2
5544  $id = function_exists( 'spl_object_id' )
5545  ? spl_object_id( $this )
5546  : spl_object_hash( $this );
5547 
5548  $description = $this->getType() . ' object #' . $id;
5549  if ( is_resource( $this->conn ) ) {
5550  $description .= ' (' . (string)$this->conn . ')'; // "resource id #<ID>"
5551  } elseif ( is_object( $this->conn ) ) {
5552  // spl_object_id is PHP >= 7.2
5553  $handleId = function_exists( 'spl_object_id' )
5554  ? spl_object_id( $this->conn )
5555  : spl_object_hash( $this->conn );
5556  $description .= " (handle id #$handleId)";
5557  }
5558 
5559  return $description;
5560  }
5561 
5566  public function __clone() {
5567  $this->connLogger->warning(
5568  "Cloning " . static::class . " is not recommended; forking connection",
5569  [ 'exception' => new RuntimeException() ]
5570  );
5571 
5572  if ( $this->isOpen() ) {
5573  // Open a new connection resource without messing with the old one
5574  $this->conn = null;
5575  $this->trxEndCallbacks = []; // don't copy
5576  $this->trxSectionCancelCallbacks = []; // don't copy
5577  $this->handleSessionLossPreconnect(); // no trx or locks anymore
5578  $this->open(
5579  $this->server,
5580  $this->user,
5581  $this->password,
5582  $this->currentDomain->getDatabase(),
5583  $this->currentDomain->getSchema(),
5584  $this->tablePrefix()
5585  );
5586  $this->lastPing = microtime( true );
5587  }
5588  }
5589 
5595  public function __sleep() {
5596  throw new RuntimeException( 'Database serialization may cause problems, since ' .
5597  'the connection is not restored on wakeup' );
5598  }
5599 
5603  public function __destruct() {
5604  if ( $this->trxLevel() && $this->trxDoneWrites ) {
5605  trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
5606  }
5607 
5608  $danglingWriters = $this->pendingWriteAndCallbackCallers();
5609  if ( $danglingWriters ) {
5610  $fnames = implode( ', ', $danglingWriters );
5611  trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
5612  }
5613 
5614  if ( $this->conn ) {
5615  // Avoid connection leaks for sanity. Normally, resources close at script completion.
5616  // The connection might already be closed in PHP by now, so suppress warnings.
5617  AtEase::suppressWarnings();
5618  $this->closeConnection();
5619  AtEase::restoreWarnings();
5620  $this->conn = null;
5621  }
5622  }
5623 }
5624 
5628 class_alias( Database::class, 'DatabaseBase' );
5629 
5633 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:658
LIST_OR
const LIST_OR
Definition: Defines.php:46
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:230
Wikimedia\Rdbms\Database\$schemaVars
array null $schemaVars
Current variables use for schema element placeholders.
Definition: Database.php:110
Wikimedia\Rdbms\Database\tablePrefix
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition: Database.php:574
Wikimedia\Rdbms\Database\$trxFname
string $trxFname
Name of the function that start the last transaction.
Definition: Database.php:137
Wikimedia\Rdbms\Database\getLastPHPError
getLastPHPError()
Definition: Database.php:876
Wikimedia\Rdbms\Database\setSessionOptions
setSessionOptions(array $options)
Override database's default behavior.$options include: 'connTimeout' : Set the connection timeout val...
Definition: Database.php:5053
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:50
Wikimedia\Rdbms\Database\limitResult
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.The SQL should be adjusted so that only the first $limit...
Definition: Database.php:3660
Wikimedia\Rdbms\Database\$trxDoneWrites
bool $trxDoneWrites
Whether possible write queries were done in the last transaction started.
Definition: Database.php:139
Wikimedia\Rdbms\Database\$trxEndCallbacksSuppressed
bool $trxEndCallbacksSuppressed
Whether to suppress triggering of transaction end callbacks.
Definition: Database.php:174
Wikimedia\Rdbms\Database\$DBO_MUTABLE
static int $DBO_MUTABLE
Bit field of all DBO_* flags that can be changed after connection.
Definition: Database.php:249
Wikimedia\Rdbms\Database\makeUpdateOptionsArray
makeUpdateOptionsArray( $options)
Make UPDATE options array for Database::makeUpdateOptions.
Definition: Database.php:2441
Wikimedia\Rdbms\Database\replaceLostConnection
replaceLostConnection( $fname)
Close any existing (dead) database connection and open a new connection.
Definition: Database.php:4884
Wikimedia\Rdbms\Database\$trxWriteAdjQueryCount
int $trxWriteAdjQueryCount
Number of write queries counted in trxWriteAdjDuration.
Definition: Database.php:159
Wikimedia\Rdbms\Database\getBindingHandle
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:5531
LIST_NAMES
const LIST_NAMES
Definition: Defines.php:45
Wikimedia\Rdbms\Database\$lastPhpError
string bool $lastPhpError
Definition: Database.php:186
Wikimedia\Rdbms\Database\canRecoverFromDisconnect
canRecoverFromDisconnect( $sql, $priorWritesPending)
Determine whether it is safe to retry queries after a database connection is lost.
Definition: Database.php:1556
Wikimedia\Rdbms\Database\doInsert
doInsert( $table, array $rows, $fname)
Definition: Database.php:2359
Wikimedia\Rdbms\Database\buildGroupConcatField
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.This is useful for combining a field for sev...
Definition: Database.php:2624
Wikimedia\Rdbms\Database\doInitConnection
doInitConnection()
Actually connect to the database over the wire (or to local files)
Definition: Database.php:328
Wikimedia\Rdbms\Database\$trxReplicaLag
float $trxReplicaLag
Replication lag estimate at the time of BEGIN for the last transaction.
Definition: Database.php:135
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:3173
Wikimedia\Rdbms\IDatabase\getServerVersion
getServerVersion()
A string describing the current software version, like from mysql_get_server_info()
Wikimedia\Rdbms\Database\upsert
upsert( $table, array $rows, $uniqueKeys, array $set, $fname=__METHOD__)
Upsert the given row(s) into a table.
Definition: Database.php:3373
Wikimedia\Rdbms\Database\fieldExists
fieldExists( $table, $field, $fname=__METHOD__)
Determines whether a field exists in a table.
Definition: Database.php:2300
Wikimedia\Rdbms\Database\deadlockLoop
deadlockLoop(... $args)
Perform a deadlock-prone transaction.This function invokes a callback function to perform a set of wr...
Definition: Database.php:3862
Wikimedia\Rdbms\Database\bitOr
bitOr( $fieldLeft, $fieldRight)
string
Definition: Database.php:2608
Wikimedia\Rdbms\Database\update
update( $table, $set, $conds, $fname=__METHOD__, $options=[])
Update all rows in a table that match a given condition.
Definition: Database.php:2466
Wikimedia\Rdbms\Database\selectRowCount
selectRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
Definition: Database.php:2062
Wikimedia\Rdbms\Database\ignoreIndexClause
ignoreIndexClause( $index)
IGNORE INDEX clause.
Definition: Database.php:3260
Wikimedia\Rdbms\Database\$sessionDirtyTempTables
array $sessionDirtyTempTables
Map of (table name => 1) for current TEMPORARY tables.
Definition: Database.php:122
Wikimedia\Rdbms\Database\trxStatus
trxStatus()
Definition: Database.php:570
Wikimedia\Rdbms\Database\fieldHasBit
fieldHasBit(int $flags, int $bit)
Definition: Database.php:5515
Wikimedia\Rdbms\Database\listTables
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.Only show tables with this prefix, e.g. mw_ Calling function name arr...
Definition: Database.php:4794
Wikimedia\Rdbms\Database\indexUnique
indexUnique( $table, $index, $fname=__METHOD__)
Determines if a given index is unique.Calling function namebool
Definition: Database.php:2325
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:32
Wikimedia\Rdbms\Database\updateTrxWriteQueryTime
updateTrxWriteQueryTime( $sql, $runtime, $affected)
Update the estimated run-time of a query, not counting large row lock times.
Definition: Database.php:1481
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:2560
Wikimedia\Rdbms\Database\$queryLogger
LoggerInterface $queryLogger
Definition: Database.php:56
Wikimedia\Rdbms\DatabaseDomain\newFromId
static newFromId( $domain)
Definition: DatabaseDomain.php:77
Wikimedia\Rdbms\Database\encodeBlob
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
Definition: Database.php:5034
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:2948
Wikimedia\Rdbms\Database\getDomainID
getDomainID()
Return the currently selected domain ID.
Definition: Database.php:826
Wikimedia\Rdbms\Database\getClass
static getClass( $dbType, $driver=null)
Definition: Database.php:478
Wikimedia\Rdbms\Database\pingAndCalculateLastTrxApplyTime
pingAndCalculateLastTrxApplyTime()
Definition: Database.php:720
Wikimedia\Rdbms\Database\$topologyRole
string $topologyRole
Replication topology role of the server; one of the class ROLE_* constants.
Definition: Database.php:89
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:993
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:3961
Wikimedia\Rdbms\Database\tableLocksHaveTransactionScope
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
Definition: Database.php:5337
Wikimedia\Rdbms\Database\wasErrorReissuable
wasErrorReissuable()
Determines if the last query error was due to something outside of the query itself.
Definition: Database.php:3828
Wikimedia\Rdbms\Database\deleteJoin
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.MySQL overrides this to use a multi-table DELETE syntax,...
Definition: Database.php:3431
Wikimedia\Rdbms\Database\$trxPostCommitOrIdleCallbacks
array[] $trxPostCommitOrIdleCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:161
Wikimedia\Rdbms\Database\setIndexAliases
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.Note that this applies to ind...
Definition: Database.php:5505
Wikimedia\Rdbms\Database\$password
string $password
Password used to establish the current connection.
Definition: Database.php:83
Wikimedia\Rdbms\Database\decodeBlob
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects....
Definition: Database.php:5042
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:3692
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:405
Wikimedia\Rdbms\Database\maxListLen
maxListLen()
Return the maximum number of items allowed in a list, or 0 for unlimited.int
Definition: Database.php:5026
Wikimedia\Rdbms\Database\selectDomain
selectDomain( $domain)
Set the current domain (database, schema, and table prefix)
Definition: Database.php:2802
Wikimedia\Rdbms\Database\buildIntegerCast
buildIntegerCast( $field)
Field or column to cast string 1.31
Definition: Database.php:2771
Wikimedia\Rdbms\Database\getServerUptime
getServerUptime()
Determines how long the server has been up.int
Definition: Database.php:3792
LIST_AND
const LIST_AND
Definition: Defines.php:43
Wikimedia\Rdbms\Database\prependDatabaseOrSchema
prependDatabaseOrSchema( $namespace, $relation, $format)
Definition: Database.php:2927
Wikimedia\Rdbms\Database\$delimiter
string $delimiter
Current SQL query delimiter.
Definition: Database.php:104
Wikimedia\Rdbms\Database\__destruct
__destruct()
Run a few simple sanity checks and close dangling connections.
Definition: Database.php:5603
Wikimedia\Rdbms\Database\endAtomic
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
Definition: Database.php:4389
Wikimedia\Rdbms\Database\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:3132
Wikimedia\Rdbms\Database\executeQuery
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
Definition: Database.php:1270
Wikimedia\Rdbms\IDatabase\lastError
lastError()
Get a description of the last error.
DBO_DEBUG
const DBO_DEBUG
Definition: defines.php:9
Wikimedia\Rdbms\Database\setBigSelects
setBigSelects( $value=true)
Allow or deny "big selects" for this session only.This is done by setting the sql_big_selects session...
Definition: Database.php:5467
Wikimedia\Rdbms\Database\doDropTable
doDropTable( $table, $fname)
Definition: Database.php:5403
Wikimedia\Rdbms\Database\doReplace
doReplace( $table, array $uniqueKeys, array $rows, $fname)
Definition: Database.php:3291
Wikimedia\Rdbms\DBReadOnlyRoleError
Exception class for attempted DB write access to a DBConnRef with the DB_REPLICA role.
Definition: DBReadOnlyRoleError.php:30
Wikimedia\Rdbms\DBTransactionStateError
@newable
Definition: DBTransactionStateError.php:28
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\Database\timestampOrNull
timestampOrNull( $ts=null)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
Definition: Database.php:4816
Wikimedia\Rdbms\Database\decodeExpiry
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
Definition: Database.php:5455
Wikimedia\Rdbms\Database\$trxAutomaticAtomic
bool $trxAutomaticAtomic
Whether the current transaction was started implicitly by startAtomic()
Definition: Database.php:147
Wikimedia\Rdbms\Database\initConnection
initConnection()
Initialize the connection to the database over the wire (or to local files)
Definition: Database.php:314
Wikimedia\Rdbms\Database\normalizeConditions
normalizeConditions( $conds, $fname)
Definition: Database.php:2165
Wikimedia\Rdbms\Database\anyString
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
Definition: Database.php:3226
Wikimedia\Rdbms\Database\unionSupportsOrderAndLimit
unionSupportsOrderAndLimit()
Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION....
Definition: Database.php:3678
Wikimedia\Rdbms\DBMasterPos
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:14
Wikimedia\Rdbms\Database\isInsertSelectSafe
isInsertSelectSafe(array $insertOptions, array $selectOptions)
Definition: Database.php:3544
LIST_SET
const LIST_SET
Definition: Defines.php:44
Wikimedia\Rdbms\Database\fieldNameWithAlias
fieldNameWithAlias( $name, $alias=false)
Get an aliased field name e.g.
Definition: Database.php:2998
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:1004
Wikimedia\Rdbms\Database\normalizeOptions
normalizeOptions( $options)
Definition: Database.php:2238
Wikimedia\Rdbms\Database\getDefaultSchemaVars
getDefaultSchemaVars()
Get schema variables to use if none have been set via setSchemaVars().
Definition: Database.php:5258
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:86
Wikimedia\Rdbms\GeneralizedSql
Lazy-loaded wrapper for simplification and scrubbing of SQL queries for profiling.
Definition: GeneralizedSql.php:30
Wikimedia\Rdbms\Database\extractSingleFieldFromList
extractSingleFieldFromList( $var)
Definition: Database.php:2268
Wikimedia\Rdbms\Database\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.Note that unlike most database abstract...
Definition: Database.php:4781
Wikimedia\Rdbms\Database\$trxSectionCancelCallbacks
array[] $trxSectionCancelCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:170
Wikimedia\Rdbms\Database\doTruncate
doTruncate(array $tables, $fname)
Definition: Database.php:5434
Wikimedia\Rdbms\Database\onTransactionCommitOrIdle
onTransactionCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback as soon as there is no transaction pending.
Definition: Database.php:3939
Wikimedia\Rdbms\Database\registerTempWrites
registerTempWrites( $ret, array $changes)
Definition: Database.php:1193
Wikimedia\Rdbms\Database\namedLocksEnqueue
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.bool 1.26
Definition: Database.php:5333
Wikimedia\Rdbms\Database\buildSubstring
buildSubstring( $input, $startPosition, $length=null)
Definition: Database.php:2695
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:23
Wikimedia\Rdbms\Database\tableNamesWithIndexClauseOrJOIN
tableNamesWithIndexClauseOrJOIN( $tables, $use_index=[], $ignore_index=[], $join_conds=[])
Get the aliased table name clause for a FROM clause which might have a JOIN and/or USE INDEX or IGNOR...
Definition: Database.php:3034
Wikimedia\Rdbms\Database\getReplicaPos
getReplicaPos()
Get the replication position of this replica DB.DBMasterPos|bool False if this is not a replica DB If...
Definition: Database.php:3910
Wikimedia\Rdbms\Database\getSchemaVars
getSchemaVars()
Get schema variables.
Definition: Database.php:5245
Wikimedia\Rdbms\Database\setLogger
setLogger(LoggerInterface $logger)
Set the PSR-3 logger interface to use for query logging.
Definition: Database.php:542
Wikimedia\Rdbms\Database\__clone
__clone()
Make sure that copies do not share the same client binding handle.
Definition: Database.php:5566
$res
$res
Definition: testCompression.php:57
Wikimedia\Rdbms\Database\cancelAtomic
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
Definition: Database.php:4423
$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:822
Wikimedia\Rdbms\Database\doInsertSelectGeneric
doInsertSelectGeneric( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
Implementation of insertSelect() based on select() and insert()
Definition: Database.php:3562
Wikimedia\Rdbms\Database\conditional
conditional( $cond, $trueVal, $falseVal)
Returns an SQL expression for a simple conditional.This doesn't need to be overridden unless CASE isn...
Definition: Database.php:3772
Wikimedia\Rdbms\Database\$trxAtomicLevels
array $trxAtomicLevels
List of (name, unique ID, savepoint ID) for each active atomic section level.
Definition: Database.php:145
Wikimedia\Rdbms\Database\$PING_QUERY
static string $PING_QUERY
Dummy SQL query.
Definition: Database.php:232
LIST_COMMA
const LIST_COMMA
Definition: Defines.php:42
Wikimedia\Rdbms\Database\handleSessionLossPostconnect
handleSessionLossPostconnect()
Clean things up after session (and thus transaction) loss after reconnect.
Definition: Database.php:1620
Wikimedia\Rdbms\Database\isPristineTemporaryTable
isPristineTemporaryTable( $table)
Check if the table is both a TEMPORARY table and has not yet received CRUD operations.
Definition: Database.php:1224
Wikimedia\Rdbms\Database\$connectionVariables
string[] int[] float[] $connectionVariables
SQL variables values to use for all new connections.
Definition: Database.php:95
Wikimedia\Rdbms\Database\$lastQuery
string $lastQuery
The last SQL query attempted.
Definition: Database.php:182
Wikimedia\Rdbms\Database\$trxStatusIgnoredCause
array null $trxStatusIgnoredCause
Error details of the last statement-only rollback.
Definition: Database.php:131
DBO_TRX
const DBO_TRX
Definition: defines.php:12
Wikimedia\Rdbms\Database\textFieldSize
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".int
Definition: Database.php:3458
Wikimedia\Rdbms\Database\$affectedRowCount
int null $affectedRowCount
Rows affected by the last query to query() or its CRUD wrappers.
Definition: Database.php:177
Wikimedia\Rdbms\Database\buildConcat
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.Raw SQL expression list; caller is responsible fo...
Definition: Database.php:2616
Wikimedia\Rdbms\Database\bitNot
bitNot( $field)
string
Definition: Database.php:2592
Wikimedia\Rdbms\Database\nextSavepointId
nextSavepointId( $fname)
Definition: Database.php:4343
Wikimedia\Rdbms\Database\$agent
string $agent
Agent name for query profiling.
Definition: Database.php:87
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:5595
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:550
Wikimedia\Rdbms\Database\doBegin
doBegin( $fname)
Issues the BEGIN command to the database server.
Definition: Database.php:4587
Wikimedia\Rdbms\Database\makeConditionCollidesUponKeys
makeConditionCollidesUponKeys(array $rows, array $uniqueKeys)
Definition: Database.php:3358
Wikimedia\Rdbms\Database\isWriteQuery
isWriteQuery( $sql, $flags)
Determine whether a query writes to the DB.
Definition: Database.php:1071
Wikimedia\Rdbms\Database\isFlagInOptions
isFlagInOptions( $option, array $options)
Definition: Database.php:2254
Wikimedia\Rdbms\Database\clearFlag
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
Definition: Database.php:794
Wikimedia\Rdbms\Database\getQueryExceptionAndLog
getQueryExceptionAndLog( $error, $errno, $sql, $fname)
Definition: Database.php:1689
Wikimedia\Rdbms\Database\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Definition: Database.php:4527
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:4847
Wikimedia\Rdbms\Database\doHandleSessionLossPreconnect
doHandleSessionLossPreconnect()
Reset any additional subclass trx* and session* fields.
Definition: Database.php:1613
Wikimedia\Rdbms\Database\$lastWriteTime
float bool $lastWriteTime
UNIX timestamp of last write query.
Definition: Database.php:184
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:4124
Wikimedia\Rdbms\Database\$trxStatusCause
Exception null $trxStatusCause
The last error that caused the status to become STATUS_TRX_ERROR.
Definition: Database.php:129
Wikimedia\Rdbms\Database\close
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition: Database.php:915
Wikimedia\Rdbms\Database\replaceVars
replaceVars( $ins)
Database-independent variable replacement.
Definition: Database.php:5207
Wikimedia\Rdbms\Database\handleSessionLossPreconnect
handleSessionLossPreconnect()
Clean things up after session (and thus transaction) loss before reconnect.
Definition: Database.php:1581
Wikimedia\Rdbms\Database\doInsertNonConflicting
doInsertNonConflicting( $table, array $rows, $fname)
Definition: Database.php:2376
Wikimedia\Rdbms\Database\$NOT_APPLICABLE
static string $NOT_APPLICABLE
Idiom used when a cancelable atomic section started the transaction.
Definition: Database.php:213
Wikimedia\Rdbms\Database\$trxStatus
int $trxStatus
Transaction status.
Definition: Database.php:127
Wikimedia\Rdbms\Database\runOnTransactionPreCommitCallbacks
runOnTransactionPreCommitCallbacks()
Actually consume and run any "on transaction pre-commit" callbacks.
Definition: Database.php:4193
Wikimedia\Rdbms\Database\wasLockTimeout
wasLockTimeout()
Determines if the last failure was due to a lock timeout.Note that during a lock wait timeout,...
Definition: Database.php:3808
Wikimedia\Rdbms\Database\$currentDomain
DatabaseDomain $currentDomain
Definition: Database.php:69
Wikimedia\Rdbms\Database\getLag
getLag()
Get the amount of replication lag for this database server.
Definition: Database.php:5004
Wikimedia\Rdbms\Database\$sessionTempTables
array $sessionTempTables
Map of (table name => 1) for current TEMPORARY tables.
Definition: Database.php:120
Wikimedia\Rdbms\Database\buildSelectSubquery
buildSelectSubquery( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Equivalent to IDatabase::selectSQLText() except wraps the result in Subquery.
Definition: Database.php:2775
Wikimedia\Rdbms\Database\$TEMP_PSEUDO_PERMANENT
static int $TEMP_PSEUDO_PERMANENT
Writes to this temporary table effect lastDoneWrites()
Definition: Database.php:220
Wikimedia\Rdbms\Database\getCacheSetOptions
static getCacheSetOptions(?IDatabase ... $dbs)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Definition: Database.php:4984
Wikimedia\Rdbms\Database\assertBuildSubstringParams
assertBuildSubstringParams( $startPosition, $length)
Check type and bounds for parameters to self::buildSubstring()
Definition: Database.php:2716
Wikimedia\Rdbms\Database\isReadOnly
isReadOnly()
Definition: Database.php:5471
Wikimedia\Rdbms\Database\buildStringCast
buildStringCast( $field)
Field or column to cast string 1.28
Definition: Database.php:2761
Wikimedia\Rdbms\Database\$lazyMasterHandle
IDatabase null $lazyMasterHandle
Lazy handle to the master DB this server replicates from.
Definition: Database.php:76
Wikimedia\Rdbms\Database\unlockTables
unlockTables( $method)
Unlock all tables locked via lockTables()
Definition: Database.php:5366
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:4923
Wikimedia\Rdbms\Database\$trxWriteDuration
float $trxWriteDuration
Seconds spent in write queries for the current transaction.
Definition: Database.php:151
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1034
Wikimedia\Rdbms\Database\doRollbackToSavepoint
doRollbackToSavepoint( $identifier, $fname)
Rollback to a savepoint.
Definition: Database.php:4334
Wikimedia\Rdbms\Database\dropTable
dropTable( $table, $fname=__METHOD__)
Delete a table.
Definition: Database.php:5387
Wikimedia\Rdbms\Database\getTempTableWrites
getTempTableWrites( $sql, $pseudoPermanent)
Definition: Database.php:1137
Wikimedia\Rdbms\Database\doInsertSelectNative
doInsertSelectNative( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
Native server-side implementation of insertSelect() for situations where we don't want to select ever...
Definition: Database.php:3627
Wikimedia\Rdbms\Database\startAtomic
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Definition: Database.php:4358
Wikimedia\Rdbms\DBQueryTimeoutError
Error thrown when a query times out.
Definition: DBQueryTimeoutError.php:30
Wikimedia\Rdbms\Database\selectOptionsIncludeLocking
selectOptionsIncludeLocking( $options)
Definition: Database.php:2095
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
Wikimedia\Rdbms\Database\open
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
Wikimedia\Rdbms\Database\lock
lock( $lockName, $method, $timeout=5)
Acquire a named lock.Named locks are not related to transactionsName of lock to aquire Name of the ca...
Definition: Database.php:5277
Wikimedia\Rdbms\Database\getTransactionRoundId
getTransactionRoundId()
Definition: Database.php:691
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:558
Wikimedia\Rdbms\Database\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Definition: Database.php:779
Wikimedia\Rdbms\Database\rollback
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
Definition: Database.php:4670
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:1510
Wikimedia\Rdbms\Database\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Run a callback after each time any transaction commits or rolls back.
Definition: Database.php:4094
Wikimedia\Rdbms\Database\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
Definition: Database.php:3183
Wikimedia\Rdbms\Database\$tableAliases
array[] $tableAliases
Current map of (table => (dbname, schema, prefix) map)
Definition: Database.php:106
Wikimedia\Rdbms\Database\reportQueryError
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
Definition: Database.php:1674
Wikimedia\Rdbms\Database\$cliMode
bool $cliMode
Whether this PHP instance is for a CLI script.
Definition: Database.php:85
Wikimedia\Rdbms\Database\$trxShortId
string $trxShortId
ID of the active transaction or the empty string otherwise.
Definition: Database.php:125
Wikimedia\Rdbms\Database\isTransactableQuery
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
Definition: Database.php:1121
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:2284
Wikimedia\Rdbms\Database\indexExists
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists.
Definition: Database.php:2306
Wikimedia\Rdbms\Database\writesOrCallbacksPending
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...
Definition: Database.php:674
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:5092
Wikimedia\Rdbms\Database\selectSQLText
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Take the same arguments as IDatabase::select() and return the SQL it would use.This can be useful for...
Definition: Database.php:1936
Wikimedia\Rdbms\SelectQueryBuilder
Definition: SelectQueryBuilder.php:5
Wikimedia\Rdbms\Database\makeInsertLists
makeInsertLists(array $rows)
Make SQL lists of columns, row tuples for INSERT/VALUES expressions.
Definition: Database.php:2405
$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:218
Wikimedia\Rdbms\Database\$trxWriteCallers
string[] $trxWriteCallers
Write query callers of the current transaction.
Definition: Database.php:149
Wikimedia\Rdbms\Database\doUpsert
doUpsert( $table, array $rows, array $uniqueKeys, array $set, $fname)
Definition: Database.php:3403
Wikimedia\Rdbms\Database\$lastPing
float $lastPing
UNIX timestamp.
Definition: Database.php:180
Wikimedia\Rdbms\Database\bitAnd
bitAnd( $fieldLeft, $fieldRight)
string
Definition: Database.php:2600
Wikimedia\Rdbms\Database\buildLike
buildLike( $param,... $params)
LIKE statement wrapper.This takes a variable-length argument list with parts of pattern to match cont...
Definition: Database.php:3195
Wikimedia\Rdbms\Database\$trxProfiler
TransactionProfiler $trxProfiler
Definition: Database.php:66
Wikimedia\Rdbms\Database\$user
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:81
Wikimedia\Rdbms\Database\assertNoOpenTransactions
assertNoOpenTransactions()
Assert that all explicit transactions or atomic sections have been closed.
Definition: Database.php:1537
Wikimedia\Rdbms\Database\selectDB
selectDB( $db)
Change the current database.
Definition: Database.php:2792
Wikimedia\Rdbms\Database\wasQueryTimeout
wasQueryTimeout( $error, $errno)
Checks whether the cause of the error is detected to be a timeout.
Definition: Database.php:1659
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:666
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:237
Wikimedia\Rdbms\Database\wasReadOnlyError
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.bool
Definition: Database.php:3824
Wikimedia\Rdbms\Database\beginIfImplied
beginIfImplied( $sql, $fname)
Start an implicit transaction if DBO_TRX is enabled and no transaction is active.
Definition: Database.php:1458
Wikimedia\Rdbms\Database\getQueryException
getQueryException( $error, $errno, $sql, $fname)
Definition: Database.php:1713
Wikimedia\Rdbms\Database\getServerInfo
getServerInfo()
Get a human-readable string describing the current software version.
Definition: Database.php:546
Wikimedia\Rdbms\Database\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Definition: Database.php:4591
Wikimedia\Rdbms\Database\buildLeast
buildLeast( $fields, $values)
Build a LEAST function statement comparing columns/values.Integer and float values in $values will no...
Definition: Database.php:2644
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:809
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:894
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:630
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:5293
Wikimedia\Rdbms\Database\fieldNamesWithAlias
fieldNamesWithAlias( $fields)
Gets an array of aliased field names.
Definition: Database.php:3012
Wikimedia\Rdbms\Database\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:618
Wikimedia\Rdbms\DBReadOnlyError
@newable
Definition: DBReadOnlyError.php:28
Wikimedia\Rdbms\Database\$trxWriteAffectedRows
int $trxWriteAffectedRows
Number of rows affected by write queries for the current transaction.
Definition: Database.php:155
Wikimedia\Rdbms\Database\$trxWriteAdjDuration
float $trxWriteAdjDuration
Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries.
Definition: Database.php:157
Wikimedia\Rdbms\Database\insertSelect
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper.
Definition: Database.php:3493
Wikimedia\Rdbms\Database\normalizeRowArray
normalizeRowArray(array $rowOrRows)
Definition: Database.php:2139
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:2023
Wikimedia\Rdbms\DBQueryError
@newable
Definition: DBQueryError.php:29
Wikimedia\Rdbms\Database\useIndexClause
useIndexClause( $index)
USE INDEX clause.
Definition: Database.php:3247
Wikimedia\Rdbms\Database\makeUpdateOptions
makeUpdateOptions( $options)
Make UPDATE options for the Database::update function.
Definition: Database.php:2460
Wikimedia\Rdbms\Database\getReadOnlyReason
getReadOnlyReason()
Definition: Database.php:5478
Wikimedia\Rdbms\Database\buildSuperlative
buildSuperlative( $sqlfunc, $fields, $values)
Build a superlative function statement comparing columns/values.
Definition: Database.php:2664
Wikimedia\Rdbms\DBQueryDisconnectedError
@newable
Definition: DBQueryDisconnectedError.php:29
Wikimedia\Rdbms\Database\$priorFlags
int[] $priorFlags
Prior flags member variable values.
Definition: Database.php:115
Wikimedia\Rdbms\Database\doGetLag
doGetLag()
Definition: Database.php:5018
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:853
Wikimedia\Rdbms\Database\aggregateValue
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.array|string Since 1.33
Definition: Database.php:2584
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:864
Wikimedia\Rdbms\Database\preCommitCallbacksPending
preCommitCallbacksPending()
Definition: Database.php:684
Wikimedia\Rdbms\Database\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Definition: Database.php:3854
Wikimedia\Rdbms\Database\pendingWriteAndCallbackCallers
pendingWriteAndCallbackCallers()
List the methods that have write queries or callbacks for the current transaction.
Definition: Database.php:750
Wikimedia\Rdbms\Database\$htmlErrors
string bool null $htmlErrors
Stashed value of html_errors INI setting.
Definition: Database.php:113
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:215
Wikimedia\Rdbms\Database\pendingWriteCallers
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
Definition: Database.php:734
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MAX
static int $DEADLOCK_DELAY_MAX
Maximum time to wait before retry.
Definition: Database.php:227
Wikimedia\Rdbms\Database\$trxEndCallbacks
array[] $trxEndCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:168
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:2938
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:5542
Wikimedia\Rdbms\Database\$lastRoundTripEstimate
float $lastRoundTripEstimate
Query round trip time estimate.
Definition: Database.php:188
Wikimedia\Rdbms\Database\getLogContext
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: Database.php:904
Wikimedia\Rdbms\Database\$connectionParams
array $connectionParams
Parameters used by initConnection() to establish a connection.
Definition: Database.php:93
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:141
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:4741
Wikimedia\Rdbms\Database\pendingWriteRowsAffected
pendingWriteRowsAffected()
Get the number of affected rows from pending write queries.
Definition: Database.php:738
Wikimedia\Rdbms\Database\$trxPreCommitOrIdleCallbacks
array[] $trxPreCommitOrIdleCallbacks
List of (callable, method name, atomic section id)
Definition: Database.php:163
Wikimedia\Rdbms\Database\$trxWriteQueryCount
int $trxWriteQueryCount
Number of write queries for the current transaction.
Definition: Database.php:153
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:4318
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:1367
$line
$line
Definition: mcc.php:119
Wikimedia\Rdbms\Database\currentAtomicSectionId
currentAtomicSectionId()
Definition: Database.php:3997
Wikimedia\Rdbms\Database\modifyCallbacksForCancel
modifyCallbacksForCancel(array $sectionIds, AtomicSectionIdentifier $newSectionId=null)
Update callbacks that were owned by cancelled atomic sections.
Definition: Database.php:4058
Wikimedia\Rdbms\Database\setTrxEndCallbackSuppression
setTrxEndCallbackSuppression( $suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
Definition: Database.php:4110
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $flags=self::QUERY_NORMAL)
Run an SQL query and return the result.
Definition: Database.php:1233
Wikimedia\Rdbms\IDatabase\fetchRow
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
Wikimedia\Rdbms\Database\getMasterPos
getMasterPos()
Get the position of this master.DBMasterPos|bool False if this is not a master If an error occurs,...
Definition: Database.php:3919
Wikimedia\Rdbms\Database\pendingWriteQueryDuration
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
Definition: Database.php:702
Wikimedia\Rdbms\Database\$indexAliases
string[] $indexAliases
Current map of (index alias => index)
Definition: Database.php:108
Wikimedia\Rdbms\LikeMatch
Used by Database::buildLike() to represent characters that have special meaning in SQL LIKE clauses a...
Definition: LikeMatch.php:10
Wikimedia\Rdbms\Database\tableName
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.This does two important things: it quo...
Definition: Database.php:2829
Wikimedia\Rdbms\Database\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: Database.php:3843
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:4509
Wikimedia\Rdbms\Database\replace
replace( $table, $uniqueKeys, $rows, $fname=__METHOD__)
Insert row(s) into a table, deleting all conflicting rows beforehand.
Definition: Database.php:3264
Wikimedia\Rdbms\Database\getRecordedTransactionLagStatus
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
Definition: Database.php:4940
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:4228
Wikimedia\Rdbms\Database\getServer
getServer()
Get the server hostname or IP address.
Definition: Database.php:2821
Wikimedia\Rdbms\DBUnexpectedError
@newable
Definition: DBUnexpectedError.php:29
Wikimedia\Rdbms\Database\doLockTables
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
Definition: Database.php:5362
Wikimedia\Rdbms\Database\doUnlockTables
doUnlockTables( $method)
Helper function for unlockTables() that handles the actual table unlocking.
Definition: Database.php:5383
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:4810
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:1756
Wikimedia\Rdbms\Database\anyChar
anyChar()
Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
Definition: Database.php:3222
Wikimedia\Rdbms\Database\onTransactionIdle
onTransactionIdle(callable $callback, $fname=__METHOD__)
Alias for onTransactionCommitOrIdle() for backwards-compatibility.
Definition: Database.php:3957
Wikimedia\Rdbms\Database\unlock
unlock( $lockName, $method)
Release a lock.Named locks are not related to transactionsName of lock to release Name of the calling...
Definition: Database.php:5287
Wikimedia\Rdbms\Database\$profiler
callable null $profiler
Definition: Database.php:64
Wikimedia\Rdbms\Database\$SMALL_WRITE_ROWS
static float $SMALL_WRITE_ROWS
Assume an insert of this many rows or less should be fast to replicate.
Definition: Database.php:239
Wikimedia\Rdbms\Database\addIdentifierQuotes
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.table, column, database) for use in a SQL queryDepending on the database...
Definition: Database.php:3159
Wikimedia\Rdbms\Database\getLazyMasterHandle
getLazyMasterHandle()
Get a handle to the master server of the cluster to which this server belongs.
Definition: Database.php:650
Wikimedia\Rdbms\Database\consumeTrxShortId
consumeTrxShortId()
Reset the transaction ID and return the old one.
Definition: Database.php:1641
Wikimedia\Rdbms\Database\estimateRowCount
estimateRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate the number of rows in dataset.MySQL allows you to estimate the number of rows that would be ...
Definition: Database.php:2045
Wikimedia\Rdbms\Database\truncate
truncate( $tables, $fname=__METHOD__)
Delete all data in a table(s) and reset any sequences owned by that table(s)
Definition: Database.php:5411
Wikimedia\Rdbms\Database\dbSchema
dbSchema( $schema=null)
Get/set the db schema.
Definition: Database.php:588
Wikimedia\Rdbms\Database\$trxRecurringCallbacks
callable[] $trxRecurringCallbacks
Map of (name => callable)
Definition: Database.php:172
Wikimedia\Rdbms\Database\getQueryVerb
getQueryVerb( $sql)
Definition: Database.php:1103
Wikimedia\Rdbms\Database\unionQueries
unionQueries( $sqls, $all)
Construct a UNION query.This is used for providing overload point for other DB abstractions not compa...
Definition: Database.php:3686
Wikimedia\Rdbms\DBTransactionError
@newable
Definition: DBTransactionError.php:29
Wikimedia\Rdbms\Database\reassignCallbacksForSection
reassignCallbacksForSection(AtomicSectionIdentifier $old, AtomicSectionIdentifier $new)
Hoist callback ownership for callbacks in a section to a parent section.
Definition: Database.php:4013
Wikimedia\Rdbms\Database\insert
insert( $table, $rows, $fname=__METHOD__, $options=[])
Insert the given row(s) into a table.
Definition: Database.php:2335
Wikimedia\Rdbms\IDatabase\lastErrno
lastErrno()
Get the last error number.
Wikimedia\Rdbms\Database\relationSchemaQualifier
relationSchemaQualifier()
Definition: Database.php:614
Wikimedia\Rdbms\Database\$DEADLOCK_TRIES
static int $DEADLOCK_TRIES
Number of times to re-try an operation in case of deadlock.
Definition: Database.php:223
Wikimedia\Rdbms\Database\makeInsertNonConflictingVerbAndOptions
makeInsertNonConflictingVerbAndOptions()
Definition: Database.php:2391
Wikimedia\Rdbms\Database\newExceptionAfterConnectError
newExceptionAfterConnectError( $error)
Definition: Database.php:1727
Wikimedia\Rdbms\Database\lockTables
lockTables(array $read, array $write, $method)
Lock specific tables.
Definition: Database.php:5341
Wikimedia\Rdbms\Database\$trxAtomicCounter
int $trxAtomicCounter
Counter for atomic savepoint identifiers (reset with each transaction)
Definition: Database.php:143
Wikimedia\Rdbms\Database\encodeExpiry
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
Definition: Database.php:5449
Wikimedia\Rdbms\Database\$srvCache
BagOStuff $srvCache
APC cache.
Definition: Database.php:52
Wikimedia\Rdbms\Database\buildGreatest
buildGreatest( $fields, $values)
Build a GREATEST function statement comparing columns/values.Integer and float values in $values will...
Definition: Database.php:2636
Wikimedia\Rdbms\Database\doSavepoint
doSavepoint( $identifier, $fname)
Create a savepoint.
Definition: Database.php:4302
Wikimedia\Rdbms\Database\setSchemaVars
setSchemaVars( $vars)
Set schema variables to be used when streaming commands from SQL files or stdin.
Definition: Database.php:5088
Wikimedia\Rdbms\Database\__construct
__construct(array $params)
Definition: Database.php:258
Wikimedia\Rdbms\Database\trxTimestamp
trxTimestamp()
Get the UNIX timestamp of the time that the transaction was established.
Definition: Database.php:562
Wikimedia\Rdbms\Database\$trxTimestamp
float null $trxTimestamp
UNIX timestamp at the time of BEGIN for the last transaction.
Definition: Database.php:133
Wikimedia\Rdbms\Database\makeGroupByWithHaving
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1886
Wikimedia\Rdbms\Database\tableNameWithAlias
tableNameWithAlias( $table, $alias=false)
Get an aliased table name.
Definition: Database.php:2969
Wikimedia\Rdbms\Database\getAttributes
static getAttributes()
Definition: Database.php:531
Wikimedia\Rdbms\Database\writesPending
writesPending()
Definition: Database.php:670
Wikimedia\Rdbms\Database\normalizeUpsertKeys
normalizeUpsertKeys( $uniqueKeys)
Definition: Database.php:2186
Wikimedia\Rdbms\Database\selectFieldsOrOptionsAggregate
selectFieldsOrOptionsAggregate( $fields, $options)
Definition: Database.php:2111
Wikimedia\Rdbms\Database\lockIsFree
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)Name of lock to poll Name of m...
Definition: Database.php:5266
Wikimedia\Rdbms\Database\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Definition: Database.php:4859
Wikimedia\Rdbms\Database\$nonNativeInsertSelectBatchSize
int $nonNativeInsertSelectBatchSize
Row batch size to use for emulated INSERT SELECT queries.
Definition: Database.php:97
Wikimedia\Rdbms\Database\runTransactionListenerCallbacks
runTransactionListenerCallbacks( $trigger)
Actually run any "transaction listener" callbacks.
Definition: Database.php:4269
Wikimedia\Rdbms\Database\onAtomicSectionCancel
onAtomicSectionCancel(callable $callback, $fname=__METHOD__)
Run a callback when the atomic section is cancelled.
Definition: Database.php:3987
Wikimedia\Rdbms\Database\getTopologyRootMaster
getTopologyRootMaster()
Get the host (or address) of the root master server for the replication topology.
Definition: Database.php:554
Wikimedia\Rdbms\DBConnectionError
@newable
Definition: DBConnectionError.php:27
Wikimedia\Rdbms\Database\setTableAliases
setTableAliases(array $aliases)
Make certain table names use their own database, schema, and table prefix when passed into SQL querie...
Definition: Database.php:5497
Wikimedia\Rdbms\Database\$MUTABLE_FLAGS
static string[] $MUTABLE_FLAGS
List of DBO_* flags that can be changed after connection.
Definition: Database.php:242
Wikimedia\Rdbms\Database\masterPosWait
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.Note that this does not start any new ...
Definition: Database.php:3901
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:3932
Wikimedia\Rdbms\IDatabase\getType
getType()
Get the type of the DBMS (e.g.
Wikimedia\Rdbms\Database\explicitTrxActive
explicitTrxActive()
Definition: Database.php:4773
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:79
Wikimedia\Rdbms\Database\freeResult
freeResult( $res)
Free a result object returned by query() or select()It's usually not necessary to call this,...
Definition: Database.php:1746
Wikimedia\Rdbms\Database\isOpen
isOpen()
Definition: Database.php:775
Wikimedia\Rdbms\Database\doCommit
doCommit( $fname)
Issues the COMMIT command to the database server.
Definition: Database.php:4664
$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:91
Wikimedia\Rdbms\Database\makeOrderBy
makeOrderBy( $options)
Returns an optional ORDER BY.
Definition: Database.php:1912
Wikimedia\Rdbms\Database\$flags
int $flags
Current bit field of class DBO_* constants.
Definition: Database.php:100
Wikimedia\Rdbms\Database\serverIsReadOnly
serverIsReadOnly()
bool Whether the DB is marked as read-only server-side 1.28
Definition: Database.php:3928
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:1815
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:1924
Wikimedia\Rdbms\Database\attributesFromType
static attributesFromType( $dbType, $driver=null)
Definition: Database.php:460
Wikimedia\Rdbms\Database\lastQuery
lastQuery()
Get the last query that sent on account of IDatabase::query()
Definition: Database.php:662
Wikimedia\Rdbms\Database\wasConnectionLoss
wasConnectionLoss()
Determines if the last query error was due to a dropped connection.Note that during a connection loss...
Definition: Database.php:3816
Wikimedia\Rdbms\Database\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.Note that during a deadlock, the prior transacti...
Definition: Database.php:3800
$t
$t
Definition: testCompression.php:74
Wikimedia\Rdbms\Database\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Definition: Database.php:2813
Wikimedia\Rdbms\Database\$connLogger
LoggerInterface $connLogger
Definition: Database.php:54
Wikimedia\Rdbms\Database\addQuotes
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.string
Definition: Database.php:3140
Wikimedia\Rdbms\Database\$replLogger
LoggerInterface $replLogger
Definition: Database.php:58
Wikimedia\Rdbms\Database\assertConditionIsNotEmpty
assertConditionIsNotEmpty( $conds, string $fname, bool $deprecate)
Check type and bounds conditions parameters for update.
Definition: Database.php:2746
Wikimedia\Rdbms\Database\getApproximateLagStatus
getApproximateLagStatus()
Get a replica DB lag estimate for this server at the start of a transaction.
Definition: Database.php:4955
Wikimedia\Rdbms\Database\qualifiedTableComponents
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
Definition: Database.php:2887
Wikimedia\Rdbms\Database\affectedRows
affectedRows()
Get the number of rows affected by the last write query.
Definition: Database.php:4824
Wikimedia\Rdbms\Database\$DEADLOCK_DELAY_MIN
static int $DEADLOCK_DELAY_MIN
Minimum time to wait before retry, in microseconds.
Definition: Database.php:225
Wikimedia\Rdbms\Database\fetchAffectedRowCount
fetchAffectedRowCount()
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/schema/prefix specifications for IDatabase.
Definition: DatabaseDomain.php:40
Wikimedia\Rdbms\Database\databasesAreIndependent
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.In systems like mysql/mariadb,...
Definition: Database.php:2788
Wikimedia\Rdbms\TransactionProfiler
Detect high-contention DB queries via profiling calls.
Definition: TransactionProfiler.php:39
Wikimedia\Rdbms\Database\indexInfo
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.
Wikimedia\Rdbms\Database\strreplace
strreplace( $orig, $old, $new)
Returns a SQL expression for simple string replacement (e.g.REPLACE() in mysql)Column to modify Colum...
Definition: Database.php:3784
Wikimedia\Rdbms\Database\$ownerId
int null $ownerId
Integer ID of the managing LBFactory instance or null if none.
Definition: Database.php:191
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:5056
Wikimedia\Rdbms\Database\listViews
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.Only show VIEWs with this prefix, eg. unit_test_ Name of calling ...
Definition: Database.php:4802
Wikimedia\Rdbms\Database\newSelectQueryBuilder
newSelectQueryBuilder()
Create an empty SelectQueryBuilder which can be used to run queries against this connection....
Definition: Database.php:1752
Wikimedia\Rdbms\Database\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
Definition: Database.php:5170
Wikimedia\Rdbms\Database\makeList
makeList(array $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2484
Wikimedia\Rdbms\IMaintainableDatabase
Advanced database interface for IDatabase handles that include maintenance methods.
Definition: IMaintainableDatabase.php:38
Wikimedia\Rdbms\Database\nextSequenceValue
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
Definition: Database.php:3230
Wikimedia\Rdbms\Subquery
Definition: Subquery.php:27
Wikimedia\Rdbms\Database\makeConditionCollidesUponKey
makeConditionCollidesUponKey(array $rows, array $uniqueKey)
Definition: Database.php:3317
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:1781
Wikimedia\Rdbms\Database\flatAtomicSectionList
flatAtomicSectionList()
Definition: Database.php:769
Wikimedia\Rdbms\Database\$deprecationLogger
callable $deprecationLogger
Deprecation logging callback.
Definition: Database.php:62
Wikimedia\Rdbms\Database\$errorLogger
callable $errorLogger
Error logging callback.
Definition: Database.php:60
Wikimedia\Rdbms\Database\$conn
object resource null $conn
Database connection.
Definition: Database.php:73
Wikimedia\Rdbms\Database\doRollback
doRollback( $fname)
Issues the ROLLBACK command to the database server.
Definition: Database.php:4734
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:235
Wikimedia\Rdbms\Database\$lbInfo
array $lbInfo
Current LoadBalancer tracking information.
Definition: Database.php:102
Wikimedia\Rdbms\Database\getDBname
getDBname()
Get the current DB name.
Definition: Database.php:2817
Wikimedia\Rdbms\Blob
@newable
Definition: Blob.php:9
Wikimedia\Rdbms\Database\getInfinity
getInfinity()
Find out when 'infinity' is.Most DBMSes support this. This is a special keyword for timestamps in Pos...
Definition: Database.php:5445
$type
$type
Definition: testCompression.php:52
Wikimedia\Rdbms\Database\$sessionNamedLocks
array $sessionNamedLocks
Map of (name => 1) for locks obtained via lock()
Definition: Database.php:118