MediaWiki master
|
A database connection without write operations. More...
Inherits Stringable, Wikimedia\Rdbms\Platform\ISQLPlatform, Wikimedia\Rdbms\Database\DbQuoter, and Wikimedia\Rdbms\Database\IDatabaseFlags.
Inherited by Wikimedia\Rdbms\IDatabase.
Public Member Functions | |
__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. | |
andExpr (array $conds) | |
See Expression::__construct() | |
close ( $fname=__METHOD__) | |
Close the database connection. | |
databasesAreIndependent () | |
Returns true if DBs are assumed to be on potentially different servers. | |
dbSchema ( $schema=null) | |
Get/set the db schema. | |
decodeBlob ( $b) | |
Some DBMSs return a special placeholder object representing blob fields in result objects. | |
encodeBlob ( $b) | |
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strings to be inserted. | |
estimateRowCount ( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[]) | |
Estimate the number of rows in dataset. | |
expr (string $field, string $op, $value) | |
See Expression::__construct() | |
getDBname () | |
Get the current database name; null if there isn't one. | |
getDomainID () | |
Return the currently selected domain ID. | |
getLag () | |
Get the seconds of replication lag on this database server. | |
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. | |
getServerVersion () | |
A string describing the current software version. | |
getSessionLagStatus () | |
Get a cached estimate of the seconds of replication lag on this database server, using the estimate obtained at the start of the current transaction if one is active. | |
getSoftwareLink () | |
Returns a wikitext style link to the DB's website (e.g. | |
getType () | |
Get the RDBMS type of the server (e.g. | |
isOpen () | |
lastErrno () | |
Get the RDBMS-specific error code from the last attempted query statement. | |
lastError () | |
Get the RDBMS-specific error description from the last attempted query statement. | |
newSelectQueryBuilder () | |
Create an empty SelectQueryBuilder which can be used to run queries against this connection. | |
newUnionQueryBuilder () | |
Create an empty UnionQueryBuilder which can be used to run queries against this connection. | |
orExpr (array $conds) | |
See Expression::__construct() | |
ping () | |
Ping the server and try to reconnect if it there is no connection. | |
select ( $tables, $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 ( $tables, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[]) | |
A SELECT wrapper which returns a single field from a single result row. | |
selectFieldValues ( $tables, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[]) | |
A SELECT wrapper which returns a list of single field values from result rows. | |
selectRow ( $tables, $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. | |
tablePrefix ( $prefix=null) | |
Get/set the table prefix. | |
![]() | |
addIdentifierQuotes ( $s) | |
Escape a SQL identifier (e.g. | |
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. | |
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, $tables, $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 ( $tables, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[]) | |
Equivalent to IDatabase::selectSQLText() except wraps the result in Subquery. | |
buildStringCast ( $field) | |
buildSubString ( $input, $startPosition, $length=null) | |
Build a SUBSTRING function. | |
conditional ( $cond, $caseTrueExpression, $caseFalseExpression) | |
Returns an SQL expression for a simple conditional. | |
decodeExpiry ( $expiry, $format=TS_MW) | |
Decode an expiry time into a DBMS independent format. | |
encodeExpiry ( $expiry) | |
Encode an expiry time into the DBMS dependent format. | |
factorConds ( $condsArray) | |
Given an array of condition arrays representing an OR list of AND lists, for example: | |
getInfinity () | |
Find out when 'infinity' is. | |
getTableAliases () | |
Return current table aliases. | |
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. | |
limitResult ( $sql, $limit, $offset=false) | |
Construct a LIMIT query with optional offset. | |
makeList (array $a, $mode=self::LIST_COMMA) | |
Makes an encoded list of strings from an array. | |
makeWhereFrom2d ( $data, $baseKey, $subKey) | |
Build a "OR" condition with pairs from a two-dimensional array. | |
selectSQLText ( $tables, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[]) | |
Take the same arguments as IDatabase::select() and return the SQL it would use. | |
setIndexAliases (array $aliases) | |
Convert certain index names to alternative names before querying the DB. | |
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. | |
strreplace ( $orig, $old, $new) | |
Returns a SQL expression for simple string replacement (e.g. | |
tableName (string $name, $format='quoted') | |
Format a table name ready for use in constructing an SQL query. | |
tableNamesN (... $tables) | |
Fetch a number of table names into a zero-indexed numerical array. | |
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. | |
unionQueries ( $sqls, $all, $options=[]) | |
Construct a UNION query. | |
unionSupportsOrderAndLimit () | |
Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION. | |
![]() | |
addQuotes ( $s) | |
Escape and quote a raw value string for use in a SQL query. | |
![]() | |
clearFlag ( $flag, $remember=self::REMEMBER_NOTHING) | |
Clear a flag for this connection. | |
getFlag ( $flag) | |
Returns a boolean whether the flag $flag is set for this connection. | |
restoreFlags ( $state=self::RESTORE_PRIOR) | |
Restore the flags to their prior state before the last setFlag/clearFlag call. | |
setFlag ( $flag, $remember=self::REMEMBER_NOTHING) | |
Set a flag for this connection. | |
Public Attributes | |
const | UNION_ALL = true |
Parameter to unionQueries() for UNION ALL. | |
const | UNION_DISTINCT = false |
Parameter to unionQueries() for UNION DISTINCT. | |
![]() | |
const | ALL_ROWS = '*' |
Unconditional update/delete of whole table. | |
const | CALLER_SUBQUERY = 'subquery' |
Special value for ->caller() / $fname parameter used when providing a caller is not expected, because we're formatting a subquery that won't be executed directly. | |
const | CALLER_UNKNOWN = 'unknown' |
Special value for ->caller() / $fname parameter used when a caller is not provided. | |
const | LIST_AND = 1 |
Combine list with AND clauses. | |
const | LIST_COMMA = 0 |
Combine list with comma delimiters. | |
const | LIST_NAMES = 3 |
Treat as field name and do not apply value escaping. | |
const | LIST_OR = 4 |
Combine list with OR clauses. | |
const | LIST_SET = 2 |
Convert map into a SET clause. | |
const | QUERY_CHANGE_LOCKS = 512 |
Query is a command for advisory locks. | |
const | QUERY_CHANGE_NONE = 32 |
Query is a read-only Data Query Language query. | |
const | QUERY_CHANGE_ROWS = 128 |
Query is a Data Manipulation Language command (INSERT, DELETE, LOCK, ...) | |
const | QUERY_CHANGE_SCHEMA = 256 |
Query is a Data Definition Language command. | |
const | QUERY_CHANGE_TRX = 64 |
Query is a Transaction Control Language command (BEGIN, USE, SET, ...) | |
const | QUERY_IGNORE_DBO_TRX = 8 |
Ignore the current presence of any DBO_TRX flag. | |
const | QUERY_NO_RETRY = 16 |
Do not try to retry the query if the connection was lost. | |
const | QUERY_NORMAL = 0 |
Idiom for "no special flags". | |
const | QUERY_PSEUDO_PERMANENT = 2 |
Track a TEMPORARY table CREATE as if it was for a permanent table (for testing) | |
const | QUERY_REPLICA_ROLE = 4 |
Enforce that a query does not make effective writes. | |
const | QUERY_SILENCE_ERRORS = 1 |
Ignore query errors and return false when they happen. | |
![]() | |
const | DBO_COMPRESS = 512 |
Enable compression in connection protocol. | |
const | DBO_DDLMODE = 128 |
Schema file mode; was used by Oracle. | |
const | DBO_DEBUG = 1 |
Enable debug logging of all SQL queries. | |
const | DBO_DEFAULT = 16 |
Join load balancer transaction rounds (which control DBO_TRX) in non-CLI mode. | |
const | DBO_GAUGE = 1024 |
Optimize connection for guaging server state (e.g. | |
const | DBO_IGNORE = 4 |
Unused since 1.31. | |
const | DBO_NOBUFFER = 2 |
Unused since 1.34. | |
const | DBO_PERSISTENT = 32 |
Use DB persistent connections if possible. | |
const | DBO_SSL = 256 |
Enable SSL/TLS in connection protocol. | |
const | DBO_SYSDBA = 64 |
DBA session mode; was used by Oracle. | |
const | DBO_TRX = 8 |
Automatically start a transaction before running a query if none is active. | |
const | REMEMBER_NOTHING = '' |
Do not remember the prior flags. | |
const | REMEMBER_PRIOR = 'remember' |
Remember the prior flags. | |
const | RESTORE_INITIAL = 'initial' |
Restore to the initial flag state. | |
const | RESTORE_PRIOR = 'prior' |
Restore to the prior flag state. | |
A database connection without write operations.
Definition at line 34 of file IReadableDatabase.php.
Wikimedia\Rdbms\IReadableDatabase::__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.
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::andExpr | ( | array | $conds | ) |
See Expression::__construct()
non-empty-array<string,?scalar|RawSQLValue|Blob|LikeValue|non-empty-list<scalar|Blob>>|non-empty-array<int,IExpression> | $conds |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by MediaWiki\User\TempUser\RealTempUserConfig\getMatchCondition().
Wikimedia\Rdbms\IReadableDatabase::close | ( | $fname = __METHOD__ | ) |
Close the database connection.
This should only be called after any transactions have been resolved, aside from read-only automatic transactions (assuming no callbacks are registered). If a transaction is still open anyway, it will be rolled back.
string | $fname | Caller name |
DBError |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::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.
Implemented in Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::dbSchema | ( | $schema = null | ) |
Get/set the db schema.
string | null | $schema | The database schema to set, or omitted to leave it unchanged |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::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.
string | Blob | $b |
DBError |
Implemented in Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Referenced by ArchivedFile\loadMetadataFromDbFieldValue(), and LocalFile\loadMetadataFromDbFieldValue().
Wikimedia\Rdbms\IReadableDatabase::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().
string | $b |
DBError |
Implemented in Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Referenced by ArchivedFile\getMetadataForDb(), LocalFile\getMetadataForDb(), and LCStoreDB\set().
Wikimedia\Rdbms\IReadableDatabase::estimateRowCount | ( | $tables, | |
$var = ' *', | |||
$conds = '', | |||
$fname = __METHOD__, | |||
$options = [], | |||
$join_conds = [] ) |
Estimate the number of rows in dataset.
MySQL allows you to estimate the number of rows that would be returned by a SELECT query, using EXPLAIN SELECT. The estimate is provided using index cardinality statistics, and is notoriously inaccurate, especially when large numbers of rows have recently been added or deleted.
For DBMSs that don't support fast result size estimation, this function will actually perform the SELECT COUNT(*).
Takes the same arguments as IDatabase::select().
New callers should use newSelectQueryBuilder
with SelectQueryBuilder::estimateRowCount
instead, which is more readable and less error-prone.
string | string[] | $tables | Table reference(s), using the unqualified name of tables or of the form "information_schema.<identifier>". { |
string | $var | Column for which NULL values are not counted [default "*"] @phpcs:ignore Generic.Files.LineLength |
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> | $conds Filters on the table | |
string | $fname | Function name for profiling |
array | $options | Options for select |
array | string | $join_conds | Join conditions |
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabaseMySQL, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::expr | ( | string | $field, |
string | $op, | ||
$value ) |
See Expression::__construct()
string | $field | |
string | $op | One of '>', '<', '!=', '=', '>=', '<=', IExpression::LIKE, IExpression::NOT_LIKE |
?scalar|RawSQLValue|Blob|LikeValue|non-empty-list<scalar|Blob> | $value |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by MigrateFileTables\execute(), RefreshImageMetadata\execute(), LocalFile\getHistory(), MediaWiki\User\TempUser\RealTempUserConfig\getMatchCondition(), MediaWiki\Title\Title\invalidateCache(), PurgeJobUtils\invalidatePages(), MediaWiki\Maintenance\DeleteLocalPasswords\processUsers(), MediaWiki\Block\DatabaseBlockStore\purgeExpiredBlocks(), MediaWiki\Title\Title\purgeExpiredRestrictions(), MediaWiki\Specials\SpecialWatchlist\registerFilters(), and MediaWiki\Revision\RevisionStore\userWasLastToEdit().
Wikimedia\Rdbms\IReadableDatabase::getDBname | ( | ) |
Get the current database name; null if there isn't one.
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by Wikimedia\Rdbms\Replication\ReplicationReporter\getLogContext().
Wikimedia\Rdbms\IReadableDatabase::getDomainID | ( | ) |
Return the currently selected domain ID.
Null components (database/schema) might change once a connection is established
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by MediaWiki\Deferred\LinksUpdate\LinksTable\doWrites(), Wikimedia\Rdbms\LoadBalancer\getConnLogContext(), MediaWiki\User\ActorMigrationBase\getInsertValues(), MediaWiki\User\ActorMigrationBase\getWhere(), MediaWiki\Title\Title\invalidateCache(), Wikimedia\Rdbms\LBFactorySingle\newFromConnection(), Wikimedia\Rdbms\LoadBalancerSingle\newFromConnection(), and Wikimedia\Rdbms\TransactionManager\transactionWritingOut().
Wikimedia\Rdbms\IReadableDatabase::getLag | ( | ) |
Get the seconds of replication lag on this database server.
Callers should avoid using this method while a transaction is active
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::getServer | ( | ) |
Get the hostname or IP address of the server.
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::getServerInfo | ( | ) |
Get a human-readable string describing the current software version.
Use getServerVersion() to get machine-friendly information.
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::getServerName | ( | ) |
Get the readable name for the server.
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by Wikimedia\Rdbms\Replication\MysqlReplicationReporter\getApproximateLagStatus(), Wikimedia\Rdbms\LoadBalancer\getConnLogContext(), Wikimedia\Rdbms\Replication\ReplicationReporter\getLogContext(), Wikimedia\Rdbms\Replication\MysqlReplicationReporter\getServerId(), Wikimedia\Rdbms\Replication\MysqlReplicationReporter\getServerUUID(), and Wikimedia\Rdbms\TransactionManager\transactionWritingOut().
Wikimedia\Rdbms\IReadableDatabase::getServerVersion | ( | ) |
A string describing the current software version.
Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Referenced by Wikimedia\Rdbms\Database\getServerInfo(), and MediaWiki\Installer\DatabaseInstaller\meetsMinimumRequirement().
Wikimedia\Rdbms\IReadableDatabase::getSessionLagStatus | ( | ) |
Get a cached estimate of the seconds of replication lag on this database server, using the estimate obtained at the start of the current transaction if one is active.
This is useful when transactions might use snapshot isolation (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data is this lag plus transaction duration. If they don't, it is still safe to be pessimistic. In AUTOCOMMIT mode, this still gives an indication of the staleness of subsequent reads.
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::getSoftwareLink | ( | ) |
Returns a wikitext style link to the DB's website (e.g.
"[https://www.mysql.com/ MySQL]")
Should at least contain plain text, if for some reason your database has no website.
Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Referenced by MediaWiki\Installer\MysqlInstaller\meetsMinimumRequirement().
Wikimedia\Rdbms\IReadableDatabase::getType | ( | ) |
Get the RDBMS type of the server (e.g.
"mysql", "sqlite")
Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Referenced by Wikimedia\Rdbms\LoadBalancerSingle\__construct(), Wikimedia\Rdbms\InsertQueryBuilder\connection(), Wikimedia\Rdbms\ReplaceQueryBuilder\connection(), Wikimedia\Rdbms\UpdateQueryBuilder\connection(), Wikimedia\Rdbms\SelectQueryBuilder\connection(), SqlBagOStuff\createTables(), MediaWiki\Installer\DatabaseUpdater\newForDB(), and MediaWiki\Installer\DatabaseUpdater\patchPath().
Wikimedia\Rdbms\IReadableDatabase::isOpen | ( | ) |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::lastErrno | ( | ) |
Get the RDBMS-specific error code from the last attempted query statement.
Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::lastError | ( | ) |
Get the RDBMS-specific error description from the last attempted query statement.
Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::newSelectQueryBuilder | ( | ) |
Create an empty SelectQueryBuilder which can be used to run queries against this connection.
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by BatchRowIterator\__construct(), MediaWiki\User\User\addToDatabase(), MediaWiki\Revision\RevisionStore\countRevisionsByPageId(), MediaWiki\CommentStore\CommentStore\createComment(), JobQueueDB\doBatchPushInternal(), MigrateFileTables\execute(), MediaWiki\Installer\MysqlDatabaseCreator\existsInConnection(), MediaWiki\ResourceLoader\WikiModule\fetchTitleInfo(), DumpCategoriesAsRdf\getCategoryIterator(), CategoryChangesAsRdf\getCategoryLinksIterator(), DumpCategoriesAsRdf\getCategoryLinksIterator(), CategoryChangesAsRdf\getDeletedCatsIterator(), MediaWiki\Block\HideUserUtils\getExpression(), MediaWiki\ExternalLinks\ExternalLinksLookup\getExternalLinksForPage(), LocalFile\getHistory(), MediaWiki\Revision\RevisionStore\getTimestampFromId(), CategoryChangesAsRdf\handleCategorization(), PurgeJobUtils\invalidatePages(), PageArchive\listPages(), MediaWiki\Revision\RevisionStore\newNullRevision(), MediaWiki\User\User\newQueryBuilder(), MediaWiki\Block\DatabaseBlockStore\purgeExpiredBlocks(), MediaWiki\Title\Title\purgeExpiredRestrictions(), and LocalFileMoveBatch\verifyDBUpdates().
Wikimedia\Rdbms\IReadableDatabase::newUnionQueryBuilder | ( | ) |
Create an empty UnionQueryBuilder which can be used to run queries against this connection.
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::orExpr | ( | array | $conds | ) |
See Expression::__construct()
non-empty-array<string,?scalar|RawSQLValue|Blob|LikeValue|non-empty-list<scalar|Blob>>|non-empty-array<int,IExpression> | $conds |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by MediaWiki\User\TempUser\RealTempUserConfig\getMatchCondition().
Wikimedia\Rdbms\IReadableDatabase::ping | ( | ) |
Ping the server and try to reconnect if it there is no connection.
Implemented in Wikimedia\Rdbms\Database.
Wikimedia\Rdbms\IReadableDatabase::select | ( | $tables, | |
$vars, | |||
$conds = '', | |||
$fname = __METHOD__, | |||
$options = [], | |||
$join_conds = [] ) |
Execute a SELECT query constructed using the various parameters provided.
New callers should use newSelectQueryBuilder
with SelectQueryBuilder::fetchResultSet
instead, which is more readable and less error-prone.
string | array | $tables | Table reference(s), using the unqualified name of tables or of the form "information_schema.<identifier>". |
Each table reference assigns a table name to a specified collection of rows for the context of the query (e.g. field expressions, WHERE clause, GROUP BY clause, HAVING clause, ect...). Use of multiple table references implies a JOIN.
If a string is given, it must hold the name of the table having the specified collection of rows. If an array is given, each entry must be one of the following:
String keys allow table aliases to be specified, for example:
[ 'a' => 'user' ]
This includes the user table in the query, with the alias "a" available for use in field names (e.g. a.user_name).
A derived table, defined by the result of selectSQLText(), requires an alias key and a Subquery instance value which wraps the SQL query, for example:
[ 'c' => new Subquery( 'SELECT ...' ) ]
Joins using parentheses for grouping (since MediaWiki 1.31) may be constructed using nested arrays. For example,
[ 'tableA', 'nestedB' => [ 'tableB', 'b2' => 'tableB2' ] ]
along with $join_conds
like
[ 'b2' => [ 'JOIN', 'b_id = b2_id' ], 'nestedB' => [ 'LEFT JOIN', 'b_a = a_id' ] ]
will produce SQL something like
FROM tableA LEFT JOIN (tableB JOIN tableB2 AS b2 ON (b_id = b2_id)) ON (b_a = a_id)
All of the table names given here are automatically run through Database::tableName(), which causes the table prefix (if any) to be added, and various other table name mappings to be performed.
Do not use untrusted user input as a table name. Alias names should not have characters outside of the Basic multilingual plane.
string | array | $vars | Field name(s) |
May be either a field name or an array of field names. The field names can be complete fragments of SQL, for direct inclusion into the SELECT query. If an array is given, field aliases can be specified, for example:
[ 'maxrev' => 'MAX(rev_id)' ]
This includes an expression with the alias "maxrev" in the query.
If an expression is given, care must be taken to ensure that it is DBMS-independent.
Untrusted user input must not be passed to this parameter.
@phpcs:ignore Generic.Files.LineLength
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> | $conds |
May be either a string containing a single condition, or an array of conditions. If an array is given, the conditions constructed from each element are combined with AND.
Array elements may take one of two forms:
Note that expressions are often DBMS-dependent in their syntax. DBMS-independent wrappers are provided for constructing several types of expression commonly used in condition queries. See:
Untrusted user input is safe in the values of string keys, however untrusted input must not be used in the array key names or in the values of numeric keys. Escaping of untrusted input used in values of numeric keys should be done via IDatabase::addQuotes()
Use an empty array, string, or IDatabase::ALL_ROWS to select all rows.
You can put simple join conditions here, but this is strongly discouraged. Instead of
// $conds... 'rev_actor = actor_id',
use (see below for $join_conds):
// $join_conds... 'actor' => [ 'JOIN', 'rev_actor = actor_id' ],
string | $fname | Caller function name |
string | array | $options | Query options |
Optional: Array of query options. Boolean options are specified by including them in the array as a string value with a numeric key, for example:
[ 'FOR UPDATE' ]
The supported options are:
And also the following boolean MySQL extensions, see the MySQL manual for documentation:
string | array | $join_conds | Join conditions |
Optional associative array of table-specific join conditions. Simple conditions can also be specified in the regular $conds, but this is strongly discouraged in favor of the more explicit syntax here.
The key of the array contains the table name or alias. The value is an array with two elements, numbered 0 and 1. The first gives the type of join, the second is the same as the $conds parameter. Thus it can be an SQL fragment, or an array where the string keys are equality and the numeric keys are SQL fragments all AND'd together. For example:
[ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::selectDomain | ( | $domain | ) |
Set the current domain (database, schema, and table prefix)
This will throw an error for some database types if the database is unspecified
This should only be called by a load balancer or if the handle is not attached to one
string | DatabaseDomain | $domain |
DBConnectionError | If databasesAreIndependent() is true and connection change fails |
DBError | On query error, if domain changes are disallowed, or the domain is invalid |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by MediaWiki\Installer\DatabaseInstaller\changeConnType().
Wikimedia\Rdbms\IReadableDatabase::selectField | ( | $tables, | |
$var, | |||
$cond = '', | |||
$fname = __METHOD__, | |||
$options = [], | |||
$join_conds = [] ) |
A SELECT wrapper which returns a single field from a single result row.
If no result rows are returned from the query, false is returned.
New callers should use newSelectQueryBuilder
with SelectQueryBuilder::fetchField
instead, which is more readable and less error-prone.
string | array | $tables | Table reference(s), using the unqualified name of tables or of the form "information_schema.<identifier>". { |
string | array | $var | The field name to select. This must be a valid SQL fragment: do not use unvalidated user input. Can be an array, but must contain exactly 1 element then. { |
@phpcs:ignore Generic.Files.LineLength
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> | $cond The condition array. { |
string | $fname | The function name of the caller. |
string | array | $options | The query options. { |
string | array | $join_conds | The query join conditions. { |
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by MediaWiki\Installer\PostgresDatabaseCreator\existsInConnection().
Wikimedia\Rdbms\IReadableDatabase::selectFieldValues | ( | $tables, | |
$var, | |||
$cond = '', | |||
$fname = __METHOD__, | |||
$options = [], | |||
$join_conds = [] ) |
A SELECT wrapper which returns a list of single field values from result rows.
If no result rows are returned from the query, an empty array is returned.
New callers should use newSelectQueryBuilder
with SelectQueryBuilder::fetchFieldValues
instead, which is more readable and less error-prone.
string | array | $tables | Table reference(s), using the unqualified name of tables or of the form "information_schema.<identifier>". { |
string | $var | The field name to select. This must be a valid SQL fragment: do not use unvalidated user input. |
@phpcs:ignore Generic.Files.LineLength
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> | $cond The condition array. { |
string | $fname | The function name of the caller. |
string | array | $options | The query options. { |
string | array | $join_conds | The query join conditions. { |
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::selectRow | ( | $tables, | |
$vars, | |||
$conds, | |||
$fname = __METHOD__, | |||
$options = [], | |||
$join_conds = [] ) |
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
If the query returns no rows, false is returned.
This method is convenient for fetching a row based on a unique key condition.
New callers should use newSelectQueryBuilder
with SelectQueryBuilder::fetchRow
instead, which is more readable and less error-prone.
string | array | $tables | Table reference(s), using the unqualified name of tables or of the form "information_schema.<identifier>". { |
string | array | $vars | Field names |
@phpcs:ignore Generic.Files.LineLength
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> | $conds Conditions | |
string | $fname | Caller function name |
string | array | $options | Query options |
array | string | $join_conds | Join conditions |
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by Wikimedia\Rdbms\Replication\MysqlReplicationReporter\getReplicationSafetyInfo().
Wikimedia\Rdbms\IReadableDatabase::selectRowCount | ( | $tables, | |
$var = ' *', | |||
$conds = '', | |||
$fname = __METHOD__, | |||
$options = [], | |||
$join_conds = [] ) |
Get the number of rows in dataset.
This is useful when trying to do COUNT(*) but with a LIMIT for performance.
Takes the same arguments as IDatabase::select().
New callers should use newSelectQueryBuilder
with SelectQueryBuilder::fetchRowCount
instead, which is more readable and less error-prone.
string | string[] | $tables | Table reference(s), using the unqualified name of tables or of the form "information_schema.<identifier>". { |
string | $var | Column for which NULL values are not counted [default "*"] |
@phpcs:ignore Generic.Files.LineLength
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> | $conds Filters on the table | |
string | $fname | Function name for profiling |
array | $options | Options for select |
array | $join_conds | Join conditions (since 1.27) |
DBError | If an error occurs, { |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Wikimedia\Rdbms\IReadableDatabase::tablePrefix | ( | $prefix = null | ) |
Get/set the table prefix.
string | null | $prefix | The table prefix to set, or omitted to leave it unchanged |
Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.
Referenced by CloneDatabase\__construct().
const Wikimedia\Rdbms\IReadableDatabase::UNION_ALL = true |
Parameter to unionQueries() for UNION ALL.
Definition at line 37 of file IReadableDatabase.php.
const Wikimedia\Rdbms\IReadableDatabase::UNION_DISTINCT = false |
Parameter to unionQueries() for UNION DISTINCT.
Definition at line 39 of file IReadableDatabase.php.