3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
20 namespace Wikimedia\Rdbms
;
22 use InvalidArgumentException
;
23 use Wikimedia\ScopedCallback
;
28 * @defgroup Database Database
29 * This group deals with database interface functions
30 * and query specifics/optimisations.
33 * Basic database interface for live and lazy-loaded relation database handles
35 * @note IDatabase and DBConnRef should be updated to reflect any changes
39 /** @var int Callback triggered immediately due to no active transaction */
40 const TRIGGER_IDLE
= 1;
41 /** @var int Callback triggered by COMMIT */
42 const TRIGGER_COMMIT
= 2;
43 /** @var int Callback triggered by ROLLBACK */
44 const TRIGGER_ROLLBACK
= 3;
46 /** @var string Transaction is requested by regular caller outside of the DB layer */
47 const TRANSACTION_EXPLICIT
= '';
48 /** @var string Transaction is requested internally via DBO_TRX/startAtomic() */
49 const TRANSACTION_INTERNAL
= 'implicit';
51 /** @var string Atomic section is not cancelable */
52 const ATOMIC_NOT_CANCELABLE
= '';
53 /** @var string Atomic section is cancelable */
54 const ATOMIC_CANCELABLE
= 'cancelable';
56 /** @var string Commit/rollback is from outside the IDatabase handle and connection manager */
57 const FLUSHING_ONE
= '';
58 /** @var string Commit/rollback is from the connection manager for the IDatabase handle */
59 const FLUSHING_ALL_PEERS
= 'flush';
60 /** @var string Commit/rollback is from the IDatabase handle internally */
61 const FLUSHING_INTERNAL
= 'flush-internal';
63 /** @var string Do not remember the prior flags */
64 const REMEMBER_NOTHING
= '';
65 /** @var string Remember the prior flags */
66 const REMEMBER_PRIOR
= 'remember';
67 /** @var string Restore to the prior flag state */
68 const RESTORE_PRIOR
= 'prior';
69 /** @var string Restore to the initial flag state */
70 const RESTORE_INITIAL
= 'initial';
72 /** @var string Estimate total time (RTT, scanning, waiting on locks, applying) */
73 const ESTIMATE_TOTAL
= 'total';
74 /** @var string Estimate time to apply (scanning, applying) */
75 const ESTIMATE_DB_APPLY
= 'apply';
77 /** @var int Combine list with comma delimeters */
79 /** @var int Combine list with AND clauses */
81 /** @var int Convert map into a SET clause */
83 /** @var int Treat as field name and do not apply value escaping */
85 /** @var int Combine list with OR clauses */
88 /** @var int Enable debug logging */
90 /** @var int Disable query buffering (only one result set can be iterated at a time) */
91 const DBO_NOBUFFER
= 2;
92 /** @var int Ignore query errors (internal use only!) */
94 /** @var int Automatically start a transaction before running a query if none is active */
96 /** @var int Use DBO_TRX in non-CLI mode */
97 const DBO_DEFAULT
= 16;
98 /** @var int Use DB persistent connections if possible */
99 const DBO_PERSISTENT
= 32;
100 /** @var int DBA session mode; mostly for Oracle */
101 const DBO_SYSDBA
= 64;
102 /** @var int Schema file mode; mostly for Oracle */
103 const DBO_DDLMODE
= 128;
104 /** @var int Enable SSL/TLS in connection protocol */
106 /** @var int Enable compression in connection protocol */
107 const DBO_COMPRESS
= 512;
109 /** @var int Ignore query errors and return false when they happen */
110 const QUERY_SILENCE_ERRORS
= 1; // b/c for 1.32 query() argument; note that (int)true = 1
112 * @var int Treat the TEMPORARY table from the given CREATE query as if it is
113 * permanent as far as write tracking is concerned. This is useful for testing.
115 const QUERY_PSEUDO_PERMANENT
= 2;
118 * A string describing the current software version, and possibly
119 * other details in a user-friendly way. Will be listed on Special:Version, etc.
120 * Use getServerVersion() to get machine-friendly information.
122 * @return string Version information from the database server
124 public function getServerInfo();
127 * Turns buffering of SQL result sets on (true) or off (false). Default is "on".
129 * Unbuffered queries are very troublesome in MySQL:
131 * - If another query is executed while the first query is being read
132 * out, the first query is killed. This means you can't call normal
133 * Database functions while you are reading an unbuffered query result
134 * from a normal Database connection.
136 * - Unbuffered queries cause the MySQL server to use large amounts of
137 * memory and to hold broad locks which block other queries.
139 * If you want to limit client-side memory, it's almost always better to
140 * split up queries into batches using a LIMIT clause than to switch off
143 * @param null|bool $buffer
144 * @return null|bool The previous value of the flag
146 public function bufferResults( $buffer = null );
149 * Gets the current transaction level.
151 * Historically, transactions were allowed to be "nested". This is no
152 * longer supported, so this function really only returns a boolean.
154 * @return int The previous value
156 public function trxLevel();
159 * Get the UNIX timestamp of the time that the transaction was established
161 * This can be used to reason about the staleness of SELECT data
162 * in REPEATABLE-READ transaction isolation level.
164 * @return float|null Returns null if there is not active transaction
167 public function trxTimestamp();
170 * @return bool Whether an explicit transaction or atomic sections are still open
173 public function explicitTrxActive();
176 * Assert that all explicit transactions or atomic sections have been closed.
177 * @throws DBTransactionError
180 public function assertNoOpenTransactions();
183 * Get/set the table prefix.
184 * @param string|null $prefix The table prefix to set, or omitted to leave it unchanged.
185 * @return string The previous table prefix
186 * @throws DBUnexpectedError
188 public function tablePrefix( $prefix = null );
191 * Get/set the db schema.
192 * @param string|null $schema The database schema to set, or omitted to leave it unchanged.
193 * @return string The previous db schema
195 public function dbSchema( $schema = null );
198 * Get properties passed down from the server info array of the load
201 * @param string|null $name The entry of the info array to get, or null to get the
204 * @return array|mixed|null
206 public function getLBInfo( $name = null );
209 * Set the LB info array, or a member of it. If called with one parameter,
210 * the LB info array is set to that parameter. If it is called with two
211 * parameters, the member with the given name is set to the given value.
213 * @param string $name
214 * @param array|null $value
216 public function setLBInfo( $name, $value = null );
219 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
221 * @param IDatabase $conn
224 public function setLazyMasterHandle( IDatabase
$conn );
227 * Returns true if this database does an implicit sort when doing GROUP BY
230 * @deprecated Since 1.30; only use grouped or aggregated fields in the SELECT
232 public function implicitGroupby();
235 * Returns true if this database does an implicit order by when the column has an index
236 * For example: SELECT page_title FROM page LIMIT 1
240 public function implicitOrderby();
243 * Return the last query that went through IDatabase::query()
246 public function lastQuery();
249 * Returns true if the connection may have been used for write queries.
250 * Should return true if unsure.
253 * @deprecated Since 1.31; use lastDoneWrites()
255 public function doneWrites();
258 * Returns the last time the connection may have been used for write queries.
259 * Should return a timestamp if unsure.
261 * @return int|float UNIX timestamp or false
264 public function lastDoneWrites();
267 * @return bool Whether there is a transaction open with possible write queries
270 public function writesPending();
273 * @return bool Whether there is a transaction open with pre-commit callbacks pending
276 public function preCommitCallbacksPending();
279 * Whether there is a transaction open with either possible write queries
280 * or unresolved pre-commit/commit/resolution callbacks pending
282 * This does *not* count recurring callbacks, e.g. from setTransactionListener().
286 public function writesOrCallbacksPending();
289 * Get the time spend running write queries for this transaction
291 * High times could be due to scanning, updates, locking, and such
293 * @param string $type IDatabase::ESTIMATE_* constant [default: ESTIMATE_ALL]
294 * @return float|bool Returns false if not transaction is active
297 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
);
300 * Get the list of method names that did write queries for this transaction
305 public function pendingWriteCallers();
308 * Get the number of affected rows from pending write queries
313 public function pendingWriteRowsAffected();
316 * Is a connection to the database open?
319 public function isOpen();
322 * Set a flag for this connection
324 * @param int $flag DBO_* constants from Defines.php:
325 * - DBO_DEBUG: output some debug info (same as debug())
326 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
327 * - DBO_TRX: automatically start transactions
328 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
329 * and removes it in command line mode
330 * - DBO_PERSISTENT: use persistant database connection
331 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
333 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
);
336 * Clear a flag for this connection
338 * @param int $flag DBO_* constants from Defines.php:
339 * - DBO_DEBUG: output some debug info (same as debug())
340 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
341 * - DBO_TRX: automatically start transactions
342 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
343 * and removes it in command line mode
344 * - DBO_PERSISTENT: use persistant database connection
345 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
347 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
);
350 * Restore the flags to their prior state before the last setFlag/clearFlag call
352 * @param string $state IDatabase::RESTORE_* constant. [default: RESTORE_PRIOR]
355 public function restoreFlags( $state = self
::RESTORE_PRIOR
);
358 * Returns a boolean whether the flag $flag is set for this connection
360 * @param int $flag DBO_* constants from Defines.php:
361 * - DBO_DEBUG: output some debug info (same as debug())
362 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
363 * - DBO_TRX: automatically start transactions
364 * - DBO_PERSISTENT: use persistant database connection
367 public function getFlag( $flag );
370 * Return the currently selected domain ID
372 * Null components (database/schema) might change once a connection is established
376 public function getDomainID();
379 * Alias for getDomainID()
384 public function getWikiID();
387 * Get the type of the DBMS, as it appears in $wgDBtype.
391 public function getType();
394 * Fetch the next row from the given result object, in object form.
395 * Fields can be retrieved with $row->fieldname, with fields acting like
397 * If no more rows are available, false is returned.
399 * @param IResultWrapper|stdClass $res Object as returned from IDatabase::query(), etc.
400 * @return stdClass|bool
401 * @throws DBUnexpectedError Thrown if the database returns an error
403 public function fetchObject( $res );
406 * Fetch the next row from the given result object, in associative array
407 * form. Fields are retrieved with $row['fieldname'].
408 * If no more rows are available, false is returned.
410 * @param IResultWrapper $res Result object as returned from IDatabase::query(), etc.
412 * @throws DBUnexpectedError Thrown if the database returns an error
414 public function fetchRow( $res );
417 * Get the number of rows in a query result. If the query did not return
418 * any rows (for example, if it was a write query), this returns zero.
420 * @param mixed $res A SQL result
423 public function numRows( $res );
426 * Get the number of fields in a result object
427 * @see https://secure.php.net/mysql_num_fields
429 * @param mixed $res A SQL result
432 public function numFields( $res );
435 * Get a field name in a result object
436 * @see https://secure.php.net/mysql_field_name
438 * @param mixed $res A SQL result
442 public function fieldName( $res, $n );
445 * Get the inserted value of an auto-increment row
447 * This should only be called after an insert that used an auto-incremented
448 * value. If no such insert was previously done in the current database
449 * session, the return value is undefined.
453 public function insertId();
456 * Change the position of the cursor in a result object
457 * @see https://secure.php.net/mysql_data_seek
459 * @param mixed $res A SQL result
462 public function dataSeek( $res, $row );
465 * Get the last error number
466 * @see https://secure.php.net/mysql_errno
470 public function lastErrno();
473 * Get a description of the last error
474 * @see https://secure.php.net/mysql_error
478 public function lastError();
481 * Get the number of rows affected by the last write query
482 * @see https://secure.php.net/mysql_affected_rows
486 public function affectedRows();
489 * Returns a wikitext link to the DB's website, e.g.,
490 * return "[https://www.mysql.com/ MySQL]";
491 * Should at least contain plain text, if for some reason
492 * your database has no website.
494 * @return string Wikitext of a link to the server software's web site
496 public function getSoftwareLink();
499 * A string describing the current software version, like from
500 * mysql_get_server_info().
502 * @return string Version information from the database server.
504 public function getServerVersion();
507 * Close the database connection
509 * This should only be called after any transactions have been resolved,
510 * aside from read-only automatic transactions (assuming no callbacks are registered).
511 * If a transaction is still open anyway, it will be rolled back.
514 * @return bool Operation success. true if already closed.
516 public function close();
519 * Run an SQL query and return the result. Normally throws a DBQueryError
520 * on failure. If errors are ignored, returns false instead.
522 * If a connection loss is detected, then an attempt to reconnect will be made.
523 * For queries that involve no larger transactions or locks, they will be re-issued
524 * for convenience, provided the connection was re-established.
526 * In new code, the query wrappers select(), insert(), update(), delete(),
527 * etc. should be used where possible, since they give much better DBMS
528 * independence and automatically quote or validate user input in a variety
529 * of contexts. This function is generally only useful for queries which are
530 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
533 * However, the query wrappers themselves should call this function.
535 * @param string $sql SQL query
536 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
537 * comment (you can use __METHOD__ or add some extra info)
538 * @param int $flags Bitfield of IDatabase::QUERY_* constants. Note that suppression
539 * of errors is best handled by try/catch rather than using one of these flags.
540 * @return bool|IResultWrapper True for a successful write query, IResultWrapper object
541 * for a successful read query, or false on failure if QUERY_SILENCE_ERRORS is set.
544 public function query( $sql, $fname = __METHOD__
, $flags = 0 );
547 * Free a result object returned by query() or select(). It's usually not
548 * necessary to call this, just use unset() or let the variable holding
549 * the result object go out of scope.
551 * @param mixed $res A SQL result
553 public function freeResult( $res );
556 * A SELECT wrapper which returns a single field from a single result row.
558 * Usually throws a DBQueryError on failure. If errors are explicitly
559 * ignored, returns false on failure.
561 * If no result rows are returned from the query, false is returned.
563 * @param string|array $table Table name. See IDatabase::select() for details.
564 * @param string $var The field name to select. This must be a valid SQL
565 * fragment: do not use unvalidated user input.
566 * @param string|array $cond The condition array. See IDatabase::select() for details.
567 * @param string $fname The function name of the caller.
568 * @param string|array $options The query options. See IDatabase::select() for details.
569 * @param string|array $join_conds The query join conditions. See IDatabase::select() for details.
571 * @return mixed The value from the field
574 public function selectField(
575 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
579 * A SELECT wrapper which returns a list of single field values from result rows.
581 * Usually throws a DBQueryError on failure. If errors are explicitly
582 * ignored, returns false on failure.
584 * If no result rows are returned from the query, false is returned.
586 * @param string|array $table Table name. See IDatabase::select() for details.
587 * @param string $var The field name to select. This must be a valid SQL
588 * fragment: do not use unvalidated user input.
589 * @param string|array $cond The condition array. See IDatabase::select() for details.
590 * @param string $fname The function name of the caller.
591 * @param string|array $options The query options. See IDatabase::select() for details.
592 * @param string|array $join_conds The query join conditions. See IDatabase::select() for details.
594 * @return array The values from the field in the order they were returned from the DB
598 public function selectFieldValues(
599 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
603 * Execute a SELECT query constructed using the various parameters provided.
604 * See below for full details of the parameters.
606 * @param string|array $table Table name(s)
608 * May be either an array of table names, or a single string holding a table
609 * name. If an array is given, table aliases can be specified, for example:
613 * This includes the user table in the query, with the alias "a" available
614 * for use in field names (e.g. a.user_name).
616 * A derived table, defined by the result of selectSQLText(), requires an alias
617 * key and a Subquery instance value which wraps the SQL query, for example:
619 * [ 'c' => new Subquery( 'SELECT ...' ) ]
621 * Joins using parentheses for grouping (since MediaWiki 1.31) may be
622 * constructed using nested arrays. For example,
624 * [ 'tableA', 'nestedB' => [ 'tableB', 'b2' => 'tableB2' ] ]
626 * along with `$join_conds` like
628 * [ 'b2' => [ 'JOIN', 'b_id = b2_id' ], 'nestedB' => [ 'LEFT JOIN', 'b_a = a_id' ] ]
630 * will produce SQL something like
632 * FROM tableA LEFT JOIN (tableB JOIN tableB2 AS b2 ON (b_id = b2_id)) ON (b_a = a_id)
634 * All of the table names given here are automatically run through
635 * Database::tableName(), which causes the table prefix (if any) to be
636 * added, and various other table name mappings to be performed.
638 * Do not use untrusted user input as a table name. Alias names should
639 * not have characters outside of the Basic multilingual plane.
641 * @param string|array $vars Field name(s)
643 * May be either a field name or an array of field names. The field names
644 * can be complete fragments of SQL, for direct inclusion into the SELECT
645 * query. If an array is given, field aliases can be specified, for example:
647 * [ 'maxrev' => 'MAX(rev_id)' ]
649 * This includes an expression with the alias "maxrev" in the query.
651 * If an expression is given, care must be taken to ensure that it is
654 * Untrusted user input must not be passed to this parameter.
656 * @param string|array $conds
658 * May be either a string containing a single condition, or an array of
659 * conditions. If an array is given, the conditions constructed from each
660 * element are combined with AND.
662 * Array elements may take one of two forms:
664 * - Elements with a numeric key are interpreted as raw SQL fragments.
665 * - Elements with a string key are interpreted as equality conditions,
666 * where the key is the field name.
667 * - If the value of such an array element is a scalar (such as a
668 * string), it will be treated as data and thus quoted appropriately.
669 * If it is null, an IS NULL clause will be added.
670 * - If the value is an array, an IN (...) clause will be constructed
671 * from its non-null elements, and an IS NULL clause will be added
672 * if null is present, such that the field may match any of the
673 * elements in the array. The non-null elements will be quoted.
675 * Note that expressions are often DBMS-dependent in their syntax.
676 * DBMS-independent wrappers are provided for constructing several types of
677 * expression commonly used in condition queries. See:
678 * - IDatabase::buildLike()
679 * - IDatabase::conditional()
681 * Untrusted user input is safe in the values of string keys, however untrusted
682 * input must not be used in the array key names or in the values of numeric keys.
683 * Escaping of untrusted input used in values of numeric keys should be done via
684 * IDatabase::addQuotes()
686 * Use an empty array, string, or '*' to update all rows.
688 * @param string $fname Caller function name
690 * @param string|array $options Query options
692 * Optional: Array of query options. Boolean options are specified by
693 * including them in the array as a string value with a numeric key, for
698 * The supported options are:
700 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
701 * with LIMIT can theoretically be used for paging through a result set,
702 * but this is discouraged for performance reasons.
704 * - LIMIT: Integer: return at most this many rows. The rows are sorted
705 * and then the first rows are taken until the limit is reached. LIMIT
706 * is applied to a result set after OFFSET.
708 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
709 * changed until the next COMMIT.
711 * - DISTINCT: Boolean: return only unique result rows.
713 * - GROUP BY: May be either an SQL fragment string naming a field or
714 * expression to group by, or an array of such SQL fragments.
716 * - HAVING: May be either an string containing a HAVING clause or an array of
717 * conditions building the HAVING clause. If an array is given, the conditions
718 * constructed from each element are combined with AND.
720 * - ORDER BY: May be either an SQL fragment giving a field name or
721 * expression to order by, or an array of such SQL fragments.
723 * - USE INDEX: This may be either a string giving the index name to use
724 * for the query, or an array. If it is an associative array, each key
725 * gives the table name (or alias), each value gives the index name to
726 * use for that table. All strings are SQL fragments and so should be
727 * validated by the caller.
729 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
732 * And also the following boolean MySQL extensions, see the MySQL manual
735 * - LOCK IN SHARE MODE
739 * - SQL_BUFFER_RESULT
741 * - SQL_CALC_FOUND_ROWS
746 * @param string|array $join_conds Join conditions
748 * Optional associative array of table-specific join conditions. In the
749 * most common case, this is unnecessary, since the join condition can be
750 * in $conds. However, it is useful for doing a LEFT JOIN.
752 * The key of the array contains the table name or alias. The value is an
753 * array with two elements, numbered 0 and 1. The first gives the type of
754 * join, the second is the same as the $conds parameter. Thus it can be
755 * an SQL fragment, or an array where the string keys are equality and the
756 * numeric keys are SQL fragments all AND'd together. For example:
758 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
760 * @return IResultWrapper Resulting rows
763 public function select(
764 $table, $vars, $conds = '', $fname = __METHOD__
,
765 $options = [], $join_conds = []
769 * The equivalent of IDatabase::select() except that the constructed SQL
770 * is returned, instead of being immediately executed. This can be useful for
771 * doing UNION queries, where the SQL text of each query is needed. In general,
772 * however, callers outside of Database classes should just use select().
774 * @see IDatabase::select()
776 * @param string|array $table Table name
777 * @param string|array $vars Field names
778 * @param string|array $conds Conditions
779 * @param string $fname Caller function name
780 * @param string|array $options Query options
781 * @param string|array $join_conds Join conditions
782 * @return string SQL query string
784 public function selectSQLText(
785 $table, $vars, $conds = '', $fname = __METHOD__
,
786 $options = [], $join_conds = []
790 * Single row SELECT wrapper. Equivalent to IDatabase::select(), except
791 * that a single row object is returned. If the query returns no rows,
794 * @param string|array $table Table name
795 * @param string|array $vars Field names
796 * @param array $conds Conditions
797 * @param string $fname Caller function name
798 * @param string|array $options Query options
799 * @param array|string $join_conds Join conditions
801 * @return stdClass|bool
804 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
805 $options = [], $join_conds = []
809 * Estimate the number of rows in dataset
811 * MySQL allows you to estimate the number of rows that would be returned
812 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
813 * index cardinality statistics, and is notoriously inaccurate, especially
814 * when large numbers of rows have recently been added or deleted.
816 * For DBMSs that don't support fast result size estimation, this function
817 * will actually perform the SELECT COUNT(*).
819 * Takes the same arguments as IDatabase::select().
821 * @param string $table Table name
822 * @param string $var Column for which NULL values are not counted [default "*"]
823 * @param array|string $conds Filters on the table
824 * @param string $fname Function name for profiling
825 * @param array $options Options for select
826 * @param array|string $join_conds Join conditions
827 * @return int Row count
830 public function estimateRowCount(
831 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
835 * Get the number of rows in dataset
837 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
839 * Takes the same arguments as IDatabase::select().
841 * @since 1.27 Added $join_conds parameter
843 * @param array|string $tables Table names
844 * @param string $var Column for which NULL values are not counted [default "*"]
845 * @param array|string $conds Filters on the table
846 * @param string $fname Function name for profiling
847 * @param array $options Options for select
848 * @param array $join_conds Join conditions (since 1.27)
849 * @return int Row count
852 public function selectRowCount(
853 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
857 * Lock all rows meeting the given conditions/options FOR UPDATE
859 * @param array|string $table Table names
860 * @param array|string $conds Filters on the table
861 * @param string $fname Function name for profiling
862 * @param array $options Options for select ("FOR UPDATE" is added automatically)
863 * @param array $join_conds Join conditions
864 * @return int Number of matching rows found (and locked)
867 public function lockForUpdate(
868 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
872 * Determines whether a field exists in a table
874 * @param string $table Table name
875 * @param string $field Filed to check on that table
876 * @param string $fname Calling function name (optional)
877 * @return bool Whether $table has filed $field
880 public function fieldExists( $table, $field, $fname = __METHOD__
);
883 * Determines whether an index exists
884 * Usually throws a DBQueryError on failure
885 * If errors are explicitly ignored, returns NULL on failure
887 * @param string $table
888 * @param string $index
889 * @param string $fname
893 public function indexExists( $table, $index, $fname = __METHOD__
);
896 * Query whether a given table exists
898 * @param string $table
899 * @param string $fname
903 public function tableExists( $table, $fname = __METHOD__
);
906 * INSERT wrapper, inserts an array into a table.
910 * - A single associative array. The array keys are the field names, and
911 * the values are the values to insert. The values are treated as data
912 * and will be quoted appropriately. If NULL is inserted, this will be
913 * converted to a database NULL.
914 * - An array with numeric keys, holding a list of associative arrays.
915 * This causes a multi-row INSERT on DBMSs that support it. The keys in
916 * each subarray must be identical to each other, and in the same order.
918 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
921 * $options is an array of options, with boolean options encoded as values
922 * with numeric keys, in the same style as $options in
923 * IDatabase::select(). Supported options are:
925 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
926 * any rows which cause duplicate key errors are not inserted. It's
927 * possible to determine how many rows were successfully inserted using
928 * IDatabase::affectedRows().
930 * @param string $table Table name. This will be passed through
931 * Database::tableName().
932 * @param array $a Array of rows to insert
933 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
934 * @param array $options Array of options
935 * @return bool Return true if no exception was thrown (deprecated since 1.33)
938 public function insert( $table, $a, $fname = __METHOD__
, $options = [] );
941 * UPDATE wrapper. Takes a condition array and a SET array.
943 * @param string $table Name of the table to UPDATE. This will be passed through
944 * Database::tableName().
945 * @param array $values An array of values to SET. For each array element,
946 * the key gives the field name, and the value gives the data to set
947 * that field to. The data will be quoted by IDatabase::addQuotes().
948 * Values with integer keys form unquoted SET statements, which can be used for
949 * things like "field = field + 1" or similar computed values.
950 * @param array $conds An array of conditions (WHERE). See
951 * IDatabase::select() for the details of the format of condition
952 * arrays. Use '*' to update all rows.
953 * @param string $fname The function name of the caller (from __METHOD__),
954 * for logging and profiling.
955 * @param array $options An array of UPDATE options, can be:
956 * - IGNORE: Ignore unique key conflicts
957 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
958 * @return bool Return true if no exception was thrown (deprecated since 1.33)
961 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] );
964 * Makes an encoded list of strings from an array
966 * These can be used to make conjunctions or disjunctions on SQL condition strings
967 * derived from an array (see IDatabase::select() $conds documentation).
971 * $sql = $db->makeList( [
973 * $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] )
974 * ], $db::LIST_AND );
976 * This would set $sql to "rev_page = '$id' AND (rev_minor = '1' OR rev_len < '500')"
978 * @param array $a Containing the data
979 * @param int $mode IDatabase class constant:
980 * - IDatabase::LIST_COMMA: Comma separated, no field names
981 * - IDatabase::LIST_AND: ANDed WHERE clause (without the WHERE).
982 * - IDatabase::LIST_OR: ORed WHERE clause (without the WHERE)
983 * - IDatabase::LIST_SET: Comma separated with field names, like a SET clause
984 * - IDatabase::LIST_NAMES: Comma separated field names
988 public function makeList( $a, $mode = self
::LIST_COMMA
);
991 * Build a partial where clause from a 2-d array such as used for LinkBatch.
992 * The keys on each level may be either integers or strings.
994 * @param array $data Organized as 2-d
995 * [ baseKeyVal => [ subKeyVal => [ignored], ... ], ... ]
996 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
997 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
998 * @return string|bool SQL fragment, or false if no items in array
1000 public function makeWhereFrom2d( $data, $baseKey, $subKey );
1003 * Return aggregated value alias
1005 * @param array $valuedata
1006 * @param string $valuename
1010 public function aggregateValue( $valuedata, $valuename = 'value' );
1013 * @param string $field
1016 public function bitNot( $field );
1019 * @param string $fieldLeft
1020 * @param string $fieldRight
1023 public function bitAnd( $fieldLeft, $fieldRight );
1026 * @param string $fieldLeft
1027 * @param string $fieldRight
1030 public function bitOr( $fieldLeft, $fieldRight );
1033 * Build a concatenation list to feed into a SQL query
1034 * @param array $stringList List of raw SQL expressions; caller is
1035 * responsible for any quoting
1038 public function buildConcat( $stringList );
1041 * Build a GROUP_CONCAT or equivalent statement for a query.
1043 * This is useful for combining a field for several rows into a single string.
1044 * NULL values will not appear in the output, duplicated values will appear,
1045 * and the resulting delimiter-separated values have no defined sort order.
1046 * Code using the results may need to use the PHP unique() or sort() methods.
1048 * @param string $delim Glue to bind the results together
1049 * @param string|array $table Table name
1050 * @param string $field Field name
1051 * @param string|array $conds Conditions
1052 * @param string|array $join_conds Join conditions
1053 * @return string SQL text
1056 public function buildGroupConcatField(
1057 $delim, $table, $field, $conds = '', $join_conds = []
1061 * Build a SUBSTRING function.
1063 * Behavior for non-ASCII values is undefined.
1065 * @param string $input Field name
1066 * @param int $startPosition Positive integer
1067 * @param int|null $length Non-negative integer length or null for no limit
1068 * @throws InvalidArgumentException
1069 * @return string SQL text
1072 public function buildSubString( $input, $startPosition, $length = null );
1075 * @param string $field Field or column to cast
1079 public function buildStringCast( $field );
1082 * @param string $field Field or column to cast
1086 public function buildIntegerCast( $field );
1089 * Equivalent to IDatabase::selectSQLText() except wraps the result in Subqyery
1091 * @see IDatabase::selectSQLText()
1093 * @param string|array $table Table name
1094 * @param string|array $vars Field names
1095 * @param string|array $conds Conditions
1096 * @param string $fname Caller function name
1097 * @param string|array $options Query options
1098 * @param string|array $join_conds Join conditions
1102 public function buildSelectSubquery(
1103 $table, $vars, $conds = '', $fname = __METHOD__
,
1104 $options = [], $join_conds = []
1108 * Returns true if DBs are assumed to be on potentially different servers
1110 * In systems like mysql/mariadb, different databases can easily be referenced on a single
1111 * connection merely by name, even in a single query via JOIN. On the other hand, Postgres
1112 * treats databases as fully separate, only allowing mechanisms like postgres_fdw to
1113 * effectively "mount" foreign DBs. This is true even among DBs on the same server.
1118 public function databasesAreIndependent();
1121 * Change the current database
1123 * This should not be called outside LoadBalancer for connections managed by a LoadBalancer
1126 * @return bool True unless an exception was thrown
1127 * @throws DBConnectionError If databasesAreIndependent() is true and an error occurs
1129 * @deprecated Since 1.32 Use selectDomain() instead
1131 public function selectDB( $db );
1134 * Set the current domain (database, schema, and table prefix)
1136 * This will throw an error for some database types if the database unspecified
1138 * This should not be called outside LoadBalancer for connections managed by a LoadBalancer
1140 * @param string|DatabaseDomain $domain
1142 * @throws DBConnectionError
1144 public function selectDomain( $domain );
1147 * Get the current DB name
1148 * @return string|null
1150 public function getDBname();
1153 * Get the server hostname or IP address
1156 public function getServer();
1159 * Adds quotes and backslashes.
1161 * @param string|int|null|bool|Blob $s
1162 * @return string|int
1164 public function addQuotes( $s );
1167 * Quotes an identifier, in order to make user controlled input safe
1169 * Depending on the database this will either be `backticks` or "double quotes"
1175 public function addIdentifierQuotes( $s );
1178 * LIKE statement wrapper, receives a variable-length argument list with
1179 * parts of pattern to match containing either string literals that will be
1180 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
1181 * the function could be provided with an array of aforementioned
1184 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
1185 * a LIKE clause that searches for subpages of 'My page title'.
1187 * $pattern = [ 'My_page_title/', $dbr->anyString() ];
1188 * $query .= $dbr->buildLike( $pattern );
1191 * @return string Fully built LIKE statement
1193 public function buildLike();
1196 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1200 public function anyChar();
1203 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1207 public function anyString();
1210 * Deprecated method, calls should be removed.
1212 * This was formerly used for PostgreSQL and Oracle to handle
1213 * self::insertId() auto-incrementing fields. It is no longer necessary
1214 * since DatabasePostgres::insertId() has been reimplemented using
1215 * `lastval()` and Oracle has been reimplemented using triggers.
1217 * Implementations should return null if inserting `NULL` into an
1218 * auto-incrementing field works, otherwise it should return an instance of
1219 * NextSequenceValue and filter it on calls to relevant methods.
1221 * @deprecated since 1.30, no longer needed
1222 * @param string $seqName
1223 * @return null|NextSequenceValue
1225 public function nextSequenceValue( $seqName );
1228 * REPLACE query wrapper.
1230 * REPLACE is a very handy MySQL extension, which functions like an INSERT
1231 * except that when there is a duplicate key error, the old row is deleted
1232 * and the new row is inserted in its place.
1234 * We simulate this with standard SQL with a DELETE followed by INSERT. To
1235 * perform the delete, we need to know what the unique indexes are so that
1236 * we know how to find the conflicting rows.
1238 * It may be more efficient to leave off unique indexes which are unlikely
1239 * to collide. However if you do this, you run the risk of encountering
1240 * errors which wouldn't have occurred in MySQL.
1242 * @param string $table The table to replace the row(s) in.
1243 * @param array[]|string[]|string $uniqueIndexes All unique indexes. One of the following:
1244 * a) the one unique field in the table (when no composite unique key exist)
1245 * b) a list of all unique fields in the table (when no composite unique key exist)
1246 * c) a list of all unique indexes in the table (each as a list of the indexed fields)
1247 * @param array $rows Can be either a single row to insert, or multiple rows,
1248 * in the same format as for IDatabase::insert()
1249 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1252 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
);
1255 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
1257 * This updates any conflicting rows (according to the unique indexes) using
1258 * the provided SET clause and inserts any remaining (non-conflicted) rows.
1260 * $rows may be either:
1261 * - A single associative array. The array keys are the field names, and
1262 * the values are the values to insert. The values are treated as data
1263 * and will be quoted appropriately. If NULL is inserted, this will be
1264 * converted to a database NULL.
1265 * - An array with numeric keys, holding a list of associative arrays.
1266 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1267 * each subarray must be identical to each other, and in the same order.
1269 * It may be more efficient to leave off unique indexes which are unlikely
1270 * to collide. However if you do this, you run the risk of encountering
1271 * errors which wouldn't have occurred in MySQL.
1273 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1278 * @param string $table Table name. This will be passed through Database::tableName().
1279 * @param array $rows A single row or list of rows to insert
1280 * @param array[]|string[]|string $uniqueIndexes All unique indexes. One of the following:
1281 * a) the one unique field in the table (when no composite unique key exist)
1282 * b) a list of all unique fields in the table (when no composite unique key exist)
1283 * c) a list of all unique indexes in the table (each as a list of the indexed fields)
1284 * @param array $set An array of values to SET. For each array element, the
1285 * key gives the field name, and the value gives the data to set that
1286 * field to. The data will be quoted by IDatabase::addQuotes().
1287 * Values with integer keys form unquoted SET statements, which can be used for
1288 * things like "field = field + 1" or similar computed values.
1289 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1291 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1293 public function upsert(
1294 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1298 * DELETE where the condition is a join.
1300 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
1301 * we use sub-selects
1303 * For safety, an empty $conds will not delete everything. If you want to
1304 * delete all rows where the join condition matches, set $conds='*'.
1306 * DO NOT put the join condition in $conds.
1308 * @param string $delTable The table to delete from.
1309 * @param string $joinTable The other table.
1310 * @param string $delVar The variable to join on, in the first table.
1311 * @param string $joinVar The variable to join on, in the second table.
1312 * @param array $conds Condition array of field names mapped to variables,
1313 * ANDed together in the WHERE clause
1314 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1317 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
1322 * DELETE query wrapper.
1324 * @param string $table Table name
1325 * @param string|array $conds Array of conditions. See $conds in IDatabase::select()
1326 * for the format. Use $conds == "*" to delete all rows
1327 * @param string $fname Name of the calling function
1328 * @throws DBUnexpectedError
1329 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1332 public function delete( $table, $conds, $fname = __METHOD__
);
1335 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
1336 * into another table.
1338 * @warning If the insert will use an auto-increment or sequence to
1339 * determine the value of a column, this may break replication on
1340 * databases using statement-based replication if the SELECT is not
1341 * deterministically ordered.
1343 * @param string $destTable The table name to insert into
1344 * @param string|array $srcTable May be either a table name, or an array of table names
1345 * to include in a join.
1347 * @param array $varMap Must be an associative array of the form
1348 * [ 'dest1' => 'source1', ... ]. Source items may be literals
1349 * rather than field names, but strings should be quoted with
1350 * IDatabase::addQuotes()
1352 * @param array $conds Condition array. See $conds in IDatabase::select() for
1353 * the details of the format of condition arrays. May be "*" to copy the
1356 * @param string $fname The function name of the caller, from __METHOD__
1358 * @param array $insertOptions Options for the INSERT part of the query, see
1359 * IDatabase::insert() for details. Also, one additional option is
1360 * available: pass 'NO_AUTO_COLUMNS' to hint that the query does not use
1361 * an auto-increment or sequence to determine any column values.
1362 * @param array $selectOptions Options for the SELECT part of the query, see
1363 * IDatabase::select() for details.
1364 * @param array $selectJoinConds Join conditions for the SELECT part of the query, see
1365 * IDatabase::select() for details.
1367 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1370 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
1371 $fname = __METHOD__
,
1372 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
1376 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1377 * within the UNION construct.
1380 public function unionSupportsOrderAndLimit();
1383 * Construct a UNION query
1384 * This is used for providing overload point for other DB abstractions
1385 * not compatible with the MySQL syntax.
1386 * @param array $sqls SQL statements to combine
1387 * @param bool $all Use UNION ALL
1388 * @return string SQL fragment
1390 public function unionQueries( $sqls, $all );
1393 * Construct a UNION query for permutations of conditions
1395 * Databases sometimes have trouble with queries that have multiple values
1396 * for multiple condition parameters combined with limits and ordering.
1397 * This method constructs queries for the Cartesian product of the
1398 * conditions and unions them all together.
1400 * @see IDatabase::select()
1402 * @param string|array $table Table name
1403 * @param string|array $vars Field names
1404 * @param array $permute_conds Conditions for the Cartesian product. Keys
1405 * are field names, values are arrays of the possible values for that
1407 * @param string|array $extra_conds Additional conditions to include in the
1409 * @param string $fname Caller function name
1410 * @param string|array $options Query options. In addition to the options
1411 * recognized by IDatabase::select(), the following may be used:
1412 * - NOTALL: Set to use UNION instead of UNION ALL.
1413 * - INNER ORDER BY: If specified and supported, subqueries will use this
1414 * instead of ORDER BY.
1415 * @param string|array $join_conds Join conditions
1416 * @return string SQL query string.
1418 public function unionConditionPermutations(
1419 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
1420 $options = [], $join_conds = []
1424 * Returns an SQL expression for a simple conditional. This doesn't need
1425 * to be overridden unless CASE isn't supported in your DBMS.
1427 * @param string|array $cond SQL expression which will result in a boolean value
1428 * @param string $trueVal SQL expression to return if true
1429 * @param string $falseVal SQL expression to return if false
1430 * @return string SQL fragment
1432 public function conditional( $cond, $trueVal, $falseVal );
1435 * Returns a command for str_replace function in SQL query.
1436 * Uses REPLACE() in MySQL
1438 * @param string $orig Column to modify
1439 * @param string $old Column to seek
1440 * @param string $new Column to replace with
1444 public function strreplace( $orig, $old, $new );
1447 * Determines how long the server has been up
1452 public function getServerUptime();
1455 * Determines if the last failure was due to a deadlock
1457 * Note that during a deadlock, the prior transaction will have been lost
1461 public function wasDeadlock();
1464 * Determines if the last failure was due to a lock timeout
1466 * Note that during a lock wait timeout, the prior transaction will have been lost
1470 public function wasLockTimeout();
1473 * Determines if the last query error was due to a dropped connection
1475 * Note that during a connection loss, the prior transaction will have been lost
1480 public function wasConnectionLoss();
1483 * Determines if the last failure was due to the database being read-only.
1487 public function wasReadOnlyError();
1490 * Determines if the last query error was due to something outside of the query itself
1492 * Note that the transaction may have been lost, discarding prior writes and results
1496 public function wasErrorReissuable();
1499 * Wait for the replica DB to catch up to a given master position
1501 * Note that this does not start any new transactions. If any existing transaction
1502 * is flushed, and this is called, then queries will reflect the point the DB was synced
1503 * up to (on success) without interference from REPEATABLE-READ snapshots.
1505 * @param DBMasterPos $pos
1506 * @param int $timeout The maximum number of seconds to wait for synchronisation
1507 * @return int|null Zero if the replica DB was past that position already,
1508 * greater than zero if we waited for some period of time, less than
1509 * zero if it timed out, and null on error
1512 public function masterPosWait( DBMasterPos
$pos, $timeout );
1515 * Get the replication position of this replica DB
1517 * @return DBMasterPos|bool False if this is not a replica DB
1520 public function getReplicaPos();
1523 * Get the position of this master
1525 * @return DBMasterPos|bool False if this is not a master
1528 public function getMasterPos();
1531 * @return bool Whether the DB is marked as read-only server-side
1534 public function serverIsReadOnly();
1537 * Run a callback as soon as the current transaction commits or rolls back.
1538 * An error is thrown if no transaction is pending. Queries in the function will run in
1539 * AUTOCOMMIT mode unless there are begin() calls. Callbacks must commit any transactions
1542 * This is useful for combining cooperative locks and DB transactions.
1544 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1546 * The callback takes the following arguments:
1547 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK)
1548 * - This IDatabase instance (since 1.32)
1550 * @param callable $callback
1551 * @param string $fname Caller name
1555 public function onTransactionResolution( callable
$callback, $fname = __METHOD__
);
1558 * Run a callback as soon as there is no transaction pending.
1559 * If there is a transaction and it is rolled back, then the callback is cancelled.
1561 * When transaction round mode (DBO_TRX) is set, the callback will run at the end
1562 * of the round, just after all peer transactions COMMIT. If the transaction round
1563 * is rolled back, then the callback is cancelled.
1565 * Queries in the function will run in AUTOCOMMIT mode unless there are begin() calls.
1566 * Callbacks must commit any transactions that they begin.
1568 * This is useful for updates to different systems or when separate transactions are needed.
1569 * For example, one might want to enqueue jobs into a system outside the database, but only
1570 * after the database is updated so that the jobs will see the data when they actually run.
1571 * It can also be used for updates that easily suffer from lock timeouts and deadlocks,
1572 * but where atomicity is not essential.
1574 * Avoid using IDatabase instances aside from this one in the callback, unless such instances
1575 * never have IDatabase::DBO_TRX set. This keeps callbacks from interfering with one another.
1577 * Updates will execute in the order they were enqueued.
1579 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1581 * The callback takes the following arguments:
1582 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_IDLE)
1583 * - This IDatabase instance (since 1.32)
1585 * @param callable $callback
1586 * @param string $fname Caller name
1589 public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
);
1592 * Alias for onTransactionCommitOrIdle() for backwards-compatibility
1594 * @param callable $callback
1595 * @param string $fname
1598 * @deprecated Since 1.32
1600 public function onTransactionIdle( callable
$callback, $fname = __METHOD__
);
1603 * Run a callback before the current transaction commits or now if there is none.
1604 * If there is a transaction and it is rolled back, then the callback is cancelled.
1606 * When transaction round mode (DBO_TRX) is set, the callback will run at the end
1607 * of the round, just before all peer transactions COMMIT. If the transaction round
1608 * is rolled back, then the callback is cancelled.
1610 * Callbacks must not start nor commit any transactions. If no transaction is active,
1611 * then a transaction will wrap the callback.
1613 * This is useful for updates that easily suffer from lock timeouts and deadlocks,
1614 * but where atomicity is strongly desired for these updates and some related updates.
1616 * Updates will execute in the order they were enqueued.
1618 * The callback takes the one argument:
1619 * - This IDatabase instance (since 1.32)
1621 * @param callable $callback
1622 * @param string $fname Caller name
1625 public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
);
1628 * Run a callback after each time any transaction commits or rolls back
1630 * The callback takes two arguments:
1631 * - IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK
1632 * - This IDatabase object
1633 * Callbacks must commit any transactions that they begin.
1635 * Registering a callback here will not affect writesOrCallbacks() pending.
1637 * Since callbacks from this or onTransactionCommitOrIdle() can start and end transactions,
1638 * a single call to IDatabase::commit might trigger multiple runs of the listener callbacks.
1640 * @param string $name Callback name
1641 * @param callable|null $callback Use null to unset a listener
1645 public function setTransactionListener( $name, callable
$callback = null );
1648 * Begin an atomic section of SQL statements
1650 * Start an implicit transaction if no transaction is already active, set a savepoint
1651 * (if $cancelable is ATOMIC_CANCELABLE), and track the given section name to enforce
1652 * that the transaction is not committed prematurely. The end of the section must be
1653 * signified exactly once, either by endAtomic() or cancelAtomic(). Sections can have
1654 * have layers of inner sections (sub-sections), but all sections must be ended in order
1655 * of innermost to outermost. Transactions cannot be started or committed until all
1656 * atomic sections are closed.
1658 * ATOMIC_CANCELABLE is useful when the caller needs to handle specific failure cases
1659 * by discarding the section's writes. This should not be used for failures when:
1660 * - upsert() could easily be used instead
1661 * - insert() with IGNORE could easily be used instead
1662 * - select() with FOR UPDATE could be checked before issuing writes instead
1663 * - The failure is from code that runs after the first write but doesn't need to
1664 * - The failures are from contention solvable via onTransactionPreCommitOrIdle()
1665 * - The failures are deadlocks; the RDBMs usually discard the whole transaction
1667 * @note callers must use additional measures for situations involving two or more
1668 * (peer) transactions (e.g. updating two database servers at once). The transaction
1669 * and savepoint logic of this method only applies to this specific IDatabase instance.
1673 * // Start a transaction if there isn't one already
1674 * $dbw->startAtomic( __METHOD__ );
1675 * // Serialize these thread table updates
1676 * $dbw->select( 'thread', '1', [ 'td_id' => $tid ], __METHOD__, 'FOR UPDATE' );
1677 * // Add a new comment for the thread
1678 * $dbw->insert( 'comment', $row, __METHOD__ );
1679 * $cid = $db->insertId();
1680 * // Update thread reference to last comment
1681 * $dbw->update( 'thread', [ 'td_latest' => $cid ], [ 'td_id' => $tid ], __METHOD__ );
1682 * // Demark the end of this conceptual unit of updates
1683 * $dbw->endAtomic( __METHOD__ );
1686 * Example usage (atomic changes that might have to be discarded):
1688 * // Start a transaction if there isn't one already
1689 * $sectionId = $dbw->startAtomic( __METHOD__, $dbw::ATOMIC_CANCELABLE );
1690 * // Create new record metadata row
1691 * $dbw->insert( 'records', $row, __METHOD__ );
1692 * // Figure out where to store the data based on the new row's ID
1693 * $path = $recordDirectory . '/' . $dbw->insertId();
1694 * // Write the record data to the storage system
1695 * $status = $fileBackend->create( [ 'dst' => $path, 'content' => $data ] );
1696 * if ( $status->isOK() ) {
1697 * // Try to cleanup files orphaned by transaction rollback
1698 * $dbw->onTransactionResolution(
1699 * function ( $type ) use ( $fileBackend, $path ) {
1700 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) {
1701 * $fileBackend->delete( [ 'src' => $path ] );
1706 * // Demark the end of this conceptual unit of updates
1707 * $dbw->endAtomic( __METHOD__ );
1709 * // Discard these writes from the transaction (preserving prior writes)
1710 * $dbw->cancelAtomic( __METHOD__, $sectionId );
1715 * @param string $fname
1716 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a
1717 * savepoint and enable self::cancelAtomic() for this section.
1718 * @return AtomicSectionIdentifier section ID token
1721 public function startAtomic( $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
);
1724 * Ends an atomic section of SQL statements
1726 * Ends the next section of atomic SQL statements and commits the transaction
1730 * @see IDatabase::startAtomic
1731 * @param string $fname
1734 public function endAtomic( $fname = __METHOD__
);
1737 * Cancel an atomic section of SQL statements
1739 * This will roll back only the statements executed since the start of the
1740 * most recent atomic section, and close that section. If a transaction was
1741 * open before the corresponding startAtomic() call, any statements before
1742 * that call are *not* rolled back and the transaction remains open. If the
1743 * corresponding startAtomic() implicitly started a transaction, that
1744 * transaction is rolled back.
1746 * @note callers must use additional measures for situations involving two or more
1747 * (peer) transactions (e.g. updating two database servers at once). The transaction
1748 * and savepoint logic of startAtomic() are bound to specific IDatabase instances.
1750 * Note that a call to IDatabase::rollback() will also roll back any open atomic sections.
1752 * @note As a micro-optimization to save a few DB calls, this method may only
1753 * be called when startAtomic() was called with the ATOMIC_CANCELABLE flag.
1755 * @see IDatabase::startAtomic
1756 * @param string $fname
1757 * @param AtomicSectionIdentifier|null $sectionId Section ID from startAtomic();
1758 * passing this enables cancellation of unclosed nested sections [optional]
1761 public function cancelAtomic( $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null );
1764 * Perform an atomic section of reversable SQL statements from a callback
1766 * The $callback takes the following arguments:
1767 * - This database object
1768 * - The value of $fname
1770 * This will execute the callback inside a pair of startAtomic()/endAtomic() calls.
1771 * If any exception occurs during execution of the callback, it will be handled as follows:
1772 * - If $cancelable is ATOMIC_CANCELABLE, cancelAtomic() will be called to back out any
1773 * (and only) statements executed during the atomic section. If that succeeds, then the
1774 * exception will be re-thrown; if it fails, then a different exception will be thrown
1775 * and any further query attempts will fail until rollback() is called.
1776 * - If $cancelable is ATOMIC_NOT_CANCELABLE, cancelAtomic() will be called to mark the
1777 * end of the section and the error will be re-thrown. Any further query attempts will
1778 * fail until rollback() is called.
1780 * This method is convenient for letting calls to the caller of this method be wrapped
1781 * in a try/catch blocks for exception types that imply that the caller failed but was
1782 * able to properly discard the changes it made in the transaction. This method can be
1783 * an alternative to explicit calls to startAtomic()/endAtomic()/cancelAtomic().
1785 * Example usage, "RecordStore::save" method:
1787 * $dbw->doAtomicSection( __METHOD__, function ( $dbw ) use ( $record ) {
1788 * // Create new record metadata row
1789 * $dbw->insert( 'records', $record->toArray(), __METHOD__ );
1790 * // Figure out where to store the data based on the new row's ID
1791 * $path = $this->recordDirectory . '/' . $dbw->insertId();
1792 * // Write the record data to the storage system;
1793 * // blob store throughs StoreFailureException on failure
1794 * $this->blobStore->create( $path, $record->getJSON() );
1795 * // Try to cleanup files orphaned by transaction rollback
1796 * $dbw->onTransactionResolution(
1797 * function ( $type ) use ( $path ) {
1798 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) {
1799 * $this->blobStore->delete( $path );
1804 * }, $dbw::ATOMIC_CANCELABLE );
1807 * Example usage, caller of the "RecordStore::save" method:
1809 * $dbw->startAtomic( __METHOD__ );
1810 * // ...various SQL writes happen...
1812 * $recordStore->save( $record );
1813 * } catch ( StoreFailureException $e ) {
1814 * // ...various SQL writes happen...
1816 * // ...various SQL writes happen...
1817 * $dbw->endAtomic( __METHOD__ );
1820 * @see Database::startAtomic
1821 * @see Database::endAtomic
1822 * @see Database::cancelAtomic
1824 * @param string $fname Caller name (usually __METHOD__)
1825 * @param callable $callback Callback that issues DB updates
1826 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a
1827 * savepoint and enable self::cancelAtomic() for this section.
1828 * @return mixed $res Result of the callback (since 1.28)
1830 * @throws RuntimeException
1831 * @since 1.27; prior to 1.31 this did a rollback() instead of
1832 * cancelAtomic(), and assumed no callers up the stack would ever try to
1833 * catch the exception.
1835 public function doAtomicSection(
1836 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
1840 * Begin a transaction. If a transaction is already in progress,
1841 * that transaction will be committed before the new transaction is started.
1843 * Only call this from code with outer transcation scope.
1844 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1845 * Nesting of transactions is not supported.
1847 * Note that when the DBO_TRX flag is set (which is usually the case for web
1848 * requests, but not for maintenance scripts), any previous database query
1849 * will have started a transaction automatically.
1851 * Nesting of transactions is not supported. Attempts to nest transactions
1852 * will cause a warning, unless the current transaction was started
1853 * automatically because of the DBO_TRX flag.
1855 * @param string $fname Calling function name
1856 * @param string $mode A situationally valid IDatabase::TRANSACTION_* constant [optional]
1859 public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
);
1862 * Commits a transaction previously started using begin().
1863 * If no transaction is in progress, a warning is issued.
1865 * Only call this from code with outer transcation scope.
1866 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1867 * Nesting of transactions is not supported.
1869 * @param string $fname
1870 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_*
1871 * constant to disable warnings about explicitly committing implicit transactions,
1872 * or calling commit when no transaction is in progress.
1874 * This will trigger an exception if there is an ongoing explicit transaction.
1876 * Only set the flush flag if you are sure that these warnings are not applicable,
1877 * and no explicit transactions are open.
1881 public function commit( $fname = __METHOD__
, $flush = '' );
1884 * Rollback a transaction previously started using begin().
1885 * If no transaction is in progress, a warning is issued.
1887 * Only call this from code with outer transcation scope.
1888 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1889 * Nesting of transactions is not supported. If a serious unexpected error occurs,
1890 * throwing an Exception is preferrable, using a pre-installed error handler to trigger
1891 * rollback (in any case, failure to issue COMMIT will cause rollback server-side).
1893 * Query, connection, and onTransaction* callback errors will be suppressed and logged.
1895 * @param string $fname Calling function name
1896 * @param string $flush Flush flag, set to a situationally valid IDatabase::FLUSHING_*
1897 * constant to disable warnings about calling rollback when no transaction is in
1898 * progress. This will silently break any ongoing explicit transaction. Only set the
1899 * flush flag if you are sure that it is safe to ignore these warnings in your context.
1901 * @since 1.23 Added $flush parameter
1903 public function rollback( $fname = __METHOD__
, $flush = '' );
1906 * Commit any transaction but error out if writes or callbacks are pending
1908 * This is intended for clearing out REPEATABLE-READ snapshots so that callers can
1909 * see a new point-in-time of the database. This is useful when one of many transaction
1910 * rounds finished and significant time will pass in the script's lifetime. It is also
1911 * useful to call on a replica DB after waiting on replication to catch up to the master.
1913 * @param string $fname Calling function name
1917 public function flushSnapshot( $fname = __METHOD__
);
1920 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1921 * to the format used for inserting into timestamp fields in this DBMS.
1923 * The result is unquoted, and needs to be passed through addQuotes()
1924 * before it can be included in raw SQL.
1926 * @param string|int $ts
1930 public function timestamp( $ts = 0 );
1933 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1934 * to the format used for inserting into timestamp fields in this DBMS. If
1935 * NULL is input, it is passed through, allowing NULL values to be inserted
1936 * into timestamp fields.
1938 * The result is unquoted, and needs to be passed through addQuotes()
1939 * before it can be included in raw SQL.
1941 * @param string|int|null $ts
1945 public function timestampOrNull( $ts = null );
1948 * Ping the server and try to reconnect if it there is no connection
1950 * @param float|null &$rtt Value to store the estimated RTT [optional]
1951 * @return bool Success or failure
1953 public function ping( &$rtt = null );
1956 * Get the amount of replication lag for this database server
1958 * Callers should avoid using this method while a transaction is active
1960 * @return int|bool Database replication lag in seconds or false on error
1963 public function getLag();
1966 * Get the replica DB lag when the current transaction started
1967 * or a general lag estimate if not transaction is active
1969 * This is useful when transactions might use snapshot isolation
1970 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
1971 * is this lag plus transaction duration. If they don't, it is still
1972 * safe to be pessimistic. In AUTOCOMMIT mode, this still gives an
1973 * indication of the staleness of subsequent reads.
1975 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
1979 public function getSessionLagStatus();
1982 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1986 public function maxListLen();
1989 * Some DBMSs have a special format for inserting into blob fields, they
1990 * don't allow simple quoted strings to be inserted. To insert into such
1991 * a field, pass the data through this function before passing it to
1992 * IDatabase::insert().
1995 * @return string|Blob
1997 public function encodeBlob( $b );
2000 * Some DBMSs return a special placeholder object representing blob fields
2001 * in result objects. Pass the object through this function to return the
2004 * @param string|Blob $b
2007 public function decodeBlob( $b );
2010 * Override database's default behavior. $options include:
2011 * 'connTimeout' : Set the connection timeout value in seconds.
2012 * May be useful for very long batch queries such as
2013 * full-wiki dumps, where a single query reads out over
2016 * @param array $options
2020 public function setSessionOptions( array $options );
2023 * Set variables to be used in sourceFile/sourceStream, in preference to the
2024 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2025 * all. If it's set to false, $GLOBALS will be used.
2027 * @param bool|array $vars Mapping variable name to value.
2029 public function setSchemaVars( $vars );
2032 * Check to see if a named lock is not locked by any thread (non-blocking)
2034 * @param string $lockName Name of lock to poll
2035 * @param string $method Name of method calling us
2040 public function lockIsFree( $lockName, $method );
2043 * Acquire a named lock
2045 * Named locks are not related to transactions
2047 * @param string $lockName Name of lock to aquire
2048 * @param string $method Name of the calling method
2049 * @param int $timeout Acquisition timeout in seconds
2053 public function lock( $lockName, $method, $timeout = 5 );
2058 * Named locks are not related to transactions
2060 * @param string $lockName Name of lock to release
2061 * @param string $method Name of the calling method
2063 * @return int Returns 1 if the lock was released, 0 if the lock was not established
2064 * by this thread (in which case the lock is not released), and NULL if the named lock
2069 public function unlock( $lockName, $method );
2072 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object
2074 * Only call this from outer transcation scope and when only one DB will be affected.
2075 * See https://www.mediawiki.org/wiki/Database_transactions for details.
2077 * This is suitiable for transactions that need to be serialized using cooperative locks,
2078 * where each transaction can see each others' changes. Any transaction is flushed to clear
2079 * out stale REPEATABLE-READ snapshot data. Once the returned object falls out of PHP scope,
2080 * the lock will be released unless a transaction is active. If one is active, then the lock
2081 * will be released when it either commits or rolls back.
2083 * If the lock acquisition failed, then no transaction flush happens, and null is returned.
2085 * @param string $lockKey Name of lock to release
2086 * @param string $fname Name of the calling method
2087 * @param int $timeout Acquisition timeout in seconds
2088 * @return ScopedCallback|null
2092 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
2095 * Check to see if a named lock used by lock() use blocking queues
2100 public function namedLocksEnqueue();
2103 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2104 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2105 * because "i" sorts after all numbers.
2109 public function getInfinity();
2112 * Encode an expiry time into the DBMS dependent format
2114 * @param string $expiry Timestamp for expiry, or the 'infinity' string
2117 public function encodeExpiry( $expiry );
2120 * Decode an expiry time into a DBMS independent format
2122 * @param string $expiry DB timestamp field value for expiry
2123 * @param int $format TS_* constant, defaults to TS_MW
2126 public function decodeExpiry( $expiry, $format = TS_MW
);
2129 * Allow or deny "big selects" for this session only. This is done by setting
2130 * the sql_big_selects session variable.
2132 * This is a MySQL-specific feature.
2134 * @param bool|string $value True for allow, false for deny, or "default" to
2135 * restore the initial value
2137 public function setBigSelects( $value = true );
2140 * @return bool Whether this DB is read-only
2143 public function isReadOnly();
2146 * Make certain table names use their own database, schema, and table prefix
2147 * when passed into SQL queries pre-escaped and without a qualified database name
2149 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
2150 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
2152 * Calling this twice will completely clear any old table aliases. Also, note that
2153 * callers are responsible for making sure the schemas and databases actually exist.
2155 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
2158 public function setTableAliases( array $aliases );
2161 * Convert certain index names to alternative names before querying the DB
2163 * Note that this applies to indexes regardless of the table they belong to.
2165 * This can be employed when an index was renamed X => Y in code, but the new Y-named
2166 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
2167 * the aliases can be removed, and then the old X-named indexes dropped.
2169 * @param string[] $aliases
2173 public function setIndexAliases( array $aliases );
2177 * @deprecated since 1.29
2179 class_alias( IDatabase
::class, 'IDatabase' );