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;
45 /** @var int Callback triggered by atomic section cancel (ROLLBACK TO SAVEPOINT) */
46 const TRIGGER_CANCEL
= 4;
48 /** @var string Transaction is requested by regular caller outside of the DB layer */
49 const TRANSACTION_EXPLICIT
= '';
50 /** @var string Transaction is requested internally via DBO_TRX/startAtomic() */
51 const TRANSACTION_INTERNAL
= 'implicit';
53 /** @var string Atomic section is not cancelable */
54 const ATOMIC_NOT_CANCELABLE
= '';
55 /** @var string Atomic section is cancelable */
56 const ATOMIC_CANCELABLE
= 'cancelable';
58 /** @var string Commit/rollback is from outside the IDatabase handle and connection manager */
59 const FLUSHING_ONE
= '';
60 /** @var string Commit/rollback is from the connection manager for the IDatabase handle */
61 const FLUSHING_ALL_PEERS
= 'flush';
62 /** @var string Commit/rollback is from the IDatabase handle internally */
63 const FLUSHING_INTERNAL
= 'flush-internal';
65 /** @var string Do not remember the prior flags */
66 const REMEMBER_NOTHING
= '';
67 /** @var string Remember the prior flags */
68 const REMEMBER_PRIOR
= 'remember';
69 /** @var string Restore to the prior flag state */
70 const RESTORE_PRIOR
= 'prior';
71 /** @var string Restore to the initial flag state */
72 const RESTORE_INITIAL
= 'initial';
74 /** @var string Estimate total time (RTT, scanning, waiting on locks, applying) */
75 const ESTIMATE_TOTAL
= 'total';
76 /** @var string Estimate time to apply (scanning, applying) */
77 const ESTIMATE_DB_APPLY
= 'apply';
79 /** @var int Combine list with comma delimeters */
81 /** @var int Combine list with AND clauses */
83 /** @var int Convert map into a SET clause */
85 /** @var int Treat as field name and do not apply value escaping */
87 /** @var int Combine list with OR clauses */
90 /** @var int Enable debug logging of all SQL queries */
92 /** @var int Unused since 1.34 */
93 const DBO_NOBUFFER
= 2;
94 /** @var int Unused since 1.31 */
96 /** @var int Automatically start a transaction before running a query if none is active */
98 /** @var int Use DBO_TRX in non-CLI mode */
99 const DBO_DEFAULT
= 16;
100 /** @var int Use DB persistent connections if possible */
101 const DBO_PERSISTENT
= 32;
102 /** @var int DBA session mode; was used by Oracle */
103 const DBO_SYSDBA
= 64;
104 /** @var int Schema file mode; was used by Oracle */
105 const DBO_DDLMODE
= 128;
106 /** @var int Enable SSL/TLS in connection protocol */
108 /** @var int Enable compression in connection protocol */
109 const DBO_COMPRESS
= 512;
111 /** @var int Idiom for "no special flags" */
112 const QUERY_NORMAL
= 0;
113 /** @var int Ignore query errors and return false when they happen */
114 const QUERY_SILENCE_ERRORS
= 1; // b/c for 1.32 query() argument; note that (int)true = 1
116 * @var int Treat the TEMPORARY table from the given CREATE query as if it is
117 * permanent as far as write tracking is concerned. This is useful for testing.
119 const QUERY_PSEUDO_PERMANENT
= 2;
120 /** @var int Enforce that a query does not make effective writes */
121 const QUERY_REPLICA_ROLE
= 4;
122 /** @var int Ignore the current presence of any DBO_TRX flag */
123 const QUERY_IGNORE_DBO_TRX
= 8;
124 /** @var int Do not try to retry the query if the connection was lost */
125 const QUERY_NO_RETRY
= 16;
127 /** @var bool Parameter to unionQueries() for UNION ALL */
128 const UNION_ALL
= true;
129 /** @var bool Parameter to unionQueries() for UNION DISTINCT */
130 const UNION_DISTINCT
= false;
133 * Get a human-readable string describing the current software version
135 * Use getServerVersion() to get machine-friendly information.
137 * @return string Version information from the database server
139 public function getServerInfo();
142 * Gets the current transaction level.
144 * Historically, transactions were allowed to be "nested". This is no
145 * longer supported, so this function really only returns a boolean.
147 * @return int The previous value
149 public function trxLevel();
152 * Get the UNIX timestamp of the time that the transaction was established
154 * This can be used to reason about the staleness of SELECT data in REPEATABLE-READ
155 * transaction isolation level. Callers can assume that if a view-snapshot isolation
156 * is used, then the data read by SQL queries is *at least* up to date to that point
157 * (possibly more up-to-date since the first SELECT defines the snapshot).
159 * @return float|null Returns null if there is not active transaction
162 public function trxTimestamp();
165 * @return bool Whether an explicit transaction or atomic sections are still open
168 public function explicitTrxActive();
171 * Assert that all explicit transactions or atomic sections have been closed
173 * @throws DBTransactionError
176 public function assertNoOpenTransactions();
179 * Get/set the table prefix
181 * @param string|null $prefix The table prefix to set, or omitted to leave it unchanged
182 * @return string The previous table prefix
184 public function tablePrefix( $prefix = null );
187 * Get/set the db schema
189 * @param string|null $schema The database schema to set, or omitted to leave it unchanged
190 * @return string The previous db schema
192 public function dbSchema( $schema = null );
195 * Get properties passed down from the server info array of the load balancer
197 * @param string|null $name The entry of the info array to get, or null to get the whole array
198 * @return array|mixed|null
200 public function getLBInfo( $name = null );
203 * Set the entire array or a particular key of the managing load balancer info array
205 * @param array|string $nameOrArray The new array or the name of a key to set
206 * @param array|null $value If $nameOrArray is a string, the new key value (null to unset)
208 public function setLBInfo( $nameOrArray, $value = null );
211 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
213 * @param IDatabase $conn
216 public function setLazyMasterHandle( IDatabase
$conn );
219 * Returns true if this database does an implicit order by when the column has an index
220 * For example: SELECT page_title FROM page LIMIT 1
224 public function implicitOrderby();
227 * Get the last query that sent on account of IDatabase::query()
229 * @return string SQL text or empty string if there was no such query
231 public function lastQuery();
234 * Get the last time the connection may have been used for a write query
236 * @return int|float UNIX timestamp or false
239 public function lastDoneWrites();
242 * @return bool Whether there is a transaction open with possible write queries
245 public function writesPending();
248 * @return bool Whether there is a transaction open with pre-commit callbacks pending
251 public function preCommitCallbacksPending();
254 * Whether there is a transaction open with either possible write queries
255 * or unresolved pre-commit/commit/resolution callbacks pending
257 * This does *not* count recurring callbacks, e.g. from setTransactionListener().
261 public function writesOrCallbacksPending();
264 * Get the time spend running write queries for this transaction
266 * High values could be due to scanning, updates, locking, and such.
268 * @param string $type IDatabase::ESTIMATE_* constant [default: ESTIMATE_ALL]
269 * @return float|bool Returns false if not transaction is active
272 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
);
275 * Get the list of method names that did write queries for this transaction
280 public function pendingWriteCallers();
283 * Get the number of affected rows from pending write queries
288 public function pendingWriteRowsAffected();
291 * @return bool Whether a connection to the database open
293 public function isOpen();
296 * Set a flag for this connection
298 * @param int $flag One of (IDatabase::DBO_DEBUG, IDatabase::DBO_TRX)
299 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
301 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
);
304 * Clear a flag for this connection
306 * @param int $flag One of (IDatabase::DBO_DEBUG, IDatabase::DBO_TRX)
307 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
309 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
);
312 * Restore the flags to their prior state before the last setFlag/clearFlag call
314 * @param string $state IDatabase::RESTORE_* constant. [default: RESTORE_PRIOR]
317 public function restoreFlags( $state = self
::RESTORE_PRIOR
);
320 * Returns a boolean whether the flag $flag is set for this connection
322 * @param int $flag One of the class IDatabase::DBO_* constants
325 public function getFlag( $flag );
328 * Return the currently selected domain ID
330 * Null components (database/schema) might change once a connection is established
334 public function getDomainID();
337 * Get the type of the DBMS (e.g. "mysql", "sqlite")
341 public function getType();
344 * Fetch the next row from the given result object, in object form
346 * Fields can be retrieved with $row->fieldname, with fields acting like
347 * member variables. If no more rows are available, false is returned.
349 * @param IResultWrapper|stdClass $res Object as returned from IDatabase::query(), etc.
350 * @return stdClass|bool
352 public function fetchObject( $res );
355 * Fetch the next row from the given result object, in associative array form
357 * Fields are retrieved with $row['fieldname'].
358 * If no more rows are available, false is returned.
360 * @param IResultWrapper $res Result object as returned from IDatabase::query(), etc.
363 public function fetchRow( $res );
366 * Get the number of rows in a query result
368 * Returns zero if the query did not return any rows or was a write query.
370 * @param mixed $res A SQL result
373 public function numRows( $res );
376 * Get the number of fields in a result object
377 * @see https://www.php.net/mysql_num_fields
379 * @param mixed $res A SQL result
382 public function numFields( $res );
385 * Get a field name in a result object
386 * @see https://www.php.net/mysql_field_name
388 * @param mixed $res A SQL result
392 public function fieldName( $res, $n );
395 * Get the inserted value of an auto-increment row
397 * This should only be called after an insert that used an auto-incremented
398 * value. If no such insert was previously done in the current database
399 * session, the return value is undefined.
403 public function insertId();
406 * Change the position of the cursor in a result object
407 * @see https://www.php.net/mysql_data_seek
409 * @param mixed $res A SQL result
412 public function dataSeek( $res, $row );
415 * Get the last error number
416 * @see https://www.php.net/mysql_errno
420 public function lastErrno();
423 * Get a description of the last error
424 * @see https://www.php.net/mysql_error
428 public function lastError();
431 * Get the number of rows affected by the last write query.
432 * Similar to https://www.php.net/mysql_affected_rows but includes rows matched
433 * but not changed (ie. an UPDATE which sets all fields to the same value they already have).
434 * To get the old mysql_affected_rows behavior, include non-equality of the fields in WHERE.
438 public function affectedRows();
441 * Returns a wikitext style link to the DB's website (e.g. "[https://www.mysql.com/ MySQL]")
443 * Should at least contain plain text, if for some reason your database has no website.
445 * @return string Wikitext of a link to the server software's web site
447 public function getSoftwareLink();
450 * A string describing the current software version, like from mysql_get_server_info()
452 * @return string Version information from the database server.
454 public function getServerVersion();
457 * Close the database connection
459 * This should only be called after any transactions have been resolved,
460 * aside from read-only automatic transactions (assuming no callbacks are registered).
461 * If a transaction is still open anyway, it will be rolled back.
463 * @return bool Success
466 public function close();
469 * Run an SQL query and return the result
471 * If a connection loss is detected, then an attempt to reconnect will be made.
472 * For queries that involve no larger transactions or locks, they will be re-issued
473 * for convenience, provided the connection was re-established.
475 * In new code, the query wrappers select(), insert(), update(), delete(),
476 * etc. should be used where possible, since they give much better DBMS
477 * independence and automatically quote or validate user input in a variety
478 * of contexts. This function is generally only useful for queries which are
479 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
482 * However, the query wrappers themselves should call this function.
484 * @param string $sql SQL query
485 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
486 * comment (you can use __METHOD__ or add some extra info)
487 * @param int $flags Bitfield of IDatabase::QUERY_* constants. Note that suppression
488 * of errors is best handled by try/catch rather than using one of these flags.
489 * @return bool|IResultWrapper True for a successful write query, IResultWrapper object
490 * for a successful read query, or false on failure if QUERY_SILENCE_ERRORS is set.
491 * @throws DBQueryError If the query is issued, fails, and QUERY_SILENCE_ERRORS is not set.
492 * @throws DBExpectedError If the query is not, and cannot, be issued yet (non-DBQueryError)
493 * @throws DBError If the query is inherently not allowed (non-DBExpectedError)
495 public function query( $sql, $fname = __METHOD__
, $flags = 0 );
498 * Free a result object returned by query() or select()
500 * It's usually not necessary to call this, just use unset() or let the variable
501 * holding the result object go out of scope.
503 * @param mixed $res A SQL result
505 public function freeResult( $res );
508 * A SELECT wrapper which returns a single field from a single result row
510 * If no result rows are returned from the query, false is returned.
512 * @param string|array $table Table name. See IDatabase::select() for details.
513 * @param string $var The field name to select. This must be a valid SQL
514 * fragment: do not use unvalidated user input.
515 * @param string|array $cond The condition array. See IDatabase::select() for details.
516 * @param string $fname The function name of the caller.
517 * @param string|array $options The query options. See IDatabase::select() for details.
518 * @param string|array $join_conds The query join conditions. See IDatabase::select() for details.
519 * @return mixed The value from the field
520 * @throws DBError If an error occurs, see IDatabase::query()
522 public function selectField(
523 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
527 * A SELECT wrapper which returns a list of single field values from result rows
529 * If no result rows are returned from the query, false is returned.
531 * @param string|array $table Table name. See IDatabase::select() for details.
532 * @param string $var The field name to select. This must be a valid SQL
533 * fragment: do not use unvalidated user input.
534 * @param string|array $cond The condition array. See IDatabase::select() for details.
535 * @param string $fname The function name of the caller.
536 * @param string|array $options The query options. See IDatabase::select() for details.
537 * @param string|array $join_conds The query join conditions. See IDatabase::select() for details.
539 * @return array The values from the field in the order they were returned from the DB
540 * @throws DBError If an error occurs, see IDatabase::query()
543 public function selectFieldValues(
544 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
548 * Execute a SELECT query constructed using the various parameters provided
550 * @param string|array $table Table name(s)
552 * May be either an array of table names, or a single string holding a table
553 * name. If an array is given, table aliases can be specified, for example:
557 * This includes the user table in the query, with the alias "a" available
558 * for use in field names (e.g. a.user_name).
560 * A derived table, defined by the result of selectSQLText(), requires an alias
561 * key and a Subquery instance value which wraps the SQL query, for example:
563 * [ 'c' => new Subquery( 'SELECT ...' ) ]
565 * Joins using parentheses for grouping (since MediaWiki 1.31) may be
566 * constructed using nested arrays. For example,
568 * [ 'tableA', 'nestedB' => [ 'tableB', 'b2' => 'tableB2' ] ]
570 * along with `$join_conds` like
572 * [ 'b2' => [ 'JOIN', 'b_id = b2_id' ], 'nestedB' => [ 'LEFT JOIN', 'b_a = a_id' ] ]
574 * will produce SQL something like
576 * FROM tableA LEFT JOIN (tableB JOIN tableB2 AS b2 ON (b_id = b2_id)) ON (b_a = a_id)
578 * All of the table names given here are automatically run through
579 * Database::tableName(), which causes the table prefix (if any) to be
580 * added, and various other table name mappings to be performed.
582 * Do not use untrusted user input as a table name. Alias names should
583 * not have characters outside of the Basic multilingual plane.
585 * @param string|array $vars Field name(s)
587 * May be either a field name or an array of field names. The field names
588 * can be complete fragments of SQL, for direct inclusion into the SELECT
589 * query. If an array is given, field aliases can be specified, for example:
591 * [ 'maxrev' => 'MAX(rev_id)' ]
593 * This includes an expression with the alias "maxrev" in the query.
595 * If an expression is given, care must be taken to ensure that it is
598 * Untrusted user input must not be passed to this parameter.
600 * @param string|array $conds
602 * May be either a string containing a single condition, or an array of
603 * conditions. If an array is given, the conditions constructed from each
604 * element are combined with AND.
606 * Array elements may take one of two forms:
608 * - Elements with a numeric key are interpreted as raw SQL fragments.
609 * - Elements with a string key are interpreted as equality conditions,
610 * where the key is the field name.
611 * - If the value of such an array element is a scalar (such as a
612 * string), it will be treated as data and thus quoted appropriately.
613 * If it is null, an IS NULL clause will be added.
614 * - If the value is an array, an IN (...) clause will be constructed
615 * from its non-null elements, and an IS NULL clause will be added
616 * if null is present, such that the field may match any of the
617 * elements in the array. The non-null elements will be quoted.
619 * Note that expressions are often DBMS-dependent in their syntax.
620 * DBMS-independent wrappers are provided for constructing several types of
621 * expression commonly used in condition queries. See:
622 * - IDatabase::buildLike()
623 * - IDatabase::conditional()
625 * Untrusted user input is safe in the values of string keys, however untrusted
626 * input must not be used in the array key names or in the values of numeric keys.
627 * Escaping of untrusted input used in values of numeric keys should be done via
628 * IDatabase::addQuotes()
630 * Use an empty array, string, or '*' to update all rows.
632 * @param string $fname Caller function name
634 * @param string|array $options Query options
636 * Optional: Array of query options. Boolean options are specified by
637 * including them in the array as a string value with a numeric key, for
642 * The supported options are:
644 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
645 * with LIMIT can theoretically be used for paging through a result set,
646 * but this is discouraged for performance reasons.
648 * - LIMIT: Integer: return at most this many rows. The rows are sorted
649 * and then the first rows are taken until the limit is reached. LIMIT
650 * is applied to a result set after OFFSET.
652 * - LOCK IN SHARE MODE: Boolean: lock the returned rows so that they can't be
653 * changed until the next COMMIT. Cannot be used with aggregate functions
654 * (COUNT, MAX, etc., but also DISTINCT).
656 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
657 * changed nor read with LOCK IN SHARE MODE until the next COMMIT.
658 * Cannot be used with aggregate functions (COUNT, MAX, etc., but also DISTINCT).
660 * - DISTINCT: Boolean: return only unique result rows.
662 * - GROUP BY: May be either an SQL fragment string naming a field or
663 * expression to group by, or an array of such SQL fragments.
665 * - HAVING: May be either an string containing a HAVING clause or an array of
666 * conditions building the HAVING clause. If an array is given, the conditions
667 * constructed from each element are combined with AND.
669 * - ORDER BY: May be either an SQL fragment giving a field name or
670 * expression to order by, or an array of such SQL fragments.
672 * - USE INDEX: This may be either a string giving the index name to use
673 * for the query, or an array. If it is an associative array, each key
674 * gives the table name (or alias), each value gives the index name to
675 * use for that table. All strings are SQL fragments and so should be
676 * validated by the caller.
678 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
681 * And also the following boolean MySQL extensions, see the MySQL manual
686 * - SQL_BUFFER_RESULT
688 * - SQL_CALC_FOUND_ROWS
690 * @param string|array $join_conds Join conditions
692 * Optional associative array of table-specific join conditions. In the
693 * most common case, this is unnecessary, since the join condition can be
694 * in $conds. However, it is useful for doing a LEFT JOIN.
696 * The key of the array contains the table name or alias. The value is an
697 * array with two elements, numbered 0 and 1. The first gives the type of
698 * join, the second is the same as the $conds parameter. Thus it can be
699 * an SQL fragment, or an array where the string keys are equality and the
700 * numeric keys are SQL fragments all AND'd together. For example:
702 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
704 * @return IResultWrapper Resulting rows
705 * @throws DBError If an error occurs, see IDatabase::query()
707 public function select(
717 * Take the same arguments as IDatabase::select() and return the SQL it would use
719 * This can be useful for making UNION queries, where the SQL text of each query
720 * is needed. In general, however, callers outside of Database classes should just
723 * @see IDatabase::select()
725 * @param string|array $table Table name
726 * @param string|array $vars Field names
727 * @param string|array $conds Conditions
728 * @param string $fname Caller function name
729 * @param string|array $options Query options
730 * @param string|array $join_conds Join conditions
731 * @return string SQL query string
733 public function selectSQLText(
743 * Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
745 * If the query returns no rows, false is returned.
747 * This method is convenient for fetching a row based on a unique key condition.
749 * @param string|array $table Table name
750 * @param string|array $vars Field names
751 * @param string|array $conds Conditions
752 * @param string $fname Caller function name
753 * @param string|array $options Query options
754 * @param array|string $join_conds Join conditions
755 * @return stdClass|bool
756 * @throws DBError If an error occurs, see IDatabase::query()
758 public function selectRow(
768 * Estimate the number of rows in dataset
770 * MySQL allows you to estimate the number of rows that would be returned
771 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
772 * index cardinality statistics, and is notoriously inaccurate, especially
773 * when large numbers of rows have recently been added or deleted.
775 * For DBMSs that don't support fast result size estimation, this function
776 * will actually perform the SELECT COUNT(*).
778 * Takes the same arguments as IDatabase::select().
780 * @param string $table Table name
781 * @param string $var Column for which NULL values are not counted [default "*"]
782 * @param array|string $conds Filters on the table
783 * @param string $fname Function name for profiling
784 * @param array $options Options for select
785 * @param array|string $join_conds Join conditions
786 * @return int Row count
787 * @throws DBError If an error occurs, see IDatabase::query()
789 public function estimateRowCount(
790 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
794 * Get the number of rows in dataset
796 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
798 * Takes the same arguments as IDatabase::select().
800 * @since 1.27 Added $join_conds parameter
802 * @param array|string $tables Table names
803 * @param string $var Column for which NULL values are not counted [default "*"]
804 * @param array|string $conds Filters on the table
805 * @param string $fname Function name for profiling
806 * @param array $options Options for select
807 * @param array $join_conds Join conditions (since 1.27)
808 * @return int Row count
809 * @throws DBError If an error occurs, see IDatabase::query()
811 public function selectRowCount(
812 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
816 * Lock all rows meeting the given conditions/options FOR UPDATE
818 * @param array|string $table Table names
819 * @param array|string $conds Filters on the table
820 * @param string $fname Function name for profiling
821 * @param array $options Options for select ("FOR UPDATE" is added automatically)
822 * @param array $join_conds Join conditions
823 * @return int Number of matching rows found (and locked)
824 * @throws DBError If an error occurs, see IDatabase::query()
827 public function lockForUpdate(
828 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
832 * Determines whether a field exists in a table
834 * @param string $table Table name
835 * @param string $field Filed to check on that table
836 * @param string $fname Calling function name (optional)
837 * @return bool Whether $table has filed $field
838 * @throws DBError If an error occurs, see IDatabase::query()
840 public function fieldExists( $table, $field, $fname = __METHOD__
);
843 * Determines whether an index exists
845 * @param string $table
846 * @param string $index
847 * @param string $fname
849 * @throws DBError If an error occurs, see IDatabase::query()
851 public function indexExists( $table, $index, $fname = __METHOD__
);
854 * Query whether a given table exists
856 * @param string $table
857 * @param string $fname
859 * @throws DBError If an error occurs, see IDatabase::query()
861 public function tableExists( $table, $fname = __METHOD__
);
864 * INSERT wrapper, inserts an array into a table
868 * - A single associative array. The array keys are the field names, and
869 * the values are the values to insert. The values are treated as data
870 * and will be quoted appropriately. If NULL is inserted, this will be
871 * converted to a database NULL.
872 * - An array with numeric keys, holding a list of associative arrays.
873 * This causes a multi-row INSERT on DBMSs that support it. The keys in
874 * each subarray must be identical to each other, and in the same order.
876 * $options is an array of options, with boolean options encoded as values
877 * with numeric keys, in the same style as $options in
878 * IDatabase::select(). Supported options are:
880 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
881 * any rows which cause duplicate key errors are not inserted. It's
882 * possible to determine how many rows were successfully inserted using
883 * IDatabase::affectedRows().
885 * @param string $table Table name. This will be passed through
886 * Database::tableName().
887 * @param array $a Array of rows to insert
888 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
889 * @param array $options Array of options
890 * @return bool Return true if no exception was thrown (deprecated since 1.33)
891 * @throws DBError If an error occurs, see IDatabase::query()
893 public function insert( $table, $a, $fname = __METHOD__
, $options = [] );
896 * UPDATE wrapper. Takes a condition array and a SET array.
898 * @param string $table Name of the table to UPDATE. This will be passed through
899 * Database::tableName().
900 * @param array $values An array of values to SET. For each array element,
901 * the key gives the field name, and the value gives the data to set
902 * that field to. The data will be quoted by IDatabase::addQuotes().
903 * Values with integer keys form unquoted SET statements, which can be used for
904 * things like "field = field + 1" or similar computed values.
905 * @param array|string $conds An array of conditions (WHERE). See
906 * IDatabase::select() for the details of the format of condition
907 * arrays. Use '*' to update all rows.
908 * @param string $fname The function name of the caller (from __METHOD__),
909 * for logging and profiling.
910 * @param array $options An array of UPDATE options, can be:
911 * - IGNORE: Ignore unique key conflicts
912 * @return bool Return true if no exception was thrown (deprecated since 1.33)
913 * @throws DBError If an error occurs, see IDatabase::query()
915 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] );
918 * Makes an encoded list of strings from an array
920 * These can be used to make conjunctions or disjunctions on SQL condition strings
921 * derived from an array (see IDatabase::select() $conds documentation).
925 * $sql = $db->makeList( [
927 * $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] )
928 * ], $db::LIST_AND );
930 * This would set $sql to "rev_page = '$id' AND (rev_minor = '1' OR rev_len < '500')"
932 * @param array $a Containing the data
933 * @param int $mode IDatabase class constant:
934 * - IDatabase::LIST_COMMA: Comma separated, no field names
935 * - IDatabase::LIST_AND: ANDed WHERE clause (without the WHERE).
936 * - IDatabase::LIST_OR: ORed WHERE clause (without the WHERE)
937 * - IDatabase::LIST_SET: Comma separated with field names, like a SET clause
938 * - IDatabase::LIST_NAMES: Comma separated field names
939 * @throws DBError If an error occurs, see IDatabase::query()
942 public function makeList( $a, $mode = self
::LIST_COMMA
);
945 * Build a partial where clause from a 2-d array such as used for LinkBatch.
946 * The keys on each level may be either integers or strings.
948 * @param array $data Organized as 2-d
949 * [ baseKeyVal => [ subKeyVal => [ignored], ... ], ... ]
950 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
951 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
952 * @return string|bool SQL fragment, or false if no items in array
954 public function makeWhereFrom2d( $data, $baseKey, $subKey );
957 * Return aggregated value alias
959 * @param array $valuedata
960 * @param string $valuename
962 * @return array|string
963 * @deprecated Since 1.33
965 public function aggregateValue( $valuedata, $valuename = 'value' );
968 * @param string $field
971 public function bitNot( $field );
974 * @param string $fieldLeft
975 * @param string $fieldRight
978 public function bitAnd( $fieldLeft, $fieldRight );
981 * @param string $fieldLeft
982 * @param string $fieldRight
985 public function bitOr( $fieldLeft, $fieldRight );
988 * Build a concatenation list to feed into a SQL query
989 * @param string[] $stringList Raw SQL expression list; caller is responsible for escaping
992 public function buildConcat( $stringList );
995 * Build a GROUP_CONCAT or equivalent statement for a query.
997 * This is useful for combining a field for several rows into a single string.
998 * NULL values will not appear in the output, duplicated values will appear,
999 * and the resulting delimiter-separated values have no defined sort order.
1000 * Code using the results may need to use the PHP unique() or sort() methods.
1002 * @param string $delim Glue to bind the results together
1003 * @param string|array $table Table name
1004 * @param string $field Field name
1005 * @param string|array $conds Conditions
1006 * @param string|array $join_conds Join conditions
1007 * @return string SQL text
1010 public function buildGroupConcatField(
1011 $delim, $table, $field, $conds = '', $join_conds = []
1015 * Build a SUBSTRING function
1017 * Behavior for non-ASCII values is undefined.
1019 * @param string $input Field name
1020 * @param int $startPosition Positive integer
1021 * @param int|null $length Non-negative integer length or null for no limit
1022 * @throws InvalidArgumentException
1023 * @return string SQL text
1026 public function buildSubString( $input, $startPosition, $length = null );
1029 * @param string $field Field or column to cast
1033 public function buildStringCast( $field );
1036 * @param string $field Field or column to cast
1040 public function buildIntegerCast( $field );
1043 * Equivalent to IDatabase::selectSQLText() except wraps the result in Subqyery
1045 * @see IDatabase::selectSQLText()
1047 * @param string|array $table Table name
1048 * @param string|array $vars Field names
1049 * @param string|array $conds Conditions
1050 * @param string $fname Caller function name
1051 * @param string|array $options Query options
1052 * @param string|array $join_conds Join conditions
1056 public function buildSelectSubquery(
1060 $fname = __METHOD__
,
1066 * Construct a LIMIT query with optional offset
1068 * The SQL should be adjusted so that only the first $limit rows
1069 * are returned. If $offset is provided as well, then the first $offset
1070 * rows should be discarded, and the next $limit rows should be returned.
1071 * If the result of the query is not ordered, then the rows to be returned
1072 * are theoretically arbitrary.
1074 * $sql is expected to be a SELECT, if that makes a difference.
1076 * @param string $sql SQL query we will append the limit too
1077 * @param int $limit The SQL limit
1078 * @param int|bool $offset The SQL offset (default false)
1082 public function limitResult( $sql, $limit, $offset = false );
1085 * Returns true if DBs are assumed to be on potentially different servers
1087 * In systems like mysql/mariadb, different databases can easily be referenced on a single
1088 * connection merely by name, even in a single query via JOIN. On the other hand, Postgres
1089 * treats databases as fully separate, only allowing mechanisms like postgres_fdw to
1090 * effectively "mount" foreign DBs. This is true even among DBs on the same server.
1095 public function databasesAreIndependent();
1098 * Change the current database
1100 * This should only be called by a load balancer or if the handle is not attached to one
1103 * @return bool True unless an exception was thrown
1104 * @throws DBConnectionError If databasesAreIndependent() is true and connection change fails
1105 * @throws DBError On query error or if database changes are disallowed
1106 * @deprecated Since 1.32 Use selectDomain() instead
1108 public function selectDB( $db );
1111 * Set the current domain (database, schema, and table prefix)
1113 * This will throw an error for some database types if the database is unspecified
1115 * This should only be called by a load balancer or if the handle is not attached to one
1117 * @param string|DatabaseDomain $domain
1118 * @throws DBConnectionError If databasesAreIndependent() is true and connection change fails
1119 * @throws DBError On query error, if domain changes are disallowed, or the domain is invalid
1122 public function selectDomain( $domain );
1125 * Get the current DB name
1126 * @return string|null
1128 public function getDBname();
1131 * Get the server hostname or IP address
1134 public function getServer();
1137 * Escape and quote a raw value string for use in a SQL query
1139 * @param string|int|null|bool|Blob $s
1140 * @return string|int
1142 public function addQuotes( $s );
1145 * Escape a SQL identifier (e.g. table, column, database) for use in a SQL query
1147 * Depending on the database this will either be `backticks` or "double quotes"
1153 public function addIdentifierQuotes( $s );
1156 * LIKE statement wrapper
1158 * This takes a variable-length argument list with parts of pattern to match
1159 * containing either string literals that will be escaped or tokens returned by
1160 * anyChar() or anyString(). Alternatively, the function could be provided with
1161 * an array of aforementioned parameters.
1163 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
1164 * a LIKE clause that searches for subpages of 'My page title'.
1166 * $pattern = [ 'My_page_title/', $dbr->anyString() ];
1167 * $query .= $dbr->buildLike( $pattern );
1170 * @param array[]|string|LikeMatch $param
1171 * @return string Fully built LIKE statement
1172 * @phan-suppress-next-line PhanMismatchVariadicComment
1173 * @phan-param array|string|LikeMatch ...$param T226223
1175 public function buildLike( $param );
1178 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1182 public function anyChar();
1185 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1189 public function anyString();
1192 * Deprecated method, calls should be removed
1194 * This was formerly used for PostgreSQL to handle
1195 * self::insertId() auto-incrementing fields. It is no longer necessary
1196 * since DatabasePostgres::insertId() has been reimplemented using
1199 * Implementations should return null if inserting `NULL` into an
1200 * auto-incrementing field works, otherwise it should return an instance of
1201 * NextSequenceValue and filter it on calls to relevant methods.
1203 * @deprecated since 1.30, no longer needed
1204 * @param string $seqName
1205 * @return null|NextSequenceValue
1207 public function nextSequenceValue( $seqName );
1210 * REPLACE query wrapper
1212 * REPLACE is a very handy MySQL extension, which functions like an INSERT
1213 * except that when there is a duplicate key error, the old row is deleted
1214 * and the new row is inserted in its place.
1216 * We simulate this with standard SQL with a DELETE followed by INSERT. To
1217 * perform the delete, we need to know what the unique indexes are so that
1218 * we know how to find the conflicting rows.
1220 * It may be more efficient to leave off unique indexes which are unlikely
1221 * to collide. However if you do this, you run the risk of encountering
1222 * errors which wouldn't have occurred in MySQL.
1224 * @param string $table The table to replace the row(s) in.
1225 * @param array[]|string[]|string $uniqueIndexes All unique indexes. One of the following:
1226 * a) the one unique field in the table (when no composite unique key exist)
1227 * b) a list of all unique fields in the table (when no composite unique key exist)
1228 * c) a list of all unique indexes in the table (each as a list of the indexed fields)
1229 * @param array $rows Can be either a single row to insert, or multiple rows,
1230 * in the same format as for IDatabase::insert()
1231 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1232 * @throws DBError If an error occurs, see IDatabase::query()
1234 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
);
1237 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
1239 * This updates any conflicting rows (according to the unique indexes) using
1240 * the provided SET clause and inserts any remaining (non-conflicted) rows.
1242 * $rows may be either:
1243 * - A single associative array. The array keys are the field names, and
1244 * the values are the values to insert. The values are treated as data
1245 * and will be quoted appropriately. If NULL is inserted, this will be
1246 * converted to a database NULL.
1247 * - An array with numeric keys, holding a list of associative arrays.
1248 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1249 * each subarray must be identical to each other, and in the same order.
1251 * It may be more efficient to leave off unique indexes which are unlikely
1252 * to collide. However if you do this, you run the risk of encountering
1253 * errors which wouldn't have occurred in MySQL.
1255 * @param string $table Table name. This will be passed through Database::tableName().
1256 * @param array $rows A single row or list of rows to insert
1257 * @param array[]|string[]|string $uniqueIndexes All unique indexes. One of the following:
1258 * a) the one unique field in the table (when no composite unique key exist)
1259 * b) a list of all unique fields in the table (when no composite unique key exist)
1260 * c) a list of all unique indexes in the table (each as a list of the indexed fields)
1261 * @param array $set An array of values to SET. For each array element, the
1262 * key gives the field name, and the value gives the data to set that
1263 * field to. The data will be quoted by IDatabase::addQuotes().
1264 * Values with integer keys form unquoted SET statements, which can be used for
1265 * things like "field = field + 1" or similar computed values.
1266 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1267 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1268 * @throws DBError If an error occurs, see IDatabase::query()
1271 public function upsert(
1272 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1276 * DELETE where the condition is a join.
1278 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
1279 * we use sub-selects
1281 * For safety, an empty $conds will not delete everything. If you want to
1282 * delete all rows where the join condition matches, set $conds='*'.
1284 * DO NOT put the join condition in $conds.
1286 * @param string $delTable The table to delete from.
1287 * @param string $joinTable The other table.
1288 * @param string $delVar The variable to join on, in the first table.
1289 * @param string $joinVar The variable to join on, in the second table.
1290 * @param array|string $conds Condition array of field names mapped to variables,
1291 * ANDed together in the WHERE clause
1292 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1293 * @throws DBError If an error occurs, see IDatabase::query()
1295 public function deleteJoin(
1305 * DELETE query wrapper
1307 * @param string $table Table name
1308 * @param string|array $conds Array of conditions. See $conds in IDatabase::select()
1309 * for the format. Use $conds == "*" to delete all rows
1310 * @param string $fname Name of the calling function
1311 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1312 * @throws DBError If an error occurs, see IDatabase::query()
1314 public function delete( $table, $conds, $fname = __METHOD__
);
1317 * INSERT SELECT wrapper
1319 * @warning If the insert will use an auto-increment or sequence to
1320 * determine the value of a column, this may break replication on
1321 * databases using statement-based replication if the SELECT is not
1322 * deterministically ordered.
1324 * @param string $destTable The table name to insert into
1325 * @param string|array $srcTable May be either a table name, or an array of table names
1326 * to include in a join.
1327 * @param array $varMap Must be an associative array of the form
1328 * [ 'dest1' => 'source1', ... ]. Source items may be literals
1329 * rather than field names, but strings should be quoted with
1330 * IDatabase::addQuotes()
1331 * @param array $conds Condition array. See $conds in IDatabase::select() for
1332 * the details of the format of condition arrays. May be "*" to copy the
1334 * @param string $fname The function name of the caller, from __METHOD__
1335 * @param array $insertOptions Options for the INSERT part of the query, see
1336 * IDatabase::insert() for details. Also, one additional option is
1337 * available: pass 'NO_AUTO_COLUMNS' to hint that the query does not use
1338 * an auto-increment or sequence to determine any column values.
1339 * @param array $selectOptions Options for the SELECT part of the query, see
1340 * IDatabase::select() for details.
1341 * @param array $selectJoinConds Join conditions for the SELECT part of the query, see
1342 * IDatabase::select() for details.
1343 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1344 * @throws DBError If an error occurs, see IDatabase::query()
1346 public function insertSelect(
1351 $fname = __METHOD__
,
1352 $insertOptions = [],
1353 $selectOptions = [],
1354 $selectJoinConds = []
1358 * Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION
1362 public function unionSupportsOrderAndLimit();
1365 * Construct a UNION query
1367 * This is used for providing overload point for other DB abstractions
1368 * not compatible with the MySQL syntax.
1369 * @param array $sqls SQL statements to combine
1370 * @param bool $all Either IDatabase::UNION_ALL or IDatabase::UNION_DISTINCT
1371 * @return string SQL fragment
1373 public function unionQueries( $sqls, $all );
1376 * Construct a UNION query for permutations of conditions
1378 * Databases sometimes have trouble with queries that have multiple values
1379 * for multiple condition parameters combined with limits and ordering.
1380 * This method constructs queries for the Cartesian product of the
1381 * conditions and unions them all together.
1383 * @see IDatabase::select()
1384 * @param string|array $table Table name
1385 * @param string|array $vars Field names
1386 * @param array $permute_conds Conditions for the Cartesian product. Keys
1387 * are field names, values are arrays of the possible values for that
1389 * @param string|array $extra_conds Additional conditions to include in the
1391 * @param string $fname Caller function name
1392 * @param string|array $options Query options. In addition to the options
1393 * recognized by IDatabase::select(), the following may be used:
1394 * - NOTALL: Set to use UNION instead of UNION ALL.
1395 * - INNER ORDER BY: If specified and supported, subqueries will use this
1396 * instead of ORDER BY.
1397 * @param string|array $join_conds Join conditions
1398 * @return string SQL query string.
1401 public function unionConditionPermutations(
1404 array $permute_conds,
1406 $fname = __METHOD__
,
1412 * Returns an SQL expression for a simple conditional
1414 * This doesn't need to be overridden unless CASE isn't supported in the RDBMS.
1416 * @param string|array $cond SQL expression which will result in a boolean value
1417 * @param string $trueVal SQL expression to return if true
1418 * @param string $falseVal SQL expression to return if false
1419 * @return string SQL fragment
1421 public function conditional( $cond, $trueVal, $falseVal );
1424 * Returns a SQL expression for simple string replacement (e.g. REPLACE() in mysql)
1426 * @param string $orig Column to modify
1427 * @param string $old Column to seek
1428 * @param string $new Column to replace with
1431 public function strreplace( $orig, $old, $new );
1434 * Determines how long the server has been up
1439 public function getServerUptime();
1442 * Determines if the last failure was due to a deadlock
1444 * Note that during a deadlock, the prior transaction will have been lost
1448 public function wasDeadlock();
1451 * Determines if the last failure was due to a lock timeout
1453 * Note that during a lock wait timeout, the prior transaction will have been lost
1457 public function wasLockTimeout();
1460 * Determines if the last query error was due to a dropped connection
1462 * Note that during a connection loss, the prior transaction will have been lost
1467 public function wasConnectionLoss();
1470 * Determines if the last failure was due to the database being read-only
1474 public function wasReadOnlyError();
1477 * Determines if the last query error was due to something outside of the query itself
1479 * Note that the transaction may have been lost, discarding prior writes and results
1483 public function wasErrorReissuable();
1486 * Wait for the replica DB to catch up to a given master position
1488 * Note that this does not start any new transactions. If any existing transaction
1489 * is flushed, and this is called, then queries will reflect the point the DB was synced
1490 * up to (on success) without interference from REPEATABLE-READ snapshots.
1492 * @param DBMasterPos $pos
1493 * @param int $timeout The maximum number of seconds to wait for synchronisation
1494 * @return int|null Zero if the replica DB was past that position already,
1495 * greater than zero if we waited for some period of time, less than
1496 * zero if it timed out, and null on error
1497 * @throws DBError If an error occurs, see IDatabase::query()
1499 public function masterPosWait( DBMasterPos
$pos, $timeout );
1502 * Get the replication position of this replica DB
1504 * @return DBMasterPos|bool False if this is not a replica DB
1505 * @throws DBError If an error occurs, see IDatabase::query()
1507 public function getReplicaPos();
1510 * Get the position of this master
1512 * @return DBMasterPos|bool False if this is not a master
1513 * @throws DBError If an error occurs, see IDatabase::query()
1515 public function getMasterPos();
1518 * @return bool Whether the DB is marked as read-only server-side
1521 public function serverIsReadOnly();
1524 * Run a callback as soon as the current transaction commits or rolls back
1526 * An error is thrown if no transaction is pending. Queries in the function will run in
1527 * AUTOCOMMIT mode unless there are begin() calls. Callbacks must commit any transactions
1530 * This is useful for combining cooperative locks and DB transactions.
1532 * Note this is called when the whole transaction is resolved. To take action immediately
1533 * when an atomic section is cancelled, use onAtomicSectionCancel().
1535 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1537 * The callback takes the following arguments:
1538 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK)
1539 * - This IDatabase instance (since 1.32)
1541 * @param callable $callback
1542 * @param string $fname Caller name
1543 * @throws DBError If an error occurs, see IDatabase::query()
1544 * @throws Exception If the callback runs immediately and an error occurs in it
1547 public function onTransactionResolution( callable
$callback, $fname = __METHOD__
);
1550 * Run a callback as soon as there is no transaction pending
1552 * If there is a transaction and it is rolled back, then the callback is cancelled.
1554 * When transaction round mode (DBO_TRX) is set, the callback will run at the end
1555 * of the round, just after all peer transactions COMMIT. If the transaction round
1556 * is rolled back, then the callback is cancelled.
1558 * Queries in the function will run in AUTOCOMMIT mode unless there are begin() calls.
1559 * Callbacks must commit any transactions that they begin.
1561 * This is useful for updates to different systems or when separate transactions are needed.
1562 * For example, one might want to enqueue jobs into a system outside the database, but only
1563 * after the database is updated so that the jobs will see the data when they actually run.
1564 * It can also be used for updates that easily suffer from lock timeouts and deadlocks,
1565 * but where atomicity is not essential.
1567 * Avoid using IDatabase instances aside from this one in the callback, unless such instances
1568 * never have IDatabase::DBO_TRX set. This keeps callbacks from interfering with one another.
1570 * Updates will execute in the order they were enqueued.
1572 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1574 * The callback takes the following arguments:
1575 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_IDLE)
1576 * - This IDatabase instance (since 1.32)
1578 * @param callable $callback
1579 * @param string $fname Caller name
1580 * @throws DBError If an error occurs, see IDatabase::query()
1581 * @throws Exception If the callback runs immediately and an error occurs in it
1584 public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
);
1587 * Alias for onTransactionCommitOrIdle() for backwards-compatibility
1589 * @param callable $callback
1590 * @param string $fname
1592 * @deprecated Since 1.32
1594 public function onTransactionIdle( callable
$callback, $fname = __METHOD__
);
1597 * Run a callback before the current transaction commits or now if there is none
1599 * If there is a transaction and it is rolled back, then the callback is cancelled.
1601 * When transaction round mode (DBO_TRX) is set, the callback will run at the end
1602 * of the round, just before all peer transactions COMMIT. If the transaction round
1603 * is rolled back, then the callback is cancelled.
1605 * Callbacks must not start nor commit any transactions. If no transaction is active,
1606 * then a transaction will wrap the callback.
1608 * This is useful for updates that easily suffer from lock timeouts and deadlocks,
1609 * but where atomicity is strongly desired for these updates and some related updates.
1611 * Updates will execute in the order they were enqueued.
1613 * The callback takes the one argument:
1614 * - This IDatabase instance (since 1.32)
1616 * @param callable $callback
1617 * @param string $fname Caller name
1618 * @throws DBError If an error occurs, see IDatabase::query()
1619 * @throws Exception If the callback runs immediately and an error occurs in it
1622 public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
);
1625 * Run a callback when the atomic section is cancelled
1627 * The callback is run just after the current atomic section, any outer
1628 * atomic section, or the whole transaction is rolled back.
1630 * An error is thrown if no atomic section is pending. The atomic section
1631 * need not have been created with the ATOMIC_CANCELABLE flag.
1633 * Queries in the function may be running in the context of an outer
1634 * transaction or may be running in AUTOCOMMIT mode. The callback should
1635 * use atomic sections if necessary.
1637 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1639 * The callback takes the following arguments:
1640 * - IDatabase::TRIGGER_CANCEL or IDatabase::TRIGGER_ROLLBACK
1641 * - This IDatabase instance
1643 * @param callable $callback
1644 * @param string $fname Caller name
1647 public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
);
1650 * Run a callback after each time any transaction commits or rolls back
1652 * The callback takes two arguments:
1653 * - IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK
1654 * - This IDatabase object
1655 * Callbacks must commit any transactions that they begin.
1657 * Registering a callback here will not affect writesOrCallbacks() pending.
1659 * Since callbacks from this or onTransactionCommitOrIdle() can start and end transactions,
1660 * a single call to IDatabase::commit might trigger multiple runs of the listener callbacks.
1662 * @param string $name Callback name
1663 * @param callable|null $callback Use null to unset a listener
1666 public function setTransactionListener( $name, callable
$callback = null );
1669 * Begin an atomic section of SQL statements
1671 * Start an implicit transaction if no transaction is already active, set a savepoint
1672 * (if $cancelable is ATOMIC_CANCELABLE), and track the given section name to enforce
1673 * that the transaction is not committed prematurely. The end of the section must be
1674 * signified exactly once, either by endAtomic() or cancelAtomic(). Sections can have
1675 * have layers of inner sections (sub-sections), but all sections must be ended in order
1676 * of innermost to outermost. Transactions cannot be started or committed until all
1677 * atomic sections are closed.
1679 * ATOMIC_CANCELABLE is useful when the caller needs to handle specific failure cases
1680 * by discarding the section's writes. This should not be used for failures when:
1681 * - upsert() could easily be used instead
1682 * - insert() with IGNORE could easily be used instead
1683 * - select() with FOR UPDATE could be checked before issuing writes instead
1684 * - The failure is from code that runs after the first write but doesn't need to
1685 * - The failures are from contention solvable via onTransactionPreCommitOrIdle()
1686 * - The failures are deadlocks; the RDBMs usually discard the whole transaction
1688 * @note callers must use additional measures for situations involving two or more
1689 * (peer) transactions (e.g. updating two database servers at once). The transaction
1690 * and savepoint logic of this method only applies to this specific IDatabase instance.
1694 * // Start a transaction if there isn't one already
1695 * $dbw->startAtomic( __METHOD__ );
1696 * // Serialize these thread table updates
1697 * $dbw->select( 'thread', '1', [ 'td_id' => $tid ], __METHOD__, 'FOR UPDATE' );
1698 * // Add a new comment for the thread
1699 * $dbw->insert( 'comment', $row, __METHOD__ );
1700 * $cid = $db->insertId();
1701 * // Update thread reference to last comment
1702 * $dbw->update( 'thread', [ 'td_latest' => $cid ], [ 'td_id' => $tid ], __METHOD__ );
1703 * // Demark the end of this conceptual unit of updates
1704 * $dbw->endAtomic( __METHOD__ );
1707 * Example usage (atomic changes that might have to be discarded):
1709 * // Start a transaction if there isn't one already
1710 * $sectionId = $dbw->startAtomic( __METHOD__, $dbw::ATOMIC_CANCELABLE );
1711 * // Create new record metadata row
1712 * $dbw->insert( 'records', $row, __METHOD__ );
1713 * // Figure out where to store the data based on the new row's ID
1714 * $path = $recordDirectory . '/' . $dbw->insertId();
1715 * // Write the record data to the storage system
1716 * $status = $fileBackend->create( [ 'dst' => $path, 'content' => $data ] );
1717 * if ( $status->isOK() ) {
1718 * // Try to cleanup files orphaned by transaction rollback
1719 * $dbw->onTransactionResolution(
1720 * function ( $type ) use ( $fileBackend, $path ) {
1721 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) {
1722 * $fileBackend->delete( [ 'src' => $path ] );
1727 * // Demark the end of this conceptual unit of updates
1728 * $dbw->endAtomic( __METHOD__ );
1730 * // Discard these writes from the transaction (preserving prior writes)
1731 * $dbw->cancelAtomic( __METHOD__, $sectionId );
1736 * @param string $fname
1737 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a
1738 * savepoint and enable self::cancelAtomic() for this section.
1739 * @return AtomicSectionIdentifier section ID token
1740 * @throws DBError If an error occurs, see IDatabase::query()
1742 public function startAtomic( $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
);
1745 * Ends an atomic section of SQL statements
1747 * Ends the next section of atomic SQL statements and commits the transaction
1751 * @see IDatabase::startAtomic
1752 * @param string $fname
1753 * @throws DBError If an error occurs, see IDatabase::query()
1755 public function endAtomic( $fname = __METHOD__
);
1758 * Cancel an atomic section of SQL statements
1760 * This will roll back only the statements executed since the start of the
1761 * most recent atomic section, and close that section. If a transaction was
1762 * open before the corresponding startAtomic() call, any statements before
1763 * that call are *not* rolled back and the transaction remains open. If the
1764 * corresponding startAtomic() implicitly started a transaction, that
1765 * transaction is rolled back.
1767 * @note callers must use additional measures for situations involving two or more
1768 * (peer) transactions (e.g. updating two database servers at once). The transaction
1769 * and savepoint logic of startAtomic() are bound to specific IDatabase instances.
1771 * Note that a call to IDatabase::rollback() will also roll back any open atomic sections.
1773 * @note As a micro-optimization to save a few DB calls, this method may only
1774 * be called when startAtomic() was called with the ATOMIC_CANCELABLE flag.
1776 * @see IDatabase::startAtomic
1777 * @param string $fname
1778 * @param AtomicSectionIdentifier|null $sectionId Section ID from startAtomic();
1779 * passing this enables cancellation of unclosed nested sections [optional]
1780 * @throws DBError If an error occurs, see IDatabase::query()
1782 public function cancelAtomic( $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null );
1785 * Perform an atomic section of reversable SQL statements from a callback
1787 * The $callback takes the following arguments:
1788 * - This database object
1789 * - The value of $fname
1791 * This will execute the callback inside a pair of startAtomic()/endAtomic() calls.
1792 * If any exception occurs during execution of the callback, it will be handled as follows:
1793 * - If $cancelable is ATOMIC_CANCELABLE, cancelAtomic() will be called to back out any
1794 * (and only) statements executed during the atomic section. If that succeeds, then the
1795 * exception will be re-thrown; if it fails, then a different exception will be thrown
1796 * and any further query attempts will fail until rollback() is called.
1797 * - If $cancelable is ATOMIC_NOT_CANCELABLE, cancelAtomic() will be called to mark the
1798 * end of the section and the error will be re-thrown. Any further query attempts will
1799 * fail until rollback() is called.
1801 * This method is convenient for letting calls to the caller of this method be wrapped
1802 * in a try/catch blocks for exception types that imply that the caller failed but was
1803 * able to properly discard the changes it made in the transaction. This method can be
1804 * an alternative to explicit calls to startAtomic()/endAtomic()/cancelAtomic().
1806 * Example usage, "RecordStore::save" method:
1808 * $dbw->doAtomicSection( __METHOD__, function ( $dbw ) use ( $record ) {
1809 * // Create new record metadata row
1810 * $dbw->insert( 'records', $record->toArray(), __METHOD__ );
1811 * // Figure out where to store the data based on the new row's ID
1812 * $path = $this->recordDirectory . '/' . $dbw->insertId();
1813 * // Write the record data to the storage system;
1814 * // blob store throughs StoreFailureException on failure
1815 * $this->blobStore->create( $path, $record->getJSON() );
1816 * // Try to cleanup files orphaned by transaction rollback
1817 * $dbw->onTransactionResolution(
1818 * function ( $type ) use ( $path ) {
1819 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) {
1820 * $this->blobStore->delete( $path );
1825 * }, $dbw::ATOMIC_CANCELABLE );
1828 * Example usage, caller of the "RecordStore::save" method:
1830 * $dbw->startAtomic( __METHOD__ );
1831 * // ...various SQL writes happen...
1833 * $recordStore->save( $record );
1834 * } catch ( StoreFailureException $e ) {
1835 * // ...various SQL writes happen...
1837 * // ...various SQL writes happen...
1838 * $dbw->endAtomic( __METHOD__ );
1841 * @see Database::startAtomic
1842 * @see Database::endAtomic
1843 * @see Database::cancelAtomic
1845 * @param string $fname Caller name (usually __METHOD__)
1846 * @param callable $callback Callback that issues DB updates
1847 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a
1848 * savepoint and enable self::cancelAtomic() for this section.
1849 * @return mixed $res Result of the callback (since 1.28)
1850 * @throws DBError If an error occurs, see IDatabase::query()
1851 * @throws Exception If an error occurs in the callback
1852 * @since 1.27; prior to 1.31 this did a rollback() instead of
1853 * cancelAtomic(), and assumed no callers up the stack would ever try to
1854 * catch the exception.
1856 public function doAtomicSection(
1857 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
1861 * Begin a transaction
1863 * Only call this from code with outer transcation scope.
1864 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1865 * Nesting of transactions is not supported.
1867 * Note that when the DBO_TRX flag is set (which is usually the case for web
1868 * requests, but not for maintenance scripts), any previous database query
1869 * will have started a transaction automatically.
1871 * Nesting of transactions is not supported. Attempts to nest transactions
1872 * will cause a warning, unless the current transaction was started
1873 * automatically because of the DBO_TRX flag.
1875 * @param string $fname Calling function name
1876 * @param string $mode A situationally valid IDatabase::TRANSACTION_* constant [optional]
1877 * @throws DBError If an error occurs, see IDatabase::query()
1879 public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
);
1882 * Commits a transaction previously started using begin()
1884 * If no transaction is in progress, a warning is issued.
1886 * Only call this from code with outer transcation scope.
1887 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1888 * Nesting of transactions is not supported.
1890 * @param string $fname
1891 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_*
1892 * constant to disable warnings about explicitly committing implicit transactions,
1893 * or calling commit when no transaction is in progress.
1894 * This will trigger an exception if there is an ongoing explicit transaction.
1895 * Only set the flush flag if you are sure that these warnings are not applicable,
1896 * and no explicit transactions are open.
1897 * @throws DBError If an error occurs, see IDatabase::query()
1899 public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
);
1902 * Rollback a transaction previously started using begin()
1904 * Only call this from code with outer transcation scope.
1905 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1906 * Nesting of transactions is not supported. If a serious unexpected error occurs,
1907 * throwing an Exception is preferrable, using a pre-installed error handler to trigger
1908 * rollback (in any case, failure to issue COMMIT will cause rollback server-side).
1910 * Query, connection, and onTransaction* callback errors will be suppressed and logged.
1912 * @param string $fname Calling function name
1913 * @param string $flush Flush flag, set to a situationally valid IDatabase::FLUSHING_*
1914 * constant to disable warnings about calling rollback when no transaction is in
1915 * progress. This will silently break any ongoing explicit transaction. Only set the
1916 * flush flag if you are sure that it is safe to ignore these warnings in your context.
1917 * @throws DBError If an error occurs, see IDatabase::query()
1918 * @since 1.23 Added $flush parameter
1920 public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
);
1923 * Commit any transaction but error out if writes or callbacks are pending
1925 * This is intended for clearing out REPEATABLE-READ snapshots so that callers can
1926 * see a new point-in-time of the database. This is useful when one of many transaction
1927 * rounds finished and significant time will pass in the script's lifetime. It is also
1928 * useful to call on a replica DB after waiting on replication to catch up to the master.
1930 * @param string $fname Calling function name
1931 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_*
1932 * constant to disable warnings about explicitly committing implicit transactions,
1933 * or calling commit when no transaction is in progress.
1934 * This will trigger an exception if there is an ongoing explicit transaction.
1935 * Only set the flush flag if you are sure that these warnings are not applicable,
1936 * and no explicit transactions are open.
1937 * @throws DBError If an error occurs, see IDatabase::query()
1939 * @since 1.34 Added $flush parameter
1941 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
);
1944 * Convert a timestamp in one of the formats accepted by ConvertibleTimestamp
1945 * to the format used for inserting into timestamp fields in this DBMS
1947 * The result is unquoted, and needs to be passed through addQuotes()
1948 * before it can be included in raw SQL.
1950 * @param string|int $ts
1954 public function timestamp( $ts = 0 );
1957 * Convert a timestamp in one of the formats accepted by ConvertibleTimestamp
1958 * to the format used for inserting into timestamp fields in this DBMS
1960 * If NULL is input, it is passed through, allowing NULL values to be inserted
1961 * into timestamp fields.
1963 * The result is unquoted, and needs to be passed through addQuotes()
1964 * before it can be included in raw SQL.
1966 * @param string|int|null $ts
1970 public function timestampOrNull( $ts = null );
1973 * Ping the server and try to reconnect if it there is no connection
1975 * @param float|null &$rtt Value to store the estimated RTT [optional]
1976 * @return bool Success or failure
1978 public function ping( &$rtt = null );
1981 * Get the amount of replication lag for this database server
1983 * Callers should avoid using this method while a transaction is active
1985 * @return int|bool Database replication lag in seconds or false on error
1986 * @throws DBError If an error occurs, see IDatabase::query()
1988 public function getLag();
1991 * Get the replica DB lag when the current transaction started
1992 * or a general lag estimate if not transaction is active
1994 * This is useful when transactions might use snapshot isolation
1995 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
1996 * is this lag plus transaction duration. If they don't, it is still
1997 * safe to be pessimistic. In AUTOCOMMIT mode, this still gives an
1998 * indication of the staleness of subsequent reads.
2000 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2001 * @throws DBError If an error occurs, see IDatabase::query()
2004 public function getSessionLagStatus();
2007 * Return the maximum number of items allowed in a list, or 0 for unlimited
2011 public function maxListLen();
2014 * Some DBMSs have a special format for inserting into blob fields, they
2015 * don't allow simple quoted strings to be inserted. To insert into such
2016 * a field, pass the data through this function before passing it to
2017 * IDatabase::insert().
2020 * @return string|Blob
2023 public function encodeBlob( $b );
2026 * Some DBMSs return a special placeholder object representing blob fields
2027 * in result objects. Pass the object through this function to return the
2030 * @param string|Blob $b
2034 public function decodeBlob( $b );
2037 * Override database's default behavior. $options include:
2038 * 'connTimeout' : Set the connection timeout value in seconds.
2039 * May be useful for very long batch queries such as
2040 * full-wiki dumps, where a single query reads out over
2043 * @param array $options
2045 * @throws DBError If an error occurs, see IDatabase::query()
2047 public function setSessionOptions( array $options );
2050 * Set variables to be used in sourceFile/sourceStream, in preference to the
2051 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2052 * all. If it's set to false, $GLOBALS will be used.
2054 * @param bool|array $vars Mapping variable name to value.
2056 public function setSchemaVars( $vars );
2059 * Check to see if a named lock is not locked by any thread (non-blocking)
2061 * @param string $lockName Name of lock to poll
2062 * @param string $method Name of method calling us
2064 * @throws DBError If an error occurs, see IDatabase::query()
2067 public function lockIsFree( $lockName, $method );
2070 * Acquire a named lock
2072 * Named locks are not related to transactions
2074 * @param string $lockName Name of lock to aquire
2075 * @param string $method Name of the calling method
2076 * @param int $timeout Acquisition timeout in seconds (0 means non-blocking)
2077 * @return bool Success
2078 * @throws DBError If an error occurs, see IDatabase::query()
2080 public function lock( $lockName, $method, $timeout = 5 );
2085 * Named locks are not related to transactions
2087 * @param string $lockName Name of lock to release
2088 * @param string $method Name of the calling method
2089 * @return bool Success
2090 * @throws DBError If an error occurs, see IDatabase::query()
2092 public function unlock( $lockName, $method );
2095 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object
2097 * Only call this from outer transcation scope and when only one DB will be affected.
2098 * See https://www.mediawiki.org/wiki/Database_transactions for details.
2100 * This is suitiable for transactions that need to be serialized using cooperative locks,
2101 * where each transaction can see each others' changes. Any transaction is flushed to clear
2102 * out stale REPEATABLE-READ snapshot data. Once the returned object falls out of PHP scope,
2103 * the lock will be released unless a transaction is active. If one is active, then the lock
2104 * will be released when it either commits or rolls back.
2106 * If the lock acquisition failed, then no transaction flush happens, and null is returned.
2108 * @param string $lockKey Name of lock to release
2109 * @param string $fname Name of the calling method
2110 * @param int $timeout Acquisition timeout in seconds
2111 * @return ScopedCallback|null
2112 * @throws DBError If an error occurs, see IDatabase::query()
2115 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
2118 * Check to see if a named lock used by lock() use blocking queues
2123 public function namedLocksEnqueue();
2126 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2127 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2128 * because "i" sorts after all numbers.
2132 public function getInfinity();
2135 * Encode an expiry time into the DBMS dependent format
2137 * @param string $expiry Timestamp for expiry, or the 'infinity' string
2140 public function encodeExpiry( $expiry );
2143 * Decode an expiry time into a DBMS independent format
2145 * @param string $expiry DB timestamp field value for expiry
2146 * @param int $format TS_* constant, defaults to TS_MW
2149 public function decodeExpiry( $expiry, $format = TS_MW
);
2152 * Allow or deny "big selects" for this session only. This is done by setting
2153 * the sql_big_selects session variable.
2155 * This is a MySQL-specific feature.
2157 * @param bool|string $value True for allow, false for deny, or "default" to
2158 * restore the initial value
2160 public function setBigSelects( $value = true );
2163 * @return bool Whether this DB is read-only
2166 public function isReadOnly();
2169 * Make certain table names use their own database, schema, and table prefix
2170 * when passed into SQL queries pre-escaped and without a qualified database name
2172 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
2173 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
2175 * Calling this twice will completely clear any old table aliases. Also, note that
2176 * callers are responsible for making sure the schemas and databases actually exist.
2178 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
2181 public function setTableAliases( array $aliases );
2184 * Convert certain index names to alternative names before querying the DB
2186 * Note that this applies to indexes regardless of the table they belong to.
2188 * This can be employed when an index was renamed X => Y in code, but the new Y-named
2189 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
2190 * the aliases can be removed, and then the old X-named indexes dropped.
2192 * @param string[] $aliases
2195 public function setIndexAliases( array $aliases );
2198 * Get a debugging string that mentions the database type, the ID of this instance,
2199 * and the ID of any underlying connection resource or driver object if one is present
2201 * @return string "<db type> object #<X>" or "<db type> object #<X> (resource/handle id #<Y>)"
2204 public function __toString();
2208 * @deprecated since 1.29
2210 class_alias( IDatabase
::class, 'IDatabase' );