MediaWiki REL1_34
DatabaseMysqlBase.php
Go to the documentation of this file.
1<?php
23namespace Wikimedia\Rdbms;
24
25use DateTime;
26use DateTimeZone;
27use Wikimedia\AtEase\AtEase;
28use InvalidArgumentException;
29use Exception;
30use RuntimeException;
31use stdClass;
32
41abstract 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() {
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 'exception' => new RuntimeException()
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->getLBInfo( 'clusterMasterHost' ) ?: $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->getLBInfo( 'is static' ) === true ) {
853 $this->queryLogger->debug(
854 "Bypassed replication wait; database has a static dataset",
855 $this->getLogContext( [ 'method' => __METHOD__ ] )
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 already known to have reached $pos",
862 $this->getLogContext( [ 'method' => __METHOD__ ] )
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",
875 $this->getLogContext( [ 'method' => __METHOD__ ] )
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 $pos share a domain with those in $refPos",
885 $this->getLogContext( [ 'method' => __METHOD__, 'activeDomain' => $pos ] )
886 );
887
888 return -1; // $pos is from the wrong cluster?
889 }
890 // Wait on the GTID set
891 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
892 if ( strpos( $gtidArg, ':' ) !== false ) {
893 // MySQL GTIDs, e.g "source_id:transaction_id"
894 $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
895 } else {
896 // MariaDB GTIDs, e.g."domain:server:sequence"
897 $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
898 }
899 } else {
900 // Wait on the binlog coordinates
901 $encFile = $this->addQuotes( $pos->getLogFile() );
902 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT] );
903 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
904 }
905
906 $res = $this->query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
907 $row = $this->fetchRow( $res );
908
909 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
910 $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
911 if ( $status === null ) {
912 $this->queryLogger->error(
913 "An error occurred while waiting for replication to reach $pos",
914 $this->getLogContext( [ 'method' => __METHOD__, 'sql' => $sql ] )
915 );
916 } elseif ( $status < 0 ) {
917 $this->queryLogger->error(
918 "Timed out waiting for replication to reach $pos",
919 $this->getLogContext( [
920 'method' => __METHOD__, 'sql' => $sql, 'timeout' => $timeout
921 ] )
922 );
923 } elseif ( $status >= 0 ) {
924 $this->queryLogger->debug(
925 "Replication has reached $pos",
926 $this->getLogContext( [ 'method' => __METHOD__ ] )
927 );
928 // Remember that this position was reached to save queries next time
929 $this->lastKnownReplicaPos = $pos;
930 }
931
932 return $status;
933 }
934
940 public function getReplicaPos() {
941 $now = microtime( true ); // as-of-time *before* fetching GTID variables
942
943 if ( $this->useGTIDs() ) {
944 // Try to use GTIDs, fallbacking to binlog positions if not possible
945 $data = $this->getServerGTIDs( __METHOD__ );
946 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
947 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
948 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
949 return new MySQLMasterPos( $data[$name], $now );
950 }
951 }
952 }
953
954 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__ );
955 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
956 return new MySQLMasterPos(
957 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
958 $now
959 );
960 }
961
962 return false;
963 }
964
970 public function getMasterPos() {
971 $now = microtime( true ); // as-of-time *before* fetching GTID variables
972
973 $pos = false;
974 if ( $this->useGTIDs() ) {
975 // Try to use GTIDs, fallbacking to binlog positions if not possible
976 $data = $this->getServerGTIDs( __METHOD__ );
977 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
978 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
979 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
980 $pos = new MySQLMasterPos( $data[$name], $now );
981 break;
982 }
983 }
984 // Filter domains that are inactive or not relevant to the session
985 if ( $pos ) {
986 $pos->setActiveOriginServerId( $this->getServerId() );
987 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
988 if ( isset( $data['gtid_domain_id'] ) ) {
989 $pos->setActiveDomain( $data['gtid_domain_id'] );
990 }
991 }
992 }
993
994 if ( !$pos ) {
995 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__ );
996 if ( $data && strlen( $data['File'] ) ) {
997 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
998 }
999 }
1000
1001 return $pos;
1002 }
1003
1008 protected function getServerId() {
1009 $fname = __METHOD__;
1010 return $this->srvCache->getWithSetCallback(
1011 $this->srvCache->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1012 self::SERVER_ID_CACHE_TTL,
1013 function () use ( $fname ) {
1014 $flags = self::QUERY_IGNORE_DBO_TRX;
1015 $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
1016
1017 return intval( $this->fetchObject( $res )->id );
1018 }
1019 );
1020 }
1021
1025 protected function getServerUUID() {
1026 $fname = __METHOD__;
1027 return $this->srvCache->getWithSetCallback(
1028 $this->srvCache->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1029 self::SERVER_ID_CACHE_TTL,
1030 function () use ( $fname ) {
1031 $flags = self::QUERY_IGNORE_DBO_TRX;
1032 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
1033 $row = $this->fetchObject( $res );
1034
1035 return $row ? $row->Value : null;
1036 }
1037 );
1038 }
1039
1044 protected function getServerGTIDs( $fname = __METHOD__ ) {
1045 $map = [];
1046
1047 $flags = self::QUERY_IGNORE_DBO_TRX;
1048 // Get global-only variables like gtid_executed
1049 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
1050 foreach ( $res as $row ) {
1051 $map[$row->Variable_name] = $row->Value;
1052 }
1053 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1054 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
1055 foreach ( $res as $row ) {
1056 $map[$row->Variable_name] = $row->Value;
1057 }
1058
1059 return $map;
1060 }
1061
1067 protected function getServerRoleStatus( $role, $fname = __METHOD__ ) {
1068 $flags = self::QUERY_IGNORE_DBO_TRX;
1069
1070 return $this->query( "SHOW $role STATUS", $fname, $flags )->fetchRow() ?: [];
1071 }
1072
1073 public function serverIsReadOnly() {
1074 // Avoid SHOW to avoid internal temporary tables
1075 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
1076 $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__, $flags );
1077 $row = $this->fetchObject( $res );
1078
1079 return $row ? (bool)$row->Value : false;
1080 }
1081
1086 function useIndexClause( $index ) {
1087 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1088 }
1089
1094 function ignoreIndexClause( $index ) {
1095 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1096 }
1097
1101 public function getSoftwareLink() {
1102 // MariaDB includes its name in its version string; this is how MariaDB's version of
1103 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1104 // in libmysql/libmysql.c).
1105 $version = $this->getServerVersion();
1106 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
1107 return '[{{int:version-db-mariadb-url}} MariaDB]';
1108 }
1109
1110 // Percona Server's version suffix is not very distinctive, and @@version_comment
1111 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1112 // (Even Percona's version of mysql doesn't try to make the distinction.)
1113 return '[{{int:version-db-mysql-url}} MySQL]';
1114 }
1115
1119 public function getServerVersion() {
1121 $fname = __METHOD__;
1122
1123 return $cache->getWithSetCallback(
1124 $cache->makeGlobalKey( 'mysql-server-version', $this->getServer() ),
1125 $cache::TTL_HOUR,
1126 function () use ( $fname ) {
1127 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1128 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1129 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1130 return $this->selectField( '', 'VERSION()', '', $fname );
1131 }
1132 );
1133 }
1134
1138 public function setSessionOptions( array $options ) {
1139 if ( isset( $options['connTimeout'] ) ) {
1140 $flags = self::QUERY_IGNORE_DBO_TRX;
1141 $timeout = (int)$options['connTimeout'];
1142 $this->query( "SET net_read_timeout=$timeout", __METHOD__, $flags );
1143 $this->query( "SET net_write_timeout=$timeout", __METHOD__, $flags );
1144 }
1145 }
1146
1152 public function streamStatementEnd( &$sql, &$newLine ) {
1153 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1154 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1155 $this->delimiter = $m[1];
1156 $newLine = '';
1157 }
1158
1159 return parent::streamStatementEnd( $sql, $newLine );
1160 }
1161
1170 public function lockIsFree( $lockName, $method ) {
1171 if ( !parent::lockIsFree( $lockName, $method ) ) {
1172 return false; // already held
1173 }
1174
1175 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1176
1177 $flags = self::QUERY_IGNORE_DBO_TRX;
1178 $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
1179 $row = $this->fetchObject( $res );
1180
1181 return ( $row->lockstatus == 1 );
1182 }
1183
1190 public function lock( $lockName, $method, $timeout = 5 ) {
1191 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1192
1193 $flags = self::QUERY_IGNORE_DBO_TRX;
1194 $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
1195 $row = $this->fetchObject( $res );
1196
1197 if ( $row->lockstatus == 1 ) {
1198 parent::lock( $lockName, $method, $timeout ); // record
1199 return true;
1200 }
1201
1202 $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
1203 [ 'lockname' => $lockName ] );
1204
1205 return false;
1206 }
1207
1215 public function unlock( $lockName, $method ) {
1216 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1217
1218 $flags = self::QUERY_IGNORE_DBO_TRX;
1219 $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
1220 $row = $this->fetchObject( $res );
1221
1222 if ( $row->lockstatus == 1 ) {
1223 parent::unlock( $lockName, $method ); // record
1224 return true;
1225 }
1226
1227 $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1228
1229 return false;
1230 }
1231
1232 private function makeLockName( $lockName ) {
1233 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1234 // Newer version enforce a 64 char length limit.
1235 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1236 }
1237
1238 public function namedLocksEnqueue() {
1239 return true;
1240 }
1241
1243 return false; // tied to TCP connection
1244 }
1245
1246 protected function doLockTables( array $read, array $write, $method ) {
1247 $items = [];
1248 foreach ( $write as $table ) {
1249 $items[] = $this->tableName( $table ) . ' WRITE';
1250 }
1251 foreach ( $read as $table ) {
1252 $items[] = $this->tableName( $table ) . ' READ';
1253 }
1254
1255 $sql = "LOCK TABLES " . implode( ',', $items );
1256 $this->query( $sql, $method, self::QUERY_IGNORE_DBO_TRX );
1257
1258 return true;
1259 }
1260
1261 protected function doUnlockTables( $method ) {
1262 $this->query( "UNLOCK TABLES", $method, self::QUERY_IGNORE_DBO_TRX );
1263
1264 return true;
1265 }
1266
1270 public function setBigSelects( $value = true ) {
1271 if ( $value === 'default' ) {
1272 if ( $this->defaultBigSelects === null ) {
1273 # Function hasn't been called before so it must already be set to the default
1274 return;
1275 } else {
1276 $value = $this->defaultBigSelects;
1277 }
1278 } elseif ( $this->defaultBigSelects === null ) {
1279 $this->defaultBigSelects =
1280 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1281 }
1282 $encValue = $value ? '1' : '0';
1283 $this->query( "SET sql_big_selects=$encValue", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
1284 }
1285
1296 public function deleteJoin(
1297 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1298 ) {
1299 if ( !$conds ) {
1300 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1301 }
1302
1303 $delTable = $this->tableName( $delTable );
1304 $joinTable = $this->tableName( $joinTable );
1305 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1306
1307 if ( $conds != '*' ) {
1308 $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1309 }
1310
1311 $this->query( $sql, $fname );
1312 }
1313
1314 public function upsert(
1315 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1316 ) {
1317 if ( $rows === [] ) {
1318 return true; // nothing to do
1319 }
1320
1321 if ( !is_array( reset( $rows ) ) ) {
1322 $rows = [ $rows ];
1323 }
1324
1325 $table = $this->tableName( $table );
1326 $columns = array_keys( $rows[0] );
1327
1328 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1329 $rowTuples = [];
1330 foreach ( $rows as $row ) {
1331 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1332 }
1333 $sql .= implode( ',', $rowTuples );
1334 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1335
1336 $this->query( $sql, $fname );
1337
1338 return true;
1339 }
1340
1346 public function getServerUptime() {
1347 $vars = $this->getMysqlStatus( 'Uptime' );
1348
1349 return (int)$vars['Uptime'];
1350 }
1351
1357 public function wasDeadlock() {
1358 return $this->lastErrno() == 1213;
1359 }
1360
1366 public function wasLockTimeout() {
1367 return $this->lastErrno() == 1205;
1368 }
1369
1375 public function wasReadOnlyError() {
1376 return $this->lastErrno() == 1223 ||
1377 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1378 }
1379
1380 public function wasConnectionError( $errno ) {
1381 return $errno == 2013 || $errno == 2006;
1382 }
1383
1384 protected function wasKnownStatementRollbackError() {
1385 $errno = $this->lastErrno();
1386
1387 if ( $errno === 1205 ) { // lock wait timeout
1388 // Note that this is uncached to avoid stale values of SET is used
1389 $row = $this->selectRow(
1390 false,
1391 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1392 [],
1393 __METHOD__
1394 );
1395 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1396 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1397 return $row->innodb_rollback_on_timeout ? false : true;
1398 }
1399
1400 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1401 return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1402 }
1403
1412 $oldName, $newName, $temporary = false, $fname = __METHOD__
1413 ) {
1414 $tmp = $temporary ? 'TEMPORARY ' : '';
1415 $newName = $this->addIdentifierQuotes( $newName );
1416 $oldName = $this->addIdentifierQuotes( $oldName );
1417 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1418
1419 return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT );
1420 }
1421
1429 public function listTables( $prefix = null, $fname = __METHOD__ ) {
1430 $result = $this->query( "SHOW TABLES", $fname );
1431
1432 $endArray = [];
1433
1434 foreach ( $result as $table ) {
1435 $vars = get_object_vars( $table );
1436 $table = array_pop( $vars );
1437
1438 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1439 $endArray[] = $table;
1440 }
1441 }
1442
1443 return $endArray;
1444 }
1445
1451 public function dropTable( $tableName, $fName = __METHOD__ ) {
1452 if ( !$this->tableExists( $tableName, $fName ) ) {
1453 return false;
1454 }
1455
1456 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1457 }
1458
1465 private function getMysqlStatus( $which = "%" ) {
1466 $flags = self::QUERY_IGNORE_DBO_TRX;
1467 $res = $this->query( "SHOW STATUS LIKE '{$which}'", __METHOD__, $flags );
1468 $status = [];
1469
1470 foreach ( $res as $row ) {
1471 $status[$row->Variable_name] = $row->Value;
1472 }
1473
1474 return $status;
1475 }
1476
1486 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1487 // The name of the column containing the name of the VIEW
1488 $propertyName = 'Tables_in_' . $this->getDBname();
1489
1490 // Query for the VIEWS
1491 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1492 $allViews = [];
1493 foreach ( $res as $row ) {
1494 array_push( $allViews, $row->$propertyName );
1495 }
1496
1497 if ( is_null( $prefix ) || $prefix === '' ) {
1498 return $allViews;
1499 }
1500
1501 $filteredViews = [];
1502 foreach ( $allViews as $viewName ) {
1503 // Does the name of this VIEW start with the table-prefix?
1504 if ( strpos( $viewName, $prefix ) === 0 ) {
1505 array_push( $filteredViews, $viewName );
1506 }
1507 }
1508
1509 return $filteredViews;
1510 }
1511
1520 public function isView( $name, $prefix = null ) {
1521 return in_array( $name, $this->listViews( $prefix ) );
1522 }
1523
1524 protected function isTransactableQuery( $sql ) {
1525 return parent::isTransactableQuery( $sql ) &&
1526 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\‍(/', $sql );
1527 }
1528
1529 public function buildStringCast( $field ) {
1530 return "CAST( $field AS BINARY )";
1531 }
1532
1537 public function buildIntegerCast( $field ) {
1538 return 'CAST( ' . $field . ' AS SIGNED )';
1539 }
1540
1541 /*
1542 * @return bool Whether GTID support is used (mockable for testing)
1543 */
1544 protected function useGTIDs() {
1545 return $this->useGTIDs;
1546 }
1547}
1548
1552class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );
getWithSetCallback( $key, $ttl, $callback, $flags=0)
Get an item with the given key, regenerating and setting it if not found.
makeGlobalKey( $class,... $components)
Make a global cache key.
Database error base class.
Definition DBError.php:30
Base class for the more common types of database errors.
Class to handle database/schema/prefix specifications for IDatabase.
Database abstraction object for MySQL.
doSelectDomain(DatabaseDomain $domain)
__construct(array $params)
Additional $params include:
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
getMysqlStatus( $which="%")
Get status information from SHOW STATUS in an associative array.
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
mysqlFetchArray( $res)
Fetch a result row as an associative and numeric array.
array $lagDetectionOptions
Method to detect replica DB lag.
isInsertSelectSafe(array $insertOptions, array $selectOptions)
dropTable( $tableName, $fName=__METHOD__)
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
fieldType( $res, $n)
mysql_field_type() wrapper
getMasterPos()
Get the position of the master from SHOW MASTER STATUS.
mysqlFetchField( $res, $n)
Get column information from a result.
string $lagDetectionMethod
Method to detect replica DB lag.
getApproximateLagStatus()
Get a replica DB lag estimate for this server.
mysqlFieldType( $res, $n)
Get the type of the specified field in a result.
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
upsert( $table, array $rows, $uniqueIndexes, array $set, $fname=__METHOD__)
INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
mysqlConnect( $realServer, $dbName)
Open a connection to a MySQL server.
mysqlFreeResult( $res)
Free result memory.
lockIsFree( $lockName, $method)
Check to see if a named lock is available.
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object Returns false if the index does not exist.
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...
mysqlDataSeek( $res, $row)
Move internal result pointer.
mysqlError( $conn=null)
Returns the text of the error message from previous MySQL operation.
addIdentifierQuotes( $s)
MySQL uses backticks for identifier quoting instead of the sql standard "double quotes".
mysqlFetchObject( $res)
Fetch a result row as an object.
mysqlFieldName( $res, $n)
Get the name of the specified field in a result.
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
lock( $lockName, $method, $timeout=5)
wasQueryTimeout( $error, $errno)
Checks whether the cause of the error is detected to be a timeout.
unlock( $lockName, $method)
FROM MYSQL DOCS: https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_releas...
bool $utf8Mode
Use experimental UTF-8 transmission encoding.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
bool $useGTIDs
bool Whether to use GTID methods
getServerRoleStatus( $role, $fname=__METHOD__)
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
string $sqlMode
sql_mode value to send on connection
mysqlNumRows( $res)
Get number of rows in result.
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
getServerUptime()
Determines how long the server has been up.
doUnlockTables( $method)
Helper function for unlockTables() that handles the actual table unlocking.
getReplicaPos()
Get the position of the master from SHOW SLAVE STATUS.
listViews( $prefix=null, $fname=__METHOD__)
Lists VIEWs in the database.
isView( $name, $prefix=null)
Differentiates between a TABLE and a VIEW.
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
wasDeadlock()
Determines if the last failure was due to a deadlock.
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
mysqlNumFields( $res)
Get number of fields in result.
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
REPLACE query wrapper.
Relational database abstraction object.
Definition Database.php:49
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition Database.php:825
object resource null $conn
Database connection.
Definition Database.php:69
newExceptionAfterConnectError( $error)
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
string $user
User that this instance is currently connected under the name of.
Definition Database.php:77
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
int $flags
Current bit field of class DBO_* constants.
Definition Database.php:92
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition Database.php:814
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition Database.php:876
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition Database.php:585
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition Database.php:865
nativeReplace( $table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
getServer()
Get the server hostname or IP address.
string $password
Password used to establish the current connection.
Definition Database.php:79
escapeLikeInternal( $s, $escapeChar='`')
string $server
Server that this instance is currently connected to.
Definition Database.php:75
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
normalizeConditions( $conds, $fname)
BagOStuff $srvCache
APC cache.
Definition Database.php:51
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query and return the result.
getDBname()
Get the current DB name.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
DBMasterPos class for MySQL/MariaDB.
static & unwrap(&$res)
Get the underlying RDBMS driver-specific result resource.
An object representing a master or replica DB position in a replicated setup.
lastErrno()
Get the last error number.
$cache
Definition mcc.php:33