MediaWiki  master
IDatabase.php
Go to the documentation of this file.
1 <?php
20 namespace Wikimedia\Rdbms;
21 
22 use Exception;
23 use stdClass;
26 use Wikimedia\ScopedCallback;
27 
39 interface IDatabase extends ISQLPlatform, DbQuoter {
41  public const TRIGGER_IDLE = 1;
43  public const TRIGGER_COMMIT = 2;
45  public const TRIGGER_ROLLBACK = 3;
47  public const TRIGGER_CANCEL = 4;
48 
50  public const TRANSACTION_EXPLICIT = '';
52  public const TRANSACTION_INTERNAL = 'implicit';
53 
55  public const ATOMIC_NOT_CANCELABLE = '';
57  public const ATOMIC_CANCELABLE = 'cancelable';
58 
60  public const FLUSHING_ONE = '';
62  public const FLUSHING_ALL_PEERS = 'flush';
64  public const FLUSHING_INTERNAL = 'flush-internal';
65 
67  public const REMEMBER_NOTHING = '';
69  public const REMEMBER_PRIOR = 'remember';
71  public const RESTORE_PRIOR = 'prior';
73  public const RESTORE_INITIAL = 'initial';
74 
76  public const ESTIMATE_TOTAL = 'total';
78  public const ESTIMATE_DB_APPLY = 'apply';
79 
81  public const DBO_DEBUG = 1;
83  public const DBO_NOBUFFER = 2;
85  public const DBO_IGNORE = 4;
87  public const DBO_TRX = 8;
89  public const DBO_DEFAULT = 16;
91  public const DBO_PERSISTENT = 32;
93  public const DBO_SYSDBA = 64;
95  public const DBO_DDLMODE = 128;
100  public const DBO_SSL = 256;
102  public const DBO_COMPRESS = 512;
103 
105  public const QUERY_NORMAL = 0;
107  public const QUERY_SILENCE_ERRORS = 1; // b/c for 1.32 query() argument; (int)true = 1
109  public const QUERY_PSEUDO_PERMANENT = 2;
111  public const QUERY_REPLICA_ROLE = 4;
113  public const QUERY_IGNORE_DBO_TRX = 8;
115  public const QUERY_NO_RETRY = 16;
117  public const QUERY_CHANGE_NONE = 32;
119  public const QUERY_CHANGE_TRX = 64 | self::QUERY_IGNORE_DBO_TRX;
121  public const QUERY_CHANGE_ROWS = 128;
123  public const QUERY_CHANGE_SCHEMA = 256 | self::QUERY_IGNORE_DBO_TRX;
125  public const QUERY_CHANGE_LOCKS = 512 | self::QUERY_IGNORE_DBO_TRX;
126 
128  public const LOCK_TIMESTAMP = 1;
129 
131  public const UNION_ALL = true;
133  public const UNION_DISTINCT = false;
134 
136  public const LB_TRX_ROUND_ID = 'trxRoundId';
138  public const LB_READ_ONLY_REASON = 'readOnlyReason';
139 
141  public const ROLE_STREAMING_MASTER = 'streaming-master';
143  public const ROLE_STREAMING_REPLICA = 'streaming-replica';
145  public const ROLE_STATIC_CLONE = 'static-clone';
147  public const ROLE_UNKNOWN = 'unknown';
148 
150  public const ALL_ROWS = '*';
151 
159  public function getServerInfo();
160 
172  public function getTopologyBasedServerId();
173 
185  public function getTopologyRole();
186 
198  public function getTopologyRootPrimary();
199 
208  public function trxLevel();
209 
221  public function trxTimestamp();
222 
232  public function explicitTrxActive();
233 
240  public function tablePrefix( $prefix = null );
241 
248  public function dbSchema( $schema = null );
249 
256  public function getLBInfo( $name = null );
257 
266  public function setLBInfo( $nameOrArray, $value = null );
267 
273  public function lastQuery();
274 
281  public function lastDoneWrites();
282 
287  public function writesPending();
288 
297  public function writesOrCallbacksPending();
298 
308  public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL );
309 
316  public function pendingWriteCallers();
317 
321  public function isOpen();
322 
329  public function setFlag( $flag, $remember = self::REMEMBER_NOTHING );
330 
337  public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING );
338 
345  public function restoreFlags( $state = self::RESTORE_PRIOR );
346 
353  public function getFlag( $flag );
354 
362  public function getDomainID();
363 
369  public function getType();
370 
380  public function insertId();
381 
387  public function lastErrno();
388 
394  public function lastError();
395 
404  public function affectedRows();
405 
413  public function getSoftwareLink();
414 
420  public function getServerVersion();
421 
435  public function close( $fname = __METHOD__ );
436 
462  public function query( $sql, $fname = __METHOD__, $flags = 0 );
463 
476  public function queryMulti(
477  array $sqls, string $fname = __METHOD__, int $flags = 0, ?string $summarySql = null
478  );
479 
487 
504  public function selectField(
505  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
506  );
507 
525  public function selectFieldValues(
526  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
527  ): array;
528 
709  public function select(
710  $table,
711  $vars,
712  $conds = '',
713  $fname = __METHOD__,
714  $options = [],
715  $join_conds = []
716  );
717 
734  public function selectRow(
735  $table,
736  $vars,
737  $conds,
738  $fname = __METHOD__,
739  $options = [],
740  $join_conds = []
741  );
742 
765  public function estimateRowCount(
766  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
767  );
768 
787  public function selectRowCount(
788  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
789  );
790 
803  public function lockForUpdate(
804  $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
805  );
806 
816  public function fieldExists( $table, $field, $fname = __METHOD__ );
817 
827  public function indexExists( $table, $index, $fname = __METHOD__ );
828 
837  public function tableExists( $table, $fname = __METHOD__ );
838 
858  public function insert( $table, $rows, $fname = __METHOD__, $options = [] );
859 
884  public function update( $table, $set, $conds, $fname = __METHOD__, $options = [] );
885 
903  public function buildExcludedValue( $column );
904 
917  public function databasesAreIndependent();
918 
930  public function selectDB( $db );
931 
944  public function selectDomain( $domain );
945 
951  public function getDBname();
952 
958  public function getServer();
959 
966  public function getServerName();
967 
984  public function nextSequenceValue( $seqName );
985 
1017  public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ );
1018 
1058  public function upsert(
1059  $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__
1060  );
1061 
1079  public function deleteJoin(
1080  $delTable,
1081  $joinTable,
1082  $delVar,
1083  $joinVar,
1084  $conds,
1085  $fname = __METHOD__
1086  );
1087 
1100  public function delete( $table, $conds, $fname = __METHOD__ );
1101 
1132  public function insertSelect(
1133  $destTable,
1134  $srcTable,
1135  $varMap,
1136  $conds,
1137  $fname = __METHOD__,
1138  $insertOptions = [],
1139  $selectOptions = [],
1140  $selectJoinConds = []
1141  );
1142 
1150  public function wasDeadlock();
1151 
1159  public function wasLockTimeout();
1160 
1169  public function wasConnectionLoss();
1170 
1176  public function wasReadOnlyError();
1177 
1185  public function wasErrorReissuable();
1186 
1202  public function primaryPosWait( DBPrimaryPos $pos, $timeout );
1203 
1210  public function getReplicaPos();
1211 
1219  public function getPrimaryPos();
1220 
1226  public function serverIsReadOnly();
1227 
1260  public function onTransactionResolution( callable $callback, $fname = __METHOD__ );
1261 
1296  public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ );
1297 
1327  public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ );
1328 
1352  public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ );
1353 
1371  public function setTransactionListener( $name, callable $callback = null );
1372 
1447  public function startAtomic( $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE );
1448 
1460  public function endAtomic( $fname = __METHOD__ );
1461 
1487  public function cancelAtomic( $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null );
1488 
1561  public function doAtomicSection(
1562  $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
1563  );
1564 
1584  public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT );
1585 
1604  public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1605 
1625  public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1626 
1644  public function flushSession( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1645 
1665  public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1666 
1673  public function ping( &$rtt = null );
1674 
1683  public function getLag();
1684 
1699  public function getSessionLagStatus();
1700 
1711  public function encodeBlob( $b );
1712 
1722  public function decodeBlob( $b );
1723 
1735  public function setSessionOptions( array $options );
1736 
1744  public function setSchemaVars( $vars );
1745 
1755  public function lockIsFree( $lockName, $method );
1756 
1769  public function lock( $lockName, $method, $timeout = 5, $flags = 0 );
1770 
1781  public function unlock( $lockName, $method );
1782 
1804  public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
1805 
1812  public function namedLocksEnqueue();
1813 
1823  public function setBigSelects( $value = true );
1824 
1829  public function isReadOnly();
1830 
1838  public function __toString();
1839 }
1840 
1844 class_alias( IDatabase::class, 'IDatabase' );
Class used for token representing identifiers for atomic sections from IDatabase instances.
An object representing a primary or replica DB position in a replicated setup.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:39
onTransactionResolution(callable $callback, $fname=__METHOD__)
Run a callback when the current transaction commits or rolls back.
onTransactionPreCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback before the current transaction commits or now if there is none.
flushSnapshot( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commit any transaction but error out if writes or callbacks are pending.
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
setSessionOptions(array $options)
Override database's default behavior.
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
lastDoneWrites()
Get the last time the connection may have been used for a write query.
unlock( $lockName, $method)
Release a lock.
explicitTrxActive()
Check whether there is a transaction open at the specific request of a caller.
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
setBigSelects( $value=true)
Allow or deny "big selects" for this session only.
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
buildExcludedValue( $column)
Build a reference to a column value from the conflicting proposed upsert() row.
primaryPosWait(DBPrimaryPos $pos, $timeout)
Wait for the replica DB to catch up to a given primary DB position.
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
doAtomicSection( $fname, callable $callback, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Perform an atomic section of reversible SQL statements from a callback.
getDomainID()
Return the currently selected domain ID.
lastErrno()
Get the RDBMS-specific error code from the last query statement.
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
lock( $lockName, $method, $timeout=5, $flags=0)
Acquire a named lock.
close( $fname=__METHOD__)
Close the database connection.
getServer()
Get the hostname or IP address of the server.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
selectDB( $db)
Change the current database.
getReplicaPos()
Get the replication position of this replica DB.
setSchemaVars( $vars)
Set schema variables to be used when streaming commands from SQL files or stdin.
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
setLBInfo( $nameOrArray, $value=null)
Set the entire array or a particular key of the managing load balancer info array.
setTransactionListener( $name, callable $callback=null)
Run a callback after each time any transaction commits or rolls back.
getSoftwareLink()
Returns a wikitext style link to the DB's website (e.g.
wasErrorReissuable()
Determines if the last query error was due to something outside of the query itself.
flushSession( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Release important session-level state (named lock, table locks) as post-rollback cleanup.
lockForUpdate( $table, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Lock all rows meeting the given conditions/options FOR UPDATE.
queryMulti(array $sqls, string $fname=__METHOD__, int $flags=0, ?string $summarySql=null)
Run a batch of SQL query statements and return the results.
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
__toString()
Get a debugging string that mentions the database type, the ID of this instance, and the ID of any un...
restoreFlags( $state=self::RESTORE_PRIOR)
Restore the flags to their prior state before the last setFlag/clearFlag call.
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper.
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
Delete all rows in a table that match a condition which includes a join.
wasConnectionLoss()
Determines if the last query error was due to a dropped connection.
getTopologyBasedServerId()
Get a non-recycled ID that uniquely identifies this server within the replication topology.
affectedRows()
Get the number of rows affected by the last write query.
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists.
getServerInfo()
Get a human-readable string describing the current software version.
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
lastQuery()
Get the last query that sent on account of IDatabase::query()
update( $table, $set, $conds, $fname=__METHOD__, $options=[])
Update all rows in a table that match a given condition.
selectDomain( $domain)
Set the current domain (database, schema, and table prefix)
upsert( $table, array $rows, $uniqueKeys, array $set, $fname=__METHOD__)
Upsert row(s) into a table, in the provided order, while updating conflicting rows.
lastError()
Get the RDBMS-specific error description from the last query statement.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
getTopologyRole()
Get the replication topology role of this server.
getType()
Get the RDBMS type of the server (e.g.
getLag()
Get the amount of replication lag for this database server.
getSessionLagStatus()
Get the replica DB lag when the current transaction started or a general lag estimate if not transact...
onTransactionCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback when the current transaction commits or now if there is none.
newSelectQueryBuilder()
Create an empty SelectQueryBuilder which can be used to run queries against this connection.
wasDeadlock()
Determines if the last failure was due to a deadlock.
tablePrefix( $prefix=null)
Get/set the table prefix.
selectRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
getTopologyRootPrimary()
Get the readable name of the sole root primary DB server for the replication topology.
getScopedLockAndFlush( $lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
onAtomicSectionCancel(callable $callback, $fname=__METHOD__)
Run a callback when the atomic section is cancelled.
fieldExists( $table, $field, $fname=__METHOD__)
Determines whether a field exists in a table.
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query statement and return the result.
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
getServerVersion()
A string describing the current software version, like from mysql_get_server_info()
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
insert( $table, $rows, $fname=__METHOD__, $options=[])
Insert row(s) into a table, in the provided order.
replace( $table, $uniqueKeys, $rows, $fname=__METHOD__)
Insert row(s) into a table, in the provided order, while deleting conflicting rows.
const QUERY_PSEUDO_PERMANENT
Track a TEMPORARY table CREATE as if it was for a permanent table (for testing)
Definition: IDatabase.php:109
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
trxLevel()
Gets the current transaction level.
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
insertId()
Get the inserted value of an auto-increment row.
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
trxTimestamp()
Get the UNIX timestamp of the time that the transaction was established.
getDBname()
Get the current database name; null if there isn't one.
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...
getServerName()
Get the readable name for the server.
const LOCK_TIMESTAMP
Flag to return the lock acquisition timestamp (null if not acquired)
Definition: IDatabase.php:128
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
getPrimaryPos()
Get the position of this primary DB.
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
dbSchema( $schema=null)
Get/set the db schema.
estimateRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate the number of rows in dataset.
Interface for query language.
const DBO_NOBUFFER
Definition: defines.php:10
const DBO_DDLMODE
Definition: defines.php:16
const DBO_SYSDBA
Definition: defines.php:15
const DBO_COMPRESS
Definition: defines.php:19
const DBO_DEFAULT
Definition: defines.php:13
const DBO_SSL
Definition: defines.php:18
const DBO_IGNORE
Definition: defines.php:11
const DBO_PERSISTENT
Definition: defines.php:14
const DBO_DEBUG
Definition: defines.php:9
const DBO_TRX
Definition: defines.php:12