MediaWiki  master
IDatabase.php
Go to the documentation of this file.
1 <?php
20 namespace Wikimedia\Rdbms;
21 
24 use Exception;
25 use stdClass;
26 
38 interface IDatabase {
40  const TRIGGER_IDLE = 1;
42  const TRIGGER_COMMIT = 2;
44  const TRIGGER_ROLLBACK = 3;
46  const TRIGGER_CANCEL = 4;
47 
49  const TRANSACTION_EXPLICIT = '';
51  const TRANSACTION_INTERNAL = 'implicit';
52 
54  const ATOMIC_NOT_CANCELABLE = '';
56  const ATOMIC_CANCELABLE = 'cancelable';
57 
59  const FLUSHING_ONE = '';
61  const FLUSHING_ALL_PEERS = 'flush';
63  const FLUSHING_INTERNAL = 'flush-internal';
64 
66  const REMEMBER_NOTHING = '';
68  const REMEMBER_PRIOR = 'remember';
70  const RESTORE_PRIOR = 'prior';
72  const RESTORE_INITIAL = 'initial';
73 
75  const ESTIMATE_TOTAL = 'total';
77  const ESTIMATE_DB_APPLY = 'apply';
78 
80  const LIST_COMMA = 0;
82  const LIST_AND = 1;
84  const LIST_SET = 2;
86  const LIST_NAMES = 3;
88  const LIST_OR = 4;
89 
91  const DBO_DEBUG = 1;
93  const DBO_NOBUFFER = 2;
95  const DBO_IGNORE = 4;
97  const DBO_TRX = 8;
99  const DBO_DEFAULT = 16;
101  const DBO_PERSISTENT = 32;
103  const DBO_SYSDBA = 64;
105  const DBO_DDLMODE = 128;
107  const DBO_SSL = 256;
109  const DBO_COMPRESS = 512;
110 
112  const QUERY_NORMAL = 0;
114  const QUERY_SILENCE_ERRORS = 1; // b/c for 1.32 query() argument; note that (int)true = 1
119  const QUERY_PSEUDO_PERMANENT = 2;
121  const QUERY_REPLICA_ROLE = 4;
123  const QUERY_IGNORE_DBO_TRX = 8;
125  const QUERY_NO_RETRY = 16;
126 
128  const UNION_ALL = true;
130  const UNION_DISTINCT = false;
131 
139  public function getServerInfo();
140 
149  public function trxLevel();
150 
162  public function trxTimestamp();
163 
168  public function explicitTrxActive();
169 
176  public function assertNoOpenTransactions();
177 
184  public function tablePrefix( $prefix = null );
185 
192  public function dbSchema( $schema = null );
193 
200  public function getLBInfo( $name = null );
201 
208  public function setLBInfo( $nameOrArray, $value = null );
209 
216  public function setLazyMasterHandle( IDatabase $conn );
217 
224  public function implicitOrderby();
225 
231  public function lastQuery();
232 
239  public function lastDoneWrites();
240 
245  public function writesPending();
246 
251  public function preCommitCallbacksPending();
252 
261  public function writesOrCallbacksPending();
262 
272  public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL );
273 
280  public function pendingWriteCallers();
281 
288  public function pendingWriteRowsAffected();
289 
293  public function isOpen();
294 
301  public function setFlag( $flag, $remember = self::REMEMBER_NOTHING );
302 
309  public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING );
310 
317  public function restoreFlags( $state = self::RESTORE_PRIOR );
318 
325  public function getFlag( $flag );
326 
334  public function getDomainID();
335 
341  public function getType();
342 
352  public function fetchObject( $res );
353 
363  public function fetchRow( $res );
364 
373  public function numRows( $res );
374 
382  public function numFields( $res );
383 
392  public function fieldName( $res, $n );
393 
403  public function insertId();
404 
412  public function dataSeek( $res, $row );
413 
420  public function lastErrno();
421 
428  public function lastError();
429 
438  public function affectedRows();
439 
447  public function getSoftwareLink();
448 
454  public function getServerVersion();
455 
468  public function close( $fname = __METHOD__, $owner = null );
469 
497  public function query( $sql, $fname = __METHOD__, $flags = 0 );
498 
507  public function freeResult( $res );
508 
524  public function selectField(
525  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
526  );
527 
545  public function selectFieldValues(
546  $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
547  );
548 
709  public function select(
710  $table,
711  $vars,
712  $conds = '',
713  $fname = __METHOD__,
714  $options = [],
715  $join_conds = []
716  );
717 
735  public function selectSQLText(
736  $table,
737  $vars,
738  $conds = '',
739  $fname = __METHOD__,
740  $options = [],
741  $join_conds = []
742  );
743 
760  public function selectRow(
761  $table,
762  $vars,
763  $conds,
764  $fname = __METHOD__,
765  $options = [],
766  $join_conds = []
767  );
768 
791  public function estimateRowCount(
792  $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
793  );
794 
813  public function selectRowCount(
814  $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
815  );
816 
829  public function lockForUpdate(
830  $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
831  );
832 
842  public function fieldExists( $table, $field, $fname = __METHOD__ );
843 
853  public function indexExists( $table, $index, $fname = __METHOD__ );
854 
863  public function tableExists( $table, $fname = __METHOD__ );
864 
895  public function insert( $table, $a, $fname = __METHOD__, $options = [] );
896 
917  public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] );
918 
944  public function makeList( $a, $mode = self::LIST_COMMA );
945 
956  public function makeWhereFrom2d( $data, $baseKey, $subKey );
957 
967  public function aggregateValue( $valuedata, $valuename = 'value' );
968 
973  public function bitNot( $field );
974 
980  public function bitAnd( $fieldLeft, $fieldRight );
981 
987  public function bitOr( $fieldLeft, $fieldRight );
988 
994  public function buildConcat( $stringList );
995 
1012  public function buildGroupConcatField(
1013  $delim, $table, $field, $conds = '', $join_conds = []
1014  );
1015 
1028  public function buildSubString( $input, $startPosition, $length = null );
1029 
1035  public function buildStringCast( $field );
1036 
1042  public function buildIntegerCast( $field );
1043 
1058  public function buildSelectSubquery(
1059  $table,
1060  $vars,
1061  $conds = '',
1062  $fname = __METHOD__,
1063  $options = [],
1064  $join_conds = []
1065  );
1066 
1084  public function limitResult( $sql, $limit, $offset = false );
1085 
1097  public function databasesAreIndependent();
1098 
1110  public function selectDB( $db );
1111 
1124  public function selectDomain( $domain );
1125 
1130  public function getDBname();
1131 
1136  public function getServer();
1137 
1144  public function addQuotes( $s );
1145 
1155  public function addIdentifierQuotes( $s );
1156 
1177  public function buildLike( $param );
1178 
1184  public function anyChar();
1185 
1191  public function anyString();
1192 
1209  public function nextSequenceValue( $seqName );
1210 
1236  public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ );
1237 
1273  public function upsert(
1274  $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1275  );
1276 
1297  public function deleteJoin(
1298  $delTable,
1299  $joinTable,
1300  $delVar,
1301  $joinVar,
1302  $conds,
1303  $fname = __METHOD__
1304  );
1305 
1316  public function delete( $table, $conds, $fname = __METHOD__ );
1317 
1348  public function insertSelect(
1349  $destTable,
1350  $srcTable,
1351  $varMap,
1352  $conds,
1353  $fname = __METHOD__,
1354  $insertOptions = [],
1355  $selectOptions = [],
1356  $selectJoinConds = []
1357  );
1358 
1364  public function unionSupportsOrderAndLimit();
1365 
1375  public function unionQueries( $sqls, $all );
1376 
1403  public function unionConditionPermutations(
1404  $table,
1405  $vars,
1406  array $permute_conds,
1407  $extra_conds = '',
1408  $fname = __METHOD__,
1409  $options = [],
1410  $join_conds = []
1411  );
1412 
1423  public function conditional( $cond, $trueVal, $falseVal );
1424 
1433  public function strreplace( $orig, $old, $new );
1434 
1441  public function getServerUptime();
1442 
1450  public function wasDeadlock();
1451 
1459  public function wasLockTimeout();
1460 
1469  public function wasConnectionLoss();
1470 
1476  public function wasReadOnlyError();
1477 
1485  public function wasErrorReissuable();
1486 
1501  public function masterPosWait( DBMasterPos $pos, $timeout );
1502 
1509  public function getReplicaPos();
1510 
1517  public function getMasterPos();
1518 
1523  public function serverIsReadOnly();
1524 
1549  public function onTransactionResolution( callable $callback, $fname = __METHOD__ );
1550 
1586  public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ );
1587 
1596  public function onTransactionIdle( callable $callback, $fname = __METHOD__ );
1597 
1624  public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ );
1625 
1649  public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ );
1650 
1668  public function setTransactionListener( $name, callable $callback = null );
1669 
1744  public function startAtomic( $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE );
1745 
1757  public function endAtomic( $fname = __METHOD__ );
1758 
1784  public function cancelAtomic( $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null );
1785 
1858  public function doAtomicSection(
1859  $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
1860  );
1861 
1881  public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT );
1882 
1901  public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1902 
1922  public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1923 
1943  public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1944 
1956  public function timestamp( $ts = 0 );
1957 
1972  public function timestampOrNull( $ts = null );
1973 
1980  public function ping( &$rtt = null );
1981 
1990  public function getLag();
1991 
2006  public function getSessionLagStatus();
2007 
2013  public function maxListLen();
2014 
2025  public function encodeBlob( $b );
2026 
2036  public function decodeBlob( $b );
2037 
2049  public function setSessionOptions( array $options );
2050 
2058  public function setSchemaVars( $vars );
2059 
2069  public function lockIsFree( $lockName, $method );
2070 
2082  public function lock( $lockName, $method, $timeout = 5 );
2083 
2094  public function unlock( $lockName, $method );
2095 
2117  public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
2118 
2125  public function namedLocksEnqueue();
2126 
2134  public function getInfinity();
2135 
2142  public function encodeExpiry( $expiry );
2143 
2151  public function decodeExpiry( $expiry, $format = TS_MW );
2152 
2162  public function setBigSelects( $value = true );
2163 
2168  public function isReadOnly();
2169 
2183  public function setTableAliases( array $aliases );
2184 
2197  public function setIndexAliases( array $aliases );
2198 
2206  public function __toString();
2207 }
2208 
2212 class_alias( IDatabase::class, 'IDatabase' );
upsert( $table, array $rows, $uniqueIndexes, array $set, $fname=__METHOD__)
INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
selectDB( $db)
Change the current database.
const DBO_IGNORE
Definition: defines.php:11
buildSelectSubquery( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Equivalent to IDatabase::selectSQLText() except wraps the result in Subqyery.
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
dbSchema( $schema=null)
Get/set the db schema.
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper.
getServerInfo()
Get a human-readable string describing the current software version.
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.
selectDomain( $domain)
Set the current domain (database, schema, and table prefix)
setSessionOptions(array $options)
Override database&#39;s default behavior.
conditional( $cond, $trueVal, $falseVal)
Returns an SQL expression for a simple conditional.
fetchObject( $res)
Fetch the next row from the given result object, in object form.
affectedRows()
Get the number of rows affected by the last write query.
getServerUptime()
Determines how long the server has been up.
timestampOrNull( $ts=null)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
lastErrno()
Get the last error number.
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
maxListLen()
Return the maximum number of items allowed in a list, or 0 for unlimited.
getInfinity()
Find out when &#39;infinity&#39; is.
numFields( $res)
Get the number of fields in a result object.
unionSupportsOrderAndLimit()
Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION...
pendingWriteRowsAffected()
Get the number of affected rows from pending write queries.
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
const LIST_NAMES
Definition: Defines.php:41
numRows( $res)
Get the number of rows in a query result.
setLBInfo( $nameOrArray, $value=null)
Set the entire array or a particular key of the managing load balancer info array.
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
getSessionLagStatus()
Get the replica DB lag when the current transaction started or a general lag estimate if not transact...
getMasterPos()
Get the position of this master.
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don&#39;t allow simple quoted strin...
getLag()
Get the amount of replication lag for this database server.
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
insertId()
Get the inserted value of an auto-increment row.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
flushSnapshot( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commit any transaction but error out if writes or callbacks are pending.
trxLevel()
Gets the current transaction level.
wasDeadlock()
Determines if the last failure was due to a deadlock.
getDomainID()
Return the currently selected domain ID.
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate the number of rows in dataset.
const DBO_DDLMODE
Definition: defines.php:16
wasErrorReissuable()
Determines if the last query error was due to something outside of the query itself.
getServerVersion()
A string describing the current software version, like from mysql_get_server_info() ...
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
anyString()
Returns a token for buildLike() that denotes a &#39;&#39; to be used in a LIKE query.
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
const DBO_PERSISTENT
Definition: defines.php:14
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...
unionQueries( $sqls, $all)
Construct a UNION query.
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
bitAnd( $fieldLeft, $fieldRight)
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
assertNoOpenTransactions()
Assert that all explicit transactions or atomic sections have been closed.
getScopedLockAndFlush( $lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
lastDoneWrites()
Get the last time the connection may have been used for a write query.
setSchemaVars( $vars)
Set variables to be used in sourceFile/sourceStream, in preference to the ones in $GLOBALS...
const DBO_DEBUG
Definition: defines.php:9
const LIST_AND
Definition: Defines.php:39
getReplicaPos()
Get the replication position of this replica DB.
const DBO_SYSDBA
Definition: defines.php:15
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:12
__toString()
Get a debugging string that mentions the database type, the ID of this instance, and the ID of any un...
const LIST_COMMA
Definition: Defines.php:38
onTransactionIdle(callable $callback, $fname=__METHOD__)
Alias for onTransactionCommitOrIdle() for backwards-compatibility.
makeWhereFrom2d( $data, $baseKey, $subKey)
Build a partial where clause from a 2-d array such as used for LinkBatch.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
getDBname()
Get the current DB name.
fieldName( $res, $n)
Get a field name in a result object.
bitOr( $fieldLeft, $fieldRight)
dataSeek( $res, $row)
Change the position of the cursor in a result object.
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.
unionConditionPermutations( $table, $vars, array $permute_conds, $extra_conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Construct a UNION query for permutations of conditions.
getSoftwareLink()
Returns a wikitext style link to the DB&#39;s website (e.g.
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Take the same arguments as IDatabase::select() and return the SQL it would use.
setLazyMasterHandle(IDatabase $conn)
Set a lazy-connecting DB handle to the master DB (for replication status purposes) ...
onTransactionPreCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback before the current transaction commits or now if there is none.
lastError()
Get a description of the last error.
lastQuery()
Get the last query that sent on account of IDatabase::query()
selectRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
wasConnectionLoss()
Determines if the last query error was due to a dropped connection.
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
strreplace( $orig, $old, $new)
Returns a SQL expression for simple string replacement (e.g.
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)
setTransactionListener( $name, callable $callback=null)
Run a callback after each time any transaction commits or rolls back.
buildSubString( $input, $startPosition, $length=null)
Build a SUBSTRING function.
const LIST_SET
Definition: Defines.php:40
const LIST_OR
Definition: Defines.php:42
const DBO_TRX
Definition: defines.php:12
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
const DBO_NOBUFFER
Definition: defines.php:10
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
setBigSelects( $value=true)
Allow or deny "big selects" for this session only.
anyChar()
Returns a token for buildLike() that denotes a &#39;_&#39; to be used in a LIKE query.
const DBO_DEFAULT
Definition: defines.php:13
selectFieldValues( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a list of single field values from result rows.
getType()
Get the type of the DBMS (e.g.
doAtomicSection( $fname, callable $callback, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Perform an atomic section of reversable SQL statements from a callback.
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
setTableAliases(array $aliases)
Make certain table names use their own database, schema, and table prefix when passed into SQL querie...
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists.
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
freeResult( $res)
Free a result object returned by query() or select()
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
getServer()
Get the server hostname or IP address.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
restoreFlags( $state=self::RESTORE_PRIOR)
Restore the flags to their prior state before the last setFlag/clearFlag call.
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
REPLACE query wrapper.
lockForUpdate( $table, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Lock all rows meeting the given conditions/options FOR UPDATE.
close( $fname=__METHOD__, $owner=null)
Close the database connection.
onTransactionResolution(callable $callback, $fname=__METHOD__)
Run a callback as soon as the current transaction commits or rolls back.
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
trxTimestamp()
Get the UNIX timestamp of the time that the transaction was established.
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query and return the result.
unlock( $lockName, $method)
Release a lock.
Class used for token representing identifiers for atomic sections from IDatabase instances.
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
const DBO_SSL
Definition: defines.php:17
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
tablePrefix( $prefix=null)
Get/set the table prefix.
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.
onTransactionCommitOrIdle(callable $callback, $fname=__METHOD__)
Run a callback as soon as there is no transaction pending.
const DBO_COMPRESS
Definition: defines.php:18
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
buildLike( $param)
LIKE statement wrapper.
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects...