MediaWiki master
Wikimedia\Rdbms\IReadableDatabase Interface Reference

A database connection without write operations. More...

Inherits Wikimedia\Rdbms\Platform\ISQLPlatform, Wikimedia\Rdbms\Database\DbQuoter, and Wikimedia\Rdbms\Database\IDatabaseFlags.

Inherited by Wikimedia\Rdbms\IDatabase.

Collaboration diagram for Wikimedia\Rdbms\IReadableDatabase:

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.
 
 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.
 
 ping ()
 Ping the server and try to reconnect if it there is no connection.
 
 primaryPosWait (DBPrimaryPos $pos, $timeout)
 Wait for the replica server to catch up to a given primary server position.
 
 select ( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Execute a SELECT query constructed using the various parameters provided.
 
 selectDomain ( $domain)
 Set the current domain (database, schema, and table prefix)
 
 selectField ( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
 A SELECT wrapper which returns a single field from a single result row.
 
 selectFieldValues ( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
 A SELECT wrapper which returns a list of single field values from result rows.
 
 selectRow ( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
 Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
 
 selectRowCount ( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Get the number of rows in dataset.
 
 tablePrefix ( $prefix=null)
 Get/set the table prefix.
 
 wasDeadlock ()
 Determines if the last failure was due to a deadlock.
 
 wasReadOnlyError ()
 Determines if the last failure was due to the database being read-only.
 
- Public Member Functions inherited from Wikimedia\Rdbms\Platform\ISQLPlatform
 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, $table, $field, $conds='', $join_conds=[])
 Build a GROUP_CONCAT or equivalent statement for a query.
 
 buildIntegerCast ( $field)
 
 buildLeast ( $fields, $values)
 Build a LEAST function statement comparing columns/values.
 
 buildLike ( $param,... $params)
 LIKE statement wrapper.
 
 buildSelectSubquery ( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
 Equivalent to IDatabase::selectSQLText() except wraps the result in Subquery.
 
 buildStringCast ( $field)
 
 buildSubString ( $input, $startPosition, $length=null)
 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 ( $table, $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.
 
 tableNames (... $tables)
 Fetch a number of table names into an associative array.
 
 tableNamesN (... $tables)
 Fetch a number of table names into a zero-indexed numerical array.
 
 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.
 
- Public Member Functions inherited from Wikimedia\Rdbms\Database\DbQuoter
 addQuotes ( $s)
 Escape and quote a raw value string for use in a SQL query.
 
- Public Member Functions inherited from Wikimedia\Rdbms\Database\IDatabaseFlags
 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.
 

Additional Inherited Members

- Public Attributes inherited from Wikimedia\Rdbms\Platform\ISQLPlatform
const QUERY_PSEUDO_PERMANENT = 2
 Track a TEMPORARY table CREATE as if it was for a permanent table (for testing)
 
- Public Attributes inherited from Wikimedia\Rdbms\Database\IDatabaseFlags
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.
 

Detailed Description

A database connection without write operations.

Since
1.40

Definition at line 33 of file IReadableDatabase.php.

Member Function Documentation

◆ __toString()

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.

Returns
string "<db type> object #<X>" or "<db type> object #<X> (resource/handle id #<Y>)"
Since
1.34

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ close()

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.

Access: internal
Only for use by LoadBalancer
Parameters
string$fnameCaller name
Returns
bool Success
Exceptions
DBError

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ databasesAreIndependent()

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.

Returns
bool
Since
1.29

Implemented in Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.

◆ dbSchema()

Wikimedia\Rdbms\IReadableDatabase::dbSchema ( $schema = null)

Get/set the db schema.

Parameters
string | null$schemaThe database schema to set, or omitted to leave it unchanged
Returns
string The previous db schema

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ decodeBlob()

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.

Parameters
string | Blob$b
Returns
string
Exceptions
DBError

Implemented in Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.

Referenced by ArchivedFile\loadMetadataFromDbFieldValue(), and LocalFile\loadMetadataFromDbFieldValue().

◆ encodeBlob()

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().

Parameters
string$b
Returns
string|Blob
Exceptions
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().

◆ estimateRowCount()

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.

Access: internal
Parameters
string | string[]$tablesUnqualified name of table(s)
string$varColumn for which NULL values are not counted [default "*"]
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>>|array<int,string|IExpression>$conds Filters on the table
string$fnameFunction name for profiling
array$optionsOptions for select
array | string$join_condsJoin conditions
Returns
int Row count
Exceptions
DBErrorIf an error occurs, {
See also
query}

Implemented in Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabaseMySQL, and Wikimedia\Rdbms\DBConnRef.

◆ expr()

Wikimedia\Rdbms\IReadableDatabase::expr ( string $field,
string $op,
$value )

See Expression::__construct()

Since
1.42
Parameters
string$field
string$opOne of '>', '<', '!=', '=', '>=', '<=', IExpression::LIKE, IExpression::NOT_LIKE
?scalar|Blob|LikeValue|non-empty-list<scalar|Blob>$value
Returns
Expression

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

Referenced by RefreshImageMetadata\execute(), LocalFile\getHistory(), MediaWiki\User\TempUser\RealTempUserConfig\getMatchCondition(), MediaWiki\Title\Title\invalidateCache(), PurgeJobUtils\invalidatePages(), DeleteLocalPasswords\processUsers(), MediaWiki\Block\DatabaseBlockStore\purgeExpiredBlocks(), MediaWiki\Title\Title\purgeExpiredRestrictions(), and MediaWiki\Revision\RevisionStore\userWasLastToEdit().

◆ getDBname()

Wikimedia\Rdbms\IReadableDatabase::getDBname ( )

Get the current database name; null if there isn't one.

Returns
string|null

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

Referenced by Wikimedia\Rdbms\Replication\ReplicationReporter\getLogContext().

◆ getDomainID()

◆ getLag()

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

Returns
float|int|false Database replication lag in seconds or false on error
Exceptions
DBErrorIf an error occurs, {
See also
query}

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ getServer()

Wikimedia\Rdbms\IReadableDatabase::getServer ( )

Get the hostname or IP address of the server.

Returns
string|null

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ getServerInfo()

Wikimedia\Rdbms\IReadableDatabase::getServerInfo ( )

Get a human-readable string describing the current software version.

Use getServerVersion() to get machine-friendly information.

Returns
string Version information from the database server

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ getServerName()

◆ getServerVersion()

Wikimedia\Rdbms\IReadableDatabase::getServerVersion ( )

A string describing the current software version.

Returns
string Version information from the database server.

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().

◆ getSessionLagStatus()

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.

Returns
array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
Exceptions
DBErrorIf an error occurs, {
See also
query}
Since
1.27

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ getSoftwareLink()

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.

Returns
string Wikitext of a link to the server software's web site

Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.

Referenced by MediaWiki\Installer\MysqlInstaller\meetsMinimumRequirement().

◆ getType()

◆ isOpen()

Wikimedia\Rdbms\IReadableDatabase::isOpen ( )
Returns
bool Whether a connection to the database open

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ lastErrno()

Wikimedia\Rdbms\IReadableDatabase::lastErrno ( )

Get the RDBMS-specific error code from the last attempted query statement.

Returns
int|string Error code (integer or hexadecimal depending on RDBMS type)

Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.

◆ lastError()

Wikimedia\Rdbms\IReadableDatabase::lastError ( )

Get the RDBMS-specific error description from the last attempted query statement.

Returns
string

Implemented in Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.

◆ newSelectQueryBuilder()

◆ newUnionQueryBuilder()

Wikimedia\Rdbms\IReadableDatabase::newUnionQueryBuilder ( )

Create an empty UnionQueryBuilder which can be used to run queries against this connection.

Note
A new query builder must be created per query. Query builders should not be reused since this uses a fluent interface and the state of the builder changes during the query which may cause unexpected results.
Since
1.41
Returns
UnionQueryBuilder

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ ping()

Wikimedia\Rdbms\IReadableDatabase::ping ( )

Ping the server and try to reconnect if it there is no connection.

Returns
bool Success or failure

Implemented in Wikimedia\Rdbms\Database.

◆ primaryPosWait()

Wikimedia\Rdbms\IReadableDatabase::primaryPosWait ( DBPrimaryPos $pos,
$timeout )

Wait for the replica server to catch up to a given primary server position.

Note that this does not start any new transactions.

Callers might want to flush any existing transaction before invoking this method. Upon success, this assures that replica server queries will reflect all changes up to the given position, without interference from prior REPEATABLE-READ snapshots.

Parameters
DBPrimaryPos$pos
int$timeoutThe maximum number of seconds to wait for synchronisation
Returns
int|null Zero if the replica DB server was past that position already, greater than zero if we waited for some period of time, less than zero if it timed out, and null on error
Exceptions
DBErrorIf an error occurs, {
See also
query}
Since
1.37

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

Referenced by Wikimedia\Rdbms\LoadBalancer\waitForPrimaryPos().

◆ select()

Wikimedia\Rdbms\IReadableDatabase::select ( $table,
$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.

Parameters
string | array$tableUnqualified name of table(s)

May be either an array of table names, or a single string holding a table name. If an array is given, table aliases can 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.

Parameters
string | array$varsField 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.

Parameters
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>>|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:

  • Elements with a numeric key are interpreted as raw SQL fragments.
  • Elements with a string key are interpreted as equality conditions, where the key is the field name.
    • If the value of such an array element is a scalar (such as a string), it will be treated as data and thus quoted appropriately. If it is null, an IS NULL clause will be added.
    • If the value is an array, an IN (...) clause will be constructed from its non-null elements, and an IS NULL clause will be added if null is present, such that the field may match any of the elements in the array. The non-null elements will be quoted.

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:

  • IDatabase::buildLike()
  • IDatabase::conditional()

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' ],
Parameters
string$fnameCaller function name
string | array$optionsQuery 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:

  • OFFSET: Skip this many rows at the start of the result set. OFFSET with LIMIT can theoretically be used for paging through a result set, but this is discouraged for performance reasons.
  • LIMIT: Integer: return at most this many rows. The rows are sorted and then the first rows are taken until the limit is reached. LIMIT is applied to a result set after OFFSET.
  • LOCK IN SHARE MODE: Boolean: lock the returned rows so that they can't be changed until the next COMMIT. Cannot be used with aggregate functions (COUNT, MAX, etc., but also DISTINCT).
  • FOR UPDATE: Boolean: lock the returned rows so that they can't be changed nor read with LOCK IN SHARE MODE until the next COMMIT. Cannot be used with aggregate functions (COUNT, MAX, etc., but also DISTINCT).
  • DISTINCT: Boolean: return only unique result rows.
  • GROUP BY: May be either an SQL fragment string naming a field or expression to group by, or an array of such SQL fragments.
  • HAVING: May be either a string containing a HAVING clause or an array of conditions building the HAVING clause. If an array is given, the conditions constructed from each element are combined with AND.
  • ORDER BY: May be either an SQL fragment giving a field name or expression to order by, or an array of such SQL fragments.
  • USE INDEX: This may be either a string giving the index name to use for the query, or an array. If it is an associative array, each key gives the table name (or alias), each value gives the index name to use for that table. All strings are SQL fragments and so should be validated by the caller.
  • IGNORE INDEX: This may be either be a string giving an index name to ignore for the query, or an array. If it is an associative array, each key gives the table name (or alias), each value gives the index name to ignore for that table. All strings are SQL fragments and so should be validated by the caller.
  • EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run, instead of SELECT.
  • MAX_EXECUTION_TIME: (only in MySQL/MariaDB) maximum allowed time to run the query in milliseconds (if database supports it).

And also the following boolean MySQL extensions, see the MySQL manual for documentation:

  • STRAIGHT_JOIN
  • SQL_BIG_RESULT
  • SQL_BUFFER_RESULT
  • SQL_SMALL_RESULT
  • SQL_CALC_FOUND_ROWS
Parameters
string | array$join_condsJoin 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' ] ]

Access: internal
Returns
IResultWrapper Resulting rows
Exceptions
DBErrorIf an error occurs, {
See also
query}

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ selectDomain()

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

Parameters
string | DatabaseDomain$domain
Exceptions
DBConnectionErrorIf databasesAreIndependent() is true and connection change fails
DBErrorOn query error, if domain changes are disallowed, or the domain is invalid
Since
1.32

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ selectField()

Wikimedia\Rdbms\IReadableDatabase::selectField ( $table,
$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.

Access: internal
callers outside of rdbms library should use SelectQueryBuilder instead.
Parameters
string | array$tableUnqualified name of table. {
See also
select} for details.
Parameters
string | array$varThe 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. {
See also
select} for details.
Parameters
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>>|array<int,string|IExpression>$cond The condition array. {
See also
select} for details.
Parameters
string$fnameThe function name of the caller.
string | array$optionsThe query options. {
See also
select} for details.
Parameters
string | array$join_condsThe query join conditions. {
See also
select} for details.
Returns
mixed|false The value from the field, or false if nothing was found
Exceptions
DBErrorIf an error occurs, {
See also
query}

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ selectFieldValues()

Wikimedia\Rdbms\IReadableDatabase::selectFieldValues ( $table,
$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.

Access: internal
callers outside of rdbms library should use SelectQueryBuilder instead.
Parameters
string | array$tableUnqualified name of table. {
See also
select} for details.
Parameters
string$varThe field name to select. This must be a valid SQL fragment: do not use unvalidated user input.
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>>|array<int,string|IExpression>$cond The condition array. {
See also
select} for details.
Parameters
string$fnameThe function name of the caller.
string | array$optionsThe query options. {
See also
select} for details.
Parameters
string | array$join_condsThe query join conditions. {
See also
select} for details.
Returns
array The values from the field in the order they were returned from the DB
Exceptions
DBErrorIf an error occurs, {
See also
query}
Since
1.25

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ selectRow()

Wikimedia\Rdbms\IReadableDatabase::selectRow ( $table,
$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.

Access: internal
Parameters
string | array$tableUnqualified name of table
string | array$varsField names
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>>|array<int,string|IExpression>$conds Conditions
string$fnameCaller function name
string | array$optionsQuery options
array | string$join_condsJoin conditions
Returns
stdClass|false
Exceptions
DBErrorIf an error occurs, {
See also
query}

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

Referenced by Wikimedia\Rdbms\Replication\MysqlReplicationReporter\getReplicationSafetyInfo().

◆ selectRowCount()

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.

Since
1.27 Added $join_conds parameter
Access: internal
Parameters
string | string[]$tablesUnqualified name of table(s)
string$varColumn for which NULL values are not counted [default "*"]
string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>>|array<int,string|IExpression>$conds Filters on the table
string$fnameFunction name for profiling
array$optionsOptions for select
array$join_condsJoin conditions (since 1.27)
Returns
int Row count
Exceptions
DBErrorIf an error occurs, {
See also
query}

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

◆ tablePrefix()

Wikimedia\Rdbms\IReadableDatabase::tablePrefix ( $prefix = null)

Get/set the table prefix.

Parameters
string | null$prefixThe table prefix to set, or omitted to leave it unchanged
Returns
string The previous table prefix

Implemented in Wikimedia\Rdbms\Database, and Wikimedia\Rdbms\DBConnRef.

Referenced by CloneDatabase\__construct().

◆ wasDeadlock()

Wikimedia\Rdbms\IReadableDatabase::wasDeadlock ( )

Determines if the last failure was due to a deadlock.

Note that during a deadlock, the prior transaction will have been lost

Returns
bool

Implemented in Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabasePostgres, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.

◆ wasReadOnlyError()

Wikimedia\Rdbms\IReadableDatabase::wasReadOnlyError ( )

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

Returns
bool

Implemented in Wikimedia\Rdbms\Database, Wikimedia\Rdbms\DatabaseMySQL, Wikimedia\Rdbms\DatabaseSqlite, and Wikimedia\Rdbms\DBConnRef.

Referenced by LCStoreDB\finishWrite().


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