Fix use of GenderCache in ApiPageSet::processTitlesArray
[lhc/web/wiklou.git] / includes / libs / rdbms / database / IDatabase.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20 namespace Wikimedia\Rdbms;
21
22 use InvalidArgumentException;
23 use Wikimedia\ScopedCallback;
24 use Exception;
25 use stdClass;
26
27 /**
28 * @defgroup Database Database
29 * This group deals with database interface functions
30 * and query specifics/optimisations.
31 */
32 /**
33 * Basic database interface for live and lazy-loaded relation database handles
34 *
35 * @note IDatabase and DBConnRef should be updated to reflect any changes
36 * @ingroup Database
37 */
38 interface IDatabase {
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;
47
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';
52
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';
57
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';
64
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';
73
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';
78
79 /** @var int Combine list with comma delimeters */
80 const LIST_COMMA = 0;
81 /** @var int Combine list with AND clauses */
82 const LIST_AND = 1;
83 /** @var int Convert map into a SET clause */
84 const LIST_SET = 2;
85 /** @var int Treat as field name and do not apply value escaping */
86 const LIST_NAMES = 3;
87 /** @var int Combine list with OR clauses */
88 const LIST_OR = 4;
89
90 /** @var int Enable debug logging of all SQL queries */
91 const DBO_DEBUG = 1;
92 /** @var int Unused since 1.34 */
93 const DBO_NOBUFFER = 2;
94 /** @var int Unused since 1.31 */
95 const DBO_IGNORE = 4;
96 /** @var int Automatically start a transaction before running a query if none is active */
97 const DBO_TRX = 8;
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 */
107 const DBO_SSL = 256;
108 /** @var int Enable compression in connection protocol */
109 const DBO_COMPRESS = 512;
110
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
115 /**
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.
118 */
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;
126
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;
131
132 /**
133 * Get a human-readable string describing the current software version
134 *
135 * Use getServerVersion() to get machine-friendly information.
136 *
137 * @return string Version information from the database server
138 */
139 public function getServerInfo();
140
141 /**
142 * Gets the current transaction level.
143 *
144 * Historically, transactions were allowed to be "nested". This is no
145 * longer supported, so this function really only returns a boolean.
146 *
147 * @return int The previous value
148 */
149 public function trxLevel();
150
151 /**
152 * Get the UNIX timestamp of the time that the transaction was established
153 *
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).
158 *
159 * @return float|null Returns null if there is not active transaction
160 * @since 1.25
161 */
162 public function trxTimestamp();
163
164 /**
165 * @return bool Whether an explicit transaction or atomic sections are still open
166 * @since 1.28
167 */
168 public function explicitTrxActive();
169
170 /**
171 * Assert that all explicit transactions or atomic sections have been closed
172 *
173 * @throws DBTransactionError
174 * @since 1.32
175 */
176 public function assertNoOpenTransactions();
177
178 /**
179 * Get/set the table prefix
180 *
181 * @param string|null $prefix The table prefix to set, or omitted to leave it unchanged
182 * @return string The previous table prefix
183 */
184 public function tablePrefix( $prefix = null );
185
186 /**
187 * Get/set the db schema
188 *
189 * @param string|null $schema The database schema to set, or omitted to leave it unchanged
190 * @return string The previous db schema
191 */
192 public function dbSchema( $schema = null );
193
194 /**
195 * Get properties passed down from the server info array of the load balancer
196 *
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
199 */
200 public function getLBInfo( $name = null );
201
202 /**
203 * Set the entire array or a particular key of the managing load balancer info array
204 *
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)
207 */
208 public function setLBInfo( $nameOrArray, $value = null );
209
210 /**
211 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
212 *
213 * @param IDatabase $conn
214 * @since 1.27
215 */
216 public function setLazyMasterHandle( IDatabase $conn );
217
218 /**
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
221 *
222 * @return bool
223 */
224 public function implicitOrderby();
225
226 /**
227 * Get the last query that sent on account of IDatabase::query()
228 *
229 * @return string SQL text or empty string if there was no such query
230 */
231 public function lastQuery();
232
233 /**
234 * Get the last time the connection may have been used for a write query
235 *
236 * @return int|float UNIX timestamp or false
237 * @since 1.24
238 */
239 public function lastDoneWrites();
240
241 /**
242 * @return bool Whether there is a transaction open with possible write queries
243 * @since 1.27
244 */
245 public function writesPending();
246
247 /**
248 * @return bool Whether there is a transaction open with pre-commit callbacks pending
249 * @since 1.32
250 */
251 public function preCommitCallbacksPending();
252
253 /**
254 * Whether there is a transaction open with either possible write queries
255 * or unresolved pre-commit/commit/resolution callbacks pending
256 *
257 * This does *not* count recurring callbacks, e.g. from setTransactionListener().
258 *
259 * @return bool
260 */
261 public function writesOrCallbacksPending();
262
263 /**
264 * Get the time spend running write queries for this transaction
265 *
266 * High values could be due to scanning, updates, locking, and such.
267 *
268 * @param string $type IDatabase::ESTIMATE_* constant [default: ESTIMATE_ALL]
269 * @return float|bool Returns false if not transaction is active
270 * @since 1.26
271 */
272 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL );
273
274 /**
275 * Get the list of method names that did write queries for this transaction
276 *
277 * @return array
278 * @since 1.27
279 */
280 public function pendingWriteCallers();
281
282 /**
283 * Get the number of affected rows from pending write queries
284 *
285 * @return int
286 * @since 1.30
287 */
288 public function pendingWriteRowsAffected();
289
290 /**
291 * @return bool Whether a connection to the database open
292 */
293 public function isOpen();
294
295 /**
296 * Set a flag for this connection
297 *
298 * @param int $flag One of (IDatabase::DBO_DEBUG, IDatabase::DBO_TRX)
299 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
300 */
301 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING );
302
303 /**
304 * Clear a flag for this connection
305 *
306 * @param int $flag One of (IDatabase::DBO_DEBUG, IDatabase::DBO_TRX)
307 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
308 */
309 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING );
310
311 /**
312 * Restore the flags to their prior state before the last setFlag/clearFlag call
313 *
314 * @param string $state IDatabase::RESTORE_* constant. [default: RESTORE_PRIOR]
315 * @since 1.28
316 */
317 public function restoreFlags( $state = self::RESTORE_PRIOR );
318
319 /**
320 * Returns a boolean whether the flag $flag is set for this connection
321 *
322 * @param int $flag One of the class IDatabase::DBO_* constants
323 * @return bool
324 */
325 public function getFlag( $flag );
326
327 /**
328 * Return the currently selected domain ID
329 *
330 * Null components (database/schema) might change once a connection is established
331 *
332 * @return string
333 */
334 public function getDomainID();
335
336 /**
337 * Get the type of the DBMS (e.g. "mysql", "sqlite")
338 *
339 * @return string
340 */
341 public function getType();
342
343 /**
344 * Fetch the next row from the given result object, in object form
345 *
346 * Fields can be retrieved with $row->fieldname, with fields acting like
347 * member variables. If no more rows are available, false is returned.
348 *
349 * @param IResultWrapper|stdClass $res Object as returned from IDatabase::query(), etc.
350 * @return stdClass|bool
351 */
352 public function fetchObject( $res );
353
354 /**
355 * Fetch the next row from the given result object, in associative array form
356 *
357 * Fields are retrieved with $row['fieldname'].
358 * If no more rows are available, false is returned.
359 *
360 * @param IResultWrapper $res Result object as returned from IDatabase::query(), etc.
361 * @return array|bool
362 */
363 public function fetchRow( $res );
364
365 /**
366 * Get the number of rows in a query result
367 *
368 * Returns zero if the query did not return any rows or was a write query.
369 *
370 * @param mixed $res A SQL result
371 * @return int
372 */
373 public function numRows( $res );
374
375 /**
376 * Get the number of fields in a result object
377 * @see https://www.php.net/mysql_num_fields
378 *
379 * @param mixed $res A SQL result
380 * @return int
381 */
382 public function numFields( $res );
383
384 /**
385 * Get a field name in a result object
386 * @see https://www.php.net/mysql_field_name
387 *
388 * @param mixed $res A SQL result
389 * @param int $n
390 * @return string
391 */
392 public function fieldName( $res, $n );
393
394 /**
395 * Get the inserted value of an auto-increment row
396 *
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.
400 *
401 * @return int
402 */
403 public function insertId();
404
405 /**
406 * Change the position of the cursor in a result object
407 * @see https://www.php.net/mysql_data_seek
408 *
409 * @param mixed $res A SQL result
410 * @param int $row
411 */
412 public function dataSeek( $res, $row );
413
414 /**
415 * Get the last error number
416 * @see https://www.php.net/mysql_errno
417 *
418 * @return int
419 */
420 public function lastErrno();
421
422 /**
423 * Get a description of the last error
424 * @see https://www.php.net/mysql_error
425 *
426 * @return string
427 */
428 public function lastError();
429
430 /**
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.
435 *
436 * @return int
437 */
438 public function affectedRows();
439
440 /**
441 * Returns a wikitext style link to the DB's website (e.g. "[https://www.mysql.com/ MySQL]")
442 *
443 * Should at least contain plain text, if for some reason your database has no website.
444 *
445 * @return string Wikitext of a link to the server software's web site
446 */
447 public function getSoftwareLink();
448
449 /**
450 * A string describing the current software version, like from mysql_get_server_info()
451 *
452 * @return string Version information from the database server.
453 */
454 public function getServerVersion();
455
456 /**
457 * Close the database connection
458 *
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.
462 *
463 * @return bool Success
464 * @throws DBError
465 */
466 public function close();
467
468 /**
469 * Run an SQL query and return the result
470 *
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.
474 *
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
480 * as CREATE TABLE.
481 *
482 * However, the query wrappers themselves should call this function.
483 *
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)
494 */
495 public function query( $sql, $fname = __METHOD__, $flags = 0 );
496
497 /**
498 * Free a result object returned by query() or select()
499 *
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.
502 *
503 * @param mixed $res A SQL result
504 */
505 public function freeResult( $res );
506
507 /**
508 * A SELECT wrapper which returns a single field from a single result row
509 *
510 * If no result rows are returned from the query, false is returned.
511 *
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()
521 */
522 public function selectField(
523 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
524 );
525
526 /**
527 * A SELECT wrapper which returns a list of single field values from result rows
528 *
529 * If no result rows are returned from the query, false is returned.
530 *
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.
538 *
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()
541 * @since 1.25
542 */
543 public function selectFieldValues(
544 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
545 );
546
547 /**
548 * Execute a SELECT query constructed using the various parameters provided
549 *
550 * @param string|array $table Table name(s)
551 *
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:
554 *
555 * [ 'a' => 'user' ]
556 *
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).
559 *
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:
562 *
563 * [ 'c' => new Subquery( 'SELECT ...' ) ]
564 *
565 * Joins using parentheses for grouping (since MediaWiki 1.31) may be
566 * constructed using nested arrays. For example,
567 *
568 * [ 'tableA', 'nestedB' => [ 'tableB', 'b2' => 'tableB2' ] ]
569 *
570 * along with `$join_conds` like
571 *
572 * [ 'b2' => [ 'JOIN', 'b_id = b2_id' ], 'nestedB' => [ 'LEFT JOIN', 'b_a = a_id' ] ]
573 *
574 * will produce SQL something like
575 *
576 * FROM tableA LEFT JOIN (tableB JOIN tableB2 AS b2 ON (b_id = b2_id)) ON (b_a = a_id)
577 *
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.
581 *
582 * Do not use untrusted user input as a table name. Alias names should
583 * not have characters outside of the Basic multilingual plane.
584 *
585 * @param string|array $vars Field name(s)
586 *
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:
590 *
591 * [ 'maxrev' => 'MAX(rev_id)' ]
592 *
593 * This includes an expression with the alias "maxrev" in the query.
594 *
595 * If an expression is given, care must be taken to ensure that it is
596 * DBMS-independent.
597 *
598 * Untrusted user input must not be passed to this parameter.
599 *
600 * @param string|array $conds
601 *
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.
605 *
606 * Array elements may take one of two forms:
607 *
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.
618 *
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()
624 *
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()
629 *
630 * Use an empty array, string, or '*' to update all rows.
631 *
632 * @param string $fname Caller function name
633 *
634 * @param string|array $options Query options
635 *
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
638 * example:
639 *
640 * [ 'FOR UPDATE' ]
641 *
642 * The supported options are:
643 *
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.
647 *
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.
651 *
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).
655 *
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).
659 *
660 * - DISTINCT: Boolean: return only unique result rows.
661 *
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.
664 *
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.
668 *
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.
671 *
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.
677 *
678 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
679 * instead of SELECT.
680 *
681 * And also the following boolean MySQL extensions, see the MySQL manual
682 * for documentation:
683 *
684 * - STRAIGHT_JOIN
685 * - SQL_BIG_RESULT
686 * - SQL_BUFFER_RESULT
687 * - SQL_SMALL_RESULT
688 * - SQL_CALC_FOUND_ROWS
689 *
690 * @param string|array $join_conds Join conditions
691 *
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.
695 *
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:
701 *
702 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
703 *
704 * @return IResultWrapper Resulting rows
705 * @throws DBError If an error occurs, see IDatabase::query()
706 */
707 public function select(
708 $table,
709 $vars,
710 $conds = '',
711 $fname = __METHOD__,
712 $options = [],
713 $join_conds = []
714 );
715
716 /**
717 * Take the same arguments as IDatabase::select() and return the SQL it would use
718 *
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
721 * use select().
722 *
723 * @see IDatabase::select()
724 *
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
732 */
733 public function selectSQLText(
734 $table,
735 $vars,
736 $conds = '',
737 $fname = __METHOD__,
738 $options = [],
739 $join_conds = []
740 );
741
742 /**
743 * Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
744 *
745 * If the query returns no rows, false is returned.
746 *
747 * This method is convenient for fetching a row based on a unique key condition.
748 *
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()
757 */
758 public function selectRow(
759 $table,
760 $vars,
761 $conds,
762 $fname = __METHOD__,
763 $options = [],
764 $join_conds = []
765 );
766
767 /**
768 * Estimate the number of rows in dataset
769 *
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.
774 *
775 * For DBMSs that don't support fast result size estimation, this function
776 * will actually perform the SELECT COUNT(*).
777 *
778 * Takes the same arguments as IDatabase::select().
779 *
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()
788 */
789 public function estimateRowCount(
790 $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
791 );
792
793 /**
794 * Get the number of rows in dataset
795 *
796 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
797 *
798 * Takes the same arguments as IDatabase::select().
799 *
800 * @since 1.27 Added $join_conds parameter
801 *
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()
810 */
811 public function selectRowCount(
812 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
813 );
814
815 /**
816 * Lock all rows meeting the given conditions/options FOR UPDATE
817 *
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()
825 * @since 1.32
826 */
827 public function lockForUpdate(
828 $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
829 );
830
831 /**
832 * Determines whether a field exists in a table
833 *
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()
839 */
840 public function fieldExists( $table, $field, $fname = __METHOD__ );
841
842 /**
843 * Determines whether an index exists
844 *
845 * @param string $table
846 * @param string $index
847 * @param string $fname
848 * @return bool|null
849 * @throws DBError If an error occurs, see IDatabase::query()
850 */
851 public function indexExists( $table, $index, $fname = __METHOD__ );
852
853 /**
854 * Query whether a given table exists
855 *
856 * @param string $table
857 * @param string $fname
858 * @return bool
859 * @throws DBError If an error occurs, see IDatabase::query()
860 */
861 public function tableExists( $table, $fname = __METHOD__ );
862
863 /**
864 * INSERT wrapper, inserts an array into a table
865 *
866 * $a may be either:
867 *
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.
875 *
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:
879 *
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().
884 *
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()
892 */
893 public function insert( $table, $a, $fname = __METHOD__, $options = [] );
894
895 /**
896 * UPDATE wrapper. Takes a condition array and a SET array.
897 *
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()
914 */
915 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] );
916
917 /**
918 * Makes an encoded list of strings from an array
919 *
920 * These can be used to make conjunctions or disjunctions on SQL condition strings
921 * derived from an array (see IDatabase::select() $conds documentation).
922 *
923 * Example usage:
924 * @code
925 * $sql = $db->makeList( [
926 * 'rev_page' => $id,
927 * $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] )
928 * ], $db::LIST_AND );
929 * @endcode
930 * This would set $sql to "rev_page = '$id' AND (rev_minor = '1' OR rev_len < '500')"
931 *
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()
940 * @return string
941 */
942 public function makeList( $a, $mode = self::LIST_COMMA );
943
944 /**
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.
947 *
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
953 */
954 public function makeWhereFrom2d( $data, $baseKey, $subKey );
955
956 /**
957 * Return aggregated value alias
958 *
959 * @param array $valuedata
960 * @param string $valuename
961 *
962 * @return array|string
963 * @deprecated Since 1.33
964 */
965 public function aggregateValue( $valuedata, $valuename = 'value' );
966
967 /**
968 * @param string $field
969 * @return string
970 */
971 public function bitNot( $field );
972
973 /**
974 * @param string $fieldLeft
975 * @param string $fieldRight
976 * @return string
977 */
978 public function bitAnd( $fieldLeft, $fieldRight );
979
980 /**
981 * @param string $fieldLeft
982 * @param string $fieldRight
983 * @return string
984 */
985 public function bitOr( $fieldLeft, $fieldRight );
986
987 /**
988 * Build a concatenation list to feed into a SQL query
989 * @param string[] $stringList Raw SQL expression list; caller is responsible for escaping
990 * @return string
991 */
992 public function buildConcat( $stringList );
993
994 /**
995 * Build a GROUP_CONCAT or equivalent statement for a query.
996 *
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.
1001 *
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
1008 * @since 1.23
1009 */
1010 public function buildGroupConcatField(
1011 $delim, $table, $field, $conds = '', $join_conds = []
1012 );
1013
1014 /**
1015 * Build a SUBSTRING function
1016 *
1017 * Behavior for non-ASCII values is undefined.
1018 *
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
1024 * @since 1.31
1025 */
1026 public function buildSubString( $input, $startPosition, $length = null );
1027
1028 /**
1029 * @param string $field Field or column to cast
1030 * @return string
1031 * @since 1.28
1032 */
1033 public function buildStringCast( $field );
1034
1035 /**
1036 * @param string $field Field or column to cast
1037 * @return string
1038 * @since 1.31
1039 */
1040 public function buildIntegerCast( $field );
1041
1042 /**
1043 * Equivalent to IDatabase::selectSQLText() except wraps the result in Subqyery
1044 *
1045 * @see IDatabase::selectSQLText()
1046 *
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
1053 * @return Subquery
1054 * @since 1.31
1055 */
1056 public function buildSelectSubquery(
1057 $table,
1058 $vars,
1059 $conds = '',
1060 $fname = __METHOD__,
1061 $options = [],
1062 $join_conds = []
1063 );
1064
1065 /**
1066 * Construct a LIMIT query with optional offset
1067 *
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.
1073 *
1074 * $sql is expected to be a SELECT, if that makes a difference.
1075 *
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)
1079 * @return string
1080 * @since 1.34
1081 */
1082 public function limitResult( $sql, $limit, $offset = false );
1083
1084 /**
1085 * Returns true if DBs are assumed to be on potentially different servers
1086 *
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.
1091 *
1092 * @return bool
1093 * @since 1.29
1094 */
1095 public function databasesAreIndependent();
1096
1097 /**
1098 * Change the current database
1099 *
1100 * This should only be called by a load balancer or if the handle is not attached to one
1101 *
1102 * @param string $db
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
1107 */
1108 public function selectDB( $db );
1109
1110 /**
1111 * Set the current domain (database, schema, and table prefix)
1112 *
1113 * This will throw an error for some database types if the database is unspecified
1114 *
1115 * This should only be called by a load balancer or if the handle is not attached to one
1116 *
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
1120 * @since 1.32
1121 */
1122 public function selectDomain( $domain );
1123
1124 /**
1125 * Get the current DB name
1126 * @return string|null
1127 */
1128 public function getDBname();
1129
1130 /**
1131 * Get the server hostname or IP address
1132 * @return string
1133 */
1134 public function getServer();
1135
1136 /**
1137 * Escape and quote a raw value string for use in a SQL query
1138 *
1139 * @param string|int|null|bool|Blob $s
1140 * @return string|int
1141 */
1142 public function addQuotes( $s );
1143
1144 /**
1145 * Escape a SQL identifier (e.g. table, column, database) for use in a SQL query
1146 *
1147 * Depending on the database this will either be `backticks` or "double quotes"
1148 *
1149 * @param string $s
1150 * @return string
1151 * @since 1.33
1152 */
1153 public function addIdentifierQuotes( $s );
1154
1155 /**
1156 * LIKE statement wrapper
1157 *
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.
1162 *
1163 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
1164 * a LIKE clause that searches for subpages of 'My page title'.
1165 * Alternatively:
1166 * $pattern = [ 'My_page_title/', $dbr->anyString() ];
1167 * $query .= $dbr->buildLike( $pattern );
1168 *
1169 * @since 1.16
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
1174 */
1175 public function buildLike( $param );
1176
1177 /**
1178 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1179 *
1180 * @return LikeMatch
1181 */
1182 public function anyChar();
1183
1184 /**
1185 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1186 *
1187 * @return LikeMatch
1188 */
1189 public function anyString();
1190
1191 /**
1192 * Deprecated method, calls should be removed
1193 *
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
1197 * `lastval()`
1198 *
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.
1202 *
1203 * @deprecated since 1.30, no longer needed
1204 * @param string $seqName
1205 * @return null|NextSequenceValue
1206 */
1207 public function nextSequenceValue( $seqName );
1208
1209 /**
1210 * REPLACE query wrapper
1211 *
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.
1215 *
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.
1219 *
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.
1223 *
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()
1233 */
1234 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ );
1235
1236 /**
1237 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
1238 *
1239 * This updates any conflicting rows (according to the unique indexes) using
1240 * the provided SET clause and inserts any remaining (non-conflicted) rows.
1241 *
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.
1250 *
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.
1254 *
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()
1269 * @since 1.22
1270 */
1271 public function upsert(
1272 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1273 );
1274
1275 /**
1276 * DELETE where the condition is a join.
1277 *
1278 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
1279 * we use sub-selects
1280 *
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='*'.
1283 *
1284 * DO NOT put the join condition in $conds.
1285 *
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()
1294 */
1295 public function deleteJoin(
1296 $delTable,
1297 $joinTable,
1298 $delVar,
1299 $joinVar,
1300 $conds,
1301 $fname = __METHOD__
1302 );
1303
1304 /**
1305 * DELETE query wrapper
1306 *
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()
1313 */
1314 public function delete( $table, $conds, $fname = __METHOD__ );
1315
1316 /**
1317 * INSERT SELECT wrapper
1318 *
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.
1323 *
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
1333 * whole table.
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()
1345 */
1346 public function insertSelect(
1347 $destTable,
1348 $srcTable,
1349 $varMap,
1350 $conds,
1351 $fname = __METHOD__,
1352 $insertOptions = [],
1353 $selectOptions = [],
1354 $selectJoinConds = []
1355 );
1356
1357 /**
1358 * Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION
1359 *
1360 * @return bool
1361 */
1362 public function unionSupportsOrderAndLimit();
1363
1364 /**
1365 * Construct a UNION query
1366 *
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
1372 */
1373 public function unionQueries( $sqls, $all );
1374
1375 /**
1376 * Construct a UNION query for permutations of conditions
1377 *
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.
1382 *
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
1388 * field.
1389 * @param string|array $extra_conds Additional conditions to include in the
1390 * query.
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.
1399 * @since 1.30
1400 */
1401 public function unionConditionPermutations(
1402 $table,
1403 $vars,
1404 array $permute_conds,
1405 $extra_conds = '',
1406 $fname = __METHOD__,
1407 $options = [],
1408 $join_conds = []
1409 );
1410
1411 /**
1412 * Returns an SQL expression for a simple conditional
1413 *
1414 * This doesn't need to be overridden unless CASE isn't supported in the RDBMS.
1415 *
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
1420 */
1421 public function conditional( $cond, $trueVal, $falseVal );
1422
1423 /**
1424 * Returns a SQL expression for simple string replacement (e.g. REPLACE() in mysql)
1425 *
1426 * @param string $orig Column to modify
1427 * @param string $old Column to seek
1428 * @param string $new Column to replace with
1429 * @return string
1430 */
1431 public function strreplace( $orig, $old, $new );
1432
1433 /**
1434 * Determines how long the server has been up
1435 *
1436 * @return int
1437 * @throws DBError
1438 */
1439 public function getServerUptime();
1440
1441 /**
1442 * Determines if the last failure was due to a deadlock
1443 *
1444 * Note that during a deadlock, the prior transaction will have been lost
1445 *
1446 * @return bool
1447 */
1448 public function wasDeadlock();
1449
1450 /**
1451 * Determines if the last failure was due to a lock timeout
1452 *
1453 * Note that during a lock wait timeout, the prior transaction will have been lost
1454 *
1455 * @return bool
1456 */
1457 public function wasLockTimeout();
1458
1459 /**
1460 * Determines if the last query error was due to a dropped connection
1461 *
1462 * Note that during a connection loss, the prior transaction will have been lost
1463 *
1464 * @return bool
1465 * @since 1.31
1466 */
1467 public function wasConnectionLoss();
1468
1469 /**
1470 * Determines if the last failure was due to the database being read-only
1471 *
1472 * @return bool
1473 */
1474 public function wasReadOnlyError();
1475
1476 /**
1477 * Determines if the last query error was due to something outside of the query itself
1478 *
1479 * Note that the transaction may have been lost, discarding prior writes and results
1480 *
1481 * @return bool
1482 */
1483 public function wasErrorReissuable();
1484
1485 /**
1486 * Wait for the replica DB to catch up to a given master position
1487 *
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.
1491 *
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()
1498 */
1499 public function masterPosWait( DBMasterPos $pos, $timeout );
1500
1501 /**
1502 * Get the replication position of this replica DB
1503 *
1504 * @return DBMasterPos|bool False if this is not a replica DB
1505 * @throws DBError If an error occurs, see IDatabase::query()
1506 */
1507 public function getReplicaPos();
1508
1509 /**
1510 * Get the position of this master
1511 *
1512 * @return DBMasterPos|bool False if this is not a master
1513 * @throws DBError If an error occurs, see IDatabase::query()
1514 */
1515 public function getMasterPos();
1516
1517 /**
1518 * @return bool Whether the DB is marked as read-only server-side
1519 * @since 1.28
1520 */
1521 public function serverIsReadOnly();
1522
1523 /**
1524 * Run a callback as soon as the current transaction commits or rolls back
1525 *
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
1528 * that they begin.
1529 *
1530 * This is useful for combining cooperative locks and DB transactions.
1531 *
1532 * Note this is called when the whole transaction is resolved. To take action immediately
1533 * when an atomic section is cancelled, use onAtomicSectionCancel().
1534 *
1535 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1536 *
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)
1540 *
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
1545 * @since 1.28
1546 */
1547 public function onTransactionResolution( callable $callback, $fname = __METHOD__ );
1548
1549 /**
1550 * Run a callback as soon as there is no transaction pending
1551 *
1552 * If there is a transaction and it is rolled back, then the callback is cancelled.
1553 *
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.
1557 *
1558 * Queries in the function will run in AUTOCOMMIT mode unless there are begin() calls.
1559 * Callbacks must commit any transactions that they begin.
1560 *
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.
1566 *
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.
1569 *
1570 * Updates will execute in the order they were enqueued.
1571 *
1572 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1573 *
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)
1577 *
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
1582 * @since 1.32
1583 */
1584 public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ );
1585
1586 /**
1587 * Alias for onTransactionCommitOrIdle() for backwards-compatibility
1588 *
1589 * @param callable $callback
1590 * @param string $fname
1591 * @since 1.20
1592 * @deprecated Since 1.32
1593 */
1594 public function onTransactionIdle( callable $callback, $fname = __METHOD__ );
1595
1596 /**
1597 * Run a callback before the current transaction commits or now if there is none
1598 *
1599 * If there is a transaction and it is rolled back, then the callback is cancelled.
1600 *
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.
1604 *
1605 * Callbacks must not start nor commit any transactions. If no transaction is active,
1606 * then a transaction will wrap the callback.
1607 *
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.
1610 *
1611 * Updates will execute in the order they were enqueued.
1612 *
1613 * The callback takes the one argument:
1614 * - This IDatabase instance (since 1.32)
1615 *
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
1620 * @since 1.22
1621 */
1622 public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ );
1623
1624 /**
1625 * Run a callback when the atomic section is cancelled
1626 *
1627 * The callback is run just after the current atomic section, any outer
1628 * atomic section, or the whole transaction is rolled back.
1629 *
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.
1632 *
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.
1636 *
1637 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1638 *
1639 * The callback takes the following arguments:
1640 * - IDatabase::TRIGGER_CANCEL or IDatabase::TRIGGER_ROLLBACK
1641 * - This IDatabase instance
1642 *
1643 * @param callable $callback
1644 * @param string $fname Caller name
1645 * @since 1.34
1646 */
1647 public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ );
1648
1649 /**
1650 * Run a callback after each time any transaction commits or rolls back
1651 *
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.
1656 *
1657 * Registering a callback here will not affect writesOrCallbacks() pending.
1658 *
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.
1661 *
1662 * @param string $name Callback name
1663 * @param callable|null $callback Use null to unset a listener
1664 * @since 1.28
1665 */
1666 public function setTransactionListener( $name, callable $callback = null );
1667
1668 /**
1669 * Begin an atomic section of SQL statements
1670 *
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.
1678 *
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
1687 *
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.
1691 *
1692 * Example usage:
1693 * @code
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__ );
1705 * @endcode
1706 *
1707 * Example usage (atomic changes that might have to be discarded):
1708 * @code
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 ] );
1723 * }
1724 * },
1725 * __METHOD__
1726 * );
1727 * // Demark the end of this conceptual unit of updates
1728 * $dbw->endAtomic( __METHOD__ );
1729 * } else {
1730 * // Discard these writes from the transaction (preserving prior writes)
1731 * $dbw->cancelAtomic( __METHOD__, $sectionId );
1732 * }
1733 * @endcode
1734 *
1735 * @since 1.23
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()
1741 */
1742 public function startAtomic( $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE );
1743
1744 /**
1745 * Ends an atomic section of SQL statements
1746 *
1747 * Ends the next section of atomic SQL statements and commits the transaction
1748 * if necessary.
1749 *
1750 * @since 1.23
1751 * @see IDatabase::startAtomic
1752 * @param string $fname
1753 * @throws DBError If an error occurs, see IDatabase::query()
1754 */
1755 public function endAtomic( $fname = __METHOD__ );
1756
1757 /**
1758 * Cancel an atomic section of SQL statements
1759 *
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.
1766 *
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.
1770 *
1771 * Note that a call to IDatabase::rollback() will also roll back any open atomic sections.
1772 *
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.
1775 * @since 1.31
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()
1781 */
1782 public function cancelAtomic( $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null );
1783
1784 /**
1785 * Perform an atomic section of reversable SQL statements from a callback
1786 *
1787 * The $callback takes the following arguments:
1788 * - This database object
1789 * - The value of $fname
1790 *
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.
1800 *
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().
1805 *
1806 * Example usage, "RecordStore::save" method:
1807 * @code
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 );
1821 * }
1822 * },
1823 * __METHOD__
1824 * );
1825 * }, $dbw::ATOMIC_CANCELABLE );
1826 * @endcode
1827 *
1828 * Example usage, caller of the "RecordStore::save" method:
1829 * @code
1830 * $dbw->startAtomic( __METHOD__ );
1831 * // ...various SQL writes happen...
1832 * try {
1833 * $recordStore->save( $record );
1834 * } catch ( StoreFailureException $e ) {
1835 * // ...various SQL writes happen...
1836 * }
1837 * // ...various SQL writes happen...
1838 * $dbw->endAtomic( __METHOD__ );
1839 * @endcode
1840 *
1841 * @see Database::startAtomic
1842 * @see Database::endAtomic
1843 * @see Database::cancelAtomic
1844 *
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.
1855 */
1856 public function doAtomicSection(
1857 $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
1858 );
1859
1860 /**
1861 * Begin a transaction
1862 *
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.
1866 *
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.
1870 *
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.
1874 *
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()
1878 */
1879 public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT );
1880
1881 /**
1882 * Commits a transaction previously started using begin()
1883 *
1884 * If no transaction is in progress, a warning is issued.
1885 *
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.
1889 *
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()
1898 */
1899 public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1900
1901 /**
1902 * Rollback a transaction previously started using begin()
1903 *
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).
1909 *
1910 * Query, connection, and onTransaction* callback errors will be suppressed and logged.
1911 *
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
1919 */
1920 public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1921
1922 /**
1923 * Commit any transaction but error out if writes or callbacks are pending
1924 *
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.
1929 *
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()
1938 * @since 1.28
1939 * @since 1.34 Added $flush parameter
1940 */
1941 public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE );
1942
1943 /**
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
1946 *
1947 * The result is unquoted, and needs to be passed through addQuotes()
1948 * before it can be included in raw SQL.
1949 *
1950 * @param string|int $ts
1951 *
1952 * @return string
1953 */
1954 public function timestamp( $ts = 0 );
1955
1956 /**
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
1959 *
1960 * If NULL is input, it is passed through, allowing NULL values to be inserted
1961 * into timestamp fields.
1962 *
1963 * The result is unquoted, and needs to be passed through addQuotes()
1964 * before it can be included in raw SQL.
1965 *
1966 * @param string|int|null $ts
1967 *
1968 * @return string
1969 */
1970 public function timestampOrNull( $ts = null );
1971
1972 /**
1973 * Ping the server and try to reconnect if it there is no connection
1974 *
1975 * @param float|null &$rtt Value to store the estimated RTT [optional]
1976 * @return bool Success or failure
1977 */
1978 public function ping( &$rtt = null );
1979
1980 /**
1981 * Get the amount of replication lag for this database server
1982 *
1983 * Callers should avoid using this method while a transaction is active
1984 *
1985 * @return int|bool Database replication lag in seconds or false on error
1986 * @throws DBError If an error occurs, see IDatabase::query()
1987 */
1988 public function getLag();
1989
1990 /**
1991 * Get the replica DB lag when the current transaction started
1992 * or a general lag estimate if not transaction is active
1993 *
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.
1999 *
2000 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2001 * @throws DBError If an error occurs, see IDatabase::query()
2002 * @since 1.27
2003 */
2004 public function getSessionLagStatus();
2005
2006 /**
2007 * Return the maximum number of items allowed in a list, or 0 for unlimited
2008 *
2009 * @return int
2010 */
2011 public function maxListLen();
2012
2013 /**
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().
2018 *
2019 * @param string $b
2020 * @return string|Blob
2021 * @throws DBError
2022 */
2023 public function encodeBlob( $b );
2024
2025 /**
2026 * Some DBMSs return a special placeholder object representing blob fields
2027 * in result objects. Pass the object through this function to return the
2028 * original string.
2029 *
2030 * @param string|Blob $b
2031 * @return string
2032 * @throws DBError
2033 */
2034 public function decodeBlob( $b );
2035
2036 /**
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
2041 * hours or days.
2042 *
2043 * @param array $options
2044 * @return void
2045 * @throws DBError If an error occurs, see IDatabase::query()
2046 */
2047 public function setSessionOptions( array $options );
2048
2049 /**
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.
2053 *
2054 * @param bool|array $vars Mapping variable name to value.
2055 */
2056 public function setSchemaVars( $vars );
2057
2058 /**
2059 * Check to see if a named lock is not locked by any thread (non-blocking)
2060 *
2061 * @param string $lockName Name of lock to poll
2062 * @param string $method Name of method calling us
2063 * @return bool
2064 * @throws DBError If an error occurs, see IDatabase::query()
2065 * @since 1.20
2066 */
2067 public function lockIsFree( $lockName, $method );
2068
2069 /**
2070 * Acquire a named lock
2071 *
2072 * Named locks are not related to transactions
2073 *
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()
2079 */
2080 public function lock( $lockName, $method, $timeout = 5 );
2081
2082 /**
2083 * Release a lock
2084 *
2085 * Named locks are not related to transactions
2086 *
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()
2091 */
2092 public function unlock( $lockName, $method );
2093
2094 /**
2095 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object
2096 *
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.
2099 *
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.
2105 *
2106 * If the lock acquisition failed, then no transaction flush happens, and null is returned.
2107 *
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()
2113 * @since 1.27
2114 */
2115 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
2116
2117 /**
2118 * Check to see if a named lock used by lock() use blocking queues
2119 *
2120 * @return bool
2121 * @since 1.26
2122 */
2123 public function namedLocksEnqueue();
2124
2125 /**
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.
2129 *
2130 * @return string
2131 */
2132 public function getInfinity();
2133
2134 /**
2135 * Encode an expiry time into the DBMS dependent format
2136 *
2137 * @param string $expiry Timestamp for expiry, or the 'infinity' string
2138 * @return string
2139 */
2140 public function encodeExpiry( $expiry );
2141
2142 /**
2143 * Decode an expiry time into a DBMS independent format
2144 *
2145 * @param string $expiry DB timestamp field value for expiry
2146 * @param int $format TS_* constant, defaults to TS_MW
2147 * @return string
2148 */
2149 public function decodeExpiry( $expiry, $format = TS_MW );
2150
2151 /**
2152 * Allow or deny "big selects" for this session only. This is done by setting
2153 * the sql_big_selects session variable.
2154 *
2155 * This is a MySQL-specific feature.
2156 *
2157 * @param bool|string $value True for allow, false for deny, or "default" to
2158 * restore the initial value
2159 */
2160 public function setBigSelects( $value = true );
2161
2162 /**
2163 * @return bool Whether this DB is read-only
2164 * @since 1.27
2165 */
2166 public function isReadOnly();
2167
2168 /**
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
2171 *
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.
2174 *
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.
2177 *
2178 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
2179 * @since 1.28
2180 */
2181 public function setTableAliases( array $aliases );
2182
2183 /**
2184 * Convert certain index names to alternative names before querying the DB
2185 *
2186 * Note that this applies to indexes regardless of the table they belong to.
2187 *
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.
2191 *
2192 * @param string[] $aliases
2193 * @since 1.31
2194 */
2195 public function setIndexAliases( array $aliases );
2196
2197 /**
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
2200 *
2201 * @return string "<db type> object #<X>" or "<db type> object #<X> (resource/handle id #<Y>)"
2202 * @since 1.34
2203 */
2204 public function __toString();
2205 }
2206
2207 /**
2208 * @deprecated since 1.29
2209 */
2210 class_alias( IDatabase::class, 'IDatabase' );