MediaWiki REL1_30
IDatabase.php
Go to the documentation of this file.
1<?php
26namespace Wikimedia\Rdbms;
27
28use Wikimedia\ScopedCallback;
29use Exception;
30use RuntimeException;
31use UnexpectedValueException;
32use stdClass;
33
40interface IDatabase {
42 const TRIGGER_IDLE = 1;
44 const TRIGGER_COMMIT = 2;
46 const TRIGGER_ROLLBACK = 3;
47
49 const TRANSACTION_EXPLICIT = '';
51 const TRANSACTION_INTERNAL = 'implicit';
52
54 const FLUSHING_ALL_PEERS = 'flush';
56 const FLUSHING_INTERNAL = 'flush';
57
59 const REMEMBER_NOTHING = '';
61 const REMEMBER_PRIOR = 'remember';
63 const RESTORE_PRIOR = 'prior';
65 const RESTORE_INITIAL = 'initial';
66
68 const ESTIMATE_TOTAL = 'total';
70 const ESTIMATE_DB_APPLY = 'apply';
71
73 const LIST_COMMA = 0;
75 const LIST_AND = 1;
77 const LIST_SET = 2;
79 const LIST_NAMES = 3;
81 const LIST_OR = 4;
82
84 const DBO_DEBUG = 1;
86 const DBO_NOBUFFER = 2;
88 const DBO_IGNORE = 4;
90 const DBO_TRX = 8;
92 const DBO_DEFAULT = 16;
94 const DBO_PERSISTENT = 32;
96 const DBO_SYSDBA = 64;
98 const DBO_DDLMODE = 128;
100 const DBO_SSL = 256;
102 const DBO_COMPRESS = 512;
103
111 public function getServerInfo();
112
133 public function bufferResults( $buffer = null );
134
143 public function trxLevel();
144
154 public function trxTimestamp();
155
160 public function explicitTrxActive();
161
167 public function tablePrefix( $prefix = null );
168
174 public function dbSchema( $schema = null );
175
185 public function getLBInfo( $name = null );
186
195 public function setLBInfo( $name, $value = null );
196
203 public function setLazyMasterHandle( IDatabase $conn );
204
211 public function implicitGroupby();
212
219 public function implicitOrderby();
220
225 public function lastQuery();
226
233 public function doneWrites();
234
242 public function lastDoneWrites();
243
248 public function writesPending();
249
257 public function writesOrCallbacksPending();
258
268 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL );
269
276 public function pendingWriteCallers();
277
284 public function pendingWriteRowsAffected();
285
290 public function isOpen();
291
304 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING );
305
318 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING );
319
326 public function restoreFlags( $state = self::RESTORE_PRIOR );
327
338 public function getFlag( $flag );
339
343 public function getDomainID();
344
351 public function getWikiID();
352
358 public function getType();
359
370 public function open( $server, $user, $password, $dbName );
371
382 public function fetchObject( $res );
383
393 public function fetchRow( $res );
394
401 public function numRows( $res );
402
410 public function numFields( $res );
411
420 public function fieldName( $res, $n );
421
431 public function insertId();
432
440 public function dataSeek( $res, $row );
441
448 public function lastErrno();
449
456 public function lastError();
457
467 public function fieldInfo( $table, $field );
468
475 public function affectedRows();
476
485 public function getSoftwareLink();
486
493 public function getServerVersion();
494
502 public function close();
503
508 public function reportConnectionError( $error = 'Unknown error' );
509
532 public function query( $sql, $fname = __METHOD__, $tempIgnore = false );
533
545 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false );
546
554 public function freeResult( $res );
555
574 public function selectField(
575 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
576 );
577
597 public function selectFieldValues(
598 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
599 );
600
750 public function select(
751 $table, $vars, $conds = '', $fname = __METHOD__,
752 $options = [], $join_conds = []
753 );
754
771 public function selectSQLText(
772 $table, $vars, $conds = '', $fname = __METHOD__,
773 $options = [], $join_conds = []
774 );
775
790 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
791 $options = [], $join_conds = []
792 );
793
814 public function estimateRowCount(
815 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
816 );
817
835 public function selectRowCount(
836 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
837 );
838
847 public function fieldExists( $table, $field, $fname = __METHOD__ );
848
859 public function indexExists( $table, $index, $fname = __METHOD__ );
860
868 public function tableExists( $table, $fname = __METHOD__ );
869
878 public function indexUnique( $table, $index );
879
913 public function insert( $table, $a, $fname = __METHOD__, $options = [] );
914
935 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] );
936
962 public function makeList( $a, $mode = self::LIST_COMMA );
963
974 public function makeWhereFrom2d( $data, $baseKey, $subKey );
975
984 public function aggregateValue( $valuedata, $valuename = 'value' );
985
990 public function bitNot( $field );
991
997 public function bitAnd( $fieldLeft, $fieldRight );
998
1004 public function bitOr( $fieldLeft, $fieldRight );
1005
1012 public function buildConcat( $stringList );
1013
1030 public function buildGroupConcatField(
1031 $delim, $table, $field, $conds = '', $join_conds = []
1032 );
1033
1039 public function buildStringCast( $field );
1040
1052 public function databasesAreIndependent();
1053
1061 public function selectDB( $db );
1062
1067 public function getDBname();
1068
1073 public function getServer();
1074
1081 public function addQuotes( $s );
1082
1099 public function buildLike();
1100
1106 public function anyChar();
1107
1113 public function anyString();
1114
1131 public function nextSequenceValue( $seqName );
1132
1155 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ );
1156
1193 public function upsert(
1194 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
1195 );
1196
1217 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
1218 $fname = __METHOD__
1219 );
1220
1231 public function delete( $table, $conds, $fname = __METHOD__ );
1232
1261 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
1262 $fname = __METHOD__,
1263 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
1264 );
1265
1272
1281 public function unionQueries( $sqls, $all );
1282
1310 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
1311 $options = [], $join_conds = []
1312 );
1313
1323 public function conditional( $cond, $trueVal, $falseVal );
1324
1335 public function strreplace( $orig, $old, $new );
1336
1342 public function getServerUptime();
1343
1349 public function wasDeadlock();
1350
1356 public function wasLockTimeout();
1357
1364 public function wasErrorReissuable();
1365
1371 public function wasReadOnlyError();
1372
1382 public function masterPosWait( DBMasterPos $pos, $timeout );
1383
1389 public function getReplicaPos();
1390
1396 public function getMasterPos();
1397
1402 public function serverIsReadOnly();
1403
1420 public function onTransactionResolution( callable $callback, $fname = __METHOD__ );
1421
1442 public function onTransactionIdle( callable $callback, $fname = __METHOD__ );
1443
1459 public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ );
1460
1476 public function setTransactionListener( $name, callable $callback = null );
1477
1499 public function startAtomic( $fname = __METHOD__ );
1500
1512 public function endAtomic( $fname = __METHOD__ );
1513
1541 public function doAtomicSection( $fname, callable $callback );
1542
1563 public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT );
1564
1585 public function commit( $fname = __METHOD__, $flush = '' );
1586
1605 public function rollback( $fname = __METHOD__, $flush = '' );
1606
1619 public function flushSnapshot( $fname = __METHOD__ );
1620
1629 public function listTables( $prefix = null, $fname = __METHOD__ );
1630
1642 public function timestamp( $ts = 0 );
1643
1657 public function timestampOrNull( $ts = null );
1658
1665 public function ping( &$rtt = null );
1666
1676 public function getLag();
1677
1691 public function getSessionLagStatus();
1692
1698 public function maxListLen();
1699
1709 public function encodeBlob( $b );
1710
1719 public function decodeBlob( $b );
1720
1732
1740 public function setSchemaVars( $vars );
1741
1750 public function lockIsFree( $lockName, $method );
1751
1762 public function lock( $lockName, $method, $timeout = 5 );
1763
1776 public function unlock( $lockName, $method );
1777
1799 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
1800
1807 public function namedLocksEnqueue();
1808
1816 public function getInfinity();
1817
1824 public function encodeExpiry( $expiry );
1825
1833 public function decodeExpiry( $expiry, $format = TS_MW );
1834
1844 public function setBigSelects( $value = true );
1845
1850 public function isReadOnly();
1851
1865 public function setTableAliases( array $aliases );
1866}
1867
1868class_alias( IDatabase::class, 'IDatabase' );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition Setup.php:36
$res
Definition database.txt:21
const LIST_NAMES
Definition Defines.php:46
const LIST_COMMA
Definition Defines.php:43
const LIST_SET
Definition Defines.php:45
const LIST_OR
Definition Defines.php:47
const LIST_AND
Definition Defines.php:44
the array() calling protocol came about after MediaWiki 1.4rc1.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition hooks.txt:2198
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition hooks.txt:2746
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition hooks.txt:1013
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:1971
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
An object representing a master or replica DB position in a replicated setup.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:40
freeResult( $res)
Free a result object returned by query() or select().
onTransactionResolution(callable $callback, $fname=__METHOD__)
Run a callback as soon as 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.
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
REPLACE query wrapper.
setSessionOptions(array $options)
Override database's default behavior.
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=[])
Build a GROUP_CONCAT or equivalent statement for a query.
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
setLazyMasterHandle(IDatabase $conn)
Set a lazy-connecting DB handle to the master DB (for replication status purposes)
lastDoneWrites()
Returns the last time the connection may have been used for write queries.
selectRowCount( $tables, $vars=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Get the number of rows in dataset.
upsert( $table, array $rows, array $uniqueIndexes, array $set, $fname=__METHOD__)
INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
unlock( $lockName, $method)
Release a lock.
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=[])
Single row SELECT wrapper.
doneWrites()
Returns true if the connection may have been used for write queries.
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
The equivalent of IDatabase::select() except that the constructed SQL is returned,...
bitAnd( $fieldLeft, $fieldRight)
conditional( $cond, $trueVal, $falseVal)
Returns an SQL expression for a simple conditional.
lastErrno()
Get the last error number.
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
getServer()
Get the server hostname or IP address.
getWikiID()
Alias for getDomainID()
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
isOpen()
Is a connection to the database open?
dataSeek( $res, $row)
Change the position of the cursor in a result object.
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
selectDB( $db)
Change the current database.
getReplicaPos()
Get the replication position of this replica DB.
setSchemaVars( $vars)
Set variables to be used in sourceFile/sourceStream, in preference to the ones in $GLOBALS.
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
setTransactionListener( $name, callable $callback=null)
Run a callback each time any transaction commits or rolls back.
getSoftwareLink()
Returns a wikitext link to the DB's website, e.g., return "[https://www.mysql.com/ MySQL]"; Should at...
setLBInfo( $name, $value=null)
Set the LB info array, or a member of it.
wasErrorReissuable()
Determines if the last query error was due to a dropped connection and should be dealt with by pingin...
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
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.
reportQueryError( $error, $errno, $sql, $fname, $tempIgnore=false)
Report a query error.
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
getInfinity()
Find out when 'infinity' is.
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
flushSnapshot( $fname=__METHOD__)
Commit any transaction but error out if writes or callbacks are pending.
affectedRows()
Get the number of rows affected by the last write query.
getServerUptime()
Determines how long the server has been up.
doAtomicSection( $fname, callable $callback)
Run a callback to do an atomic set of updates for this database.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists Usually throws a DBQueryError on failure If errors are explicitly ...
getServerInfo()
A string describing the current software version, and possibly other details in a user-friendly way.
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
buildLike()
LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match conta...
makeWhereFrom2d( $data, $baseKey, $subKey)
Build a partial where clause from a 2-d array such as used for LinkBatch.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
anyChar()
Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
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 available (non-blocking)
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
pendingWriteRowsAffected()
Get the number of affected rows from pending write queries.
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
lastQuery()
Return the last query that went through IDatabase::query()
numFields( $res)
Get the number of fields in a result object.
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
addQuotes( $s)
Adds quotes and backslashes.
fieldName( $res, $n)
Get a field name in a result object.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
lastError()
Get a description of the last error.
maxListLen()
Return the maximum number of items allowed in a list, or 0 for unlimited.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
reportConnectionError( $error='Unknown error')
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
getLag()
Get replica DB lag.
getSessionLagStatus()
Get the replica DB lag when the current transaction started or a general lag estimate if not transact...
unionSupportsOrderAndLimit()
Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries within th...
bitOr( $fieldLeft, $fieldRight)
rollback( $fname=__METHOD__, $flush='')
Rollback a transaction previously started using begin().
update( $table, $values, $conds, $fname=__METHOD__, $options=[])
UPDATE wrapper.
close()
Closes a database connection.
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
fetchObject( $res)
Fetch the next row from the given result object, in object form.
wasDeadlock()
Determines if the last failure was due to a deadlock.
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
tablePrefix( $prefix=null)
Get/set the table prefix.
setTableAliases(array $aliases)
Make certain table names use their own database, schema, and table prefix when passed into SQL querie...
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
numRows( $res)
Get the number of rows in a result object.
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=[])
Estimate the number of rows in dataset.
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
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.
fieldExists( $table, $field, $fname=__METHOD__)
Determines whether a field exists in a table.
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
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.
open( $server, $user, $password, $dbName)
Open a connection to the database.
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.
unionConditionPermutations( $table, $vars, array $permute_conds, $extra_conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Construct a UNION query for permutations of conditions.
insertId()
Get the inserted value of an auto-increment row.
strreplace( $orig, $old, $new)
Returns a command for str_replace function in SQL query.
startAtomic( $fname=__METHOD__)
Begin an atomic section of statements.
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
trxTimestamp()
Get the UNIX timestamp of the time that the transaction was established.
getMasterPos()
Get the position of this master.
getDBname()
Get the current DB name.
writesOrCallbacksPending()
Returns true if there is a transaction open with possible write queries or transaction pre-commit/idl...
bufferResults( $buffer=null)
Turns buffering of SQL result sets on (true) or off (false).
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
unionQueries( $sqls, $all)
Construct a UNION query This is used for providing overload point for other DB abstractions not compa...
dbSchema( $schema=null)
Get/set the db schema.
timestampOrNull( $ts=null)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
indexUnique( $table, $index)
Determines if a given index is unique.
onTransactionIdle(callable $callback, $fname=__METHOD__)
Run a callback as soon as there is no transaction pending.
$buffer
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:18
const DBO_DEFAULT
Definition defines.php:13
const DBO_SSL
Definition defines.php:17
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