MediaWiki  master
DatabaseMysqlBase.php
Go to the documentation of this file.
1 <?php
23 namespace Wikimedia\Rdbms;
24 
25 use DateTime;
26 use DateTimeZone;
29 use Exception;
31 use stdClass;
32 
41 abstract class DatabaseMysqlBase extends Database {
47  protected $lagDetectionOptions = [];
49  protected $useGTIDs = false;
51  protected $sslKeyPath;
53  protected $sslCertPath;
55  protected $sslCAFile;
57  protected $sslCAPath;
59  protected $sslCiphers;
61  protected $sqlMode;
63  protected $utf8Mode;
65  protected $defaultBigSelects = null;
66 
68  private $insertSelectIsSafe = null;
70  private $replicationInfoRow = null;
71 
72  // Cache getServerId() for 24 hours
73  const SERVER_ID_CACHE_TTL = 86400;
74 
76  const LAG_STALE_WARN_THRESHOLD = 0.100;
77 
97  public function __construct( array $params ) {
98  $this->lagDetectionMethod = $params['lagDetectionMethod'] ?? 'Seconds_Behind_Master';
99  $this->lagDetectionOptions = $params['lagDetectionOptions'] ?? [];
100  $this->useGTIDs = !empty( $params['useGTIDs' ] );
101  foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
102  $var = "ssl{$name}";
103  if ( isset( $params[$var] ) ) {
104  $this->$var = $params[$var];
105  }
106  }
107  $this->sqlMode = $params['sqlMode'] ?? null;
108  $this->utf8Mode = !empty( $params['utf8Mode'] );
109  $this->insertSelectIsSafe = isset( $params['insertSelectIsSafe'] )
110  ? (bool)$params['insertSelectIsSafe'] : null;
111 
112  parent::__construct( $params );
113  }
114 
118  public function getType() {
119  return 'mysql';
120  }
121 
122  protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
123  $this->close();
124 
125  if ( $schema !== null ) {
126  throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
127  }
128 
129  $this->server = $server;
130  $this->user = $user;
131  $this->password = $password;
132 
133  $this->installErrorHandler();
134  try {
135  $this->conn = $this->mysqlConnect( $this->server, $dbName );
136  } catch ( Exception $e ) {
137  $this->restoreErrorHandler();
138  throw $this->newExceptionAfterConnectError( $e->getMessage() );
139  }
140  $error = $this->restoreErrorHandler();
141 
142  if ( !$this->conn ) {
143  throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
144  }
145 
146  try {
147  $this->currentDomain = new DatabaseDomain(
148  strlen( $dbName ) ? $dbName : null,
149  null,
150  $tablePrefix
151  );
152  // Abstract over any insane MySQL defaults
153  $set = [ 'group_concat_max_len = 262144' ];
154  // Set SQL mode, default is turning them all off, can be overridden or skipped with null
155  if ( is_string( $this->sqlMode ) ) {
156  $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
157  }
158  // Set any custom settings defined by site config
159  // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
160  foreach ( $this->connectionVariables as $var => $val ) {
161  // Escape strings but not numbers to avoid MySQL complaining
162  if ( !is_int( $val ) && !is_float( $val ) ) {
163  $val = $this->addQuotes( $val );
164  }
165  $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
166  }
167 
168  if ( $set ) {
169  $this->query(
170  'SET ' . implode( ', ', $set ),
171  __METHOD__,
172  self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY
173  );
174  }
175  } catch ( Exception $e ) {
176  throw $this->newExceptionAfterConnectError( $e->getMessage() );
177  }
178  }
179 
180  protected function doSelectDomain( DatabaseDomain $domain ) {
181  if ( $domain->getSchema() !== null ) {
182  throw new DBExpectedError(
183  $this,
184  __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
185  );
186  }
187 
188  $database = $domain->getDatabase();
189  // A null database means "don't care" so leave it as is and update the table prefix
190  if ( $database === null ) {
191  $this->currentDomain = new DatabaseDomain(
192  $this->currentDomain->getDatabase(),
193  null,
194  $domain->getTablePrefix()
195  );
196 
197  return true;
198  }
199 
200  if ( $database !== $this->getDBname() ) {
201  $sql = 'USE ' . $this->addIdentifierQuotes( $database );
202  list( $res, $err, $errno ) =
203  $this->executeQuery( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
204 
205  if ( $res === false ) {
206  $this->reportQueryError( $err, $errno, $sql, __METHOD__ );
207  return false; // unreachable
208  }
209  }
210 
211  // Update that domain fields on success (no exception thrown)
212  $this->currentDomain = $domain;
213 
214  return true;
215  }
216 
225  abstract protected function mysqlConnect( $realServer, $dbName );
226 
231  public function freeResult( $res ) {
232  AtEase::suppressWarnings();
233  $ok = $this->mysqlFreeResult( ResultWrapper::unwrap( $res ) );
234  AtEase::restoreWarnings();
235  if ( !$ok ) {
236  throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
237  }
238  }
239 
246  abstract protected function mysqlFreeResult( $res );
247 
253  public function fetchObject( $res ) {
254  AtEase::suppressWarnings();
255  $row = $this->mysqlFetchObject( ResultWrapper::unwrap( $res ) );
256  AtEase::restoreWarnings();
257 
258  $errno = $this->lastErrno();
259  // Unfortunately, mysql_fetch_object does not reset the last errno.
260  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
261  // these are the only errors mysql_fetch_object can cause.
262  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
263  if ( $errno == 2000 || $errno == 2013 ) {
264  throw new DBUnexpectedError(
265  $this,
266  'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
267  );
268  }
269 
270  return $row;
271  }
272 
279  abstract protected function mysqlFetchObject( $res );
280 
286  public function fetchRow( $res ) {
287  AtEase::suppressWarnings();
288  $row = $this->mysqlFetchArray( ResultWrapper::unwrap( $res ) );
289  AtEase::restoreWarnings();
290 
291  $errno = $this->lastErrno();
292  // Unfortunately, mysql_fetch_array does not reset the last errno.
293  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
294  // these are the only errors mysql_fetch_array can cause.
295  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
296  if ( $errno == 2000 || $errno == 2013 ) {
297  throw new DBUnexpectedError(
298  $this,
299  'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
300  );
301  }
302 
303  return $row;
304  }
305 
312  abstract protected function mysqlFetchArray( $res );
313 
319  function numRows( $res ) {
320  if ( is_bool( $res ) ) {
321  $n = 0;
322  } else {
323  AtEase::suppressWarnings();
324  $n = $this->mysqlNumRows( ResultWrapper::unwrap( $res ) );
325  AtEase::restoreWarnings();
326  }
327 
328  // Unfortunately, mysql_num_rows does not reset the last errno.
329  // We are not checking for any errors here, since
330  // there are no errors mysql_num_rows can cause.
331  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
332  // See https://phabricator.wikimedia.org/T44430
333  return $n;
334  }
335 
342  abstract protected function mysqlNumRows( $res );
343 
348  public function numFields( $res ) {
349  return $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
350  }
351 
358  abstract protected function mysqlNumFields( $res );
359 
365  public function fieldName( $res, $n ) {
366  return $this->mysqlFieldName( ResultWrapper::unwrap( $res ), $n );
367  }
368 
376  abstract protected function mysqlFieldName( $res, $n );
377 
384  public function fieldType( $res, $n ) {
385  return $this->mysqlFieldType( ResultWrapper::unwrap( $res ), $n );
386  }
387 
395  abstract protected function mysqlFieldType( $res, $n );
396 
402  public function dataSeek( $res, $row ) {
403  return $this->mysqlDataSeek( ResultWrapper::unwrap( $res ), $row );
404  }
405 
413  abstract protected function mysqlDataSeek( $res, $row );
414 
418  public function lastError() {
419  if ( $this->conn ) {
420  # Even if it's non-zero, it can still be invalid
421  AtEase::suppressWarnings();
422  $error = $this->mysqlError( $this->conn );
423  if ( !$error ) {
424  $error = $this->mysqlError();
425  }
426  AtEase::restoreWarnings();
427  } else {
428  $error = $this->mysqlError();
429  }
430  if ( $error ) {
431  $error .= ' (' . $this->server . ')';
432  }
433 
434  return $error;
435  }
436 
443  abstract protected function mysqlError( $conn = null );
444 
445  protected function wasQueryTimeout( $error, $errno ) {
446  // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
447  // https://phabricator.wikimedia.org/T170638
448  return in_array( $errno, [ 2062, 3024 ] );
449  }
450 
451  public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
452  $this->nativeReplace( $table, $rows, $fname );
453  }
454 
455  protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
456  $row = $this->getReplicationSafetyInfo();
457  // For row-based-replication, the resulting changes will be relayed, not the query
458  if ( $row->binlog_format === 'ROW' ) {
459  return true;
460  }
461  // LIMIT requires ORDER BY on a unique key or it is non-deterministic
462  if ( isset( $selectOptions['LIMIT'] ) ) {
463  return false;
464  }
465  // In MySQL, an INSERT SELECT is only replication safe with row-based
466  // replication or if innodb_autoinc_lock_mode is 0. When those
467  // conditions aren't met, use non-native mode.
468  // While we could try to determine if the insert is safe anyway by
469  // checking if the target table has an auto-increment column that
470  // isn't set in $varMap, that seems unlikely to be worth the extra
471  // complexity.
472  return (
473  in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
474  (int)$row->innodb_autoinc_lock_mode === 0
475  );
476  }
477 
481  protected function getReplicationSafetyInfo() {
482  if ( $this->replicationInfoRow === null ) {
483  $this->replicationInfoRow = $this->selectRow(
484  false,
485  [
486  'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
487  'binlog_format' => '@@binlog_format',
488  ],
489  [],
490  __METHOD__
491  );
492  }
493 
495  }
496 
510  public function estimateRowCount( $table, $var = '*', $conds = '',
511  $fname = __METHOD__, $options = [], $join_conds = []
512  ) {
513  $conds = $this->normalizeConditions( $conds, $fname );
514  $column = $this->extractSingleFieldFromList( $var );
515  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
516  $conds[] = "$column IS NOT NULL";
517  }
518 
519  $options['EXPLAIN'] = true;
520  $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
521  if ( $res === false ) {
522  return false;
523  }
524  if ( !$this->numRows( $res ) ) {
525  return 0;
526  }
527 
528  $rows = 1;
529  foreach ( $res as $plan ) {
530  $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
531  }
532 
533  return (int)$rows;
534  }
535 
536  public function tableExists( $table, $fname = __METHOD__ ) {
537  // Split database and table into proper variables as Database::tableName() returns
538  // shared tables prefixed with their database, which do not work in SHOW TABLES statements
539  list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
540  $tableName = "{$prefix}{$table}";
541 
542  if ( isset( $this->sessionTempTables[$tableName] ) ) {
543  return true; // already known to exist and won't show in SHOW TABLES anyway
544  }
545 
546  // We can't use buildLike() here, because it specifies an escape character
547  // other than the backslash, which is the only one supported by SHOW TABLES
548  $encLike = $this->escapeLikeInternal( $tableName, '\\' );
549 
550  // If the database has been specified (such as for shared tables), use "FROM"
551  if ( $database !== '' ) {
552  $encDatabase = $this->addIdentifierQuotes( $database );
553  $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
554  } else {
555  $query = "SHOW TABLES LIKE '$encLike'";
556  }
557 
558  return $this->query( $query, $fname )->numRows() > 0;
559  }
560 
566  public function fieldInfo( $table, $field ) {
567  $table = $this->tableName( $table );
568  $flags = self::QUERY_SILENCE_ERRORS;
569  $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, $flags );
570  if ( !$res ) {
571  return false;
572  }
573  $n = $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
574  for ( $i = 0; $i < $n; $i++ ) {
575  $meta = $this->mysqlFetchField( ResultWrapper::unwrap( $res ), $i );
576  if ( $field == $meta->name ) {
577  return new MySQLField( $meta );
578  }
579  }
580 
581  return false;
582  }
583 
591  abstract protected function mysqlFetchField( $res, $n );
592 
602  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
603  # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
604  # SHOW INDEX should work for 3.x and up:
605  # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
606  $table = $this->tableName( $table );
607  $index = $this->indexName( $index );
608 
609  $sql = 'SHOW INDEX FROM ' . $table;
610  $res = $this->query( $sql, $fname );
611 
612  if ( !$res ) {
613  return null;
614  }
615 
616  $result = [];
617 
618  foreach ( $res as $row ) {
619  if ( $row->Key_name == $index ) {
620  $result[] = $row;
621  }
622  }
623 
624  return $result ?: false;
625  }
626 
631  public function strencode( $s ) {
632  return $this->mysqlRealEscapeString( $s );
633  }
634 
639  abstract protected function mysqlRealEscapeString( $s );
640 
641  public function addQuotes( $s ) {
642  if ( is_bool( $s ) ) {
643  // Parent would transform to int, which does not play nice with MySQL type juggling.
644  // When searching for an int in a string column, the strings are cast to int, which
645  // means false would match any string not starting with a number.
646  $s = (string)(int)$s;
647  }
648  return parent::addQuotes( $s );
649  }
650 
657  public function addIdentifierQuotes( $s ) {
658  // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
659  // Remove NUL bytes and escape backticks by doubling
660  return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
661  }
662 
667  public function isQuotedIdentifier( $name ) {
668  return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
669  }
670 
671  protected function doGetLag() {
672  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
673  return $this->getLagFromPtHeartbeat();
674  } else {
675  return $this->getLagFromSlaveStatus();
676  }
677  }
678 
682  protected function getLagDetectionMethod() {
684  }
685 
689  protected function getLagFromSlaveStatus() {
690  $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX;
691  $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__, $flags );
692  $row = $res ? $res->fetchObject() : false;
693  // If the server is not replicating, there will be no row
694  if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
695  return intval( $row->Seconds_Behind_Master );
696  }
697 
698  return false;
699  }
700 
704  protected function getLagFromPtHeartbeat() {
705  $options = $this->lagDetectionOptions;
706 
707  $currentTrxInfo = $this->getRecordedTransactionLagStatus();
708  if ( $currentTrxInfo ) {
709  // There is an active transaction and the initial lag was already queried
710  $staleness = microtime( true ) - $currentTrxInfo['since'];
711  if ( $staleness > self::LAG_STALE_WARN_THRESHOLD ) {
712  // Avoid returning higher and higher lag value due to snapshot age
713  // given that the isolation level will typically be REPEATABLE-READ
714  $this->queryLogger->warning(
715  "Using cached lag value for {db_server} due to active transaction",
716  $this->getLogContext( [
717  'method' => __METHOD__,
718  'age' => $staleness,
719  'trace' => ( new RuntimeException() )->getTraceAsString()
720  ] )
721  );
722  }
723 
724  return $currentTrxInfo['lag'];
725  }
726 
727  if ( isset( $options['conds'] ) ) {
728  // Best method for multi-DC setups: use logical channel names
729  $data = $this->getHeartbeatData( $options['conds'] );
730  } else {
731  // Standard method: use master server ID (works with stock pt-heartbeat)
732  $masterInfo = $this->getMasterServerInfo();
733  if ( !$masterInfo ) {
734  $this->queryLogger->error(
735  "Unable to query master of {db_server} for server ID",
736  $this->getLogContext( [
737  'method' => __METHOD__
738  ] )
739  );
740 
741  return false; // could not get master server ID
742  }
743 
744  $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
745  $data = $this->getHeartbeatData( $conds );
746  }
747 
748  list( $time, $nowUnix ) = $data;
749  if ( $time !== null ) {
750  // @time is in ISO format like "2015-09-25T16:48:10.000510"
751  $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
752  $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
753 
754  return max( $nowUnix - $timeUnix, 0.0 );
755  }
756 
757  $this->queryLogger->error(
758  "Unable to find pt-heartbeat row for {db_server}",
759  $this->getLogContext( [
760  'method' => __METHOD__
761  ] )
762  );
763 
764  return false;
765  }
766 
767  protected function getMasterServerInfo() {
769  $key = $cache->makeGlobalKey(
770  'mysql',
771  'master-info',
772  // Using one key for all cluster replica DBs is preferable
773  $this->topologyRootMaster ?? $this->getServer()
774  );
775  $fname = __METHOD__;
776 
777  return $cache->getWithSetCallback(
778  $key,
779  $cache::TTL_INDEFINITE,
780  function () use ( $cache, $key, $fname ) {
781  // Get and leave a lock key in place for a short period
782  if ( !$cache->lock( $key, 0, 10 ) ) {
783  return false; // avoid master connection spike slams
784  }
785 
786  $conn = $this->getLazyMasterHandle();
787  if ( !$conn ) {
788  return false; // something is misconfigured
789  }
790 
791  // Connect to and query the master; catch errors to avoid outages
792  try {
793  $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX;
794  $res = $conn->query( 'SELECT @@server_id AS id', $fname, $flags );
795  $row = $res ? $res->fetchObject() : false;
796  $id = $row ? (int)$row->id : 0;
797  } catch ( DBError $e ) {
798  $id = 0;
799  }
800 
801  // Cache the ID if it was retrieved
802  return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
803  }
804  );
805  }
806 
812  protected function getHeartbeatData( array $conds ) {
813  // Query time and trip time are not counted
814  $nowUnix = microtime( true );
815  $whereSQL = $this->makeList( $conds, self::LIST_AND );
816  // Use ORDER BY for channel based queries since that field might not be UNIQUE.
817  // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
818  // percision field is not supported in MySQL <= 5.5.
819  $res = $this->query(
820  "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
821  __METHOD__,
822  self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX
823  );
824  $row = $res ? $res->fetchObject() : false;
825 
826  return [ $row ? $row->ts : null, $nowUnix ];
827  }
828 
829  protected function getApproximateLagStatus() {
830  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
831  // Disable caching since this is fast enough and we don't wan't
832  // to be *too* pessimistic by having both the cache TTL and the
833  // pt-heartbeat interval count as lag in getSessionLagStatus()
834  return parent::getApproximateLagStatus();
835  }
836 
837  $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
838  $approxLag = $this->srvCache->get( $key );
839  if ( !$approxLag ) {
840  $approxLag = parent::getApproximateLagStatus();
841  $this->srvCache->set( $key, $approxLag, 1 );
842  }
843 
844  return $approxLag;
845  }
846 
847  public function masterPosWait( DBMasterPos $pos, $timeout ) {
848  if ( !( $pos instanceof MySQLMasterPos ) ) {
849  throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
850  }
851 
852  if ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
853  $this->queryLogger->debug(
854  "Bypassed replication wait; database has a static dataset",
855  $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
856  );
857 
858  return 0; // this is a copy of a read-only dataset with no master DB
859  } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
860  $this->queryLogger->debug(
861  "Bypassed replication wait; replication known to have reached {raw_pos}",
862  $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
863  );
864 
865  return 0; // already reached this point for sure
866  }
867 
868  // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
869  if ( $pos->getGTIDs() ) {
870  // Get the GTIDs from this replica server too see the domains (channels)
871  $refPos = $this->getReplicaPos();
872  if ( !$refPos ) {
873  $this->queryLogger->error(
874  "Could not get replication position on replica DB to compare to {raw_pos}",
875  $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
876  );
877 
878  return -1; // this is the master itself?
879  }
880  // GTIDs with domains (channels) that are active and are present on the replica
881  $gtidsWait = $pos::getRelevantActiveGTIDs( $pos, $refPos );
882  if ( !$gtidsWait ) {
883  $this->queryLogger->error(
884  "No active GTIDs in {raw_pos} share a domain with those in {current_pos}",
885  $this->getLogContext( [
886  'method' => __METHOD__,
887  'raw_pos' => $pos,
888  'current_pos' => $refPos
889  ] )
890  );
891 
892  return -1; // $pos is from the wrong cluster?
893  }
894  // Wait on the GTID set
895  $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
896  if ( strpos( $gtidArg, ':' ) !== false ) {
897  // MySQL GTIDs, e.g "source_id:transaction_id"
898  $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
899  } else {
900  // MariaDB GTIDs, e.g."domain:server:sequence"
901  $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
902  }
903  $waitPos = implode( ',', $gtidsWait );
904  } else {
905  // Wait on the binlog coordinates
906  $encFile = $this->addQuotes( $pos->getLogFile() );
907  $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT] );
908  $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
909  $waitPos = $pos->__toString();
910  }
911 
912  $res = $this->query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
913  $row = $this->fetchRow( $res );
914 
915  // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
916  $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
917  if ( $status === null ) {
918  $this->queryLogger->error(
919  "An error occurred while waiting for replication to reach {raw_pos}",
920  $this->getLogContext( [
921  'method' => __METHOD__,
922  'raw_pos' => $pos,
923  'wait_pos' => $waitPos,
924  'sql' => $sql
925  ] )
926  );
927  } elseif ( $status < 0 ) {
928  $this->queryLogger->error(
929  "Timed out waiting for replication to reach {raw_pos}",
930  $this->getLogContext( [
931  'method' => __METHOD__,
932  'raw_pos' => $pos,
933  'wait_pos' => $waitPos,
934  'timeout' => $timeout,
935  'sql' => $sql,
936 
937  ] )
938  );
939  } elseif ( $status >= 0 ) {
940  $this->queryLogger->debug(
941  "Replication has reached {raw_pos}",
942  $this->getLogContext( [
943  'method' => __METHOD__,
944  'raw_pos' => $pos,
945  'wait_pos' => $waitPos
946  ] )
947  );
948  // Remember that this position was reached to save queries next time
949  $this->lastKnownReplicaPos = $pos;
950  }
951 
952  return $status;
953  }
954 
960  public function getReplicaPos() {
961  $now = microtime( true ); // as-of-time *before* fetching GTID variables
962 
963  if ( $this->useGTIDs() ) {
964  // Try to use GTIDs, fallbacking to binlog positions if not possible
965  $data = $this->getServerGTIDs( __METHOD__ );
966  // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
967  foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
968  if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
969  return new MySQLMasterPos( $data[$name], $now );
970  }
971  }
972  }
973 
974  $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__ );
975  if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
976  return new MySQLMasterPos(
977  "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
978  $now
979  );
980  }
981 
982  return false;
983  }
984 
990  public function getMasterPos() {
991  $now = microtime( true ); // as-of-time *before* fetching GTID variables
992 
993  $pos = false;
994  if ( $this->useGTIDs() ) {
995  // Try to use GTIDs, fallbacking to binlog positions if not possible
996  $data = $this->getServerGTIDs( __METHOD__ );
997  // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
998  foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
999  if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1000  $pos = new MySQLMasterPos( $data[$name], $now );
1001  break;
1002  }
1003  }
1004  // Filter domains that are inactive or not relevant to the session
1005  if ( $pos ) {
1006  $pos->setActiveOriginServerId( $this->getServerId() );
1007  $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1008  if ( isset( $data['gtid_domain_id'] ) ) {
1009  $pos->setActiveDomain( $data['gtid_domain_id'] );
1010  }
1011  }
1012  }
1013 
1014  if ( !$pos ) {
1015  $data = $this->getServerRoleStatus( 'MASTER', __METHOD__ );
1016  if ( $data && strlen( $data['File'] ) ) {
1017  $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1018  }
1019  }
1020 
1021  return $pos;
1022  }
1023 
1028  protected function getServerId() {
1029  $fname = __METHOD__;
1030  return $this->srvCache->getWithSetCallback(
1031  $this->srvCache->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1032  self::SERVER_ID_CACHE_TTL,
1033  function () use ( $fname ) {
1034  $flags = self::QUERY_IGNORE_DBO_TRX;
1035  $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
1036 
1037  return intval( $this->fetchObject( $res )->id );
1038  }
1039  );
1040  }
1041 
1045  protected function getServerUUID() {
1046  $fname = __METHOD__;
1047  return $this->srvCache->getWithSetCallback(
1048  $this->srvCache->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1049  self::SERVER_ID_CACHE_TTL,
1050  function () use ( $fname ) {
1051  $flags = self::QUERY_IGNORE_DBO_TRX;
1052  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
1053  $row = $this->fetchObject( $res );
1054 
1055  return $row ? $row->Value : null;
1056  }
1057  );
1058  }
1059 
1064  protected function getServerGTIDs( $fname = __METHOD__ ) {
1065  $map = [];
1066 
1067  $flags = self::QUERY_IGNORE_DBO_TRX;
1068  // Get global-only variables like gtid_executed
1069  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
1070  foreach ( $res as $row ) {
1071  $map[$row->Variable_name] = $row->Value;
1072  }
1073  // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1074  $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
1075  foreach ( $res as $row ) {
1076  $map[$row->Variable_name] = $row->Value;
1077  }
1078 
1079  return $map;
1080  }
1081 
1087  protected function getServerRoleStatus( $role, $fname = __METHOD__ ) {
1088  $flags = self::QUERY_IGNORE_DBO_TRX;
1089 
1090  return $this->query( "SHOW $role STATUS", $fname, $flags )->fetchRow() ?: [];
1091  }
1092 
1093  public function serverIsReadOnly() {
1094  // Avoid SHOW to avoid internal temporary tables
1095  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
1096  $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__, $flags );
1097  $row = $this->fetchObject( $res );
1098 
1099  return $row ? (bool)$row->Value : false;
1100  }
1101 
1106  function useIndexClause( $index ) {
1107  return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1108  }
1109 
1114  function ignoreIndexClause( $index ) {
1115  return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1116  }
1117 
1121  public function getSoftwareLink() {
1122  // MariaDB includes its name in its version string; this is how MariaDB's version of
1123  // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1124  // in libmysql/libmysql.c).
1125  $version = $this->getServerVersion();
1126  if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
1127  return '[{{int:version-db-mariadb-url}} MariaDB]';
1128  }
1129 
1130  // Percona Server's version suffix is not very distinctive, and @@version_comment
1131  // doesn't give the necessary info for source builds, so assume the server is MySQL.
1132  // (Even Percona's version of mysql doesn't try to make the distinction.)
1133  return '[{{int:version-db-mysql-url}} MySQL]';
1134  }
1135 
1139  public function getServerVersion() {
1141  $fname = __METHOD__;
1142 
1143  return $cache->getWithSetCallback(
1144  $cache->makeGlobalKey( 'mysql-server-version', $this->getServer() ),
1145  $cache::TTL_HOUR,
1146  function () use ( $fname ) {
1147  // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1148  // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1149  // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1150  return $this->selectField( '', 'VERSION()', '', $fname );
1151  }
1152  );
1153  }
1154 
1158  public function setSessionOptions( array $options ) {
1159  if ( isset( $options['connTimeout'] ) ) {
1160  $flags = self::QUERY_IGNORE_DBO_TRX;
1161  $timeout = (int)$options['connTimeout'];
1162  $this->query( "SET net_read_timeout=$timeout", __METHOD__, $flags );
1163  $this->query( "SET net_write_timeout=$timeout", __METHOD__, $flags );
1164  }
1165  }
1166 
1172  public function streamStatementEnd( &$sql, &$newLine ) {
1173  if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1174  preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1175  $this->delimiter = $m[1];
1176  $newLine = '';
1177  }
1178 
1179  return parent::streamStatementEnd( $sql, $newLine );
1180  }
1181 
1190  public function lockIsFree( $lockName, $method ) {
1191  if ( !parent::lockIsFree( $lockName, $method ) ) {
1192  return false; // already held
1193  }
1194 
1195  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1196 
1197  $flags = self::QUERY_IGNORE_DBO_TRX;
1198  $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
1199  $row = $this->fetchObject( $res );
1200 
1201  return ( $row->lockstatus == 1 );
1202  }
1203 
1210  public function lock( $lockName, $method, $timeout = 5 ) {
1211  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1212 
1213  $flags = self::QUERY_IGNORE_DBO_TRX;
1214  $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
1215  $row = $this->fetchObject( $res );
1216 
1217  if ( $row->lockstatus == 1 ) {
1218  parent::lock( $lockName, $method, $timeout ); // record
1219  return true;
1220  }
1221 
1222  $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
1223  [ 'lockname' => $lockName ] );
1224 
1225  return false;
1226  }
1227 
1235  public function unlock( $lockName, $method ) {
1236  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1237 
1238  $flags = self::QUERY_IGNORE_DBO_TRX;
1239  $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
1240  $row = $this->fetchObject( $res );
1241 
1242  if ( $row->lockstatus == 1 ) {
1243  parent::unlock( $lockName, $method ); // record
1244  return true;
1245  }
1246 
1247  $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1248 
1249  return false;
1250  }
1251 
1252  private function makeLockName( $lockName ) {
1253  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1254  // Newer version enforce a 64 char length limit.
1255  return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1256  }
1257 
1258  public function namedLocksEnqueue() {
1259  return true;
1260  }
1261 
1263  return false; // tied to TCP connection
1264  }
1265 
1266  protected function doLockTables( array $read, array $write, $method ) {
1267  $items = [];
1268  foreach ( $write as $table ) {
1269  $items[] = $this->tableName( $table ) . ' WRITE';
1270  }
1271  foreach ( $read as $table ) {
1272  $items[] = $this->tableName( $table ) . ' READ';
1273  }
1274 
1275  $sql = "LOCK TABLES " . implode( ',', $items );
1276  $this->query( $sql, $method, self::QUERY_IGNORE_DBO_TRX );
1277 
1278  return true;
1279  }
1280 
1281  protected function doUnlockTables( $method ) {
1282  $this->query( "UNLOCK TABLES", $method, self::QUERY_IGNORE_DBO_TRX );
1283 
1284  return true;
1285  }
1286 
1290  public function setBigSelects( $value = true ) {
1291  if ( $value === 'default' ) {
1292  if ( $this->defaultBigSelects === null ) {
1293  # Function hasn't been called before so it must already be set to the default
1294  return;
1295  } else {
1296  $value = $this->defaultBigSelects;
1297  }
1298  } elseif ( $this->defaultBigSelects === null ) {
1299  $this->defaultBigSelects =
1300  (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1301  }
1302  $encValue = $value ? '1' : '0';
1303  $this->query( "SET sql_big_selects=$encValue", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
1304  }
1305 
1316  public function deleteJoin(
1317  $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1318  ) {
1319  if ( !$conds ) {
1320  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1321  }
1322 
1323  $delTable = $this->tableName( $delTable );
1324  $joinTable = $this->tableName( $joinTable );
1325  $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1326 
1327  if ( $conds != '*' ) {
1328  $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1329  }
1330 
1331  $this->query( $sql, $fname );
1332  }
1333 
1334  public function upsert(
1335  $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1336  ) {
1337  if ( $rows === [] ) {
1338  return true; // nothing to do
1339  }
1340 
1341  if ( !is_array( reset( $rows ) ) ) {
1342  $rows = [ $rows ];
1343  }
1344 
1345  $table = $this->tableName( $table );
1346  $columns = array_keys( $rows[0] );
1347 
1348  $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1349  $rowTuples = [];
1350  foreach ( $rows as $row ) {
1351  $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1352  }
1353  $sql .= implode( ',', $rowTuples );
1354  $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1355 
1356  $this->query( $sql, $fname );
1357 
1358  return true;
1359  }
1360 
1366  public function getServerUptime() {
1367  $vars = $this->getMysqlStatus( 'Uptime' );
1368 
1369  return (int)$vars['Uptime'];
1370  }
1371 
1377  public function wasDeadlock() {
1378  return $this->lastErrno() == 1213;
1379  }
1380 
1386  public function wasLockTimeout() {
1387  return $this->lastErrno() == 1205;
1388  }
1389 
1395  public function wasReadOnlyError() {
1396  return $this->lastErrno() == 1223 ||
1397  ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1398  }
1399 
1400  public function wasConnectionError( $errno ) {
1401  return $errno == 2013 || $errno == 2006;
1402  }
1403 
1404  protected function wasKnownStatementRollbackError() {
1405  $errno = $this->lastErrno();
1406 
1407  if ( $errno === 1205 ) { // lock wait timeout
1408  // Note that this is uncached to avoid stale values of SET is used
1409  $row = $this->selectRow(
1410  false,
1411  [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1412  [],
1413  __METHOD__
1414  );
1415  // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1416  // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1417  return $row->innodb_rollback_on_timeout ? false : true;
1418  }
1419 
1420  // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1421  return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1422  }
1423 
1431  public function duplicateTableStructure(
1432  $oldName, $newName, $temporary = false, $fname = __METHOD__
1433  ) {
1434  $tmp = $temporary ? 'TEMPORARY ' : '';
1435  $newName = $this->addIdentifierQuotes( $newName );
1436  $oldName = $this->addIdentifierQuotes( $oldName );
1437  $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1438 
1439  return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT );
1440  }
1441 
1449  public function listTables( $prefix = null, $fname = __METHOD__ ) {
1450  $result = $this->query( "SHOW TABLES", $fname );
1451 
1452  $endArray = [];
1453 
1454  foreach ( $result as $table ) {
1455  $vars = get_object_vars( $table );
1456  $table = array_pop( $vars );
1457 
1458  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1459  $endArray[] = $table;
1460  }
1461  }
1462 
1463  return $endArray;
1464  }
1465 
1471  public function dropTable( $tableName, $fName = __METHOD__ ) {
1472  if ( !$this->tableExists( $tableName, $fName ) ) {
1473  return false;
1474  }
1475 
1476  return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1477  }
1478 
1485  private function getMysqlStatus( $which = "%" ) {
1486  $flags = self::QUERY_IGNORE_DBO_TRX;
1487  $res = $this->query( "SHOW STATUS LIKE '{$which}'", __METHOD__, $flags );
1488  $status = [];
1489 
1490  foreach ( $res as $row ) {
1491  $status[$row->Variable_name] = $row->Value;
1492  }
1493 
1494  return $status;
1495  }
1496 
1506  public function listViews( $prefix = null, $fname = __METHOD__ ) {
1507  // The name of the column containing the name of the VIEW
1508  $propertyName = 'Tables_in_' . $this->getDBname();
1509 
1510  // Query for the VIEWS
1511  $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1512  $allViews = [];
1513  foreach ( $res as $row ) {
1514  array_push( $allViews, $row->$propertyName );
1515  }
1516 
1517  if ( is_null( $prefix ) || $prefix === '' ) {
1518  return $allViews;
1519  }
1520 
1521  $filteredViews = [];
1522  foreach ( $allViews as $viewName ) {
1523  // Does the name of this VIEW start with the table-prefix?
1524  if ( strpos( $viewName, $prefix ) === 0 ) {
1525  array_push( $filteredViews, $viewName );
1526  }
1527  }
1528 
1529  return $filteredViews;
1530  }
1531 
1540  public function isView( $name, $prefix = null ) {
1541  return in_array( $name, $this->listViews( $prefix ) );
1542  }
1543 
1544  protected function isTransactableQuery( $sql ) {
1545  return parent::isTransactableQuery( $sql ) &&
1546  !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1547  }
1548 
1549  public function buildStringCast( $field ) {
1550  return "CAST( $field AS BINARY )";
1551  }
1552 
1557  public function buildIntegerCast( $field ) {
1558  return 'CAST( ' . $field . ' AS SIGNED )';
1559  }
1560 
1561  /*
1562  * @return bool Whether GTID support is used (mockable for testing)
1563  */
1564  protected function useGTIDs() {
1565  return $this->useGTIDs;
1566  }
1567 }
1568 
1572 class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );
getLazyMasterHandle()
Get a handle to the master server of the cluster to which this server belongs.
Definition: Database.php:636
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
normalizeConditions( $conds, $fname)
Definition: Database.php:2026
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition: Database.php:892
addIdentifierQuotes( $s)
MySQL uses backticks for identifier quoting instead of the sql standard "double quotes".
bool $utf8Mode
Use experimental UTF-8 transmission encoding.
array $lagDetectionOptions
Method to detect replica DB lag.
lastErrno()
Get the last error number.
wasDeadlock()
Determines if the last failure was due to a deadlock.
escapeLikeInternal( $s, $escapeChar='`')
Definition: Database.php:2797
mysqlError( $conn=null)
Returns the text of the error message from previous MySQL operation.
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
Definition: Database.php:1192
getServer()
Get the server hostname or IP address.
Definition: Database.php:2433
mysqlFieldName( $res, $n)
Get the name of the specified field in a result.
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
Definition: Database.php:1652
int $flags
Current bit field of class DBO_* constants.
Definition: Database.php:96
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
nativeReplace( $table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
Definition: Database.php:2931
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query and return the result.
Definition: Database.php:1155
string $server
Server that this instance is currently connected to.
Definition: Database.php:75
getReplicaPos()
Get the position of the master from SHOW SLAVE STATUS.
mysqlDataSeek( $res, $row)
Move internal result pointer.
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
newExceptionAfterConnectError( $error)
Definition: Database.php:1634
getMysqlStatus( $which="%")
Get status information from SHOW STATUS in an associative array.
getServerUptime()
Determines how long the server has been up.
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:830
bool $useGTIDs
bool Whether to use GTID methods
getDBname()
Get the current DB name.
Definition: Database.php:2429
mysqlFieldType( $res, $n)
Get the type of the specified field in a result.
mysqlFetchObject( $res)
Fetch a result row as an object.
mysqlFetchField( $res, $n)
Get column information from a result.
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
mysqlFetchArray( $res)
Fetch a result row as an associative and numeric array.
const LIST_AND
Definition: Defines.php:39
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
Definition: Database.php:1583
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:12
unlock( $lockName, $method)
FROM MYSQL DOCS: https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_releas...
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:2754
fieldType( $res, $n)
mysql_field_type() wrapper
getMasterPos()
Get the position of the master from SHOW MASTER STATUS.
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
Definition: Database.php:2437
$cache
Definition: mcc.php:33
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
lockIsFree( $lockName, $method)
Check to see if a named lock is available.
dropTable( $tableName, $fName=__METHOD__)
mysqlNumRows( $res)
Get number of rows in result.
upsert( $table, array $rows, $uniqueIndexes, array $set, $fname=__METHOD__)
INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
doLockTables(array $read, array $write, $method)
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2221
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
Definition: Database.php:2495
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
Definition: Database.php:4392
const LIST_SET
Definition: Defines.php:40
listViews( $prefix=null, $fname=__METHOD__)
Lists VIEWs in the database.
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
REPLACE query wrapper.
BagOStuff $srvCache
APC cache.
Definition: Database.php:51
lock( $lockName, $method, $timeout=5)
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
DBMasterPos class for MySQL/MariaDB.
Class to handle database/schema/prefix specifications for IDatabase.
isView( $name, $prefix=null)
Differentiates between a TABLE and a VIEW.
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: Database.php:881
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
Definition: Database.php:1914
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object Returns false if the index does not exist...
__construct(array $params)
Additional $params include:
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
Relational database abstraction object.
Definition: Database.php:49
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1823
mysqlNumFields( $res)
Get number of fields in result.
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:841
string $sqlMode
sql_mode value to send on connection
object resource null $conn
Database connection.
Definition: Database.php:69
isInsertSelectSafe(array $insertOptions, array $selectOptions)
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:77
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output Takes same arguments as Dat...
string $lagDetectionMethod
Method to detect replica DB lag.
mysqlConnect( $realServer, $dbName)
Open a connection to a MySQL server.
doSelectDomain(DatabaseDomain $domain)
mysqlFreeResult( $res)
Free result memory.
Database abstraction object for MySQL.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
Database error base class.
Definition: DBError.php:30
static & unwrap(&$res)
Get the underlying RDBMS driver-specific result resource.
string $password
Password used to establish the current connection.
Definition: Database.php:79
Base class for the more common types of database errors.
getServerRoleStatus( $role, $fname=__METHOD__)
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.