Merge "Drop the UserRights hook, deprecated in 1.26"
[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 RuntimeException;
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
46 /** @var string Transaction is requested by regular caller outside of the DB layer */
47 const TRANSACTION_EXPLICIT = '';
48 /** @var string Transaction is requested internally via DBO_TRX/startAtomic() */
49 const TRANSACTION_INTERNAL = 'implicit';
50
51 /** @var string Atomic section is not cancelable */
52 const ATOMIC_NOT_CANCELABLE = '';
53 /** @var string Atomic section is cancelable */
54 const ATOMIC_CANCELABLE = 'cancelable';
55
56 /** @var string Commit/rollback is from outside the IDatabase handle and connection manager */
57 const FLUSHING_ONE = '';
58 /** @var string Commit/rollback is from the connection manager for the IDatabase handle */
59 const FLUSHING_ALL_PEERS = 'flush';
60 /** @var string Commit/rollback is from the IDatabase handle internally */
61 const FLUSHING_INTERNAL = 'flush-internal';
62
63 /** @var string Do not remember the prior flags */
64 const REMEMBER_NOTHING = '';
65 /** @var string Remember the prior flags */
66 const REMEMBER_PRIOR = 'remember';
67 /** @var string Restore to the prior flag state */
68 const RESTORE_PRIOR = 'prior';
69 /** @var string Restore to the initial flag state */
70 const RESTORE_INITIAL = 'initial';
71
72 /** @var string Estimate total time (RTT, scanning, waiting on locks, applying) */
73 const ESTIMATE_TOTAL = 'total';
74 /** @var string Estimate time to apply (scanning, applying) */
75 const ESTIMATE_DB_APPLY = 'apply';
76
77 /** @var int Combine list with comma delimeters */
78 const LIST_COMMA = 0;
79 /** @var int Combine list with AND clauses */
80 const LIST_AND = 1;
81 /** @var int Convert map into a SET clause */
82 const LIST_SET = 2;
83 /** @var int Treat as field name and do not apply value escaping */
84 const LIST_NAMES = 3;
85 /** @var int Combine list with OR clauses */
86 const LIST_OR = 4;
87
88 /** @var int Enable debug logging */
89 const DBO_DEBUG = 1;
90 /** @var int Disable query buffering (only one result set can be iterated at a time) */
91 const DBO_NOBUFFER = 2;
92 /** @var int Ignore query errors (internal use only!) */
93 const DBO_IGNORE = 4;
94 /** @var int Automatically start a transaction before running a query if none is active */
95 const DBO_TRX = 8;
96 /** @var int Use DBO_TRX in non-CLI mode */
97 const DBO_DEFAULT = 16;
98 /** @var int Use DB persistent connections if possible */
99 const DBO_PERSISTENT = 32;
100 /** @var int DBA session mode; mostly for Oracle */
101 const DBO_SYSDBA = 64;
102 /** @var int Schema file mode; mostly for Oracle */
103 const DBO_DDLMODE = 128;
104 /** @var int Enable SSL/TLS in connection protocol */
105 const DBO_SSL = 256;
106 /** @var int Enable compression in connection protocol */
107 const DBO_COMPRESS = 512;
108
109 /** @var int Ignore query errors and return false when they happen */
110 const QUERY_SILENCE_ERRORS = 1; // b/c for 1.32 query() argument; note that (int)true = 1
111 /**
112 * @var int Treat the TEMPORARY table from the given CREATE query as if it is
113 * permanent as far as write tracking is concerned. This is useful for testing.
114 */
115 const QUERY_PSEUDO_PERMANENT = 2;
116 /** @var int Enforce that a query does not make effective writes */
117 const QUERY_REPLICA_ROLE = 4;
118 /** @var int Ignore the current presence of any DBO_TRX flag */
119 const QUERY_IGNORE_DBO_TRX = 8;
120
121 /** @var bool Parameter to unionQueries() for UNION ALL */
122 const UNION_ALL = true;
123 /** @var bool Parameter to unionQueries() for UNION DISTINCT */
124 const UNION_DISTINCT = false;
125
126 /**
127 * A string describing the current software version, and possibly
128 * other details in a user-friendly way. Will be listed on Special:Version, etc.
129 * Use getServerVersion() to get machine-friendly information.
130 *
131 * @return string Version information from the database server
132 */
133 public function getServerInfo();
134
135 /**
136 * Turns buffering of SQL result sets on (true) or off (false). Default is "on".
137 *
138 * Unbuffered queries are very troublesome in MySQL:
139 *
140 * - If another query is executed while the first query is being read
141 * out, the first query is killed. This means you can't call normal
142 * Database functions while you are reading an unbuffered query result
143 * from a normal Database connection.
144 *
145 * - Unbuffered queries cause the MySQL server to use large amounts of
146 * memory and to hold broad locks which block other queries.
147 *
148 * If you want to limit client-side memory, it's almost always better to
149 * split up queries into batches using a LIMIT clause than to switch off
150 * buffering.
151 *
152 * @param null|bool $buffer
153 * @return null|bool The previous value of the flag
154 */
155 public function bufferResults( $buffer = null );
156
157 /**
158 * Gets the current transaction level.
159 *
160 * Historically, transactions were allowed to be "nested". This is no
161 * longer supported, so this function really only returns a boolean.
162 *
163 * @return int The previous value
164 */
165 public function trxLevel();
166
167 /**
168 * Get the UNIX timestamp of the time that the transaction was established
169 *
170 * This can be used to reason about the staleness of SELECT data in REPEATABLE-READ
171 * transaction isolation level. Callers can assume that if a view-snapshot isolation
172 * is used, then the data read by SQL queries is *at least* up to date to that point
173 * (possibly more up-to-date since the first SELECT defines the snapshot).
174 *
175 * @return float|null Returns null if there is not active transaction
176 * @since 1.25
177 */
178 public function trxTimestamp();
179
180 /**
181 * @return bool Whether an explicit transaction or atomic sections are still open
182 * @since 1.28
183 */
184 public function explicitTrxActive();
185
186 /**
187 * Assert that all explicit transactions or atomic sections have been closed.
188 * @throws DBTransactionError
189 * @since 1.32
190 */
191 public function assertNoOpenTransactions();
192
193 /**
194 * Get/set the table prefix.
195 * @param string|null $prefix The table prefix to set, or omitted to leave it unchanged.
196 * @return string The previous table prefix
197 * @throws DBUnexpectedError
198 */
199 public function tablePrefix( $prefix = null );
200
201 /**
202 * Get/set the db schema.
203 * @param string|null $schema The database schema to set, or omitted to leave it unchanged.
204 * @return string The previous db schema
205 */
206 public function dbSchema( $schema = null );
207
208 /**
209 * Get properties passed down from the server info array of the load
210 * balancer.
211 *
212 * @param string|null $name The entry of the info array to get, or null to get the
213 * whole array
214 *
215 * @return array|mixed|null
216 */
217 public function getLBInfo( $name = null );
218
219 /**
220 * Set the LB info array, or a member of it. If called with one parameter,
221 * the LB info array is set to that parameter. If it is called with two
222 * parameters, the member with the given name is set to the given value.
223 *
224 * @param array|string $name
225 * @param array|null $value
226 */
227 public function setLBInfo( $name, $value = null );
228
229 /**
230 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
231 *
232 * @param IDatabase $conn
233 * @since 1.27
234 */
235 public function setLazyMasterHandle( IDatabase $conn );
236
237 /**
238 * Returns true if this database does an implicit sort when doing GROUP BY
239 *
240 * @return bool
241 * @deprecated Since 1.30; only use grouped or aggregated fields in the SELECT
242 */
243 public function implicitGroupby();
244
245 /**
246 * Returns true if this database does an implicit order by when the column has an index
247 * For example: SELECT page_title FROM page LIMIT 1
248 *
249 * @return bool
250 */
251 public function implicitOrderby();
252
253 /**
254 * Return the last query that sent on account of IDatabase::query()
255 * @return string SQL text or empty string if there was no such query
256 */
257 public function lastQuery();
258
259 /**
260 * Returns true if the connection may have been used for write queries.
261 * Should return true if unsure.
262 *
263 * @return bool
264 * @deprecated Since 1.31; use lastDoneWrites()
265 */
266 public function doneWrites();
267
268 /**
269 * Returns the last time the connection may have been used for write queries.
270 * Should return a timestamp if unsure.
271 *
272 * @return int|float UNIX timestamp or false
273 * @since 1.24
274 */
275 public function lastDoneWrites();
276
277 /**
278 * @return bool Whether there is a transaction open with possible write queries
279 * @since 1.27
280 */
281 public function writesPending();
282
283 /**
284 * @return bool Whether there is a transaction open with pre-commit callbacks pending
285 * @since 1.32
286 */
287 public function preCommitCallbacksPending();
288
289 /**
290 * Whether there is a transaction open with either possible write queries
291 * or unresolved pre-commit/commit/resolution callbacks pending
292 *
293 * This does *not* count recurring callbacks, e.g. from setTransactionListener().
294 *
295 * @return bool
296 */
297 public function writesOrCallbacksPending();
298
299 /**
300 * Get the time spend running write queries for this transaction
301 *
302 * High times could be due to scanning, updates, locking, and such
303 *
304 * @param string $type IDatabase::ESTIMATE_* constant [default: ESTIMATE_ALL]
305 * @return float|bool Returns false if not transaction is active
306 * @since 1.26
307 */
308 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL );
309
310 /**
311 * Get the list of method names that did write queries for this transaction
312 *
313 * @return array
314 * @since 1.27
315 */
316 public function pendingWriteCallers();
317
318 /**
319 * Get the number of affected rows from pending write queries
320 *
321 * @return int
322 * @since 1.30
323 */
324 public function pendingWriteRowsAffected();
325
326 /**
327 * Is a connection to the database open?
328 * @return bool
329 */
330 public function isOpen();
331
332 /**
333 * Set a flag for this connection
334 *
335 * @param int $flag DBO_* constants from Defines.php:
336 * - DBO_DEBUG: output some debug info (same as debug())
337 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
338 * - DBO_TRX: automatically start transactions
339 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
340 * and removes it in command line mode
341 * - DBO_PERSISTENT: use persistant database connection
342 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
343 */
344 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING );
345
346 /**
347 * Clear a flag for this connection
348 *
349 * @param int $flag DBO_* constants from Defines.php:
350 * - DBO_DEBUG: output some debug info (same as debug())
351 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
352 * - DBO_TRX: automatically start transactions
353 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
354 * and removes it in command line mode
355 * - DBO_PERSISTENT: use persistant database connection
356 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
357 */
358 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING );
359
360 /**
361 * Restore the flags to their prior state before the last setFlag/clearFlag call
362 *
363 * @param string $state IDatabase::RESTORE_* constant. [default: RESTORE_PRIOR]
364 * @since 1.28
365 */
366 public function restoreFlags( $state = self::RESTORE_PRIOR );
367
368 /**
369 * Returns a boolean whether the flag $flag is set for this connection
370 *
371 * @param int $flag DBO_* constants from Defines.php:
372 * - DBO_DEBUG: output some debug info (same as debug())
373 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
374 * - DBO_TRX: automatically start transactions
375 * - DBO_PERSISTENT: use persistant database connection
376 * @return bool
377 */
378 public function getFlag( $flag );
379
380 /**
381 * Return the currently selected domain ID
382 *
383 * Null components (database/schema) might change once a connection is established
384 *
385 * @return string
386 */
387 public function getDomainID();
388
389 /**
390 * Alias for getDomainID()
391 *
392 * @return string
393 * @deprecated 1.30
394 */
395 public function getWikiID();
396
397 /**
398 * Get the type of the DBMS, as it appears in $wgDBtype.
399 *
400 * @return string
401 */
402 public function getType();
403
404 /**
405 * Fetch the next row from the given result object, in object form.
406 * Fields can be retrieved with $row->fieldname, with fields acting like
407 * member variables.
408 * If no more rows are available, false is returned.
409 *
410 * @param IResultWrapper|stdClass $res Object as returned from IDatabase::query(), etc.
411 * @return stdClass|bool
412 * @throws DBUnexpectedError Thrown if the database returns an error
413 */
414 public function fetchObject( $res );
415
416 /**
417 * Fetch the next row from the given result object, in associative array
418 * form. Fields are retrieved with $row['fieldname'].
419 * If no more rows are available, false is returned.
420 *
421 * @param IResultWrapper $res Result object as returned from IDatabase::query(), etc.
422 * @return array|bool
423 * @throws DBUnexpectedError Thrown if the database returns an error
424 */
425 public function fetchRow( $res );
426
427 /**
428 * Get the number of rows in a query result. If the query did not return
429 * any rows (for example, if it was a write query), this returns zero.
430 *
431 * @param mixed $res A SQL result
432 * @return int
433 */
434 public function numRows( $res );
435
436 /**
437 * Get the number of fields in a result object
438 * @see https://www.php.net/mysql_num_fields
439 *
440 * @param mixed $res A SQL result
441 * @return int
442 */
443 public function numFields( $res );
444
445 /**
446 * Get a field name in a result object
447 * @see https://www.php.net/mysql_field_name
448 *
449 * @param mixed $res A SQL result
450 * @param int $n
451 * @return string
452 */
453 public function fieldName( $res, $n );
454
455 /**
456 * Get the inserted value of an auto-increment row
457 *
458 * This should only be called after an insert that used an auto-incremented
459 * value. If no such insert was previously done in the current database
460 * session, the return value is undefined.
461 *
462 * @return int
463 */
464 public function insertId();
465
466 /**
467 * Change the position of the cursor in a result object
468 * @see https://www.php.net/mysql_data_seek
469 *
470 * @param mixed $res A SQL result
471 * @param int $row
472 */
473 public function dataSeek( $res, $row );
474
475 /**
476 * Get the last error number
477 * @see https://www.php.net/mysql_errno
478 *
479 * @return int
480 */
481 public function lastErrno();
482
483 /**
484 * Get a description of the last error
485 * @see https://www.php.net/mysql_error
486 *
487 * @return string
488 */
489 public function lastError();
490
491 /**
492 * Get the number of rows affected by the last write query
493 * @see https://www.php.net/mysql_affected_rows
494 *
495 * @return int
496 */
497 public function affectedRows();
498
499 /**
500 * Returns a wikitext link to the DB's website, e.g.,
501 * return "[https://www.mysql.com/ MySQL]";
502 * Should at least contain plain text, if for some reason
503 * your database has no website.
504 *
505 * @return string Wikitext of a link to the server software's web site
506 */
507 public function getSoftwareLink();
508
509 /**
510 * A string describing the current software version, like from
511 * mysql_get_server_info().
512 *
513 * @return string Version information from the database server.
514 */
515 public function getServerVersion();
516
517 /**
518 * Close the database connection
519 *
520 * This should only be called after any transactions have been resolved,
521 * aside from read-only automatic transactions (assuming no callbacks are registered).
522 * If a transaction is still open anyway, it will be rolled back.
523 *
524 * @throws DBError
525 * @return bool Operation success. true if already closed.
526 */
527 public function close();
528
529 /**
530 * Run an SQL query and return the result. Normally throws a DBQueryError
531 * on failure. If errors are ignored, returns false instead.
532 *
533 * If a connection loss is detected, then an attempt to reconnect will be made.
534 * For queries that involve no larger transactions or locks, they will be re-issued
535 * for convenience, provided the connection was re-established.
536 *
537 * In new code, the query wrappers select(), insert(), update(), delete(),
538 * etc. should be used where possible, since they give much better DBMS
539 * independence and automatically quote or validate user input in a variety
540 * of contexts. This function is generally only useful for queries which are
541 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
542 * as CREATE TABLE.
543 *
544 * However, the query wrappers themselves should call this function.
545 *
546 * @param string $sql SQL query
547 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
548 * comment (you can use __METHOD__ or add some extra info)
549 * @param int $flags Bitfield of IDatabase::QUERY_* constants. Note that suppression
550 * of errors is best handled by try/catch rather than using one of these flags.
551 * @return bool|IResultWrapper True for a successful write query, IResultWrapper object
552 * for a successful read query, or false on failure if QUERY_SILENCE_ERRORS is set.
553 * @throws DBError
554 */
555 public function query( $sql, $fname = __METHOD__, $flags = 0 );
556
557 /**
558 * Free a result object returned by query() or select(). It's usually not
559 * necessary to call this, just use unset() or let the variable holding
560 * the result object go out of scope.
561 *
562 * @param mixed $res A SQL result
563 */
564 public function freeResult( $res );
565
566 /**
567 * A SELECT wrapper which returns a single field from a single result row.
568 *
569 * Usually throws a DBQueryError on failure. If errors are explicitly
570 * ignored, returns false on failure.
571 *
572 * If no result rows are returned from the query, false is returned.
573 *
574 * @param string|array $table Table name. See IDatabase::select() for details.
575 * @param string $var The field name to select. This must be a valid SQL
576 * fragment: do not use unvalidated user input.
577 * @param string|array $cond The condition array. See IDatabase::select() for details.
578 * @param string $fname The function name of the caller.
579 * @param string|array $options The query options. See IDatabase::select() for details.
580 * @param string|array $join_conds The query join conditions. See IDatabase::select() for details.
581 *
582 * @return mixed The value from the field
583 * @throws DBError
584 */
585 public function selectField(
586 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
587 );
588
589 /**
590 * A SELECT wrapper which returns a list of single field values from result rows.
591 *
592 * Usually throws a DBQueryError on failure. If errors are explicitly
593 * ignored, returns false on failure.
594 *
595 * If no result rows are returned from the query, false is returned.
596 *
597 * @param string|array $table Table name. See IDatabase::select() for details.
598 * @param string $var The field name to select. This must be a valid SQL
599 * fragment: do not use unvalidated user input.
600 * @param string|array $cond The condition array. See IDatabase::select() for details.
601 * @param string $fname The function name of the caller.
602 * @param string|array $options The query options. See IDatabase::select() for details.
603 * @param string|array $join_conds The query join conditions. See IDatabase::select() for details.
604 *
605 * @return array The values from the field in the order they were returned from the DB
606 * @throws DBError
607 * @since 1.25
608 */
609 public function selectFieldValues(
610 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
611 );
612
613 /**
614 * Execute a SELECT query constructed using the various parameters provided.
615 * See below for full details of the parameters.
616 *
617 * @param string|array $table Table name(s)
618 *
619 * May be either an array of table names, or a single string holding a table
620 * name. If an array is given, table aliases can be specified, for example:
621 *
622 * [ 'a' => 'user' ]
623 *
624 * This includes the user table in the query, with the alias "a" available
625 * for use in field names (e.g. a.user_name).
626 *
627 * A derived table, defined by the result of selectSQLText(), requires an alias
628 * key and a Subquery instance value which wraps the SQL query, for example:
629 *
630 * [ 'c' => new Subquery( 'SELECT ...' ) ]
631 *
632 * Joins using parentheses for grouping (since MediaWiki 1.31) may be
633 * constructed using nested arrays. For example,
634 *
635 * [ 'tableA', 'nestedB' => [ 'tableB', 'b2' => 'tableB2' ] ]
636 *
637 * along with `$join_conds` like
638 *
639 * [ 'b2' => [ 'JOIN', 'b_id = b2_id' ], 'nestedB' => [ 'LEFT JOIN', 'b_a = a_id' ] ]
640 *
641 * will produce SQL something like
642 *
643 * FROM tableA LEFT JOIN (tableB JOIN tableB2 AS b2 ON (b_id = b2_id)) ON (b_a = a_id)
644 *
645 * All of the table names given here are automatically run through
646 * Database::tableName(), which causes the table prefix (if any) to be
647 * added, and various other table name mappings to be performed.
648 *
649 * Do not use untrusted user input as a table name. Alias names should
650 * not have characters outside of the Basic multilingual plane.
651 *
652 * @param string|array $vars Field name(s)
653 *
654 * May be either a field name or an array of field names. The field names
655 * can be complete fragments of SQL, for direct inclusion into the SELECT
656 * query. If an array is given, field aliases can be specified, for example:
657 *
658 * [ 'maxrev' => 'MAX(rev_id)' ]
659 *
660 * This includes an expression with the alias "maxrev" in the query.
661 *
662 * If an expression is given, care must be taken to ensure that it is
663 * DBMS-independent.
664 *
665 * Untrusted user input must not be passed to this parameter.
666 *
667 * @param string|array $conds
668 *
669 * May be either a string containing a single condition, or an array of
670 * conditions. If an array is given, the conditions constructed from each
671 * element are combined with AND.
672 *
673 * Array elements may take one of two forms:
674 *
675 * - Elements with a numeric key are interpreted as raw SQL fragments.
676 * - Elements with a string key are interpreted as equality conditions,
677 * where the key is the field name.
678 * - If the value of such an array element is a scalar (such as a
679 * string), it will be treated as data and thus quoted appropriately.
680 * If it is null, an IS NULL clause will be added.
681 * - If the value is an array, an IN (...) clause will be constructed
682 * from its non-null elements, and an IS NULL clause will be added
683 * if null is present, such that the field may match any of the
684 * elements in the array. The non-null elements will be quoted.
685 *
686 * Note that expressions are often DBMS-dependent in their syntax.
687 * DBMS-independent wrappers are provided for constructing several types of
688 * expression commonly used in condition queries. See:
689 * - IDatabase::buildLike()
690 * - IDatabase::conditional()
691 *
692 * Untrusted user input is safe in the values of string keys, however untrusted
693 * input must not be used in the array key names or in the values of numeric keys.
694 * Escaping of untrusted input used in values of numeric keys should be done via
695 * IDatabase::addQuotes()
696 *
697 * Use an empty array, string, or '*' to update all rows.
698 *
699 * @param string $fname Caller function name
700 *
701 * @param string|array $options Query options
702 *
703 * Optional: Array of query options. Boolean options are specified by
704 * including them in the array as a string value with a numeric key, for
705 * example:
706 *
707 * [ 'FOR UPDATE' ]
708 *
709 * The supported options are:
710 *
711 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
712 * with LIMIT can theoretically be used for paging through a result set,
713 * but this is discouraged for performance reasons.
714 *
715 * - LIMIT: Integer: return at most this many rows. The rows are sorted
716 * and then the first rows are taken until the limit is reached. LIMIT
717 * is applied to a result set after OFFSET.
718 *
719 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
720 * changed until the next COMMIT. Cannot be used with aggregate functions
721 * (COUNT, MAX, etc., but also DISTINCT).
722 *
723 * - DISTINCT: Boolean: return only unique result rows.
724 *
725 * - GROUP BY: May be either an SQL fragment string naming a field or
726 * expression to group by, or an array of such SQL fragments.
727 *
728 * - HAVING: May be either an string containing a HAVING clause or an array of
729 * conditions building the HAVING clause. If an array is given, the conditions
730 * constructed from each element are combined with AND.
731 *
732 * - ORDER BY: May be either an SQL fragment giving a field name or
733 * expression to order by, or an array of such SQL fragments.
734 *
735 * - USE INDEX: This may be either a string giving the index name to use
736 * for the query, or an array. If it is an associative array, each key
737 * gives the table name (or alias), each value gives the index name to
738 * use for that table. All strings are SQL fragments and so should be
739 * validated by the caller.
740 *
741 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
742 * instead of SELECT.
743 *
744 * And also the following boolean MySQL extensions, see the MySQL manual
745 * for documentation:
746 *
747 * - LOCK IN SHARE MODE
748 * - STRAIGHT_JOIN
749 * - HIGH_PRIORITY
750 * - SQL_BIG_RESULT
751 * - SQL_BUFFER_RESULT
752 * - SQL_SMALL_RESULT
753 * - SQL_CALC_FOUND_ROWS
754 * - SQL_CACHE
755 * - SQL_NO_CACHE
756 *
757 *
758 * @param string|array $join_conds Join conditions
759 *
760 * Optional associative array of table-specific join conditions. In the
761 * most common case, this is unnecessary, since the join condition can be
762 * in $conds. However, it is useful for doing a LEFT JOIN.
763 *
764 * The key of the array contains the table name or alias. The value is an
765 * array with two elements, numbered 0 and 1. The first gives the type of
766 * join, the second is the same as the $conds parameter. Thus it can be
767 * an SQL fragment, or an array where the string keys are equality and the
768 * numeric keys are SQL fragments all AND'd together. For example:
769 *
770 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
771 *
772 * @return IResultWrapper Resulting rows
773 * @throws DBError
774 */
775 public function select(
776 $table, $vars, $conds = '', $fname = __METHOD__,
777 $options = [], $join_conds = []
778 );
779
780 /**
781 * The equivalent of IDatabase::select() except that the constructed SQL
782 * is returned, instead of being immediately executed. This can be useful for
783 * doing UNION queries, where the SQL text of each query is needed. In general,
784 * however, callers outside of Database classes should just use select().
785 *
786 * @see IDatabase::select()
787 *
788 * @param string|array $table Table name
789 * @param string|array $vars Field names
790 * @param string|array $conds Conditions
791 * @param string $fname Caller function name
792 * @param string|array $options Query options
793 * @param string|array $join_conds Join conditions
794 * @return string SQL query string
795 */
796 public function selectSQLText(
797 $table, $vars, $conds = '', $fname = __METHOD__,
798 $options = [], $join_conds = []
799 );
800
801 /**
802 * Single row SELECT wrapper. Equivalent to IDatabase::select(), except
803 * that a single row object is returned. If the query returns no rows,
804 * false is returned.
805 *
806 * @param string|array $table Table name
807 * @param string|array $vars Field names
808 * @param string|array $conds Conditions
809 * @param string $fname Caller function name
810 * @param string|array $options Query options
811 * @param array|string $join_conds Join conditions
812 *
813 * @return stdClass|bool
814 * @throws DBError
815 */
816 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
817 $options = [], $join_conds = []
818 );
819
820 /**
821 * Estimate the number of rows in dataset
822 *
823 * MySQL allows you to estimate the number of rows that would be returned
824 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
825 * index cardinality statistics, and is notoriously inaccurate, especially
826 * when large numbers of rows have recently been added or deleted.
827 *
828 * For DBMSs that don't support fast result size estimation, this function
829 * will actually perform the SELECT COUNT(*).
830 *
831 * Takes the same arguments as IDatabase::select().
832 *
833 * @param string $table Table name
834 * @param string $var Column for which NULL values are not counted [default "*"]
835 * @param array|string $conds Filters on the table
836 * @param string $fname Function name for profiling
837 * @param array $options Options for select
838 * @param array|string $join_conds Join conditions
839 * @return int Row count
840 * @throws DBError
841 */
842 public function estimateRowCount(
843 $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
844 );
845
846 /**
847 * Get the number of rows in dataset
848 *
849 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
850 *
851 * Takes the same arguments as IDatabase::select().
852 *
853 * @since 1.27 Added $join_conds parameter
854 *
855 * @param array|string $tables Table names
856 * @param string $var Column for which NULL values are not counted [default "*"]
857 * @param array|string $conds Filters on the table
858 * @param string $fname Function name for profiling
859 * @param array $options Options for select
860 * @param array $join_conds Join conditions (since 1.27)
861 * @return int Row count
862 * @throws DBError
863 */
864 public function selectRowCount(
865 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
866 );
867
868 /**
869 * Lock all rows meeting the given conditions/options FOR UPDATE
870 *
871 * @param array|string $table Table names
872 * @param array|string $conds Filters on the table
873 * @param string $fname Function name for profiling
874 * @param array $options Options for select ("FOR UPDATE" is added automatically)
875 * @param array $join_conds Join conditions
876 * @return int Number of matching rows found (and locked)
877 * @since 1.32
878 */
879 public function lockForUpdate(
880 $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
881 );
882
883 /**
884 * Determines whether a field exists in a table
885 *
886 * @param string $table Table name
887 * @param string $field Filed to check on that table
888 * @param string $fname Calling function name (optional)
889 * @return bool Whether $table has filed $field
890 * @throws DBError
891 */
892 public function fieldExists( $table, $field, $fname = __METHOD__ );
893
894 /**
895 * Determines whether an index exists
896 * Usually throws a DBQueryError on failure
897 * If errors are explicitly ignored, returns NULL on failure
898 *
899 * @param string $table
900 * @param string $index
901 * @param string $fname
902 * @return bool|null
903 * @throws DBError
904 */
905 public function indexExists( $table, $index, $fname = __METHOD__ );
906
907 /**
908 * Query whether a given table exists
909 *
910 * @param string $table
911 * @param string $fname
912 * @return bool
913 * @throws DBError
914 */
915 public function tableExists( $table, $fname = __METHOD__ );
916
917 /**
918 * INSERT wrapper, inserts an array into a table.
919 *
920 * $a may be either:
921 *
922 * - A single associative array. The array keys are the field names, and
923 * the values are the values to insert. The values are treated as data
924 * and will be quoted appropriately. If NULL is inserted, this will be
925 * converted to a database NULL.
926 * - An array with numeric keys, holding a list of associative arrays.
927 * This causes a multi-row INSERT on DBMSs that support it. The keys in
928 * each subarray must be identical to each other, and in the same order.
929 *
930 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
931 * returns success.
932 *
933 * $options is an array of options, with boolean options encoded as values
934 * with numeric keys, in the same style as $options in
935 * IDatabase::select(). Supported options are:
936 *
937 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
938 * any rows which cause duplicate key errors are not inserted. It's
939 * possible to determine how many rows were successfully inserted using
940 * IDatabase::affectedRows().
941 *
942 * @param string $table Table name. This will be passed through
943 * Database::tableName().
944 * @param array $a Array of rows to insert
945 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
946 * @param array $options Array of options
947 * @return bool Return true if no exception was thrown (deprecated since 1.33)
948 * @throws DBError
949 */
950 public function insert( $table, $a, $fname = __METHOD__, $options = [] );
951
952 /**
953 * UPDATE wrapper. Takes a condition array and a SET array.
954 *
955 * @param string $table Name of the table to UPDATE. This will be passed through
956 * Database::tableName().
957 * @param array $values An array of values to SET. For each array element,
958 * the key gives the field name, and the value gives the data to set
959 * that field to. The data will be quoted by IDatabase::addQuotes().
960 * Values with integer keys form unquoted SET statements, which can be used for
961 * things like "field = field + 1" or similar computed values.
962 * @param array $conds An array of conditions (WHERE). See
963 * IDatabase::select() for the details of the format of condition
964 * arrays. Use '*' to update all rows.
965 * @param string $fname The function name of the caller (from __METHOD__),
966 * for logging and profiling.
967 * @param array $options An array of UPDATE options, can be:
968 * - IGNORE: Ignore unique key conflicts
969 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
970 * @return bool Return true if no exception was thrown (deprecated since 1.33)
971 * @throws DBError
972 */
973 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] );
974
975 /**
976 * Makes an encoded list of strings from an array
977 *
978 * These can be used to make conjunctions or disjunctions on SQL condition strings
979 * derived from an array (see IDatabase::select() $conds documentation).
980 *
981 * Example usage:
982 * @code
983 * $sql = $db->makeList( [
984 * 'rev_page' => $id,
985 * $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] )
986 * ], $db::LIST_AND );
987 * @endcode
988 * This would set $sql to "rev_page = '$id' AND (rev_minor = '1' OR rev_len < '500')"
989 *
990 * @param array $a Containing the data
991 * @param int $mode IDatabase class constant:
992 * - IDatabase::LIST_COMMA: Comma separated, no field names
993 * - IDatabase::LIST_AND: ANDed WHERE clause (without the WHERE).
994 * - IDatabase::LIST_OR: ORed WHERE clause (without the WHERE)
995 * - IDatabase::LIST_SET: Comma separated with field names, like a SET clause
996 * - IDatabase::LIST_NAMES: Comma separated field names
997 * @throws DBError
998 * @return string
999 */
1000 public function makeList( $a, $mode = self::LIST_COMMA );
1001
1002 /**
1003 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1004 * The keys on each level may be either integers or strings.
1005 *
1006 * @param array $data Organized as 2-d
1007 * [ baseKeyVal => [ subKeyVal => [ignored], ... ], ... ]
1008 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
1009 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
1010 * @return string|bool SQL fragment, or false if no items in array
1011 */
1012 public function makeWhereFrom2d( $data, $baseKey, $subKey );
1013
1014 /**
1015 * Return aggregated value alias
1016 *
1017 * @param array $valuedata
1018 * @param string $valuename
1019 *
1020 * @return string
1021 * @deprecated Since 1.33
1022 */
1023 public function aggregateValue( $valuedata, $valuename = 'value' );
1024
1025 /**
1026 * @param string $field
1027 * @return string
1028 */
1029 public function bitNot( $field );
1030
1031 /**
1032 * @param string $fieldLeft
1033 * @param string $fieldRight
1034 * @return string
1035 */
1036 public function bitAnd( $fieldLeft, $fieldRight );
1037
1038 /**
1039 * @param string $fieldLeft
1040 * @param string $fieldRight
1041 * @return string
1042 */
1043 public function bitOr( $fieldLeft, $fieldRight );
1044
1045 /**
1046 * Build a concatenation list to feed into a SQL query
1047 * @param array $stringList List of raw SQL expressions; caller is
1048 * responsible for any quoting
1049 * @return string
1050 */
1051 public function buildConcat( $stringList );
1052
1053 /**
1054 * Build a GROUP_CONCAT or equivalent statement for a query.
1055 *
1056 * This is useful for combining a field for several rows into a single string.
1057 * NULL values will not appear in the output, duplicated values will appear,
1058 * and the resulting delimiter-separated values have no defined sort order.
1059 * Code using the results may need to use the PHP unique() or sort() methods.
1060 *
1061 * @param string $delim Glue to bind the results together
1062 * @param string|array $table Table name
1063 * @param string $field Field name
1064 * @param string|array $conds Conditions
1065 * @param string|array $join_conds Join conditions
1066 * @return string SQL text
1067 * @since 1.23
1068 */
1069 public function buildGroupConcatField(
1070 $delim, $table, $field, $conds = '', $join_conds = []
1071 );
1072
1073 /**
1074 * Build a SUBSTRING function.
1075 *
1076 * Behavior for non-ASCII values is undefined.
1077 *
1078 * @param string $input Field name
1079 * @param int $startPosition Positive integer
1080 * @param int|null $length Non-negative integer length or null for no limit
1081 * @throws InvalidArgumentException
1082 * @return string SQL text
1083 * @since 1.31
1084 */
1085 public function buildSubString( $input, $startPosition, $length = null );
1086
1087 /**
1088 * @param string $field Field or column to cast
1089 * @return string
1090 * @since 1.28
1091 */
1092 public function buildStringCast( $field );
1093
1094 /**
1095 * @param string $field Field or column to cast
1096 * @return string
1097 * @since 1.31
1098 */
1099 public function buildIntegerCast( $field );
1100
1101 /**
1102 * Equivalent to IDatabase::selectSQLText() except wraps the result in Subqyery
1103 *
1104 * @see IDatabase::selectSQLText()
1105 *
1106 * @param string|array $table Table name
1107 * @param string|array $vars Field names
1108 * @param string|array $conds Conditions
1109 * @param string $fname Caller function name
1110 * @param string|array $options Query options
1111 * @param string|array $join_conds Join conditions
1112 * @return Subquery
1113 * @since 1.31
1114 */
1115 public function buildSelectSubquery(
1116 $table, $vars, $conds = '', $fname = __METHOD__,
1117 $options = [], $join_conds = []
1118 );
1119
1120 /**
1121 * Construct a LIMIT query with optional offset. This is used for query
1122 * pages. The SQL should be adjusted so that only the first $limit rows
1123 * are returned. If $offset is provided as well, then the first $offset
1124 * rows should be discarded, and the next $limit rows should be returned.
1125 * If the result of the query is not ordered, then the rows to be returned
1126 * are theoretically arbitrary.
1127 *
1128 * $sql is expected to be a SELECT, if that makes a difference.
1129 *
1130 * @param string $sql SQL query we will append the limit too
1131 * @param int $limit The SQL limit
1132 * @param int|bool $offset The SQL offset (default false)
1133 * @throws DBUnexpectedError
1134 * @return string
1135 * @since 1.34
1136 */
1137 public function limitResult( $sql, $limit, $offset = false );
1138
1139 /**
1140 * Returns true if DBs are assumed to be on potentially different servers
1141 *
1142 * In systems like mysql/mariadb, different databases can easily be referenced on a single
1143 * connection merely by name, even in a single query via JOIN. On the other hand, Postgres
1144 * treats databases as fully separate, only allowing mechanisms like postgres_fdw to
1145 * effectively "mount" foreign DBs. This is true even among DBs on the same server.
1146 *
1147 * @return bool
1148 * @since 1.29
1149 */
1150 public function databasesAreIndependent();
1151
1152 /**
1153 * Change the current database
1154 *
1155 * This should not be called outside LoadBalancer for connections managed by a LoadBalancer
1156 *
1157 * @param string $db
1158 * @return bool True unless an exception was thrown
1159 * @throws DBConnectionError If databasesAreIndependent() is true and an error occurs
1160 * @throws DBError
1161 * @deprecated Since 1.32 Use selectDomain() instead
1162 */
1163 public function selectDB( $db );
1164
1165 /**
1166 * Set the current domain (database, schema, and table prefix)
1167 *
1168 * This will throw an error for some database types if the database unspecified
1169 *
1170 * This should not be called outside LoadBalancer for connections managed by a LoadBalancer
1171 *
1172 * @param string|DatabaseDomain $domain
1173 * @since 1.32
1174 * @throws DBConnectionError
1175 */
1176 public function selectDomain( $domain );
1177
1178 /**
1179 * Get the current DB name
1180 * @return string|null
1181 */
1182 public function getDBname();
1183
1184 /**
1185 * Get the server hostname or IP address
1186 * @return string
1187 */
1188 public function getServer();
1189
1190 /**
1191 * Adds quotes and backslashes.
1192 *
1193 * @param string|int|null|bool|Blob $s
1194 * @return string|int
1195 */
1196 public function addQuotes( $s );
1197
1198 /**
1199 * Quotes an identifier, in order to make user controlled input safe
1200 *
1201 * Depending on the database this will either be `backticks` or "double quotes"
1202 *
1203 * @param string $s
1204 * @return string
1205 * @since 1.33
1206 */
1207 public function addIdentifierQuotes( $s );
1208
1209 /**
1210 * LIKE statement wrapper, receives a variable-length argument list with
1211 * parts of pattern to match containing either string literals that will be
1212 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
1213 * the function could be provided with an array of aforementioned
1214 * parameters.
1215 *
1216 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
1217 * a LIKE clause that searches for subpages of 'My page title'.
1218 * Alternatively:
1219 * $pattern = [ 'My_page_title/', $dbr->anyString() ];
1220 * $query .= $dbr->buildLike( $pattern );
1221 *
1222 * @since 1.16
1223 * @param array[]|string|LikeMatch $param
1224 * @return string Fully built LIKE statement
1225 * @phan-suppress-next-line PhanMismatchVariadicComment
1226 * @phan-param array|string|LikeMatch ...$param T226223
1227 */
1228 public function buildLike( $param );
1229
1230 /**
1231 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1232 *
1233 * @return LikeMatch
1234 */
1235 public function anyChar();
1236
1237 /**
1238 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1239 *
1240 * @return LikeMatch
1241 */
1242 public function anyString();
1243
1244 /**
1245 * Deprecated method, calls should be removed.
1246 *
1247 * This was formerly used for PostgreSQL and Oracle to handle
1248 * self::insertId() auto-incrementing fields. It is no longer necessary
1249 * since DatabasePostgres::insertId() has been reimplemented using
1250 * `lastval()` and Oracle has been reimplemented using triggers.
1251 *
1252 * Implementations should return null if inserting `NULL` into an
1253 * auto-incrementing field works, otherwise it should return an instance of
1254 * NextSequenceValue and filter it on calls to relevant methods.
1255 *
1256 * @deprecated since 1.30, no longer needed
1257 * @param string $seqName
1258 * @return null|NextSequenceValue
1259 */
1260 public function nextSequenceValue( $seqName );
1261
1262 /**
1263 * REPLACE query wrapper.
1264 *
1265 * REPLACE is a very handy MySQL extension, which functions like an INSERT
1266 * except that when there is a duplicate key error, the old row is deleted
1267 * and the new row is inserted in its place.
1268 *
1269 * We simulate this with standard SQL with a DELETE followed by INSERT. To
1270 * perform the delete, we need to know what the unique indexes are so that
1271 * we know how to find the conflicting rows.
1272 *
1273 * It may be more efficient to leave off unique indexes which are unlikely
1274 * to collide. However if you do this, you run the risk of encountering
1275 * errors which wouldn't have occurred in MySQL.
1276 *
1277 * @param string $table The table to replace the row(s) in.
1278 * @param array[]|string[]|string $uniqueIndexes All unique indexes. One of the following:
1279 * a) the one unique field in the table (when no composite unique key exist)
1280 * b) a list of all unique fields in the table (when no composite unique key exist)
1281 * c) a list of all unique indexes in the table (each as a list of the indexed fields)
1282 * @param array $rows Can be either a single row to insert, or multiple rows,
1283 * in the same format as for IDatabase::insert()
1284 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1285 * @throws DBError
1286 */
1287 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ );
1288
1289 /**
1290 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
1291 *
1292 * This updates any conflicting rows (according to the unique indexes) using
1293 * the provided SET clause and inserts any remaining (non-conflicted) rows.
1294 *
1295 * $rows may be either:
1296 * - A single associative array. The array keys are the field names, and
1297 * the values are the values to insert. The values are treated as data
1298 * and will be quoted appropriately. If NULL is inserted, this will be
1299 * converted to a database NULL.
1300 * - An array with numeric keys, holding a list of associative arrays.
1301 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1302 * each subarray must be identical to each other, and in the same order.
1303 *
1304 * It may be more efficient to leave off unique indexes which are unlikely
1305 * to collide. However if you do this, you run the risk of encountering
1306 * errors which wouldn't have occurred in MySQL.
1307 *
1308 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1309 * returns success.
1310 *
1311 * @since 1.22
1312 *
1313 * @param string $table Table name. This will be passed through Database::tableName().
1314 * @param array $rows A single row or list of rows to insert
1315 * @param array[]|string[]|string $uniqueIndexes All unique indexes. One of the following:
1316 * a) the one unique field in the table (when no composite unique key exist)
1317 * b) a list of all unique fields in the table (when no composite unique key exist)
1318 * c) a list of all unique indexes in the table (each as a list of the indexed fields)
1319 * @param array $set An array of values to SET. For each array element, the
1320 * key gives the field name, and the value gives the data to set that
1321 * field to. The data will be quoted by IDatabase::addQuotes().
1322 * Values with integer keys form unquoted SET statements, which can be used for
1323 * things like "field = field + 1" or similar computed values.
1324 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1325 * @throws DBError
1326 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1327 */
1328 public function upsert(
1329 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1330 );
1331
1332 /**
1333 * DELETE where the condition is a join.
1334 *
1335 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
1336 * we use sub-selects
1337 *
1338 * For safety, an empty $conds will not delete everything. If you want to
1339 * delete all rows where the join condition matches, set $conds='*'.
1340 *
1341 * DO NOT put the join condition in $conds.
1342 *
1343 * @param string $delTable The table to delete from.
1344 * @param string $joinTable The other table.
1345 * @param string $delVar The variable to join on, in the first table.
1346 * @param string $joinVar The variable to join on, in the second table.
1347 * @param array $conds Condition array of field names mapped to variables,
1348 * ANDed together in the WHERE clause
1349 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1350 * @throws DBError
1351 */
1352 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
1353 $fname = __METHOD__
1354 );
1355
1356 /**
1357 * DELETE query wrapper.
1358 *
1359 * @param string $table Table name
1360 * @param string|array $conds Array of conditions. See $conds in IDatabase::select()
1361 * for the format. Use $conds == "*" to delete all rows
1362 * @param string $fname Name of the calling function
1363 * @throws DBUnexpectedError
1364 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1365 * @throws DBError
1366 */
1367 public function delete( $table, $conds, $fname = __METHOD__ );
1368
1369 /**
1370 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
1371 * into another table.
1372 *
1373 * @warning If the insert will use an auto-increment or sequence to
1374 * determine the value of a column, this may break replication on
1375 * databases using statement-based replication if the SELECT is not
1376 * deterministically ordered.
1377 *
1378 * @param string $destTable The table name to insert into
1379 * @param string|array $srcTable May be either a table name, or an array of table names
1380 * to include in a join.
1381 *
1382 * @param array $varMap Must be an associative array of the form
1383 * [ 'dest1' => 'source1', ... ]. Source items may be literals
1384 * rather than field names, but strings should be quoted with
1385 * IDatabase::addQuotes()
1386 *
1387 * @param array $conds Condition array. See $conds in IDatabase::select() for
1388 * the details of the format of condition arrays. May be "*" to copy the
1389 * whole table.
1390 *
1391 * @param string $fname The function name of the caller, from __METHOD__
1392 *
1393 * @param array $insertOptions Options for the INSERT part of the query, see
1394 * IDatabase::insert() for details. Also, one additional option is
1395 * available: pass 'NO_AUTO_COLUMNS' to hint that the query does not use
1396 * an auto-increment or sequence to determine any column values.
1397 * @param array $selectOptions Options for the SELECT part of the query, see
1398 * IDatabase::select() for details.
1399 * @param array $selectJoinConds Join conditions for the SELECT part of the query, see
1400 * IDatabase::select() for details.
1401 *
1402 * @return bool Return true if no exception was thrown (deprecated since 1.33)
1403 * @throws DBError
1404 */
1405 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
1406 $fname = __METHOD__,
1407 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
1408 );
1409
1410 /**
1411 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1412 * within the UNION construct.
1413 * @return bool
1414 */
1415 public function unionSupportsOrderAndLimit();
1416
1417 /**
1418 * Construct a UNION query
1419 * This is used for providing overload point for other DB abstractions
1420 * not compatible with the MySQL syntax.
1421 * @param array $sqls SQL statements to combine
1422 * @param bool $all Either IDatabase::UNION_ALL or IDatabase::UNION_DISTINCT
1423 * @return string SQL fragment
1424 */
1425 public function unionQueries( $sqls, $all );
1426
1427 /**
1428 * Construct a UNION query for permutations of conditions
1429 *
1430 * Databases sometimes have trouble with queries that have multiple values
1431 * for multiple condition parameters combined with limits and ordering.
1432 * This method constructs queries for the Cartesian product of the
1433 * conditions and unions them all together.
1434 *
1435 * @see IDatabase::select()
1436 * @since 1.30
1437 * @param string|array $table Table name
1438 * @param string|array $vars Field names
1439 * @param array $permute_conds Conditions for the Cartesian product. Keys
1440 * are field names, values are arrays of the possible values for that
1441 * field.
1442 * @param string|array $extra_conds Additional conditions to include in the
1443 * query.
1444 * @param string $fname Caller function name
1445 * @param string|array $options Query options. In addition to the options
1446 * recognized by IDatabase::select(), the following may be used:
1447 * - NOTALL: Set to use UNION instead of UNION ALL.
1448 * - INNER ORDER BY: If specified and supported, subqueries will use this
1449 * instead of ORDER BY.
1450 * @param string|array $join_conds Join conditions
1451 * @return string SQL query string.
1452 */
1453 public function unionConditionPermutations(
1454 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
1455 $options = [], $join_conds = []
1456 );
1457
1458 /**
1459 * Returns an SQL expression for a simple conditional. This doesn't need
1460 * to be overridden unless CASE isn't supported in your DBMS.
1461 *
1462 * @param string|array $cond SQL expression which will result in a boolean value
1463 * @param string $trueVal SQL expression to return if true
1464 * @param string $falseVal SQL expression to return if false
1465 * @return string SQL fragment
1466 */
1467 public function conditional( $cond, $trueVal, $falseVal );
1468
1469 /**
1470 * Returns a command for str_replace function in SQL query.
1471 * Uses REPLACE() in MySQL
1472 *
1473 * @param string $orig Column to modify
1474 * @param string $old Column to seek
1475 * @param string $new Column to replace with
1476 *
1477 * @return string
1478 */
1479 public function strreplace( $orig, $old, $new );
1480
1481 /**
1482 * Determines how long the server has been up
1483 *
1484 * @return int
1485 * @throws DBError
1486 */
1487 public function getServerUptime();
1488
1489 /**
1490 * Determines if the last failure was due to a deadlock
1491 *
1492 * Note that during a deadlock, the prior transaction will have been lost
1493 *
1494 * @return bool
1495 */
1496 public function wasDeadlock();
1497
1498 /**
1499 * Determines if the last failure was due to a lock timeout
1500 *
1501 * Note that during a lock wait timeout, the prior transaction will have been lost
1502 *
1503 * @return bool
1504 */
1505 public function wasLockTimeout();
1506
1507 /**
1508 * Determines if the last query error was due to a dropped connection
1509 *
1510 * Note that during a connection loss, the prior transaction will have been lost
1511 *
1512 * @return bool
1513 * @since 1.31
1514 */
1515 public function wasConnectionLoss();
1516
1517 /**
1518 * Determines if the last failure was due to the database being read-only.
1519 *
1520 * @return bool
1521 */
1522 public function wasReadOnlyError();
1523
1524 /**
1525 * Determines if the last query error was due to something outside of the query itself
1526 *
1527 * Note that the transaction may have been lost, discarding prior writes and results
1528 *
1529 * @return bool
1530 */
1531 public function wasErrorReissuable();
1532
1533 /**
1534 * Wait for the replica DB to catch up to a given master position
1535 *
1536 * Note that this does not start any new transactions. If any existing transaction
1537 * is flushed, and this is called, then queries will reflect the point the DB was synced
1538 * up to (on success) without interference from REPEATABLE-READ snapshots.
1539 *
1540 * @param DBMasterPos $pos
1541 * @param int $timeout The maximum number of seconds to wait for synchronisation
1542 * @return int|null Zero if the replica DB was past that position already,
1543 * greater than zero if we waited for some period of time, less than
1544 * zero if it timed out, and null on error
1545 * @throws DBError
1546 */
1547 public function masterPosWait( DBMasterPos $pos, $timeout );
1548
1549 /**
1550 * Get the replication position of this replica DB
1551 *
1552 * @return DBMasterPos|bool False if this is not a replica DB
1553 * @throws DBError
1554 */
1555 public function getReplicaPos();
1556
1557 /**
1558 * Get the position of this master
1559 *
1560 * @return DBMasterPos|bool False if this is not a master
1561 * @throws DBError
1562 */
1563 public function getMasterPos();
1564
1565 /**
1566 * @return bool Whether the DB is marked as read-only server-side
1567 * @since 1.28
1568 */
1569 public function serverIsReadOnly();
1570
1571 /**
1572 * Run a callback as soon as the current transaction commits or rolls back.
1573 * An error is thrown if no transaction is pending. Queries in the function will run in
1574 * AUTOCOMMIT mode unless there are begin() calls. Callbacks must commit any transactions
1575 * that they begin.
1576 *
1577 * This is useful for combining cooperative locks and DB transactions.
1578 *
1579 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1580 *
1581 * The callback takes the following arguments:
1582 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK)
1583 * - This IDatabase instance (since 1.32)
1584 *
1585 * @param callable $callback
1586 * @param string $fname Caller name
1587 * @since 1.28
1588 */
1589 public function onTransactionResolution( callable $callback, $fname = __METHOD__ );
1590
1591 /**
1592 * Run a callback as soon as there is no transaction pending.
1593 * If there is a transaction and it is rolled back, then the callback is cancelled.
1594 *
1595 * When transaction round mode (DBO_TRX) is set, the callback will run at the end
1596 * of the round, just after all peer transactions COMMIT. If the transaction round
1597 * is rolled back, then the callback is cancelled.
1598 *
1599 * Queries in the function will run in AUTOCOMMIT mode unless there are begin() calls.
1600 * Callbacks must commit any transactions that they begin.
1601 *
1602 * This is useful for updates to different systems or when separate transactions are needed.
1603 * For example, one might want to enqueue jobs into a system outside the database, but only
1604 * after the database is updated so that the jobs will see the data when they actually run.
1605 * It can also be used for updates that easily suffer from lock timeouts and deadlocks,
1606 * but where atomicity is not essential.
1607 *
1608 * Avoid using IDatabase instances aside from this one in the callback, unless such instances
1609 * never have IDatabase::DBO_TRX set. This keeps callbacks from interfering with one another.
1610 *
1611 * Updates will execute in the order they were enqueued.
1612 *
1613 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode
1614 *
1615 * The callback takes the following arguments:
1616 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_IDLE)
1617 * - This IDatabase instance (since 1.32)
1618 *
1619 * @param callable $callback
1620 * @param string $fname Caller name
1621 * @since 1.32
1622 */
1623 public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ );
1624
1625 /**
1626 * Alias for onTransactionCommitOrIdle() for backwards-compatibility
1627 *
1628 * @param callable $callback
1629 * @param string $fname
1630 * @since 1.20
1631 * @deprecated Since 1.32
1632 */
1633 public function onTransactionIdle( callable $callback, $fname = __METHOD__ );
1634
1635 /**
1636 * Run a callback before the current transaction commits or now if there is none.
1637 * If there is a transaction and it is rolled back, then the callback is cancelled.
1638 *
1639 * When transaction round mode (DBO_TRX) is set, the callback will run at the end
1640 * of the round, just before all peer transactions COMMIT. If the transaction round
1641 * is rolled back, then the callback is cancelled.
1642 *
1643 * Callbacks must not start nor commit any transactions. If no transaction is active,
1644 * then a transaction will wrap the callback.
1645 *
1646 * This is useful for updates that easily suffer from lock timeouts and deadlocks,
1647 * but where atomicity is strongly desired for these updates and some related updates.
1648 *
1649 * Updates will execute in the order they were enqueued.
1650 *
1651 * The callback takes the one argument:
1652 * - This IDatabase instance (since 1.32)
1653 *
1654 * @param callable $callback
1655 * @param string $fname Caller name
1656 * @since 1.22
1657 */
1658 public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ );
1659
1660 /**
1661 * Run a callback after each time any transaction commits or rolls back
1662 *
1663 * The callback takes two arguments:
1664 * - IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK
1665 * - This IDatabase object
1666 * Callbacks must commit any transactions that they begin.
1667 *
1668 * Registering a callback here will not affect writesOrCallbacks() pending.
1669 *
1670 * Since callbacks from this or onTransactionCommitOrIdle() can start and end transactions,
1671 * a single call to IDatabase::commit might trigger multiple runs of the listener callbacks.
1672 *
1673 * @param string $name Callback name
1674 * @param callable|null $callback Use null to unset a listener
1675 * @since 1.28
1676 */
1677 public function setTransactionListener( $name, callable $callback = null );
1678
1679 /**
1680 * Begin an atomic section of SQL statements
1681 *
1682 * Start an implicit transaction if no transaction is already active, set a savepoint
1683 * (if $cancelable is ATOMIC_CANCELABLE), and track the given section name to enforce
1684 * that the transaction is not committed prematurely. The end of the section must be
1685 * signified exactly once, either by endAtomic() or cancelAtomic(). Sections can have
1686 * have layers of inner sections (sub-sections), but all sections must be ended in order
1687 * of innermost to outermost. Transactions cannot be started or committed until all
1688 * atomic sections are closed.
1689 *
1690 * ATOMIC_CANCELABLE is useful when the caller needs to handle specific failure cases
1691 * by discarding the section's writes. This should not be used for failures when:
1692 * - upsert() could easily be used instead
1693 * - insert() with IGNORE could easily be used instead
1694 * - select() with FOR UPDATE could be checked before issuing writes instead
1695 * - The failure is from code that runs after the first write but doesn't need to
1696 * - The failures are from contention solvable via onTransactionPreCommitOrIdle()
1697 * - The failures are deadlocks; the RDBMs usually discard the whole transaction
1698 *
1699 * @note callers must use additional measures for situations involving two or more
1700 * (peer) transactions (e.g. updating two database servers at once). The transaction
1701 * and savepoint logic of this method only applies to this specific IDatabase instance.
1702 *
1703 * Example usage:
1704 * @code
1705 * // Start a transaction if there isn't one already
1706 * $dbw->startAtomic( __METHOD__ );
1707 * // Serialize these thread table updates
1708 * $dbw->select( 'thread', '1', [ 'td_id' => $tid ], __METHOD__, 'FOR UPDATE' );
1709 * // Add a new comment for the thread
1710 * $dbw->insert( 'comment', $row, __METHOD__ );
1711 * $cid = $db->insertId();
1712 * // Update thread reference to last comment
1713 * $dbw->update( 'thread', [ 'td_latest' => $cid ], [ 'td_id' => $tid ], __METHOD__ );
1714 * // Demark the end of this conceptual unit of updates
1715 * $dbw->endAtomic( __METHOD__ );
1716 * @endcode
1717 *
1718 * Example usage (atomic changes that might have to be discarded):
1719 * @code
1720 * // Start a transaction if there isn't one already
1721 * $sectionId = $dbw->startAtomic( __METHOD__, $dbw::ATOMIC_CANCELABLE );
1722 * // Create new record metadata row
1723 * $dbw->insert( 'records', $row, __METHOD__ );
1724 * // Figure out where to store the data based on the new row's ID
1725 * $path = $recordDirectory . '/' . $dbw->insertId();
1726 * // Write the record data to the storage system
1727 * $status = $fileBackend->create( [ 'dst' => $path, 'content' => $data ] );
1728 * if ( $status->isOK() ) {
1729 * // Try to cleanup files orphaned by transaction rollback
1730 * $dbw->onTransactionResolution(
1731 * function ( $type ) use ( $fileBackend, $path ) {
1732 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) {
1733 * $fileBackend->delete( [ 'src' => $path ] );
1734 * }
1735 * },
1736 * __METHOD__
1737 * );
1738 * // Demark the end of this conceptual unit of updates
1739 * $dbw->endAtomic( __METHOD__ );
1740 * } else {
1741 * // Discard these writes from the transaction (preserving prior writes)
1742 * $dbw->cancelAtomic( __METHOD__, $sectionId );
1743 * }
1744 * @endcode
1745 *
1746 * @since 1.23
1747 * @param string $fname
1748 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a
1749 * savepoint and enable self::cancelAtomic() for this section.
1750 * @return AtomicSectionIdentifier section ID token
1751 * @throws DBError
1752 */
1753 public function startAtomic( $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE );
1754
1755 /**
1756 * Ends an atomic section of SQL statements
1757 *
1758 * Ends the next section of atomic SQL statements and commits the transaction
1759 * if necessary.
1760 *
1761 * @since 1.23
1762 * @see IDatabase::startAtomic
1763 * @param string $fname
1764 * @throws DBError
1765 */
1766 public function endAtomic( $fname = __METHOD__ );
1767
1768 /**
1769 * Cancel an atomic section of SQL statements
1770 *
1771 * This will roll back only the statements executed since the start of the
1772 * most recent atomic section, and close that section. If a transaction was
1773 * open before the corresponding startAtomic() call, any statements before
1774 * that call are *not* rolled back and the transaction remains open. If the
1775 * corresponding startAtomic() implicitly started a transaction, that
1776 * transaction is rolled back.
1777 *
1778 * @note callers must use additional measures for situations involving two or more
1779 * (peer) transactions (e.g. updating two database servers at once). The transaction
1780 * and savepoint logic of startAtomic() are bound to specific IDatabase instances.
1781 *
1782 * Note that a call to IDatabase::rollback() will also roll back any open atomic sections.
1783 *
1784 * @note As a micro-optimization to save a few DB calls, this method may only
1785 * be called when startAtomic() was called with the ATOMIC_CANCELABLE flag.
1786 * @since 1.31
1787 * @see IDatabase::startAtomic
1788 * @param string $fname
1789 * @param AtomicSectionIdentifier|null $sectionId Section ID from startAtomic();
1790 * passing this enables cancellation of unclosed nested sections [optional]
1791 * @throws DBError
1792 */
1793 public function cancelAtomic( $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null );
1794
1795 /**
1796 * Perform an atomic section of reversable SQL statements from a callback
1797 *
1798 * The $callback takes the following arguments:
1799 * - This database object
1800 * - The value of $fname
1801 *
1802 * This will execute the callback inside a pair of startAtomic()/endAtomic() calls.
1803 * If any exception occurs during execution of the callback, it will be handled as follows:
1804 * - If $cancelable is ATOMIC_CANCELABLE, cancelAtomic() will be called to back out any
1805 * (and only) statements executed during the atomic section. If that succeeds, then the
1806 * exception will be re-thrown; if it fails, then a different exception will be thrown
1807 * and any further query attempts will fail until rollback() is called.
1808 * - If $cancelable is ATOMIC_NOT_CANCELABLE, cancelAtomic() will be called to mark the
1809 * end of the section and the error will be re-thrown. Any further query attempts will
1810 * fail until rollback() is called.
1811 *
1812 * This method is convenient for letting calls to the caller of this method be wrapped
1813 * in a try/catch blocks for exception types that imply that the caller failed but was
1814 * able to properly discard the changes it made in the transaction. This method can be
1815 * an alternative to explicit calls to startAtomic()/endAtomic()/cancelAtomic().
1816 *
1817 * Example usage, "RecordStore::save" method:
1818 * @code
1819 * $dbw->doAtomicSection( __METHOD__, function ( $dbw ) use ( $record ) {
1820 * // Create new record metadata row
1821 * $dbw->insert( 'records', $record->toArray(), __METHOD__ );
1822 * // Figure out where to store the data based on the new row's ID
1823 * $path = $this->recordDirectory . '/' . $dbw->insertId();
1824 * // Write the record data to the storage system;
1825 * // blob store throughs StoreFailureException on failure
1826 * $this->blobStore->create( $path, $record->getJSON() );
1827 * // Try to cleanup files orphaned by transaction rollback
1828 * $dbw->onTransactionResolution(
1829 * function ( $type ) use ( $path ) {
1830 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) {
1831 * $this->blobStore->delete( $path );
1832 * }
1833 * },
1834 * __METHOD__
1835 * );
1836 * }, $dbw::ATOMIC_CANCELABLE );
1837 * @endcode
1838 *
1839 * Example usage, caller of the "RecordStore::save" method:
1840 * @code
1841 * $dbw->startAtomic( __METHOD__ );
1842 * // ...various SQL writes happen...
1843 * try {
1844 * $recordStore->save( $record );
1845 * } catch ( StoreFailureException $e ) {
1846 * // ...various SQL writes happen...
1847 * }
1848 * // ...various SQL writes happen...
1849 * $dbw->endAtomic( __METHOD__ );
1850 * @endcode
1851 *
1852 * @see Database::startAtomic
1853 * @see Database::endAtomic
1854 * @see Database::cancelAtomic
1855 *
1856 * @param string $fname Caller name (usually __METHOD__)
1857 * @param callable $callback Callback that issues DB updates
1858 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a
1859 * savepoint and enable self::cancelAtomic() for this section.
1860 * @return mixed $res Result of the callback (since 1.28)
1861 * @throws DBError
1862 * @throws RuntimeException
1863 * @since 1.27; prior to 1.31 this did a rollback() instead of
1864 * cancelAtomic(), and assumed no callers up the stack would ever try to
1865 * catch the exception.
1866 */
1867 public function doAtomicSection(
1868 $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE
1869 );
1870
1871 /**
1872 * Begin a transaction. If a transaction is already in progress,
1873 * that transaction will be committed before the new transaction is started.
1874 *
1875 * Only call this from code with outer transcation scope.
1876 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1877 * Nesting of transactions is not supported.
1878 *
1879 * Note that when the DBO_TRX flag is set (which is usually the case for web
1880 * requests, but not for maintenance scripts), any previous database query
1881 * will have started a transaction automatically.
1882 *
1883 * Nesting of transactions is not supported. Attempts to nest transactions
1884 * will cause a warning, unless the current transaction was started
1885 * automatically because of the DBO_TRX flag.
1886 *
1887 * @param string $fname Calling function name
1888 * @param string $mode A situationally valid IDatabase::TRANSACTION_* constant [optional]
1889 * @throws DBError
1890 */
1891 public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT );
1892
1893 /**
1894 * Commits a transaction previously started using begin().
1895 * If no transaction is in progress, a warning is issued.
1896 *
1897 * Only call this from code with outer transcation scope.
1898 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1899 * Nesting of transactions is not supported.
1900 *
1901 * @param string $fname
1902 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_*
1903 * constant to disable warnings about explicitly committing implicit transactions,
1904 * or calling commit when no transaction is in progress.
1905 *
1906 * This will trigger an exception if there is an ongoing explicit transaction.
1907 *
1908 * Only set the flush flag if you are sure that these warnings are not applicable,
1909 * and no explicit transactions are open.
1910 *
1911 * @throws DBError
1912 */
1913 public function commit( $fname = __METHOD__, $flush = '' );
1914
1915 /**
1916 * Rollback a transaction previously started using begin().
1917 * If no transaction is in progress, a warning is issued.
1918 *
1919 * Only call this from code with outer transcation scope.
1920 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1921 * Nesting of transactions is not supported. If a serious unexpected error occurs,
1922 * throwing an Exception is preferrable, using a pre-installed error handler to trigger
1923 * rollback (in any case, failure to issue COMMIT will cause rollback server-side).
1924 *
1925 * Query, connection, and onTransaction* callback errors will be suppressed and logged.
1926 *
1927 * @param string $fname Calling function name
1928 * @param string $flush Flush flag, set to a situationally valid IDatabase::FLUSHING_*
1929 * constant to disable warnings about calling rollback when no transaction is in
1930 * progress. This will silently break any ongoing explicit transaction. Only set the
1931 * flush flag if you are sure that it is safe to ignore these warnings in your context.
1932 * @throws DBError
1933 * @since 1.23 Added $flush parameter
1934 */
1935 public function rollback( $fname = __METHOD__, $flush = '' );
1936
1937 /**
1938 * Commit any transaction but error out if writes or callbacks are pending
1939 *
1940 * This is intended for clearing out REPEATABLE-READ snapshots so that callers can
1941 * see a new point-in-time of the database. This is useful when one of many transaction
1942 * rounds finished and significant time will pass in the script's lifetime. It is also
1943 * useful to call on a replica DB after waiting on replication to catch up to the master.
1944 *
1945 * @param string $fname Calling function name
1946 * @throws DBError
1947 * @since 1.28
1948 */
1949 public function flushSnapshot( $fname = __METHOD__ );
1950
1951 /**
1952 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1953 * to the format used for inserting into timestamp fields in this DBMS.
1954 *
1955 * The result is unquoted, and needs to be passed through addQuotes()
1956 * before it can be included in raw SQL.
1957 *
1958 * @param string|int $ts
1959 *
1960 * @return string
1961 */
1962 public function timestamp( $ts = 0 );
1963
1964 /**
1965 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1966 * to the format used for inserting into timestamp fields in this DBMS. If
1967 * NULL is input, it is passed through, allowing NULL values to be inserted
1968 * into timestamp fields.
1969 *
1970 * The result is unquoted, and needs to be passed through addQuotes()
1971 * before it can be included in raw SQL.
1972 *
1973 * @param string|int|null $ts
1974 *
1975 * @return string
1976 */
1977 public function timestampOrNull( $ts = null );
1978
1979 /**
1980 * Ping the server and try to reconnect if it there is no connection
1981 *
1982 * @param float|null &$rtt Value to store the estimated RTT [optional]
1983 * @return bool Success or failure
1984 */
1985 public function ping( &$rtt = null );
1986
1987 /**
1988 * Get the amount of replication lag for this database server
1989 *
1990 * Callers should avoid using this method while a transaction is active
1991 *
1992 * @return int|bool Database replication lag in seconds or false on error
1993 * @throws DBError
1994 */
1995 public function getLag();
1996
1997 /**
1998 * Get the replica DB lag when the current transaction started
1999 * or a general lag estimate if not transaction is active
2000 *
2001 * This is useful when transactions might use snapshot isolation
2002 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2003 * is this lag plus transaction duration. If they don't, it is still
2004 * safe to be pessimistic. In AUTOCOMMIT mode, this still gives an
2005 * indication of the staleness of subsequent reads.
2006 *
2007 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2008 * @throws DBError
2009 * @since 1.27
2010 */
2011 public function getSessionLagStatus();
2012
2013 /**
2014 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2015 *
2016 * @return int
2017 */
2018 public function maxListLen();
2019
2020 /**
2021 * Some DBMSs have a special format for inserting into blob fields, they
2022 * don't allow simple quoted strings to be inserted. To insert into such
2023 * a field, pass the data through this function before passing it to
2024 * IDatabase::insert().
2025 *
2026 * @param string $b
2027 * @return string|Blob
2028 */
2029 public function encodeBlob( $b );
2030
2031 /**
2032 * Some DBMSs return a special placeholder object representing blob fields
2033 * in result objects. Pass the object through this function to return the
2034 * original string.
2035 *
2036 * @param string|Blob $b
2037 * @return string
2038 */
2039 public function decodeBlob( $b );
2040
2041 /**
2042 * Override database's default behavior. $options include:
2043 * 'connTimeout' : Set the connection timeout value in seconds.
2044 * May be useful for very long batch queries such as
2045 * full-wiki dumps, where a single query reads out over
2046 * hours or days.
2047 *
2048 * @param array $options
2049 * @return void
2050 * @throws DBError
2051 */
2052 public function setSessionOptions( array $options );
2053
2054 /**
2055 * Set variables to be used in sourceFile/sourceStream, in preference to the
2056 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2057 * all. If it's set to false, $GLOBALS will be used.
2058 *
2059 * @param bool|array $vars Mapping variable name to value.
2060 */
2061 public function setSchemaVars( $vars );
2062
2063 /**
2064 * Check to see if a named lock is not locked by any thread (non-blocking)
2065 *
2066 * @param string $lockName Name of lock to poll
2067 * @param string $method Name of method calling us
2068 * @return bool
2069 * @throws DBError
2070 * @since 1.20
2071 */
2072 public function lockIsFree( $lockName, $method );
2073
2074 /**
2075 * Acquire a named lock
2076 *
2077 * Named locks are not related to transactions
2078 *
2079 * @param string $lockName Name of lock to aquire
2080 * @param string $method Name of the calling method
2081 * @param int $timeout Acquisition timeout in seconds
2082 * @return bool
2083 * @throws DBError
2084 */
2085 public function lock( $lockName, $method, $timeout = 5 );
2086
2087 /**
2088 * Release a lock
2089 *
2090 * Named locks are not related to transactions
2091 *
2092 * @param string $lockName Name of lock to release
2093 * @param string $method Name of the calling method
2094 *
2095 * @return int Returns 1 if the lock was released, 0 if the lock was not established
2096 * by this thread (in which case the lock is not released), and NULL if the named lock
2097 * did not exist
2098 *
2099 * @throws DBError
2100 */
2101 public function unlock( $lockName, $method );
2102
2103 /**
2104 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object
2105 *
2106 * Only call this from outer transcation scope and when only one DB will be affected.
2107 * See https://www.mediawiki.org/wiki/Database_transactions for details.
2108 *
2109 * This is suitiable for transactions that need to be serialized using cooperative locks,
2110 * where each transaction can see each others' changes. Any transaction is flushed to clear
2111 * out stale REPEATABLE-READ snapshot data. Once the returned object falls out of PHP scope,
2112 * the lock will be released unless a transaction is active. If one is active, then the lock
2113 * will be released when it either commits or rolls back.
2114 *
2115 * If the lock acquisition failed, then no transaction flush happens, and null is returned.
2116 *
2117 * @param string $lockKey Name of lock to release
2118 * @param string $fname Name of the calling method
2119 * @param int $timeout Acquisition timeout in seconds
2120 * @return ScopedCallback|null
2121 * @throws DBError
2122 * @since 1.27
2123 */
2124 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
2125
2126 /**
2127 * Check to see if a named lock used by lock() use blocking queues
2128 *
2129 * @return bool
2130 * @since 1.26
2131 */
2132 public function namedLocksEnqueue();
2133
2134 /**
2135 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2136 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2137 * because "i" sorts after all numbers.
2138 *
2139 * @return string
2140 */
2141 public function getInfinity();
2142
2143 /**
2144 * Encode an expiry time into the DBMS dependent format
2145 *
2146 * @param string $expiry Timestamp for expiry, or the 'infinity' string
2147 * @return string
2148 */
2149 public function encodeExpiry( $expiry );
2150
2151 /**
2152 * Decode an expiry time into a DBMS independent format
2153 *
2154 * @param string $expiry DB timestamp field value for expiry
2155 * @param int $format TS_* constant, defaults to TS_MW
2156 * @return string
2157 */
2158 public function decodeExpiry( $expiry, $format = TS_MW );
2159
2160 /**
2161 * Allow or deny "big selects" for this session only. This is done by setting
2162 * the sql_big_selects session variable.
2163 *
2164 * This is a MySQL-specific feature.
2165 *
2166 * @param bool|string $value True for allow, false for deny, or "default" to
2167 * restore the initial value
2168 */
2169 public function setBigSelects( $value = true );
2170
2171 /**
2172 * @return bool Whether this DB is read-only
2173 * @since 1.27
2174 */
2175 public function isReadOnly();
2176
2177 /**
2178 * Make certain table names use their own database, schema, and table prefix
2179 * when passed into SQL queries pre-escaped and without a qualified database name
2180 *
2181 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
2182 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
2183 *
2184 * Calling this twice will completely clear any old table aliases. Also, note that
2185 * callers are responsible for making sure the schemas and databases actually exist.
2186 *
2187 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
2188 * @since 1.28
2189 */
2190 public function setTableAliases( array $aliases );
2191
2192 /**
2193 * Convert certain index names to alternative names before querying the DB
2194 *
2195 * Note that this applies to indexes regardless of the table they belong to.
2196 *
2197 * This can be employed when an index was renamed X => Y in code, but the new Y-named
2198 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
2199 * the aliases can be removed, and then the old X-named indexes dropped.
2200 *
2201 * @param string[] $aliases
2202 * @since 1.31
2203 */
2204 public function setIndexAliases( array $aliases );
2205
2206 /**
2207 * Get a debugging string that mentions the database type, the ID of this instance,
2208 * and the ID of any underlying connection resource or driver object if one is present
2209 *
2210 * @return string "<db type> object #<X>" or "<db type> object #<X> (resource/handle id #<Y>)"
2211 * @since 1.34
2212 */
2213 public function __toString();
2214 }
2215
2216 /**
2217 * @deprecated since 1.29
2218 */
2219 class_alias( IDatabase::class, 'IDatabase' );