12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553 |
- <?php
- /**
- * This is the MySQL database abstraction layer.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- *
- * @file
- * @ingroup Database
- */
- namespace Wikimedia\Rdbms;
- use DateTime;
- use DateTimeZone;
- use Wikimedia\AtEase\AtEase;
- use InvalidArgumentException;
- use Exception;
- use RuntimeException;
- use stdClass;
- /**
- * Database abstraction object for MySQL.
- * Defines methods independent on used MySQL extension.
- *
- * @ingroup Database
- * @since 1.22
- * @see Database
- */
- abstract class DatabaseMysqlBase extends Database {
- /** @var MysqlMasterPos */
- protected $lastKnownReplicaPos;
- /** @var string Method to detect replica DB lag */
- protected $lagDetectionMethod;
- /** @var array Method to detect replica DB lag */
- protected $lagDetectionOptions = [];
- /** @var bool bool Whether to use GTID methods */
- protected $useGTIDs = false;
- /** @var string|null */
- protected $sslKeyPath;
- /** @var string|null */
- protected $sslCertPath;
- /** @var string|null */
- protected $sslCAFile;
- /** @var string|null */
- protected $sslCAPath;
- /** @var string[]|null */
- protected $sslCiphers;
- /** @var string sql_mode value to send on connection */
- protected $sqlMode;
- /** @var bool Use experimental UTF-8 transmission encoding */
- protected $utf8Mode;
- /** @var bool|null */
- protected $defaultBigSelects = null;
- /** @var bool|null */
- private $insertSelectIsSafe = null;
- /** @var stdClass|null */
- private $replicationInfoRow = null;
- // Cache getServerId() for 24 hours
- const SERVER_ID_CACHE_TTL = 86400;
- /** @var float Warn if lag estimates are made for transactions older than this many seconds */
- const LAG_STALE_WARN_THRESHOLD = 0.100;
- /**
- * Additional $params include:
- * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
- * pt-heartbeat assumes the table is at heartbeat.heartbeat
- * and uses UTC timestamps in the heartbeat.ts column.
- * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
- * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
- * the default behavior. Normally, the heartbeat row with the server
- * ID of this server's master will be used. Set the "conds" field to
- * override the query conditions, e.g. ['shard' => 's1'].
- * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
- * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
- * - sslKeyPath : path to key file [default: null]
- * - sslCertPath : path to certificate file [default: null]
- * - sslCAFile: path to a single certificate authority PEM file [default: null]
- * - sslCAPath : parth to certificate authority PEM directory [default: null]
- * - sslCiphers : array list of allowable ciphers [default: null]
- * @param array $params
- */
- public function __construct( array $params ) {
- $this->lagDetectionMethod = $params['lagDetectionMethod'] ?? 'Seconds_Behind_Master';
- $this->lagDetectionOptions = $params['lagDetectionOptions'] ?? [];
- $this->useGTIDs = !empty( $params['useGTIDs' ] );
- foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
- $var = "ssl{$name}";
- if ( isset( $params[$var] ) ) {
- $this->$var = $params[$var];
- }
- }
- $this->sqlMode = $params['sqlMode'] ?? null;
- $this->utf8Mode = !empty( $params['utf8Mode'] );
- $this->insertSelectIsSafe = isset( $params['insertSelectIsSafe'] )
- ? (bool)$params['insertSelectIsSafe'] : null;
- parent::__construct( $params );
- }
- /**
- * @return string
- */
- public function getType() {
- return 'mysql';
- }
- protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
- $this->close();
- if ( $schema !== null ) {
- throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
- }
- $this->server = $server;
- $this->user = $user;
- $this->password = $password;
- $this->installErrorHandler();
- try {
- $this->conn = $this->mysqlConnect( $this->server, $dbName );
- } catch ( Exception $e ) {
- $this->restoreErrorHandler();
- throw $this->newExceptionAfterConnectError( $e->getMessage() );
- }
- $error = $this->restoreErrorHandler();
- if ( !$this->conn ) {
- throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
- }
- try {
- $this->currentDomain = new DatabaseDomain(
- strlen( $dbName ) ? $dbName : null,
- null,
- $tablePrefix
- );
- // Abstract over any insane MySQL defaults
- $set = [ 'group_concat_max_len = 262144' ];
- // Set SQL mode, default is turning them all off, can be overridden or skipped with null
- if ( is_string( $this->sqlMode ) ) {
- $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
- }
- // Set any custom settings defined by site config
- // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
- foreach ( $this->connectionVariables as $var => $val ) {
- // Escape strings but not numbers to avoid MySQL complaining
- if ( !is_int( $val ) && !is_float( $val ) ) {
- $val = $this->addQuotes( $val );
- }
- $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
- }
- if ( $set ) {
- $this->query(
- 'SET ' . implode( ', ', $set ),
- __METHOD__,
- self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY
- );
- }
- } catch ( Exception $e ) {
- throw $this->newExceptionAfterConnectError( $e->getMessage() );
- }
- }
- protected function doSelectDomain( DatabaseDomain $domain ) {
- if ( $domain->getSchema() !== null ) {
- throw new DBExpectedError(
- $this,
- __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
- );
- }
- $database = $domain->getDatabase();
- // A null database means "don't care" so leave it as is and update the table prefix
- if ( $database === null ) {
- $this->currentDomain = new DatabaseDomain(
- $this->currentDomain->getDatabase(),
- null,
- $domain->getTablePrefix()
- );
- return true;
- }
- if ( $database !== $this->getDBname() ) {
- $sql = 'USE ' . $this->addIdentifierQuotes( $database );
- list( $res, $err, $errno ) =
- $this->executeQuery( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
- if ( $res === false ) {
- $this->reportQueryError( $err, $errno, $sql, __METHOD__ );
- return false; // unreachable
- }
- }
- // Update that domain fields on success (no exception thrown)
- $this->currentDomain = $domain;
- return true;
- }
- /**
- * Open a connection to a MySQL server
- *
- * @param string $realServer
- * @param string|null $dbName
- * @return mixed|null Driver connection handle
- * @throws DBConnectionError
- */
- abstract protected function mysqlConnect( $realServer, $dbName );
- /**
- * @param IResultWrapper|resource $res
- * @throws DBUnexpectedError
- */
- public function freeResult( $res ) {
- AtEase::suppressWarnings();
- $ok = $this->mysqlFreeResult( ResultWrapper::unwrap( $res ) );
- AtEase::restoreWarnings();
- if ( !$ok ) {
- throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
- }
- }
- /**
- * Free result memory
- *
- * @param resource $res Raw result
- * @return bool
- */
- abstract protected function mysqlFreeResult( $res );
- /**
- * @param IResultWrapper|resource $res
- * @return stdClass|bool
- * @throws DBUnexpectedError
- */
- public function fetchObject( $res ) {
- AtEase::suppressWarnings();
- $row = $this->mysqlFetchObject( ResultWrapper::unwrap( $res ) );
- AtEase::restoreWarnings();
- $errno = $this->lastErrno();
- // Unfortunately, mysql_fetch_object does not reset the last errno.
- // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
- // these are the only errors mysql_fetch_object can cause.
- // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
- if ( $errno == 2000 || $errno == 2013 ) {
- throw new DBUnexpectedError(
- $this,
- 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
- );
- }
- return $row;
- }
- /**
- * Fetch a result row as an object
- *
- * @param resource $res Raw result
- * @return stdClass
- */
- abstract protected function mysqlFetchObject( $res );
- /**
- * @param IResultWrapper|resource $res
- * @return array|bool
- * @throws DBUnexpectedError
- */
- public function fetchRow( $res ) {
- AtEase::suppressWarnings();
- $row = $this->mysqlFetchArray( ResultWrapper::unwrap( $res ) );
- AtEase::restoreWarnings();
- $errno = $this->lastErrno();
- // Unfortunately, mysql_fetch_array does not reset the last errno.
- // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
- // these are the only errors mysql_fetch_array can cause.
- // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
- if ( $errno == 2000 || $errno == 2013 ) {
- throw new DBUnexpectedError(
- $this,
- 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
- );
- }
- return $row;
- }
- /**
- * Fetch a result row as an associative and numeric array
- *
- * @param resource $res Raw result
- * @return array|false
- */
- abstract protected function mysqlFetchArray( $res );
- /**
- * @throws DBUnexpectedError
- * @param IResultWrapper|resource $res
- * @return int
- */
- function numRows( $res ) {
- if ( is_bool( $res ) ) {
- $n = 0;
- } else {
- AtEase::suppressWarnings();
- $n = $this->mysqlNumRows( ResultWrapper::unwrap( $res ) );
- AtEase::restoreWarnings();
- }
- // Unfortunately, mysql_num_rows does not reset the last errno.
- // We are not checking for any errors here, since
- // there are no errors mysql_num_rows can cause.
- // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
- // See https://phabricator.wikimedia.org/T44430
- return $n;
- }
- /**
- * Get number of rows in result
- *
- * @param resource $res Raw result
- * @return int
- */
- abstract protected function mysqlNumRows( $res );
- /**
- * @param IResultWrapper|resource $res
- * @return int
- */
- public function numFields( $res ) {
- return $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
- }
- /**
- * Get number of fields in result
- *
- * @param resource $res Raw result
- * @return int
- */
- abstract protected function mysqlNumFields( $res );
- /**
- * @param IResultWrapper|resource $res
- * @param int $n
- * @return string
- */
- public function fieldName( $res, $n ) {
- return $this->mysqlFieldName( ResultWrapper::unwrap( $res ), $n );
- }
- /**
- * Get the name of the specified field in a result
- *
- * @param IResultWrapper|resource $res
- * @param int $n
- * @return string
- */
- abstract protected function mysqlFieldName( $res, $n );
- /**
- * mysql_field_type() wrapper
- * @param IResultWrapper|resource $res
- * @param int $n
- * @return string
- */
- public function fieldType( $res, $n ) {
- return $this->mysqlFieldType( ResultWrapper::unwrap( $res ), $n );
- }
- /**
- * Get the type of the specified field in a result
- *
- * @param IResultWrapper|resource $res
- * @param int $n
- * @return string
- */
- abstract protected function mysqlFieldType( $res, $n );
- /**
- * @param IResultWrapper|resource $res
- * @param int $row
- * @return bool
- */
- public function dataSeek( $res, $row ) {
- return $this->mysqlDataSeek( ResultWrapper::unwrap( $res ), $row );
- }
- /**
- * Move internal result pointer
- *
- * @param IResultWrapper|resource $res
- * @param int $row
- * @return bool
- */
- abstract protected function mysqlDataSeek( $res, $row );
- /**
- * @return string
- */
- public function lastError() {
- if ( $this->conn ) {
- # Even if it's non-zero, it can still be invalid
- AtEase::suppressWarnings();
- $error = $this->mysqlError( $this->conn );
- if ( !$error ) {
- $error = $this->mysqlError();
- }
- AtEase::restoreWarnings();
- } else {
- $error = $this->mysqlError();
- }
- if ( $error ) {
- $error .= ' (' . $this->server . ')';
- }
- return $error;
- }
- /**
- * Returns the text of the error message from previous MySQL operation
- *
- * @param resource|null $conn Raw connection
- * @return string
- */
- abstract protected function mysqlError( $conn = null );
- protected function wasQueryTimeout( $error, $errno ) {
- // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
- // https://phabricator.wikimedia.org/T170638
- return in_array( $errno, [ 2062, 3024 ] );
- }
- public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
- $this->nativeReplace( $table, $rows, $fname );
- }
- protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
- $row = $this->getReplicationSafetyInfo();
- // For row-based-replication, the resulting changes will be relayed, not the query
- if ( $row->binlog_format === 'ROW' ) {
- return true;
- }
- // LIMIT requires ORDER BY on a unique key or it is non-deterministic
- if ( isset( $selectOptions['LIMIT'] ) ) {
- return false;
- }
- // In MySQL, an INSERT SELECT is only replication safe with row-based
- // replication or if innodb_autoinc_lock_mode is 0. When those
- // conditions aren't met, use non-native mode.
- // While we could try to determine if the insert is safe anyway by
- // checking if the target table has an auto-increment column that
- // isn't set in $varMap, that seems unlikely to be worth the extra
- // complexity.
- return (
- in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
- (int)$row->innodb_autoinc_lock_mode === 0
- );
- }
- /**
- * @return stdClass Process cached row
- */
- protected function getReplicationSafetyInfo() {
- if ( $this->replicationInfoRow === null ) {
- $this->replicationInfoRow = $this->selectRow(
- false,
- [
- 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
- 'binlog_format' => '@@binlog_format',
- ],
- [],
- __METHOD__
- );
- }
- return $this->replicationInfoRow;
- }
- /**
- * Estimate rows in dataset
- * Returns estimated count, based on EXPLAIN output
- * Takes same arguments as Database::select()
- *
- * @param string|array $table
- * @param string|array $var
- * @param string|array $conds
- * @param string $fname
- * @param string|array $options
- * @param array $join_conds
- * @return bool|int
- */
- public function estimateRowCount( $table, $var = '*', $conds = '',
- $fname = __METHOD__, $options = [], $join_conds = []
- ) {
- $conds = $this->normalizeConditions( $conds, $fname );
- $column = $this->extractSingleFieldFromList( $var );
- if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
- $conds[] = "$column IS NOT NULL";
- }
- $options['EXPLAIN'] = true;
- $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
- if ( $res === false ) {
- return false;
- }
- if ( !$this->numRows( $res ) ) {
- return 0;
- }
- $rows = 1;
- foreach ( $res as $plan ) {
- $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
- }
- return (int)$rows;
- }
- public function tableExists( $table, $fname = __METHOD__ ) {
- // Split database and table into proper variables as Database::tableName() returns
- // shared tables prefixed with their database, which do not work in SHOW TABLES statements
- list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
- $tableName = "{$prefix}{$table}";
- if ( isset( $this->sessionTempTables[$tableName] ) ) {
- return true; // already known to exist and won't show in SHOW TABLES anyway
- }
- // We can't use buildLike() here, because it specifies an escape character
- // other than the backslash, which is the only one supported by SHOW TABLES
- $encLike = $this->escapeLikeInternal( $tableName, '\\' );
- // If the database has been specified (such as for shared tables), use "FROM"
- if ( $database !== '' ) {
- $encDatabase = $this->addIdentifierQuotes( $database );
- $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
- } else {
- $query = "SHOW TABLES LIKE '$encLike'";
- }
- return $this->query( $query, $fname )->numRows() > 0;
- }
- /**
- * @param string $table
- * @param string $field
- * @return bool|MySQLField
- */
- public function fieldInfo( $table, $field ) {
- $table = $this->tableName( $table );
- $flags = self::QUERY_SILENCE_ERRORS;
- $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, $flags );
- if ( !$res ) {
- return false;
- }
- $n = $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
- for ( $i = 0; $i < $n; $i++ ) {
- $meta = $this->mysqlFetchField( ResultWrapper::unwrap( $res ), $i );
- if ( $field == $meta->name ) {
- return new MySQLField( $meta );
- }
- }
- return false;
- }
- /**
- * Get column information from a result
- *
- * @param resource $res Raw result
- * @param int $n
- * @return stdClass
- */
- abstract protected function mysqlFetchField( $res, $n );
- /**
- * Get information about an index into an object
- * Returns false if the index does not exist
- *
- * @param string $table
- * @param string $index
- * @param string $fname
- * @return bool|array|null False or null on failure
- */
- public function indexInfo( $table, $index, $fname = __METHOD__ ) {
- # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
- # SHOW INDEX should work for 3.x and up:
- # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
- $table = $this->tableName( $table );
- $index = $this->indexName( $index );
- $sql = 'SHOW INDEX FROM ' . $table;
- $res = $this->query( $sql, $fname );
- if ( !$res ) {
- return null;
- }
- $result = [];
- foreach ( $res as $row ) {
- if ( $row->Key_name == $index ) {
- $result[] = $row;
- }
- }
- return $result ?: false;
- }
- /**
- * @param string $s
- * @return string
- */
- public function strencode( $s ) {
- return $this->mysqlRealEscapeString( $s );
- }
- /**
- * @param string $s
- * @return mixed
- */
- abstract protected function mysqlRealEscapeString( $s );
- public function addQuotes( $s ) {
- if ( is_bool( $s ) ) {
- // Parent would transform to int, which does not play nice with MySQL type juggling.
- // When searching for an int in a string column, the strings are cast to int, which
- // means false would match any string not starting with a number.
- $s = (string)(int)$s;
- }
- return parent::addQuotes( $s );
- }
- /**
- * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
- *
- * @param string $s
- * @return string
- */
- public function addIdentifierQuotes( $s ) {
- // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
- // Remove NUL bytes and escape backticks by doubling
- return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
- }
- /**
- * @param string $name
- * @return bool
- */
- public function isQuotedIdentifier( $name ) {
- return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
- }
- protected function doGetLag() {
- if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
- return $this->getLagFromPtHeartbeat();
- } else {
- return $this->getLagFromSlaveStatus();
- }
- }
- /**
- * @return string
- */
- protected function getLagDetectionMethod() {
- return $this->lagDetectionMethod;
- }
- /**
- * @return bool|int
- */
- protected function getLagFromSlaveStatus() {
- $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX;
- $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__, $flags );
- $row = $res ? $res->fetchObject() : false;
- // If the server is not replicating, there will be no row
- if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
- return intval( $row->Seconds_Behind_Master );
- }
- return false;
- }
- /**
- * @return bool|float
- */
- protected function getLagFromPtHeartbeat() {
- $options = $this->lagDetectionOptions;
- $currentTrxInfo = $this->getRecordedTransactionLagStatus();
- if ( $currentTrxInfo ) {
- // There is an active transaction and the initial lag was already queried
- $staleness = microtime( true ) - $currentTrxInfo['since'];
- if ( $staleness > self::LAG_STALE_WARN_THRESHOLD ) {
- // Avoid returning higher and higher lag value due to snapshot age
- // given that the isolation level will typically be REPEATABLE-READ
- $this->queryLogger->warning(
- "Using cached lag value for {db_server} due to active transaction",
- $this->getLogContext( [
- 'method' => __METHOD__,
- 'age' => $staleness,
- 'exception' => new RuntimeException()
- ] )
- );
- }
- return $currentTrxInfo['lag'];
- }
- if ( isset( $options['conds'] ) ) {
- // Best method for multi-DC setups: use logical channel names
- $data = $this->getHeartbeatData( $options['conds'] );
- } else {
- // Standard method: use master server ID (works with stock pt-heartbeat)
- $masterInfo = $this->getMasterServerInfo();
- if ( !$masterInfo ) {
- $this->queryLogger->error(
- "Unable to query master of {db_server} for server ID",
- $this->getLogContext( [
- 'method' => __METHOD__
- ] )
- );
- return false; // could not get master server ID
- }
- $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
- $data = $this->getHeartbeatData( $conds );
- }
- list( $time, $nowUnix ) = $data;
- if ( $time !== null ) {
- // @time is in ISO format like "2015-09-25T16:48:10.000510"
- $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
- $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
- return max( $nowUnix - $timeUnix, 0.0 );
- }
- $this->queryLogger->error(
- "Unable to find pt-heartbeat row for {db_server}",
- $this->getLogContext( [
- 'method' => __METHOD__
- ] )
- );
- return false;
- }
- protected function getMasterServerInfo() {
- $cache = $this->srvCache;
- $key = $cache->makeGlobalKey(
- 'mysql',
- 'master-info',
- // Using one key for all cluster replica DBs is preferable
- $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
- );
- $fname = __METHOD__;
- return $cache->getWithSetCallback(
- $key,
- $cache::TTL_INDEFINITE,
- function () use ( $cache, $key, $fname ) {
- // Get and leave a lock key in place for a short period
- if ( !$cache->lock( $key, 0, 10 ) ) {
- return false; // avoid master connection spike slams
- }
- $conn = $this->getLazyMasterHandle();
- if ( !$conn ) {
- return false; // something is misconfigured
- }
- // Connect to and query the master; catch errors to avoid outages
- try {
- $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX;
- $res = $conn->query( 'SELECT @@server_id AS id', $fname, $flags );
- $row = $res ? $res->fetchObject() : false;
- $id = $row ? (int)$row->id : 0;
- } catch ( DBError $e ) {
- $id = 0;
- }
- // Cache the ID if it was retrieved
- return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
- }
- );
- }
- /**
- * @param array $conds WHERE clause conditions to find a row
- * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
- * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
- */
- protected function getHeartbeatData( array $conds ) {
- // Query time and trip time are not counted
- $nowUnix = microtime( true );
- $whereSQL = $this->makeList( $conds, self::LIST_AND );
- // Use ORDER BY for channel based queries since that field might not be UNIQUE.
- // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
- // percision field is not supported in MySQL <= 5.5.
- $res = $this->query(
- "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
- __METHOD__,
- self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX
- );
- $row = $res ? $res->fetchObject() : false;
- return [ $row ? $row->ts : null, $nowUnix ];
- }
- protected function getApproximateLagStatus() {
- if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
- // Disable caching since this is fast enough and we don't wan't
- // to be *too* pessimistic by having both the cache TTL and the
- // pt-heartbeat interval count as lag in getSessionLagStatus()
- return parent::getApproximateLagStatus();
- }
- $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
- $approxLag = $this->srvCache->get( $key );
- if ( !$approxLag ) {
- $approxLag = parent::getApproximateLagStatus();
- $this->srvCache->set( $key, $approxLag, 1 );
- }
- return $approxLag;
- }
- public function masterPosWait( DBMasterPos $pos, $timeout ) {
- if ( !( $pos instanceof MySQLMasterPos ) ) {
- throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
- }
- if ( $this->getLBInfo( 'is static' ) === true ) {
- $this->queryLogger->debug(
- "Bypassed replication wait; database has a static dataset",
- $this->getLogContext( [ 'method' => __METHOD__ ] )
- );
- return 0; // this is a copy of a read-only dataset with no master DB
- } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
- $this->queryLogger->debug(
- "Bypassed replication wait; replication already known to have reached $pos",
- $this->getLogContext( [ 'method' => __METHOD__ ] )
- );
- return 0; // already reached this point for sure
- }
- // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
- if ( $pos->getGTIDs() ) {
- // Get the GTIDs from this replica server too see the domains (channels)
- $refPos = $this->getReplicaPos();
- if ( !$refPos ) {
- $this->queryLogger->error(
- "Could not get replication position",
- $this->getLogContext( [ 'method' => __METHOD__ ] )
- );
- return -1; // this is the master itself?
- }
- // GTIDs with domains (channels) that are active and are present on the replica
- $gtidsWait = $pos::getRelevantActiveGTIDs( $pos, $refPos );
- if ( !$gtidsWait ) {
- $this->queryLogger->error(
- "No active GTIDs in $pos share a domain with those in $refPos",
- $this->getLogContext( [ 'method' => __METHOD__, 'activeDomain' => $pos ] )
- );
- return -1; // $pos is from the wrong cluster?
- }
- // Wait on the GTID set
- $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
- if ( strpos( $gtidArg, ':' ) !== false ) {
- // MySQL GTIDs, e.g "source_id:transaction_id"
- $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
- } else {
- // MariaDB GTIDs, e.g."domain:server:sequence"
- $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
- }
- } else {
- // Wait on the binlog coordinates
- $encFile = $this->addQuotes( $pos->getLogFile() );
- $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT] );
- $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
- }
- $res = $this->query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
- $row = $this->fetchRow( $res );
- // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
- $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
- if ( $status === null ) {
- $this->queryLogger->error(
- "An error occurred while waiting for replication to reach $pos",
- $this->getLogContext( [ 'method' => __METHOD__, 'sql' => $sql ] )
- );
- } elseif ( $status < 0 ) {
- $this->queryLogger->error(
- "Timed out waiting for replication to reach $pos",
- $this->getLogContext( [
- 'method' => __METHOD__, 'sql' => $sql, 'timeout' => $timeout
- ] )
- );
- } elseif ( $status >= 0 ) {
- $this->queryLogger->debug(
- "Replication has reached $pos",
- $this->getLogContext( [ 'method' => __METHOD__ ] )
- );
- // Remember that this position was reached to save queries next time
- $this->lastKnownReplicaPos = $pos;
- }
- return $status;
- }
- /**
- * Get the position of the master from SHOW SLAVE STATUS
- *
- * @return MySQLMasterPos|bool
- */
- public function getReplicaPos() {
- $now = microtime( true ); // as-of-time *before* fetching GTID variables
- if ( $this->useGTIDs() ) {
- // Try to use GTIDs, fallbacking to binlog positions if not possible
- $data = $this->getServerGTIDs( __METHOD__ );
- // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
- foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
- if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
- return new MySQLMasterPos( $data[$name], $now );
- }
- }
- }
- $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__ );
- if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
- return new MySQLMasterPos(
- "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
- $now
- );
- }
- return false;
- }
- /**
- * Get the position of the master from SHOW MASTER STATUS
- *
- * @return MySQLMasterPos|bool
- */
- public function getMasterPos() {
- $now = microtime( true ); // as-of-time *before* fetching GTID variables
- $pos = false;
- if ( $this->useGTIDs() ) {
- // Try to use GTIDs, fallbacking to binlog positions if not possible
- $data = $this->getServerGTIDs( __METHOD__ );
- // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
- foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
- if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
- $pos = new MySQLMasterPos( $data[$name], $now );
- break;
- }
- }
- // Filter domains that are inactive or not relevant to the session
- if ( $pos ) {
- $pos->setActiveOriginServerId( $this->getServerId() );
- $pos->setActiveOriginServerUUID( $this->getServerUUID() );
- if ( isset( $data['gtid_domain_id'] ) ) {
- $pos->setActiveDomain( $data['gtid_domain_id'] );
- }
- }
- }
- if ( !$pos ) {
- $data = $this->getServerRoleStatus( 'MASTER', __METHOD__ );
- if ( $data && strlen( $data['File'] ) ) {
- $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
- }
- }
- return $pos;
- }
- /**
- * @return int
- * @throws DBQueryError If the variable doesn't exist for some reason
- */
- protected function getServerId() {
- $fname = __METHOD__;
- return $this->srvCache->getWithSetCallback(
- $this->srvCache->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
- self::SERVER_ID_CACHE_TTL,
- function () use ( $fname ) {
- $flags = self::QUERY_IGNORE_DBO_TRX;
- $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
- return intval( $this->fetchObject( $res )->id );
- }
- );
- }
- /**
- * @return string|null
- */
- protected function getServerUUID() {
- $fname = __METHOD__;
- return $this->srvCache->getWithSetCallback(
- $this->srvCache->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
- self::SERVER_ID_CACHE_TTL,
- function () use ( $fname ) {
- $flags = self::QUERY_IGNORE_DBO_TRX;
- $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
- $row = $this->fetchObject( $res );
- return $row ? $row->Value : null;
- }
- );
- }
- /**
- * @param string $fname
- * @return string[]
- */
- protected function getServerGTIDs( $fname = __METHOD__ ) {
- $map = [];
- $flags = self::QUERY_IGNORE_DBO_TRX;
- // Get global-only variables like gtid_executed
- $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
- foreach ( $res as $row ) {
- $map[$row->Variable_name] = $row->Value;
- }
- // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
- $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
- foreach ( $res as $row ) {
- $map[$row->Variable_name] = $row->Value;
- }
- return $map;
- }
- /**
- * @param string $role One of "MASTER"/"SLAVE"
- * @param string $fname
- * @return string[] Latest available server status row
- */
- protected function getServerRoleStatus( $role, $fname = __METHOD__ ) {
- $flags = self::QUERY_IGNORE_DBO_TRX;
- return $this->query( "SHOW $role STATUS", $fname, $flags )->fetchRow() ?: [];
- }
- public function serverIsReadOnly() {
- // Avoid SHOW to avoid internal temporary tables
- $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
- $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__, $flags );
- $row = $this->fetchObject( $res );
- return $row ? (bool)$row->Value : false;
- }
- /**
- * @param string $index
- * @return string
- */
- function useIndexClause( $index ) {
- return "FORCE INDEX (" . $this->indexName( $index ) . ")";
- }
- /**
- * @param string $index
- * @return string
- */
- function ignoreIndexClause( $index ) {
- return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
- }
- /**
- * @return string
- */
- public function getSoftwareLink() {
- // MariaDB includes its name in its version string; this is how MariaDB's version of
- // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
- // in libmysql/libmysql.c).
- $version = $this->getServerVersion();
- if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
- return '[{{int:version-db-mariadb-url}} MariaDB]';
- }
- // Percona Server's version suffix is not very distinctive, and @@version_comment
- // doesn't give the necessary info for source builds, so assume the server is MySQL.
- // (Even Percona's version of mysql doesn't try to make the distinction.)
- return '[{{int:version-db-mysql-url}} MySQL]';
- }
- /**
- * @return string
- */
- public function getServerVersion() {
- $cache = $this->srvCache;
- $fname = __METHOD__;
- return $cache->getWithSetCallback(
- $cache->makeGlobalKey( 'mysql-server-version', $this->getServer() ),
- $cache::TTL_HOUR,
- function () use ( $fname ) {
- // Not using mysql_get_server_info() or similar for consistency: in the handshake,
- // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
- // it off (see RPL_VERSION_HACK in include/mysql_com.h).
- return $this->selectField( '', 'VERSION()', '', $fname );
- }
- );
- }
- /**
- * @param array $options
- */
- public function setSessionOptions( array $options ) {
- if ( isset( $options['connTimeout'] ) ) {
- $flags = self::QUERY_IGNORE_DBO_TRX;
- $timeout = (int)$options['connTimeout'];
- $this->query( "SET net_read_timeout=$timeout", __METHOD__, $flags );
- $this->query( "SET net_write_timeout=$timeout", __METHOD__, $flags );
- }
- }
- /**
- * @param string &$sql
- * @param string &$newLine
- * @return bool
- */
- public function streamStatementEnd( &$sql, &$newLine ) {
- if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
- preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
- $this->delimiter = $m[1];
- $newLine = '';
- }
- return parent::streamStatementEnd( $sql, $newLine );
- }
- /**
- * Check to see if a named lock is available. This is non-blocking.
- *
- * @param string $lockName Name of lock to poll
- * @param string $method Name of method calling us
- * @return bool
- * @since 1.20
- */
- public function lockIsFree( $lockName, $method ) {
- if ( !parent::lockIsFree( $lockName, $method ) ) {
- return false; // already held
- }
- $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
- $flags = self::QUERY_IGNORE_DBO_TRX;
- $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
- $row = $this->fetchObject( $res );
- return ( $row->lockstatus == 1 );
- }
- /**
- * @param string $lockName
- * @param string $method
- * @param int $timeout
- * @return bool
- */
- public function lock( $lockName, $method, $timeout = 5 ) {
- $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
- $flags = self::QUERY_IGNORE_DBO_TRX;
- $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
- $row = $this->fetchObject( $res );
- if ( $row->lockstatus == 1 ) {
- parent::lock( $lockName, $method, $timeout ); // record
- return true;
- }
- $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
- [ 'lockname' => $lockName ] );
- return false;
- }
- /**
- * FROM MYSQL DOCS:
- * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
- * @param string $lockName
- * @param string $method
- * @return bool
- */
- public function unlock( $lockName, $method ) {
- $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
- $flags = self::QUERY_IGNORE_DBO_TRX;
- $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
- $row = $this->fetchObject( $res );
- if ( $row->lockstatus == 1 ) {
- parent::unlock( $lockName, $method ); // record
- return true;
- }
- $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
- return false;
- }
- private function makeLockName( $lockName ) {
- // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
- // Newer version enforce a 64 char length limit.
- return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
- }
- public function namedLocksEnqueue() {
- return true;
- }
- public function tableLocksHaveTransactionScope() {
- return false; // tied to TCP connection
- }
- protected function doLockTables( array $read, array $write, $method ) {
- $items = [];
- foreach ( $write as $table ) {
- $items[] = $this->tableName( $table ) . ' WRITE';
- }
- foreach ( $read as $table ) {
- $items[] = $this->tableName( $table ) . ' READ';
- }
- $sql = "LOCK TABLES " . implode( ',', $items );
- $this->query( $sql, $method, self::QUERY_IGNORE_DBO_TRX );
- return true;
- }
- protected function doUnlockTables( $method ) {
- $this->query( "UNLOCK TABLES", $method, self::QUERY_IGNORE_DBO_TRX );
- return true;
- }
- /**
- * @param bool $value
- */
- public function setBigSelects( $value = true ) {
- if ( $value === 'default' ) {
- if ( $this->defaultBigSelects === null ) {
- # Function hasn't been called before so it must already be set to the default
- return;
- } else {
- $value = $this->defaultBigSelects;
- }
- } elseif ( $this->defaultBigSelects === null ) {
- $this->defaultBigSelects =
- (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
- }
- $encValue = $value ? '1' : '0';
- $this->query( "SET sql_big_selects=$encValue", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
- }
- /**
- * DELETE where the condition is a join. MySql uses multi-table deletes.
- * @param string $delTable
- * @param string $joinTable
- * @param string $delVar
- * @param string $joinVar
- * @param array|string $conds
- * @param bool|string $fname
- * @throws DBUnexpectedError
- */
- public function deleteJoin(
- $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
- ) {
- if ( !$conds ) {
- throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
- }
- $delTable = $this->tableName( $delTable );
- $joinTable = $this->tableName( $joinTable );
- $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
- if ( $conds != '*' ) {
- $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
- }
- $this->query( $sql, $fname );
- }
- public function upsert(
- $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
- ) {
- if ( $rows === [] ) {
- return true; // nothing to do
- }
- if ( !is_array( reset( $rows ) ) ) {
- $rows = [ $rows ];
- }
- $table = $this->tableName( $table );
- $columns = array_keys( $rows[0] );
- $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
- $rowTuples = [];
- foreach ( $rows as $row ) {
- $rowTuples[] = '(' . $this->makeList( $row ) . ')';
- }
- $sql .= implode( ',', $rowTuples );
- $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
- $this->query( $sql, $fname );
- return true;
- }
- /**
- * Determines how long the server has been up
- *
- * @return int
- */
- public function getServerUptime() {
- $vars = $this->getMysqlStatus( 'Uptime' );
- return (int)$vars['Uptime'];
- }
- /**
- * Determines if the last failure was due to a deadlock
- *
- * @return bool
- */
- public function wasDeadlock() {
- return $this->lastErrno() == 1213;
- }
- /**
- * Determines if the last failure was due to a lock timeout
- *
- * @return bool
- */
- public function wasLockTimeout() {
- return $this->lastErrno() == 1205;
- }
- /**
- * Determines if the last failure was due to the database being read-only.
- *
- * @return bool
- */
- public function wasReadOnlyError() {
- return $this->lastErrno() == 1223 ||
- ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
- }
- public function wasConnectionError( $errno ) {
- return $errno == 2013 || $errno == 2006;
- }
- protected function wasKnownStatementRollbackError() {
- $errno = $this->lastErrno();
- if ( $errno === 1205 ) { // lock wait timeout
- // Note that this is uncached to avoid stale values of SET is used
- $row = $this->selectRow(
- false,
- [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
- [],
- __METHOD__
- );
- // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
- // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
- return $row->innodb_rollback_on_timeout ? false : true;
- }
- // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
- return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
- }
- /**
- * @param string $oldName
- * @param string $newName
- * @param bool $temporary
- * @param string $fname
- * @return bool
- */
- public function duplicateTableStructure(
- $oldName, $newName, $temporary = false, $fname = __METHOD__
- ) {
- $tmp = $temporary ? 'TEMPORARY ' : '';
- $newName = $this->addIdentifierQuotes( $newName );
- $oldName = $this->addIdentifierQuotes( $oldName );
- $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
- return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT );
- }
- /**
- * List all tables on the database
- *
- * @param string|null $prefix Only show tables with this prefix, e.g. mw_
- * @param string $fname Calling function name
- * @return array
- */
- public function listTables( $prefix = null, $fname = __METHOD__ ) {
- $result = $this->query( "SHOW TABLES", $fname );
- $endArray = [];
- foreach ( $result as $table ) {
- $vars = get_object_vars( $table );
- $table = array_pop( $vars );
- if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
- $endArray[] = $table;
- }
- }
- return $endArray;
- }
- /**
- * @param string $tableName
- * @param string $fName
- * @return bool|IResultWrapper
- */
- public function dropTable( $tableName, $fName = __METHOD__ ) {
- if ( !$this->tableExists( $tableName, $fName ) ) {
- return false;
- }
- return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
- }
- /**
- * Get status information from SHOW STATUS in an associative array
- *
- * @param string $which
- * @return array
- */
- private function getMysqlStatus( $which = "%" ) {
- $flags = self::QUERY_IGNORE_DBO_TRX;
- $res = $this->query( "SHOW STATUS LIKE '{$which}'", __METHOD__, $flags );
- $status = [];
- foreach ( $res as $row ) {
- $status[$row->Variable_name] = $row->Value;
- }
- return $status;
- }
- /**
- * Lists VIEWs in the database
- *
- * @param string|null $prefix Only show VIEWs with this prefix, eg.
- * unit_test_, or $wgDBprefix. Default: null, would return all views.
- * @param string $fname Name of calling function
- * @return array
- * @since 1.22
- */
- public function listViews( $prefix = null, $fname = __METHOD__ ) {
- // The name of the column containing the name of the VIEW
- $propertyName = 'Tables_in_' . $this->getDBname();
- // Query for the VIEWS
- $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
- $allViews = [];
- foreach ( $res as $row ) {
- array_push( $allViews, $row->$propertyName );
- }
- if ( is_null( $prefix ) || $prefix === '' ) {
- return $allViews;
- }
- $filteredViews = [];
- foreach ( $allViews as $viewName ) {
- // Does the name of this VIEW start with the table-prefix?
- if ( strpos( $viewName, $prefix ) === 0 ) {
- array_push( $filteredViews, $viewName );
- }
- }
- return $filteredViews;
- }
- /**
- * Differentiates between a TABLE and a VIEW.
- *
- * @param string $name Name of the TABLE/VIEW to test
- * @param string|null $prefix
- * @return bool
- * @since 1.22
- */
- public function isView( $name, $prefix = null ) {
- return in_array( $name, $this->listViews( $prefix ) );
- }
- protected function isTransactableQuery( $sql ) {
- return parent::isTransactableQuery( $sql ) &&
- !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
- }
- public function buildStringCast( $field ) {
- return "CAST( $field AS BINARY )";
- }
- /**
- * @param string $field Field or column to cast
- * @return string
- */
- public function buildIntegerCast( $field ) {
- return 'CAST( ' . $field . ' AS SIGNED )';
- }
- /*
- * @return bool Whether GTID support is used (mockable for testing)
- */
- protected function useGTIDs() {
- return $this->useGTIDs;
- }
- }
- /**
- * @deprecated since 1.29
- */
- class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );
|