MediaWiki REL1_40
Wikimedia\Rdbms\DatabaseMysqlBase Class Reference

MySQL database abstraction layer. More...

Inherits Wikimedia\Rdbms\Database.

Inherited by Wikimedia\Rdbms\DatabaseMysqli.

Collaboration diagram for Wikimedia\Rdbms\DatabaseMysqlBase:

Public Member Functions

 __construct (array $params)
 Additional $params include:
 
 doLock (string $lockName, string $method, int $timeout)
 
 doLockIsFree (string $lockName, string $method)
 
 doUnlock (string $lockName, string $method)
 
 duplicateTableStructure ( $oldName, $newName, $temporary=false, $fname=__METHOD__)
 
 estimateRowCount ( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Estimate rows in dataset Returns estimated count, based on EXPLAIN output Takes same arguments as Database::select()
 
 fieldInfo ( $table, $field)
 
 getServerVersion ()
 
 getSoftwareLink ()
 
 getType ()
 
 indexInfo ( $table, $index, $fname=__METHOD__)
 Get information about an index into an object Returns false if the index does not exist.
 
 isView ( $name, $prefix=null)
 Differentiates between a TABLE and a VIEW.
 
 lastError ()
 
 listTables ( $prefix=null, $fname=__METHOD__)
 List all tables on the database.
 
 listViews ( $prefix=null, $fname=__METHOD__)
 Lists VIEWs in the database.
 
 namedLocksEnqueue ()
 Check to see if a named lock used by lock() use blocking queues.
Returns
bool
Since
1.26
Stability: stable
to override

 
 selectSQLText ( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Take the same arguments as IDatabase::select() and return the SQL it would use.
 
 serverIsReadOnly ()
 
Returns
bool Whether the DB server is marked as read-only server-side
Exceptions
DBErrorIf an error occurs, {
See also
query}
Since
1.28
Stability: stable
to override

 
 setSessionOptions (array $options)
 
 streamStatementEnd (&$sql, &$newLine)
 
 strencode ( $s)
 
 tableExists ( $table, $fname=__METHOD__)
 Query whether a given table exists.
 
 wasDeadlock ()
 Determines if the last failure was due to a deadlock.
 
 wasLockTimeout ()
 Determines if the last failure was due to a lock timeout.
 
 wasReadOnlyError ()
 Determines if the last failure was due to the database being read-only.
 
- Public Member Functions inherited from Wikimedia\Rdbms\Database
 __clone ()
 Make sure that copies do not share the same client binding handle.
 
 __destruct ()
 Run a few simple checks and close dangling connections.
 
 __sleep ()
 Called by serialize.
 
 __toString ()
 Get a debugging string that mentions the database type, the ID of this instance, and the ID of any underlying connection resource or driver object if one is present.
 
 addIdentifierQuotes ( $s)
 Escape a SQL identifier (e.g.
 
 addQuotes ( $s)
 Escape and quote a raw value string for use in a SQL query.
Parameters
string | int | float | null | bool | Blob$s
Returns
string

 
 affectedRows ()
 Get the number of rows affected by the last attempted query statement.
 
 anyChar ()
 Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
 
 anyString ()
 Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
 
 begin ( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
 Begin a transaction.
 
 bitAnd ( $fieldLeft, $fieldRight)
 
 bitNot ( $field)
 
 bitOr ( $fieldLeft, $fieldRight)
 
 buildComparison (string $op, array $conds)
 Build a condition comparing multiple values, for use with indexes that cover multiple fields, common when e.g.
 
 buildConcat ( $stringList)
 Build a concatenation list to feed into a SQL query.
 
 buildExcludedValue ( $column)
 Build a reference to a column value from the conflicting proposed upsert() row.
 
 buildGreatest ( $fields, $values)
 Build a GREATEST function statement comparing columns/values.
 
 buildGroupConcatField ( $delim, $table, $field, $conds='', $join_conds=[])
 Build a GROUP_CONCAT or equivalent statement for a query.
 
 buildIntegerCast ( $field)
 
 buildLeast ( $fields, $values)
 Build a LEAST function statement comparing columns/values.
 
 buildLike ( $param,... $params)
 LIKE statement wrapper.
 
 buildSelectSubquery ( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Equivalent to IDatabase::selectSQLText() except wraps the result in Subquery.
 
 buildStringCast ( $field)
 
 buildSubstring ( $input, $startPosition, $length=null)
 
 cancelAtomic ( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
 Cancel an atomic section of SQL statements.
 
 clearFlag ( $flag, $remember=self::REMEMBER_NOTHING)
 Clear a flag for this connection.
 
 close ( $fname=__METHOD__)
 Close the database connection.
 
 commit ( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
 Commits a transaction previously started using begin()
 
 conditional ( $cond, $caseTrueExpression, $caseFalseExpression)
 Returns an SQL expression for a simple conditional.
 
 connectionErrorLogger ( $errno, $errstr)
 Error handler for logging errors during database connection.
 
 databasesAreIndependent ()
 Returns true if DBs are assumed to be on potentially different servers.In systems like mysql/mariadb, different databases can easily be referenced on a single connection merely by name, even in a single query via JOIN. On the other hand, Postgres treats databases as logically separate, with different database users, requiring special mechanisms like postgres_fdw to "mount" foreign DBs. This is true even among DBs on the same server. Changing the selected database via selectDomain() requires a new connection.
Returns
bool
Since
1.29

 
 dbSchema ( $schema=null)
 Get/set the db schema.
 
 decodeBlob ( $b)
 Some DBMSs return a special placeholder object representing blob fields in result objects.Pass the object through this function to return the original string.
Parameters
string | Blob$b
Returns
string
Exceptions
DBError

 
 decodeExpiry ( $expiry, $format=TS_MW)
 Decode an expiry time into a DBMS independent format.
 
 delete ( $table, $conds, $fname=__METHOD__)
 Delete all rows in a table that match a condition.
 
 deleteJoin ( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
 Delete all rows in a table that match a condition which includes a join.For safety, an empty $conds will not delete everything. If you want to delete all rows where the join condition matches, set $conds=IDatabase::ALL_ROWS.DO NOT put the join condition in $conds.This operation will be seen by affectedRows()/insertId() as one query statement, regardless of how many statements are actually sent by the class implementation.
Parameters
string$delTableThe table to delete from.
string$joinTableThe reference table used by the join (not modified).
string$delVarThe variable to join on, in the first table.
string$joinVarThe variable to join on, in the second table.
array | string$condsCondition array of field names mapped to variables, ANDed together in the WHERE clause
string$fnameCalling function name (use METHOD) for logs/profiling
Exceptions
DBErrorIf an error occurs, {
See also
query}

 
 doAtomicSection ( $fname, callable $callback, $cancelable=self::ATOMIC_NOT_CANCELABLE)
 Perform an atomic section of reversible SQL statements from a callback.
 
 dropTable ( $table, $fname=__METHOD__)
 Delete a table.
 
 encodeBlob ( $b)
 Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strings to be inserted.To insert into such a field, pass the data through this function before passing it to IDatabase::insert().
Parameters
string$b
Returns
string|Blob
Exceptions
DBError

 
 encodeExpiry ( $expiry)
 Encode an expiry time into the DBMS dependent format.
 
 endAtomic ( $fname=__METHOD__)
 Ends an atomic section of SQL statements.
 
 explicitTrxActive ()
 Check whether there is a transaction open at the specific request of a caller.
 
 factorConds ( $condsArray)
 Given an array of condition arrays representing an OR list of AND lists, for example:
 
 fieldExists ( $table, $field, $fname=__METHOD__)
 Determines whether a field exists in a table.
 
 flushSession ( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
 Release important session-level state (named lock, table locks) as post-rollback cleanup.
 
 flushSnapshot ( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
 Commit any transaction but error out if writes or callbacks are pending.
 
 getDBname ()
 Get the current database name; null if there isn't one.
 
 getDomainID ()
 Return the currently selected domain ID.
 
 getFlag ( $flag)
 Returns a boolean whether the flag $flag is set for this connection.
 
 getInfinity ()
 Find out when 'infinity' is.
 
 getLag ()
 Get the amount of replication lag for this database server.
 
 getLBInfo ( $name=null)
 Get properties passed down from the server info array of the load balancer.
 
 getPrimaryPos ()
 Get the position of this primary DB.
 
 getReplicaPos ()
 Get the replication position of this replica DB.
 
 getScopedLockAndFlush ( $lockKey, $fname, $timeout)
 Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
 
 getServer ()
 Get the hostname or IP address of the server.
 
 getServerInfo ()
 Get a human-readable string describing the current software version.
 
 getServerName ()
 Get the readable name for the server.
 
 getSessionLagStatus ()
 Get the replica server lag when the current transaction started or a general lag estimate if not transaction is active.
 
 getTableAliases ()
 Return current table aliases.
 
 getTopologyBasedServerId ()
 Get a non-recycled ID that uniquely identifies this server within the replication topology.
 
 getTopologyRole ()
 Get the replication topology role of this server.
 
 getValueTypesForWithClause ( $table)
 
 implicitOrderby ()
 Returns true if this database does an implicit order by when the column has an index For example: SELECT page_title FROM page LIMIT 1.
 
 indexExists ( $table, $index, $fname=__METHOD__)
 Determines whether an index exists.
 
 indexUnique ( $table, $index, $fname=__METHOD__)
 Determines if a given index is unique.
Parameters
string$table
string$index
string$fnameCalling function name
Returns
bool

 
 initConnection ()
 Initialize the connection to the database over the wire (or to local files)
 
 insert ( $table, $rows, $fname=__METHOD__, $options=[])
 Insert row(s) into a table, in the provided order.
 
 insertSelect ( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
 INSERT SELECT wrapper.
 
 isOpen ()
 
 isQuotedIdentifier ( $name)
 
 isReadOnly ()
 
 lastDoneWrites ()
 Get the last time the connection may have been used for a write query.
 
 lastQuery ()
 Get the last query that sent on account of IDatabase::query()
 
 limitResult ( $sql, $limit, $offset=false)
 Construct a LIMIT query with optional offset.
 
 lock ( $lockName, $method, $timeout=5, $flags=0)
 Acquire a named lock.Named locks are not related to transactions
Parameters
string$lockNameName of lock to acquire
string$methodName of the calling method
int$timeoutAcquisition timeout in seconds (0 means non-blocking)
int$flagsBit field of IDatabase::LOCK_* constants
Returns
bool|float|null Success (bool); acquisition time (float/null) if LOCK_TIMESTAMP
Exceptions
DBErrorIf an error occurs, {
See also
query}

 
 lockForUpdate ( $table, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Lock all rows meeting the given conditions/options FOR UPDATE.
 
 lockIsFree ( $lockName, $method)
 Check to see if a named lock is not locked by any thread (non-blocking)
Parameters
string$lockNameName of lock to poll
string$methodName of method calling us
Returns
bool
Exceptions
DBErrorIf an error occurs, {
See also
query}
Since
1.20

 
 makeList (array $a, $mode=self::LIST_COMMA)
 Makes an encoded list of strings from an array.
 
 makeWhereFrom2d ( $data, $baseKey, $subKey)
 Build a partial where clause from a 2-d array such as used for LinkBatch.
 
 newSelectQueryBuilder ()
 Get a SelectQueryBuilder bound to this connection.
 
 newUpdateQueryBuilder ()
 Get an UpdateQueryBuilder bound to this connection.
 
 nextSequenceValue ( $seqName)
 Deprecated method, calls should be removed.
 
 onAtomicSectionCancel (callable $callback, $fname=__METHOD__)
 Run a callback when the atomic section is cancelled.
 
 onTransactionCommitOrIdle (callable $callback, $fname=__METHOD__)
 Run a callback when the current transaction commits or now if there is none.
 
 onTransactionPreCommitOrIdle (callable $callback, $fname=__METHOD__)
 Run a callback before the current transaction commits or now if there is none.
 
 onTransactionResolution (callable $callback, $fname=__METHOD__)
 Run a callback when the current transaction commits or rolls back.
 
 pendingWriteAndCallbackCallers ()
 
 pendingWriteCallers ()
 Get the list of method names that did write queries for this transaction.
 
 pendingWriteQueryDuration ( $type=self::ESTIMATE_TOTAL)
 Get the time spend running write queries for this transaction.
 
 ping ()
 Ping the server and try to reconnect if it there is no connection.
 
 primaryPosWait (DBPrimaryPos $pos, $timeout)
 Wait for the replica server to catch up to a given primary server position.
 
 query ( $sql, $fname=__METHOD__, $flags=0)
 Run an SQL query statement and return the result.
 
 queryMulti (array $sqls, string $fname=__METHOD__, int $flags=0, ?string $summarySql=null)
 Run a batch of SQL query statements and return the results.
 
 replace ( $table, $uniqueKeys, $rows, $fname=__METHOD__)
 Insert row(s) into a table, in the provided order, while deleting conflicting rows.
 
 reportQueryError ( $error, $errno, $sql, $fname, $ignore=false)
 Report a query error.
 
 restoreFlags ( $state=self::RESTORE_PRIOR)
 Restore the flags to their prior state before the last setFlag/clearFlag call.
 
 rollback ( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
 Rollback a transaction previously started using begin()
 
 runOnTransactionIdleCallbacks ( $trigger, array &$errors=[])
 Consume and run any "on transaction idle/resolution" callbacks.
 
 runOnTransactionPreCommitCallbacks ()
 
 runTransactionListenerCallbacks ( $trigger, array &$errors=[])
 Actually run any "transaction listener" callbacks.
 
 select ( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Execute a SELECT query constructed using the various parameters provided.
 
 selectDomain ( $domain)
 Set the current domain (database, schema, and table prefix)
 
 selectField ( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
 A SELECT wrapper which returns a single field from a single result row.
 
 selectFieldValues ( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
 A SELECT wrapper which returns a list of single field values from result rows.
 
 selectRow ( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
 Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
 
 selectRowCount ( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Get the number of rows in dataset.
 
 sessionLocksPending ()
 
 setFlag ( $flag, $remember=self::REMEMBER_NOTHING)
 Set a flag for this connection.
 
 setIndexAliases (array $aliases)
 Convert certain index names to alternative names before querying the DB.
 
 setLBInfo ( $nameOrArray, $value=null)
 Set the entire array or a particular key of the managing load balancer info array.
 
 setLogger (LoggerInterface $logger)
 Set the PSR-3 logger interface to use.
 
 setSchemaVars ( $vars)
 Set schema variables to be used when streaming commands from SQL files or stdin.
 
 setTableAliases (array $aliases)
 Make certain table names use their own database, schema, and table prefix when passed into SQL queries pre-escaped and without a qualified database name.
 
 setTransactionListener ( $name, callable $callback=null)
 Run a callback after each time any transaction commits or rolls back.
 
 setTransactionManager (TransactionManager $transactionManager)
 
 setTrxEndCallbackSuppression ( $suppress)
 Whether to disable running of post-COMMIT/ROLLBACK callbacks.
 
 sourceFile ( $filename, callable $lineCallback=null, callable $resultCallback=null, $fname=false, callable $inputCallback=null)
 Read and execute SQL commands from a file.
 
 sourceStream ( $fp, callable $lineCallback=null, callable $resultCallback=null, $fname=__METHOD__, callable $inputCallback=null)
 Read and execute commands from an open file handle.
 
 startAtomic ( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
 Begin an atomic section of SQL statements.
 
 strreplace ( $orig, $old, $new)
 Returns a SQL expression for simple string replacement (e.g.
 
 tableName ( $name, $format='quoted')
 Format a table name ready for use in constructing an SQL query.
 
 tableNames (... $tables)
 Fetch a number of table names into an associative array.
 
 tableNamesN (... $tables)
 Fetch a number of table names into a zero-indexed numerical array.
 
 tablePrefix ( $prefix=null)
 Get/set the table prefix.
 
 textFieldSize ( $table, $field)
 Returns the size of a text field, or -1 for "unlimited".
Parameters
string$table
string$field
Returns
int

 
 timestamp ( $ts=0)
 Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for inserting into timestamp fields in this DBMS.
 
 timestampOrNull ( $ts=null)
 Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for inserting into timestamp fields in this DBMS.
 
 truncate ( $tables, $fname=__METHOD__)
 Delete all data in a table(s) and reset any sequences owned by that table(s)
 
 trxLevel ()
 Gets the current transaction level.
 
 trxStatus ()
 
 trxTimestamp ()
 Get the UNIX timestamp of the time that the transaction was established.
 
 unionConditionPermutations ( $table, $vars, array $permute_conds, $extra_conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Construct a UNION query for permutations of conditions.
 
 unionQueries ( $sqls, $all)
 Construct a UNION query.
 
 unionSupportsOrderAndLimit ()
 Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION.
 
 unlock ( $lockName, $method)
 Release a lock.Named locks are not related to transactions
Parameters
string$lockNameName of lock to release
string$methodName of the calling method
Returns
bool Success
Exceptions
DBErrorIf an error occurs, {
See also
query}

 
 update ( $table, $set, $conds, $fname=__METHOD__, $options=[])
 Update all rows in a table that match a given condition.
 
 upsert ( $table, array $rows, $uniqueKeys, array $set, $fname=__METHOD__)
 Upsert row(s) into a table, in the provided order, while updating conflicting rows.
 
 wasConnectionLoss ()
 Determines if the last query error was due to a dropped connection.Note that during a connection loss, the prior transaction will have been lost
Returns
bool
Since
1.31

 
 wasErrorReissuable ()
 Determines if the last query error was due to something outside of the query itself.
 
 writesOrCallbacksPending ()
 Whether there is a transaction open with either possible write queries or unresolved pre-commit/commit/resolution callbacks pending.
 
 writesPending ()
 
- Public Member Functions inherited from Wikimedia\Rdbms\IDatabase
 insertId ()
 Get the inserted value of an auto-increment row.
 
- Public Member Functions inherited from Wikimedia\Rdbms\IReadableDatabase
 lastErrno ()
 Get the RDBMS-specific error code from the last attempted query statement.
 
- Public Member Functions inherited from Wikimedia\Rdbms\Platform\ISQLPlatform
 buildSubString ( $input, $startPosition, $length=null)
 Build a SUBSTRING function.
 

Protected Member Functions

 doFlushSession ( $fname)
 Reset the server-side session state for named locks and table locks.
 
 doReplace ( $table, array $identityKey, array $rows, $fname)
 
 doSelectDomain (DatabaseDomain $domain)
 
 doUpsert (string $table, array $rows, array $identityKey, array $set, string $fname)
 Perform an UPSERT query.
 
 getMySqlServerVariant ()
 
 isConnectionError ( $errno)
 Do not use this method outside of Database/DBError classes.
 
 isInsertSelectSafe (array $insertOptions, array $selectOptions)
 
 isKnownStatementRollbackError ( $errno)
 
 isQueryTimeoutError ( $errno)
 Checks whether the cause of the error is detected to be a timeout.
 
 mysqlConnect ( $server, $user, $password, $db)
 Open a connection to a MySQL server.
 
 mysqlError ( $conn=null)
 Returns the text of the error message from previous MySQL operation.
 
 mysqlRealEscapeString ( $s)
 Escape special characters in a string for use in an SQL statement.
 
 open ( $server, $user, $password, $db, $schema, $tablePrefix)
 Open a new connection to the database (closing any existing one)
 
- Protected Member Functions inherited from Wikimedia\Rdbms\Database
 assertHasConnectionHandle ()
 Make sure there is an open connection handle (alive or not)
 
 assertIsWritablePrimary ()
 Make sure that this server is not marked as a replica nor read-only.
 
 closeConnection ()
 Closes underlying database connection.
 
 commenceCriticalSection (string $fname)
 Demark the start of a critical section of session/transaction state changes.
 
 completeCriticalSection (string $fname, ?CriticalSectionScope $csm, Throwable $trxError=null)
 Demark the completion of a critical section of session/transaction state changes.
 
 doBegin ( $fname)
 Issues the BEGIN command to the database server.
 
 doCommit ( $fname)
 Issues the COMMIT command to the database server.
 
 doHandleSessionLossPreconnect ()
 Reset any additional subclass trx* and session* fields.
 
 doInitConnection ()
 Actually connect to the database over the wire (or to local files)
 
 doInsertSelectGeneric ( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
 Implementation of insertSelect() based on select() and insert()
 
 doInsertSelectNative ( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
 Native server-side implementation of insertSelect() for situations where we don't want to select everything into memory.
 
 doMultiStatementQuery (array $sqls)
 Execute a batch of query statements, aborting remaining statements if one fails.
 
 doSingleStatementQuery (string $sql)
 Run a query and return a QueryStatus instance with the query result information.
 
 doTruncate (array $tables, $fname)
 
 executeQuery ( $sqls, $fname, $flags, $summarySql)
 Execute a set of queries without enforcing public (non-Database) caller restrictions.
 
 fetchAffectedRowCount ()
 
 getBindingHandle ()
 Get the underlying binding connection handle.
 
 getLastPHPError ()
 
 getLogContext (array $extras=[])
 Create a log context to pass to PSR-3 logger functions.
 
 getReadOnlyReason ()
 
 getTempTableWrites ( $sql, $pseudoPermanent)
 
 getTransactionRoundId ()
 
 indexName ( $index)
 
 installErrorHandler ()
 Set a custom error handler for logging errors during database connection.
 
 isPristineTemporaryTable ( $table)
 Check if the table is both a TEMPORARY table and has not yet received CRUD operations.
 
 newExceptionAfterConnectError ( $error)
 
 registerTempWrites ( $ret, array $changes)
 
 replaceLostConnection ( $lastErrno, $fname)
 Close any existing (dead) database connection and open a new connection.
 
 restoreErrorHandler ()
 Restore the previous error handler and return the last PHP error for this DB.
 

Protected Attributes

bool null $defaultBigSelects
 
ISQLPlatform $platform
 
MysqlReplicationReporter $replicationReporter
 
string null $sslCAFile
 
string null $sslCAPath
 
string null $sslCertPath
 
string null $sslCiphers
 Open SSL cipher list string.
 
string null $sslKeyPath
 
bool $utf8Mode
 Use experimental UTF-8 transmission encoding.
 
- Protected Attributes inherited from Wikimedia\Rdbms\Database
int null $affectedRowCount
 Affected row count for the last query statement.
 
string $agent
 Agent name for query profiling.
 
bool $cliMode
 Whether this PHP instance is for a CLI script.
 
object resource null $conn
 Database connection.
 
array< string, mixed > $connectionParams
 Connection parameters used by initConnection() and open()
 
string[] int[] float[] $connectionVariables
 SQL variables values to use for all new connections.
 
int null $connectTimeout
 Maximum seconds to wait on connection attempts.
 
CriticalSectionProvider null $csProvider
 
DatabaseDomain $currentDomain
 
string false $delimiter = ';'
 Current SQL query delimiter.
 
callable $deprecationLogger
 Deprecation logging callback.
 
callable $errorLogger
 Error logging callback.
 
DatabaseFlags $flagsHolder
 
string $lastConnectError = ''
 Last error during connection; empty string if none.
 
array $lbInfo = []
 Current LoadBalancer tracking information.
 
LoggerInterface $logger
 
int $nonNativeInsertSelectBatchSize
 Row batch size to use for emulated INSERT SELECT queries.
 
SQLPlatform $platform
 
callable null $profiler
 
int null $receiveTimeout
 Maximum seconds to wait on receiving query results.
 
ReplicationReporter $replicationReporter
 
string null $serverName
 Readable name or host/IP of the database server.
 
array< string, array > $sessionNamedLocks = []
 Map of (name => (UNIX time,trx ID)) for current lock() mutexes.
 
array< string, array > $sessionTempTables = []
 Map of (name => (type,pristine,trx ID)) for current temp tables.
 
BagOStuff $srvCache
 APC cache.
 
bool $ssl
 Whether to use SSL connections.
 
const CONN_HOST = 'host'
 Hostname or IP address to use on all connections.
 
const CONN_INITIAL_DB = 'dbname'
 Database name to use on initial connection.
 
const CONN_INITIAL_SCHEMA = 'schema'
 Schema name to use on initial connection.
 
const CONN_INITIAL_TABLE_PREFIX = 'tablePrefix'
 Table prefix to use on initial connection.
 
const CONN_PASSWORD = 'password'
 Database server password to use on all connections.
 
const CONN_USER = 'user'
 Database server username to use on all connections.
 
const DROPPED_CONN_BLAME_THRESHOLD_SEC = 3.0
 Assume that queries taking this long to yield connection loss errors are at fault.
 
const ERR_ABORT_QUERY = 2
 Abort query (no retries) due to a statement rollback (session/transaction intact)
 
const ERR_ABORT_SESSION = 8
 Abort and reset session due to server-side session-level state loss (locks, temp tables)
 
const ERR_ABORT_TRX = 4
 Abort any current transaction, by rolling it back, due to an error during the query.
 
const ERR_NONE = 0
 No errors occurred during the query.
 
const ERR_RETRY_QUERY = 1
 Retry query due to a connection loss detected while sending the query (session intact)
 

Additional Inherited Members

- Static Public Member Functions inherited from Wikimedia\Rdbms\Database
static factory ( $type, $params=[], $connect=self::NEW_CONNECTED)
 Construct a Database subclass instance given a database type and parameters.
 
static getAttributes ()
 
static getCacheSetOptions (?IDatabase ... $dbs)
 Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estimate the lag of any data derived from them in combination.
 
- Public Attributes inherited from Wikimedia\Rdbms\IDatabase
const LOCK_TIMESTAMP = 1
 Flag to return the lock acquisition timestamp (null if not acquired)
 
- Public Attributes inherited from Wikimedia\Rdbms\Platform\ISQLPlatform
const QUERY_PSEUDO_PERMANENT = 2
 Track a TEMPORARY table CREATE as if it was for a permanent table (for testing)
 

Detailed Description

MySQL database abstraction layer.

Defines methods independent of the used MySQL extension.

TODO: This could probably be merged with DatabaseMysqli. The classees were split to support a transition from the old "mysql" extension to mysqli, and there may be an argument for retaining it in order to support some future transition to something else, but it's complexity and YAGNI.

Since
1.22
See also
Database

Definition at line 41 of file DatabaseMysqlBase.php.

Constructor & Destructor Documentation

◆ __construct()

Wikimedia\Rdbms\DatabaseMysqlBase::__construct ( array $params)

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. The "conds" key overrides the WHERE clause used to find the relevant row in the heartbeat table, e.g. ['shard' => 's1']. By default, the row used is the newest row having a server_id matching that of the immediate replication source server for the given replica.
  • useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
  • 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]
    Parameters
    array$params

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 86 of file DatabaseMysqlBase.php.

Member Function Documentation

◆ doFlushSession()

Wikimedia\Rdbms\DatabaseMysqlBase::doFlushSession ( $fname)
protected

Reset the server-side session state for named locks and table locks.

Connection and query errors will be suppressed and logged

Parameters
string$fname
Since
1.38

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 550 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\Database\addQuotes(), Wikimedia\Rdbms\Database\executeQuery(), and Wikimedia\Rdbms\Database\reportQueryError().

◆ doLock()

Wikimedia\Rdbms\DatabaseMysqlBase::doLock ( string $lockName,
string $method,
int $timeout )
See also
lock()
Parameters
string$lockName
string$method
int$timeout
Returns
float|null UNIX timestamp of lock acquisition; null on failure
Exceptions
DBError
Stability: stable
to override

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 524 of file DatabaseMysqlBase.php.

References $res, and Wikimedia\Rdbms\Database\query().

◆ doLockIsFree()

Wikimedia\Rdbms\DatabaseMysqlBase::doLockIsFree ( string $lockName,
string $method )
See also
lockIsFree()
Parameters
string$lockName
string$method
Returns
bool Success
Exceptions
DBError
Stability: stable
to override

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 513 of file DatabaseMysqlBase.php.

References $res, and Wikimedia\Rdbms\Database\query().

◆ doReplace()

Wikimedia\Rdbms\DatabaseMysqlBase::doReplace ( $table,
array $identityKey,
array $rows,
$fname )
protected
Parameters
string$table
string[]$identityKeyList of columns defining a unique key
array$rowsNon-empty list of rows
string$fname
See also
Database::replace()
Stability: stable
to override
Since
1.35

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 590 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\Database\query(), and Wikimedia\Rdbms\Database\tableName().

◆ doSelectDomain()

Wikimedia\Rdbms\DatabaseMysqlBase::doSelectDomain ( DatabaseDomain $domain)
protected

◆ doUnlock()

Wikimedia\Rdbms\DatabaseMysqlBase::doUnlock ( string $lockName,
string $method )
See also
unlock()
Parameters
string$lockName
string$method
Returns
bool Success
Exceptions
DBError
Stability: stable
to override

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 535 of file DatabaseMysqlBase.php.

References $res, and Wikimedia\Rdbms\Database\query().

◆ doUpsert()

Wikimedia\Rdbms\DatabaseMysqlBase::doUpsert ( string $table,
array $rows,
array $identityKey,
array $set,
string $fname )
protected

Perform an UPSERT query.

See also
Database::upsert()
Database::buildExcludedValue()
Stability: stable
to override
Parameters
string$tableTable name
array[]$rowsNon-empty list of rows to insert
string[]$identityKeyColumns of the (unique) identity key to UPSERT upon
string[]$setNon-empty map of (column name => SQL expression or literal)
string$fname
Since
1.35

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 568 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\Database\makeList(), Wikimedia\Rdbms\Database\query(), and Wikimedia\Rdbms\Database\tableName().

◆ duplicateTableStructure()

Wikimedia\Rdbms\DatabaseMysqlBase::duplicateTableStructure ( $oldName,
$newName,
$temporary = false,
$fname = __METHOD__ )
Parameters
string$oldName
string$newName
bool$temporary
string$fname
Returns
bool

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 658 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\Database\addIdentifierQuotes(), and Wikimedia\Rdbms\Database\query().

◆ estimateRowCount()

Wikimedia\Rdbms\DatabaseMysqlBase::estimateRowCount ( $tables,
$var = '*',
$conds = '',
$fname = __METHOD__,
$options = [],
$join_conds = [] )

Estimate rows in dataset Returns estimated count, based on EXPLAIN output Takes same arguments as Database::select()

Parameters
string | array$tables
string | array$var
string | array$conds
string$fname
string | array$options
array$join_conds
Returns
int|false

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 284 of file DatabaseMysqlBase.php.

References $res, and Wikimedia\Rdbms\Database\select().

◆ fieldInfo()

Wikimedia\Rdbms\DatabaseMysqlBase::fieldInfo ( $table,
$field )
Parameters
string$table
string$field
Returns
MySQLField|false

Implements Wikimedia\Rdbms\IMaintainableDatabase.

Definition at line 352 of file DatabaseMysqlBase.php.

References $res, Wikimedia\Rdbms\Database\query(), and Wikimedia\Rdbms\Database\tableName().

◆ getMySqlServerVariant()

Wikimedia\Rdbms\DatabaseMysqlBase::getMySqlServerVariant ( )
protected
Returns
string[] (one of ("MariaDB","MySQL"), x.y.z version string)

Definition at line 440 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\DatabaseMysqlBase\getServerVersion().

Referenced by Wikimedia\Rdbms\DatabaseMysqlBase\getSoftwareLink(), and Wikimedia\Rdbms\DatabaseMysqlBase\selectSQLText().

◆ getServerVersion()

Wikimedia\Rdbms\DatabaseMysqlBase::getServerVersion ( )

◆ getSoftwareLink()

Wikimedia\Rdbms\DatabaseMysqlBase::getSoftwareLink ( )

◆ getType()

Wikimedia\Rdbms\DatabaseMysqlBase::getType ( )
Returns
string

Implements Wikimedia\Rdbms\IReadableDatabase.

Definition at line 114 of file DatabaseMysqlBase.php.

◆ indexInfo()

Wikimedia\Rdbms\DatabaseMysqlBase::indexInfo ( $table,
$index,
$fname = __METHOD__ )

Get information about an index into an object Returns false if the index does not exist.

Parameters
string$table
string$index
string$fname
Returns
bool|array|null False or null on failure

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 375 of file DatabaseMysqlBase.php.

References $res, Wikimedia\Rdbms\Database\indexName(), Wikimedia\Rdbms\Database\query(), and Wikimedia\Rdbms\Database\tableName().

◆ isConnectionError()

Wikimedia\Rdbms\DatabaseMysqlBase::isConnectionError ( $errno)
protected

Do not use this method outside of Database/DBError classes.

Stability: stable
to override
Parameters
int | string$errno
Returns
bool Whether the given query error was a connection drop
Since
1.38

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 627 of file DatabaseMysqlBase.php.

◆ isInsertSelectSafe()

Wikimedia\Rdbms\DatabaseMysqlBase::isInsertSelectSafe ( array $insertOptions,
array $selectOptions )
protected
Stability: stable
to override
Parameters
array$insertOptions
array$selectOptions
Returns
bool Whether an INSERT SELECT with these options will be replication safe
Since
1.31

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 248 of file DatabaseMysqlBase.php.

◆ isKnownStatementRollbackError()

Wikimedia\Rdbms\DatabaseMysqlBase::isKnownStatementRollbackError ( $errno)
protected
Stability: stable
to override
Parameters
int | string$errno
Returns
bool Whether it is known that the last query error only caused statement rollback
Note
This is for backwards compatibility for callers catching DBError exceptions in order to ignore problems like duplicate key errors or foreign key violations
Since
1.39

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 641 of file DatabaseMysqlBase.php.

◆ isQueryTimeoutError()

Wikimedia\Rdbms\DatabaseMysqlBase::isQueryTimeoutError ( $errno)
protected

Checks whether the cause of the error is detected to be a timeout.

It returns false by default, and not all engines support detecting this yet. If this returns false, it will be treated as a generic query error.

Stability: stable
to override
Parameters
int | string$errnoError number
Returns
bool
Since
1.39

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 634 of file DatabaseMysqlBase.php.

◆ isView()

Wikimedia\Rdbms\DatabaseMysqlBase::isView ( $name,
$prefix = null )

Differentiates between a TABLE and a VIEW.

Parameters
string$nameName of the TABLE/VIEW to test
string | null$prefix
Returns
bool
Since
1.22

Definition at line 748 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\DatabaseMysqlBase\listViews().

◆ lastError()

◆ listTables()

Wikimedia\Rdbms\DatabaseMysqlBase::listTables ( $prefix = null,
$fname = __METHOD__ )

List all tables on the database.

Parameters
string | null$prefixOnly show tables with this prefix, e.g. mw_
string$fnameCalling function name
Returns
array

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 679 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\Database\query().

◆ listViews()

Wikimedia\Rdbms\DatabaseMysqlBase::listViews ( $prefix = null,
$fname = __METHOD__ )

Lists VIEWs in the database.

Parameters
string | null$prefixOnly show VIEWs with this prefix, eg. unit_test_, or $wgDBprefix. Default: null, would return all views.
string$fnameName of calling function
Returns
array
Since
1.22

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 709 of file DatabaseMysqlBase.php.

References $res, Wikimedia\Rdbms\Database\getDBname(), and Wikimedia\Rdbms\Database\query().

Referenced by Wikimedia\Rdbms\DatabaseMysqlBase\isView().

◆ mysqlConnect()

Wikimedia\Rdbms\DatabaseMysqlBase::mysqlConnect ( $server,
$user,
$password,
$db )
abstractprotected

Open a connection to a MySQL server.

Parameters
string | null$server
string | null$user
string | null$password
string | null$db
Returns
mixed|null Driver connection handle
Exceptions
DBConnectionError

Reimplemented in Wikimedia\Rdbms\DatabaseMysqli.

Referenced by Wikimedia\Rdbms\DatabaseMysqlBase\open().

◆ mysqlError()

Wikimedia\Rdbms\DatabaseMysqlBase::mysqlError ( $conn = null)
abstractprotected

Returns the text of the error message from previous MySQL operation.

Parameters
resource | null$connRaw connection
Returns
string

Reimplemented in Wikimedia\Rdbms\DatabaseMysqli.

Referenced by Wikimedia\Rdbms\DatabaseMysqlBase\lastError().

◆ mysqlRealEscapeString()

Wikimedia\Rdbms\DatabaseMysqlBase::mysqlRealEscapeString ( $s)
abstractprotected

Escape special characters in a string for use in an SQL statement.

Parameters
string$s
Returns
mixed

Reimplemented in Wikimedia\Rdbms\DatabaseMysqli.

Referenced by Wikimedia\Rdbms\DatabaseMysqlBase\strencode().

◆ namedLocksEnqueue()

Wikimedia\Rdbms\DatabaseMysqlBase::namedLocksEnqueue ( )

Check to see if a named lock used by lock() use blocking queues.

Returns
bool
Since
1.26
Stability: stable
to override

Stability: stable
to override

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 546 of file DatabaseMysqlBase.php.

◆ open()

Wikimedia\Rdbms\DatabaseMysqlBase::open ( $server,
$user,
$password,
$db,
$schema,
$tablePrefix )
protected

Open a new connection to the database (closing any existing one)

Parameters
string | null$serverServer host/address and optional port {
See also
connectionParams}
Parameters
string | null$userUser name {
See also
connectionParams}
Parameters
string | null$passwordUser password {
See also
connectionParams}
Parameters
string | null$dbDatabase name
string | null$schemaDatabase schema name
string$tablePrefix
Exceptions
DBConnectionError

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 118 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\Database\addQuotes(), Wikimedia\Rdbms\Database\close(), Wikimedia\Rdbms\Database\executeQuery(), Wikimedia\Rdbms\Database\installErrorHandler(), Wikimedia\Rdbms\DatabaseMysqlBase\lastError(), Wikimedia\Rdbms\DatabaseMysqlBase\mysqlConnect(), Wikimedia\Rdbms\Database\newExceptionAfterConnectError(), Wikimedia\Rdbms\Database\reportQueryError(), and Wikimedia\Rdbms\Database\restoreErrorHandler().

◆ selectSQLText()

Wikimedia\Rdbms\DatabaseMysqlBase::selectSQLText ( $table,
$vars,
$conds = '',
$fname = __METHOD__,
$options = [],
$join_conds = [] )

Take the same arguments as IDatabase::select() and return the SQL it would use.

This can be useful for making UNION queries, where the SQL text of each query is needed. In general, however, callers outside of Database classes should just use select().

See also
IDatabase::select()
Parameters
string | array$tableTable name(s)
string | array$varsField names
string | array$condsConditions
string$fnameCaller function name
string | array$optionsQuery options
string | array$join_condsJoin conditions
Returns
string SQL query string

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 752 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\DatabaseMysqlBase\getMySqlServerVariant().

◆ serverIsReadOnly()

Wikimedia\Rdbms\DatabaseMysqlBase::serverIsReadOnly ( )

Returns
bool Whether the DB server is marked as read-only server-side
Exceptions
DBErrorIf an error occurs, {
See also
query}
Since
1.28
Stability: stable
to override

Stability: stable
to override

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 416 of file DatabaseMysqlBase.php.

References $res, and Wikimedia\Rdbms\Database\query().

◆ setSessionOptions()

Wikimedia\Rdbms\DatabaseMysqlBase::setSessionOptions ( array $options)
Parameters
array$options

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 481 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\Database\query().

◆ streamStatementEnd()

Wikimedia\Rdbms\DatabaseMysqlBase::streamStatementEnd ( & $sql,
& $newLine )
Parameters
string&$sql
string&$newLine
Returns
bool

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 504 of file DatabaseMysqlBase.php.

◆ strencode()

Wikimedia\Rdbms\DatabaseMysqlBase::strencode ( $s)
Parameters
string$s
Returns
string

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 404 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\DatabaseMysqlBase\mysqlRealEscapeString().

◆ tableExists()

Wikimedia\Rdbms\DatabaseMysqlBase::tableExists ( $table,
$fname = __METHOD__ )

Query whether a given table exists.

Parameters
string$table
string$fname
Returns
bool
Exceptions
DBErrorIf an error occurs, {
See also
query}

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 315 of file DatabaseMysqlBase.php.

References $res, and Wikimedia\Rdbms\Database\query().

◆ wasDeadlock()

Wikimedia\Rdbms\DatabaseMysqlBase::wasDeadlock ( )

Determines if the last failure was due to a deadlock.

Returns
bool

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 604 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\IReadableDatabase\lastErrno().

◆ wasLockTimeout()

Wikimedia\Rdbms\DatabaseMysqlBase::wasLockTimeout ( )

Determines if the last failure was due to a lock timeout.

Returns
bool

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 613 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\IReadableDatabase\lastErrno().

◆ wasReadOnlyError()

Wikimedia\Rdbms\DatabaseMysqlBase::wasReadOnlyError ( )

Determines if the last failure was due to the database being read-only.

Returns
bool

Reimplemented from Wikimedia\Rdbms\Database.

Definition at line 622 of file DatabaseMysqlBase.php.

References Wikimedia\Rdbms\IReadableDatabase\lastErrno(), and Wikimedia\Rdbms\DatabaseMysqlBase\lastError().

Member Data Documentation

◆ $defaultBigSelects

bool null Wikimedia\Rdbms\DatabaseMysqlBase::$defaultBigSelects
protected

Definition at line 59 of file DatabaseMysqlBase.php.

◆ $platform

ISQLPlatform Wikimedia\Rdbms\DatabaseMysqlBase::$platform
protected

Definition at line 62 of file DatabaseMysqlBase.php.

◆ $replicationReporter

MysqlReplicationReporter Wikimedia\Rdbms\DatabaseMysqlBase::$replicationReporter
protected

Definition at line 65 of file DatabaseMysqlBase.php.

◆ $sslCAFile

string null Wikimedia\Rdbms\DatabaseMysqlBase::$sslCAFile
protected

Definition at line 47 of file DatabaseMysqlBase.php.

◆ $sslCAPath

string null Wikimedia\Rdbms\DatabaseMysqlBase::$sslCAPath
protected

Definition at line 49 of file DatabaseMysqlBase.php.

◆ $sslCertPath

string null Wikimedia\Rdbms\DatabaseMysqlBase::$sslCertPath
protected

Definition at line 45 of file DatabaseMysqlBase.php.

◆ $sslCiphers

string null Wikimedia\Rdbms\DatabaseMysqlBase::$sslCiphers
protected

Open SSL cipher list string.

See also
https://www.openssl.org/docs/man1.0.2/man1/ciphers.html

Definition at line 55 of file DatabaseMysqlBase.php.

◆ $sslKeyPath

string null Wikimedia\Rdbms\DatabaseMysqlBase::$sslKeyPath
protected

Definition at line 43 of file DatabaseMysqlBase.php.

◆ $utf8Mode

bool Wikimedia\Rdbms\DatabaseMysqlBase::$utf8Mode
protected

Use experimental UTF-8 transmission encoding.

Definition at line 57 of file DatabaseMysqlBase.php.


The documentation for this class was generated from the following file: