Move DBMasterPos to Rdbms namespace
[lhc/web/wiklou.git] / includes / libs / rdbms / database / IDatabase.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26 use Wikimedia\ScopedCallback;
27 use Wikimedia\Rdbms\LikeMatch;
28 use Wikimedia\Rdbms\DBMasterPos;
29
30 /**
31 * Basic database interface for live and lazy-loaded relation database handles
32 *
33 * @note: IDatabase and DBConnRef should be updated to reflect any changes
34 * @ingroup Database
35 */
36 interface IDatabase {
37 /** @var int Callback triggered immediately due to no active transaction */
38 const TRIGGER_IDLE = 1;
39 /** @var int Callback triggered by COMMIT */
40 const TRIGGER_COMMIT = 2;
41 /** @var int Callback triggered by ROLLBACK */
42 const TRIGGER_ROLLBACK = 3;
43
44 /** @var string Transaction is requested by regular caller outside of the DB layer */
45 const TRANSACTION_EXPLICIT = '';
46 /** @var string Transaction is requested internally via DBO_TRX/startAtomic() */
47 const TRANSACTION_INTERNAL = 'implicit';
48
49 /** @var string Transaction operation comes from service managing all DBs */
50 const FLUSHING_ALL_PEERS = 'flush';
51 /** @var string Transaction operation comes from the database class internally */
52 const FLUSHING_INTERNAL = 'flush';
53
54 /** @var string Do not remember the prior flags */
55 const REMEMBER_NOTHING = '';
56 /** @var string Remember the prior flags */
57 const REMEMBER_PRIOR = 'remember';
58 /** @var string Restore to the prior flag state */
59 const RESTORE_PRIOR = 'prior';
60 /** @var string Restore to the initial flag state */
61 const RESTORE_INITIAL = 'initial';
62
63 /** @var string Estimate total time (RTT, scanning, waiting on locks, applying) */
64 const ESTIMATE_TOTAL = 'total';
65 /** @var string Estimate time to apply (scanning, applying) */
66 const ESTIMATE_DB_APPLY = 'apply';
67
68 /** @var int Combine list with comma delimeters */
69 const LIST_COMMA = 0;
70 /** @var int Combine list with AND clauses */
71 const LIST_AND = 1;
72 /** @var int Convert map into a SET clause */
73 const LIST_SET = 2;
74 /** @var int Treat as field name and do not apply value escaping */
75 const LIST_NAMES = 3;
76 /** @var int Combine list with OR clauses */
77 const LIST_OR = 4;
78
79 /** @var int Enable debug logging */
80 const DBO_DEBUG = 1;
81 /** @var int Disable query buffering (only one result set can be iterated at a time) */
82 const DBO_NOBUFFER = 2;
83 /** @var int Ignore query errors (internal use only!) */
84 const DBO_IGNORE = 4;
85 /** @var int Autoatically start transaction on first query (work with ILoadBalancer rounds) */
86 const DBO_TRX = 8;
87 /** @var int Use DBO_TRX in non-CLI mode */
88 const DBO_DEFAULT = 16;
89 /** @var int Use DB persistent connections if possible */
90 const DBO_PERSISTENT = 32;
91 /** @var int DBA session mode; mostly for Oracle */
92 const DBO_SYSDBA = 64;
93 /** @var int Schema file mode; mostly for Oracle */
94 const DBO_DDLMODE = 128;
95 /** @var int Enable SSL/TLS in connection protocol */
96 const DBO_SSL = 256;
97 /** @var int Enable compression in connection protocol */
98 const DBO_COMPRESS = 512;
99
100 /**
101 * A string describing the current software version, and possibly
102 * other details in a user-friendly way. Will be listed on Special:Version, etc.
103 * Use getServerVersion() to get machine-friendly information.
104 *
105 * @return string Version information from the database server
106 */
107 public function getServerInfo();
108
109 /**
110 * Turns buffering of SQL result sets on (true) or off (false). Default is "on".
111 *
112 * Unbuffered queries are very troublesome in MySQL:
113 *
114 * - If another query is executed while the first query is being read
115 * out, the first query is killed. This means you can't call normal
116 * Database functions while you are reading an unbuffered query result
117 * from a normal Database connection.
118 *
119 * - Unbuffered queries cause the MySQL server to use large amounts of
120 * memory and to hold broad locks which block other queries.
121 *
122 * If you want to limit client-side memory, it's almost always better to
123 * split up queries into batches using a LIMIT clause than to switch off
124 * buffering.
125 *
126 * @param null|bool $buffer
127 * @return null|bool The previous value of the flag
128 */
129 public function bufferResults( $buffer = null );
130
131 /**
132 * Gets the current transaction level.
133 *
134 * Historically, transactions were allowed to be "nested". This is no
135 * longer supported, so this function really only returns a boolean.
136 *
137 * @return int The previous value
138 */
139 public function trxLevel();
140
141 /**
142 * Get the UNIX timestamp of the time that the transaction was established
143 *
144 * This can be used to reason about the staleness of SELECT data
145 * in REPEATABLE-READ transaction isolation level.
146 *
147 * @return float|null Returns null if there is not active transaction
148 * @since 1.25
149 */
150 public function trxTimestamp();
151
152 /**
153 * @return bool Whether an explicit transaction or atomic sections are still open
154 * @since 1.28
155 */
156 public function explicitTrxActive();
157
158 /**
159 * Get/set the table prefix.
160 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
161 * @return string The previous table prefix.
162 */
163 public function tablePrefix( $prefix = null );
164
165 /**
166 * Get/set the db schema.
167 * @param string $schema The database schema to set, or omitted to leave it unchanged.
168 * @return string The previous db schema.
169 */
170 public function dbSchema( $schema = null );
171
172 /**
173 * Get properties passed down from the server info array of the load
174 * balancer.
175 *
176 * @param string $name The entry of the info array to get, or null to get the
177 * whole array
178 *
179 * @return array|mixed|null
180 */
181 public function getLBInfo( $name = null );
182
183 /**
184 * Set the LB info array, or a member of it. If called with one parameter,
185 * the LB info array is set to that parameter. If it is called with two
186 * parameters, the member with the given name is set to the given value.
187 *
188 * @param string $name
189 * @param array $value
190 */
191 public function setLBInfo( $name, $value = null );
192
193 /**
194 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
195 *
196 * @param IDatabase $conn
197 * @since 1.27
198 */
199 public function setLazyMasterHandle( IDatabase $conn );
200
201 /**
202 * Returns true if this database does an implicit sort when doing GROUP BY
203 *
204 * @return bool
205 */
206 public function implicitGroupby();
207
208 /**
209 * Returns true if this database does an implicit order by when the column has an index
210 * For example: SELECT page_title FROM page LIMIT 1
211 *
212 * @return bool
213 */
214 public function implicitOrderby();
215
216 /**
217 * Return the last query that went through IDatabase::query()
218 * @return string
219 */
220 public function lastQuery();
221
222 /**
223 * Returns true if the connection may have been used for write queries.
224 * Should return true if unsure.
225 *
226 * @return bool
227 */
228 public function doneWrites();
229
230 /**
231 * Returns the last time the connection may have been used for write queries.
232 * Should return a timestamp if unsure.
233 *
234 * @return int|float UNIX timestamp or false
235 * @since 1.24
236 */
237 public function lastDoneWrites();
238
239 /**
240 * @return bool Whether there is a transaction open with possible write queries
241 * @since 1.27
242 */
243 public function writesPending();
244
245 /**
246 * Returns true if there is a transaction open with possible write
247 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
248 * This does *not* count recurring callbacks, e.g. from setTransactionListener().
249 *
250 * @return bool
251 */
252 public function writesOrCallbacksPending();
253
254 /**
255 * Get the time spend running write queries for this transaction
256 *
257 * High times could be due to scanning, updates, locking, and such
258 *
259 * @param string $type IDatabase::ESTIMATE_* constant [default: ESTIMATE_ALL]
260 * @return float|bool Returns false if not transaction is active
261 * @since 1.26
262 */
263 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL );
264
265 /**
266 * Get the list of method names that did write queries for this transaction
267 *
268 * @return array
269 * @since 1.27
270 */
271 public function pendingWriteCallers();
272
273 /**
274 * Is a connection to the database open?
275 * @return bool
276 */
277 public function isOpen();
278
279 /**
280 * Set a flag for this connection
281 *
282 * @param int $flag DBO_* constants from Defines.php:
283 * - DBO_DEBUG: output some debug info (same as debug())
284 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
285 * - DBO_TRX: automatically start transactions
286 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
287 * and removes it in command line mode
288 * - DBO_PERSISTENT: use persistant database connection
289 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
290 */
291 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING );
292
293 /**
294 * Clear a flag for this connection
295 *
296 * @param int $flag DBO_* constants from Defines.php:
297 * - DBO_DEBUG: output some debug info (same as debug())
298 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
299 * - DBO_TRX: automatically start transactions
300 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
301 * and removes it in command line mode
302 * - DBO_PERSISTENT: use persistant database connection
303 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
304 */
305 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING );
306
307 /**
308 * Restore the flags to their prior state before the last setFlag/clearFlag call
309 *
310 * @param string $state IDatabase::RESTORE_* constant. [default: RESTORE_PRIOR]
311 * @since 1.28
312 */
313 public function restoreFlags( $state = self::RESTORE_PRIOR );
314
315 /**
316 * Returns a boolean whether the flag $flag is set for this connection
317 *
318 * @param int $flag DBO_* constants from Defines.php:
319 * - DBO_DEBUG: output some debug info (same as debug())
320 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
321 * - DBO_TRX: automatically start transactions
322 * - DBO_PERSISTENT: use persistant database connection
323 * @return bool
324 */
325 public function getFlag( $flag );
326
327 /**
328 * @return string
329 */
330 public function getDomainID();
331
332 /**
333 * Alias for getDomainID()
334 *
335 * @return string
336 */
337 public function getWikiID();
338
339 /**
340 * Get the type of the DBMS, as it appears in $wgDBtype.
341 *
342 * @return string
343 */
344 public function getType();
345
346 /**
347 * Open a connection to the database. Usually aborts on failure
348 *
349 * @param string $server Database server host
350 * @param string $user Database user name
351 * @param string $password Database user password
352 * @param string $dbName Database name
353 * @return bool
354 * @throws DBConnectionError
355 */
356 public function open( $server, $user, $password, $dbName );
357
358 /**
359 * Fetch the next row from the given result object, in object form.
360 * Fields can be retrieved with $row->fieldname, with fields acting like
361 * member variables.
362 * If no more rows are available, false is returned.
363 *
364 * @param ResultWrapper|stdClass $res Object as returned from IDatabase::query(), etc.
365 * @return stdClass|bool
366 * @throws DBUnexpectedError Thrown if the database returns an error
367 */
368 public function fetchObject( $res );
369
370 /**
371 * Fetch the next row from the given result object, in associative array
372 * form. Fields are retrieved with $row['fieldname'].
373 * If no more rows are available, false is returned.
374 *
375 * @param ResultWrapper $res Result object as returned from IDatabase::query(), etc.
376 * @return array|bool
377 * @throws DBUnexpectedError Thrown if the database returns an error
378 */
379 public function fetchRow( $res );
380
381 /**
382 * Get the number of rows in a result object
383 *
384 * @param mixed $res A SQL result
385 * @return int
386 */
387 public function numRows( $res );
388
389 /**
390 * Get the number of fields in a result object
391 * @see https://secure.php.net/mysql_num_fields
392 *
393 * @param mixed $res A SQL result
394 * @return int
395 */
396 public function numFields( $res );
397
398 /**
399 * Get a field name in a result object
400 * @see https://secure.php.net/mysql_field_name
401 *
402 * @param mixed $res A SQL result
403 * @param int $n
404 * @return string
405 */
406 public function fieldName( $res, $n );
407
408 /**
409 * Get the inserted value of an auto-increment row
410 *
411 * The value inserted should be fetched from nextSequenceValue()
412 *
413 * Example:
414 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
415 * $dbw->insert( 'page', [ 'page_id' => $id ] );
416 * $id = $dbw->insertId();
417 *
418 * @return int
419 */
420 public function insertId();
421
422 /**
423 * Change the position of the cursor in a result object
424 * @see https://secure.php.net/mysql_data_seek
425 *
426 * @param mixed $res A SQL result
427 * @param int $row
428 */
429 public function dataSeek( $res, $row );
430
431 /**
432 * Get the last error number
433 * @see https://secure.php.net/mysql_errno
434 *
435 * @return int
436 */
437 public function lastErrno();
438
439 /**
440 * Get a description of the last error
441 * @see https://secure.php.net/mysql_error
442 *
443 * @return string
444 */
445 public function lastError();
446
447 /**
448 * mysql_fetch_field() wrapper
449 * Returns false if the field doesn't exist
450 *
451 * @param string $table Table name
452 * @param string $field Field name
453 *
454 * @return Field
455 */
456 public function fieldInfo( $table, $field );
457
458 /**
459 * Get the number of rows affected by the last write query
460 * @see https://secure.php.net/mysql_affected_rows
461 *
462 * @return int
463 */
464 public function affectedRows();
465
466 /**
467 * Returns a wikitext link to the DB's website, e.g.,
468 * return "[https://www.mysql.com/ MySQL]";
469 * Should at least contain plain text, if for some reason
470 * your database has no website.
471 *
472 * @return string Wikitext of a link to the server software's web site
473 */
474 public function getSoftwareLink();
475
476 /**
477 * A string describing the current software version, like from
478 * mysql_get_server_info().
479 *
480 * @return string Version information from the database server.
481 */
482 public function getServerVersion();
483
484 /**
485 * Closes a database connection.
486 * if it is open : commits any open transactions
487 *
488 * @throws DBError
489 * @return bool Operation success. true if already closed.
490 */
491 public function close();
492
493 /**
494 * @param string $error Fallback error message, used if none is given by DB
495 * @throws DBConnectionError
496 */
497 public function reportConnectionError( $error = 'Unknown error' );
498
499 /**
500 * Run an SQL query and return the result. Normally throws a DBQueryError
501 * on failure. If errors are ignored, returns false instead.
502 *
503 * In new code, the query wrappers select(), insert(), update(), delete(),
504 * etc. should be used where possible, since they give much better DBMS
505 * independence and automatically quote or validate user input in a variety
506 * of contexts. This function is generally only useful for queries which are
507 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
508 * as CREATE TABLE.
509 *
510 * However, the query wrappers themselves should call this function.
511 *
512 * @param string $sql SQL query
513 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
514 * comment (you can use __METHOD__ or add some extra info)
515 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
516 * maybe best to catch the exception instead?
517 * @throws DBError
518 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
519 * for a successful read query, or false on failure if $tempIgnore set
520 */
521 public function query( $sql, $fname = __METHOD__, $tempIgnore = false );
522
523 /**
524 * Report a query error. Log the error, and if neither the object ignore
525 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
526 *
527 * @param string $error
528 * @param int $errno
529 * @param string $sql
530 * @param string $fname
531 * @param bool $tempIgnore
532 * @throws DBQueryError
533 */
534 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false );
535
536 /**
537 * Free a result object returned by query() or select(). It's usually not
538 * necessary to call this, just use unset() or let the variable holding
539 * the result object go out of scope.
540 *
541 * @param mixed $res A SQL result
542 */
543 public function freeResult( $res );
544
545 /**
546 * A SELECT wrapper which returns a single field from a single result row.
547 *
548 * Usually throws a DBQueryError on failure. If errors are explicitly
549 * ignored, returns false on failure.
550 *
551 * If no result rows are returned from the query, false is returned.
552 *
553 * @param string|array $table Table name. See IDatabase::select() for details.
554 * @param string $var The field name to select. This must be a valid SQL
555 * fragment: do not use unvalidated user input.
556 * @param string|array $cond The condition array. See IDatabase::select() for details.
557 * @param string $fname The function name of the caller.
558 * @param string|array $options The query options. See IDatabase::select() for details.
559 *
560 * @return bool|mixed The value from the field, or false on failure.
561 */
562 public function selectField(
563 $table, $var, $cond = '', $fname = __METHOD__, $options = []
564 );
565
566 /**
567 * A SELECT wrapper which returns a list of single field values from result rows.
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 *
581 * @return bool|array The values from the field, or false on failure
582 * @since 1.25
583 */
584 public function selectFieldValues(
585 $table, $var, $cond = '', $fname = __METHOD__, $options = []
586 );
587
588 /**
589 * Execute a SELECT query constructed using the various parameters provided.
590 * See below for full details of the parameters.
591 *
592 * @param string|array $table Table name
593 * @param string|array $vars Field names
594 * @param string|array $conds Conditions
595 * @param string $fname Caller function name
596 * @param array $options Query options
597 * @param array $join_conds Join conditions
598 *
599 *
600 * @param string|array $table
601 *
602 * May be either an array of table names, or a single string holding a table
603 * name. If an array is given, table aliases can be specified, for example:
604 *
605 * [ 'a' => 'user' ]
606 *
607 * This includes the user table in the query, with the alias "a" available
608 * for use in field names (e.g. a.user_name).
609 *
610 * All of the table names given here are automatically run through
611 * Database::tableName(), which causes the table prefix (if any) to be
612 * added, and various other table name mappings to be performed.
613 *
614 * Do not use untrusted user input as a table name. Alias names should
615 * not have characters outside of the Basic multilingual plane.
616 *
617 * @param string|array $vars
618 *
619 * May be either a field name or an array of field names. The field names
620 * can be complete fragments of SQL, for direct inclusion into the SELECT
621 * query. If an array is given, field aliases can be specified, for example:
622 *
623 * [ 'maxrev' => 'MAX(rev_id)' ]
624 *
625 * This includes an expression with the alias "maxrev" in the query.
626 *
627 * If an expression is given, care must be taken to ensure that it is
628 * DBMS-independent.
629 *
630 * Untrusted user input must not be passed to this parameter.
631 *
632 * @param string|array $conds
633 *
634 * May be either a string containing a single condition, or an array of
635 * conditions. If an array is given, the conditions constructed from each
636 * element are combined with AND.
637 *
638 * Array elements may take one of two forms:
639 *
640 * - Elements with a numeric key are interpreted as raw SQL fragments.
641 * - Elements with a string key are interpreted as equality conditions,
642 * where the key is the field name.
643 * - If the value of such an array element is a scalar (such as a
644 * string), it will be treated as data and thus quoted appropriately.
645 * If it is null, an IS NULL clause will be added.
646 * - If the value is an array, an IN (...) clause will be constructed
647 * from its non-null elements, and an IS NULL clause will be added
648 * if null is present, such that the field may match any of the
649 * elements in the array. The non-null elements will be quoted.
650 *
651 * Note that expressions are often DBMS-dependent in their syntax.
652 * DBMS-independent wrappers are provided for constructing several types of
653 * expression commonly used in condition queries. See:
654 * - IDatabase::buildLike()
655 * - IDatabase::conditional()
656 *
657 * Untrusted user input is safe in the values of string keys, however untrusted
658 * input must not be used in the array key names or in the values of numeric keys.
659 * Escaping of untrusted input used in values of numeric keys should be done via
660 * IDatabase::addQuotes()
661 *
662 * @param string|array $options
663 *
664 * Optional: Array of query options. Boolean options are specified by
665 * including them in the array as a string value with a numeric key, for
666 * example:
667 *
668 * [ 'FOR UPDATE' ]
669 *
670 * The supported options are:
671 *
672 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
673 * with LIMIT can theoretically be used for paging through a result set,
674 * but this is discouraged for performance reasons.
675 *
676 * - LIMIT: Integer: return at most this many rows. The rows are sorted
677 * and then the first rows are taken until the limit is reached. LIMIT
678 * is applied to a result set after OFFSET.
679 *
680 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
681 * changed until the next COMMIT.
682 *
683 * - DISTINCT: Boolean: return only unique result rows.
684 *
685 * - GROUP BY: May be either an SQL fragment string naming a field or
686 * expression to group by, or an array of such SQL fragments.
687 *
688 * - HAVING: May be either an string containing a HAVING clause or an array of
689 * conditions building the HAVING clause. If an array is given, the conditions
690 * constructed from each element are combined with AND.
691 *
692 * - ORDER BY: May be either an SQL fragment giving a field name or
693 * expression to order by, or an array of such SQL fragments.
694 *
695 * - USE INDEX: This may be either a string giving the index name to use
696 * for the query, or an array. If it is an associative array, each key
697 * gives the table name (or alias), each value gives the index name to
698 * use for that table. All strings are SQL fragments and so should be
699 * validated by the caller.
700 *
701 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
702 * instead of SELECT.
703 *
704 * And also the following boolean MySQL extensions, see the MySQL manual
705 * for documentation:
706 *
707 * - LOCK IN SHARE MODE
708 * - STRAIGHT_JOIN
709 * - HIGH_PRIORITY
710 * - SQL_BIG_RESULT
711 * - SQL_BUFFER_RESULT
712 * - SQL_SMALL_RESULT
713 * - SQL_CALC_FOUND_ROWS
714 * - SQL_CACHE
715 * - SQL_NO_CACHE
716 *
717 *
718 * @param string|array $join_conds
719 *
720 * Optional associative array of table-specific join conditions. In the
721 * most common case, this is unnecessary, since the join condition can be
722 * in $conds. However, it is useful for doing a LEFT JOIN.
723 *
724 * The key of the array contains the table name or alias. The value is an
725 * array with two elements, numbered 0 and 1. The first gives the type of
726 * join, the second is the same as the $conds parameter. Thus it can be
727 * an SQL fragment, or an array where the string keys are equality and the
728 * numeric keys are SQL fragments all AND'd together. For example:
729 *
730 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
731 *
732 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
733 * with no rows in it will be returned. If there was a query error, a
734 * DBQueryError exception will be thrown, except if the "ignore errors"
735 * option was set, in which case false will be returned.
736 */
737 public function select(
738 $table, $vars, $conds = '', $fname = __METHOD__,
739 $options = [], $join_conds = []
740 );
741
742 /**
743 * The equivalent of IDatabase::select() except that the constructed SQL
744 * is returned, instead of being immediately executed. This can be useful for
745 * doing UNION queries, where the SQL text of each query is needed. In general,
746 * however, callers outside of Database classes should just use select().
747 *
748 * @param string|array $table Table name
749 * @param string|array $vars Field names
750 * @param string|array $conds Conditions
751 * @param string $fname Caller function name
752 * @param string|array $options Query options
753 * @param string|array $join_conds Join conditions
754 *
755 * @return string SQL query string.
756 * @see IDatabase::select()
757 */
758 public function selectSQLText(
759 $table, $vars, $conds = '', $fname = __METHOD__,
760 $options = [], $join_conds = []
761 );
762
763 /**
764 * Single row SELECT wrapper. Equivalent to IDatabase::select(), except
765 * that a single row object is returned. If the query returns no rows,
766 * false is returned.
767 *
768 * @param string|array $table Table name
769 * @param string|array $vars Field names
770 * @param array $conds Conditions
771 * @param string $fname Caller function name
772 * @param string|array $options Query options
773 * @param array|string $join_conds Join conditions
774 *
775 * @return stdClass|bool
776 */
777 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
778 $options = [], $join_conds = []
779 );
780
781 /**
782 * Estimate the number of rows in dataset
783 *
784 * MySQL allows you to estimate the number of rows that would be returned
785 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
786 * index cardinality statistics, and is notoriously inaccurate, especially
787 * when large numbers of rows have recently been added or deleted.
788 *
789 * For DBMSs that don't support fast result size estimation, this function
790 * will actually perform the SELECT COUNT(*).
791 *
792 * Takes the same arguments as IDatabase::select().
793 *
794 * @param string $table Table name
795 * @param string $vars Unused
796 * @param array|string $conds Filters on the table
797 * @param string $fname Function name for profiling
798 * @param array $options Options for select
799 * @return int Row count
800 */
801 public function estimateRowCount(
802 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
803 );
804
805 /**
806 * Get the number of rows in dataset
807 *
808 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
809 *
810 * Takes the same arguments as IDatabase::select().
811 *
812 * @since 1.27 Added $join_conds parameter
813 *
814 * @param array|string $tables Table names
815 * @param string $vars Unused
816 * @param array|string $conds Filters on the table
817 * @param string $fname Function name for profiling
818 * @param array $options Options for select
819 * @param array $join_conds Join conditions (since 1.27)
820 * @return int Row count
821 */
822 public function selectRowCount(
823 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
824 );
825
826 /**
827 * Determines whether a field exists in a table
828 *
829 * @param string $table Table name
830 * @param string $field Filed to check on that table
831 * @param string $fname Calling function name (optional)
832 * @return bool Whether $table has filed $field
833 */
834 public function fieldExists( $table, $field, $fname = __METHOD__ );
835
836 /**
837 * Determines whether an index exists
838 * Usually throws a DBQueryError on failure
839 * If errors are explicitly ignored, returns NULL on failure
840 *
841 * @param string $table
842 * @param string $index
843 * @param string $fname
844 * @return bool|null
845 */
846 public function indexExists( $table, $index, $fname = __METHOD__ );
847
848 /**
849 * Query whether a given table exists
850 *
851 * @param string $table
852 * @param string $fname
853 * @return bool
854 */
855 public function tableExists( $table, $fname = __METHOD__ );
856
857 /**
858 * Determines if a given index is unique
859 *
860 * @param string $table
861 * @param string $index
862 *
863 * @return bool
864 */
865 public function indexUnique( $table, $index );
866
867 /**
868 * INSERT wrapper, inserts an array into a table.
869 *
870 * $a may be either:
871 *
872 * - A single associative array. The array keys are the field names, and
873 * the values are the values to insert. The values are treated as data
874 * and will be quoted appropriately. If NULL is inserted, this will be
875 * converted to a database NULL.
876 * - An array with numeric keys, holding a list of associative arrays.
877 * This causes a multi-row INSERT on DBMSs that support it. The keys in
878 * each subarray must be identical to each other, and in the same order.
879 *
880 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
881 * returns success.
882 *
883 * $options is an array of options, with boolean options encoded as values
884 * with numeric keys, in the same style as $options in
885 * IDatabase::select(). Supported options are:
886 *
887 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
888 * any rows which cause duplicate key errors are not inserted. It's
889 * possible to determine how many rows were successfully inserted using
890 * IDatabase::affectedRows().
891 *
892 * @param string $table Table name. This will be passed through
893 * Database::tableName().
894 * @param array $a Array of rows to insert
895 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
896 * @param array $options Array of options
897 *
898 * @return bool
899 */
900 public function insert( $table, $a, $fname = __METHOD__, $options = [] );
901
902 /**
903 * UPDATE wrapper. Takes a condition array and a SET array.
904 *
905 * @param string $table Name of the table to UPDATE. This will be passed through
906 * Database::tableName().
907 * @param array $values An array of values to SET. For each array element,
908 * the key gives the field name, and the value gives the data to set
909 * that field to. The data will be quoted by IDatabase::addQuotes().
910 * @param array $conds An array of conditions (WHERE). See
911 * IDatabase::select() for the details of the format of condition
912 * arrays. Use '*' to update all rows.
913 * @param string $fname The function name of the caller (from __METHOD__),
914 * for logging and profiling.
915 * @param array $options An array of UPDATE options, can be:
916 * - IGNORE: Ignore unique key conflicts
917 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
918 * @return bool
919 */
920 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] );
921
922 /**
923 * Makes an encoded list of strings from an array
924 *
925 * These can be used to make conjunctions or disjunctions on SQL condition strings
926 * derived from an array (see IDatabase::select() $conds documentation).
927 *
928 * Example usage:
929 * @code
930 * $sql = $db->makeList( [
931 * 'rev_user' => $id,
932 * $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] )
933 * ], $db::LIST_AND );
934 * @endcode
935 * This would set $sql to "rev_user = '$id' AND (rev_minor = '1' OR rev_len < '500')"
936 *
937 * @param array $a Containing the data
938 * @param int $mode IDatabase class constant:
939 * - IDatabase::LIST_COMMA: Comma separated, no field names
940 * - IDatabase::LIST_AND: ANDed WHERE clause (without the WHERE).
941 * - IDatabase::LIST_OR: ORed WHERE clause (without the WHERE)
942 * - IDatabase::LIST_SET: Comma separated with field names, like a SET clause
943 * - IDatabase::LIST_NAMES: Comma separated field names
944 * @throws DBError
945 * @return string
946 */
947 public function makeList( $a, $mode = self::LIST_COMMA );
948
949 /**
950 * Build a partial where clause from a 2-d array such as used for LinkBatch.
951 * The keys on each level may be either integers or strings.
952 *
953 * @param array $data Organized as 2-d
954 * [ baseKeyVal => [ subKeyVal => [ignored], ... ], ... ]
955 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
956 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
957 * @return string|bool SQL fragment, or false if no items in array
958 */
959 public function makeWhereFrom2d( $data, $baseKey, $subKey );
960
961 /**
962 * Return aggregated value alias
963 *
964 * @param array $valuedata
965 * @param string $valuename
966 *
967 * @return string
968 */
969 public function aggregateValue( $valuedata, $valuename = 'value' );
970
971 /**
972 * @param string $field
973 * @return string
974 */
975 public function bitNot( $field );
976
977 /**
978 * @param string $fieldLeft
979 * @param string $fieldRight
980 * @return string
981 */
982 public function bitAnd( $fieldLeft, $fieldRight );
983
984 /**
985 * @param string $fieldLeft
986 * @param string $fieldRight
987 * @return string
988 */
989 public function bitOr( $fieldLeft, $fieldRight );
990
991 /**
992 * Build a concatenation list to feed into a SQL query
993 * @param array $stringList List of raw SQL expressions; caller is
994 * responsible for any quoting
995 * @return string
996 */
997 public function buildConcat( $stringList );
998
999 /**
1000 * Build a GROUP_CONCAT or equivalent statement for a query.
1001 *
1002 * This is useful for combining a field for several rows into a single string.
1003 * NULL values will not appear in the output, duplicated values will appear,
1004 * and the resulting delimiter-separated values have no defined sort order.
1005 * Code using the results may need to use the PHP unique() or sort() methods.
1006 *
1007 * @param string $delim Glue to bind the results together
1008 * @param string|array $table Table name
1009 * @param string $field Field name
1010 * @param string|array $conds Conditions
1011 * @param string|array $join_conds Join conditions
1012 * @return string SQL text
1013 * @since 1.23
1014 */
1015 public function buildGroupConcatField(
1016 $delim, $table, $field, $conds = '', $join_conds = []
1017 );
1018
1019 /**
1020 * @param string $field Field or column to cast
1021 * @return string
1022 * @since 1.28
1023 */
1024 public function buildStringCast( $field );
1025
1026 /**
1027 * Change the current database
1028 *
1029 * @param string $db
1030 * @return bool Success or failure
1031 */
1032 public function selectDB( $db );
1033
1034 /**
1035 * Get the current DB name
1036 * @return string
1037 */
1038 public function getDBname();
1039
1040 /**
1041 * Get the server hostname or IP address
1042 * @return string
1043 */
1044 public function getServer();
1045
1046 /**
1047 * Adds quotes and backslashes.
1048 *
1049 * @param string|int|null|bool|Blob $s
1050 * @return string|int
1051 */
1052 public function addQuotes( $s );
1053
1054 /**
1055 * LIKE statement wrapper, receives a variable-length argument list with
1056 * parts of pattern to match containing either string literals that will be
1057 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
1058 * the function could be provided with an array of aforementioned
1059 * parameters.
1060 *
1061 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
1062 * a LIKE clause that searches for subpages of 'My page title'.
1063 * Alternatively:
1064 * $pattern = [ 'My_page_title/', $dbr->anyString() ];
1065 * $query .= $dbr->buildLike( $pattern );
1066 *
1067 * @since 1.16
1068 * @return string Fully built LIKE statement
1069 */
1070 public function buildLike();
1071
1072 /**
1073 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1074 *
1075 * @return LikeMatch
1076 */
1077 public function anyChar();
1078
1079 /**
1080 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1081 *
1082 * @return LikeMatch
1083 */
1084 public function anyString();
1085
1086 /**
1087 * Returns an appropriately quoted sequence value for inserting a new row.
1088 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1089 * subclass will return an integer, and save the value for insertId()
1090 *
1091 * Any implementation of this function should *not* involve reusing
1092 * sequence numbers created for rolled-back transactions.
1093 * See https://bugs.mysql.com/bug.php?id=30767 for details.
1094 * @param string $seqName
1095 * @return null|int
1096 */
1097 public function nextSequenceValue( $seqName );
1098
1099 /**
1100 * REPLACE query wrapper.
1101 *
1102 * REPLACE is a very handy MySQL extension, which functions like an INSERT
1103 * except that when there is a duplicate key error, the old row is deleted
1104 * and the new row is inserted in its place.
1105 *
1106 * We simulate this with standard SQL with a DELETE followed by INSERT. To
1107 * perform the delete, we need to know what the unique indexes are so that
1108 * we know how to find the conflicting rows.
1109 *
1110 * It may be more efficient to leave off unique indexes which are unlikely
1111 * to collide. However if you do this, you run the risk of encountering
1112 * errors which wouldn't have occurred in MySQL.
1113 *
1114 * @param string $table The table to replace the row(s) in.
1115 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
1116 * a field name or an array of field names
1117 * @param array $rows Can be either a single row to insert, or multiple rows,
1118 * in the same format as for IDatabase::insert()
1119 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1120 */
1121 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ );
1122
1123 /**
1124 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
1125 *
1126 * This updates any conflicting rows (according to the unique indexes) using
1127 * the provided SET clause and inserts any remaining (non-conflicted) rows.
1128 *
1129 * $rows may be either:
1130 * - A single associative array. The array keys are the field names, and
1131 * the values are the values to insert. The values are treated as data
1132 * and will be quoted appropriately. If NULL is inserted, this will be
1133 * converted to a database NULL.
1134 * - An array with numeric keys, holding a list of associative arrays.
1135 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1136 * each subarray must be identical to each other, and in the same order.
1137 *
1138 * It may be more efficient to leave off unique indexes which are unlikely
1139 * to collide. However if you do this, you run the risk of encountering
1140 * errors which wouldn't have occurred in MySQL.
1141 *
1142 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1143 * returns success.
1144 *
1145 * @since 1.22
1146 *
1147 * @param string $table Table name. This will be passed through Database::tableName().
1148 * @param array $rows A single row or list of rows to insert
1149 * @param array $uniqueIndexes List of single field names or field name tuples
1150 * @param array $set An array of values to SET. For each array element, the
1151 * key gives the field name, and the value gives the data to set that
1152 * field to. The data will be quoted by IDatabase::addQuotes().
1153 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1154 * @throws Exception
1155 * @return bool
1156 */
1157 public function upsert(
1158 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
1159 );
1160
1161 /**
1162 * DELETE where the condition is a join.
1163 *
1164 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
1165 * we use sub-selects
1166 *
1167 * For safety, an empty $conds will not delete everything. If you want to
1168 * delete all rows where the join condition matches, set $conds='*'.
1169 *
1170 * DO NOT put the join condition in $conds.
1171 *
1172 * @param string $delTable The table to delete from.
1173 * @param string $joinTable The other table.
1174 * @param string $delVar The variable to join on, in the first table.
1175 * @param string $joinVar The variable to join on, in the second table.
1176 * @param array $conds Condition array of field names mapped to variables,
1177 * ANDed together in the WHERE clause
1178 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1179 * @throws DBUnexpectedError
1180 */
1181 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
1182 $fname = __METHOD__
1183 );
1184
1185 /**
1186 * DELETE query wrapper.
1187 *
1188 * @param string $table Table name
1189 * @param string|array $conds Array of conditions. See $conds in IDatabase::select()
1190 * for the format. Use $conds == "*" to delete all rows
1191 * @param string $fname Name of the calling function
1192 * @throws DBUnexpectedError
1193 * @return bool|ResultWrapper
1194 */
1195 public function delete( $table, $conds, $fname = __METHOD__ );
1196
1197 /**
1198 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
1199 * into another table.
1200 *
1201 * @param string $destTable The table name to insert into
1202 * @param string|array $srcTable May be either a table name, or an array of table names
1203 * to include in a join.
1204 *
1205 * @param array $varMap Must be an associative array of the form
1206 * [ 'dest1' => 'source1', ... ]. Source items may be literals
1207 * rather than field names, but strings should be quoted with
1208 * IDatabase::addQuotes()
1209 *
1210 * @param array $conds Condition array. See $conds in IDatabase::select() for
1211 * the details of the format of condition arrays. May be "*" to copy the
1212 * whole table.
1213 *
1214 * @param string $fname The function name of the caller, from __METHOD__
1215 *
1216 * @param array $insertOptions Options for the INSERT part of the query, see
1217 * IDatabase::insert() for details.
1218 * @param array $selectOptions Options for the SELECT part of the query, see
1219 * IDatabase::select() for details.
1220 *
1221 * @return ResultWrapper
1222 */
1223 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
1224 $fname = __METHOD__,
1225 $insertOptions = [], $selectOptions = []
1226 );
1227
1228 /**
1229 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1230 * within the UNION construct.
1231 * @return bool
1232 */
1233 public function unionSupportsOrderAndLimit();
1234
1235 /**
1236 * Construct a UNION query
1237 * This is used for providing overload point for other DB abstractions
1238 * not compatible with the MySQL syntax.
1239 * @param array $sqls SQL statements to combine
1240 * @param bool $all Use UNION ALL
1241 * @return string SQL fragment
1242 */
1243 public function unionQueries( $sqls, $all );
1244
1245 /**
1246 * Returns an SQL expression for a simple conditional. This doesn't need
1247 * to be overridden unless CASE isn't supported in your DBMS.
1248 *
1249 * @param string|array $cond SQL expression which will result in a boolean value
1250 * @param string $trueVal SQL expression to return if true
1251 * @param string $falseVal SQL expression to return if false
1252 * @return string SQL fragment
1253 */
1254 public function conditional( $cond, $trueVal, $falseVal );
1255
1256 /**
1257 * Returns a comand for str_replace function in SQL query.
1258 * Uses REPLACE() in MySQL
1259 *
1260 * @param string $orig Column to modify
1261 * @param string $old Column to seek
1262 * @param string $new Column to replace with
1263 *
1264 * @return string
1265 */
1266 public function strreplace( $orig, $old, $new );
1267
1268 /**
1269 * Determines how long the server has been up
1270 *
1271 * @return int
1272 */
1273 public function getServerUptime();
1274
1275 /**
1276 * Determines if the last failure was due to a deadlock
1277 *
1278 * @return bool
1279 */
1280 public function wasDeadlock();
1281
1282 /**
1283 * Determines if the last failure was due to a lock timeout
1284 *
1285 * @return bool
1286 */
1287 public function wasLockTimeout();
1288
1289 /**
1290 * Determines if the last query error was due to a dropped connection and should
1291 * be dealt with by pinging the connection and reissuing the query.
1292 *
1293 * @return bool
1294 */
1295 public function wasErrorReissuable();
1296
1297 /**
1298 * Determines if the last failure was due to the database being read-only.
1299 *
1300 * @return bool
1301 */
1302 public function wasReadOnlyError();
1303
1304 /**
1305 * Wait for the replica DB to catch up to a given master position
1306 *
1307 * @param DBMasterPos $pos
1308 * @param int $timeout The maximum number of seconds to wait for synchronisation
1309 * @return int|null Zero if the replica DB was past that position already,
1310 * greater than zero if we waited for some period of time, less than
1311 * zero if it timed out, and null on error
1312 */
1313 public function masterPosWait( DBMasterPos $pos, $timeout );
1314
1315 /**
1316 * Get the replication position of this replica DB
1317 *
1318 * @return DBMasterPos|bool False if this is not a replica DB.
1319 */
1320 public function getReplicaPos();
1321
1322 /**
1323 * Get the position of this master
1324 *
1325 * @return DBMasterPos|bool False if this is not a master
1326 */
1327 public function getMasterPos();
1328
1329 /**
1330 * @return bool Whether the DB is marked as read-only server-side
1331 * @since 1.28
1332 */
1333 public function serverIsReadOnly();
1334
1335 /**
1336 * Run a callback as soon as the current transaction commits or rolls back.
1337 * An error is thrown if no transaction is pending. Queries in the function will run in
1338 * AUTO-COMMIT mode unless there are begin() calls. Callbacks must commit any transactions
1339 * that they begin.
1340 *
1341 * This is useful for combining cooperative locks and DB transactions.
1342 *
1343 * The callback takes one argument:
1344 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK)
1345 *
1346 * @param callable $callback
1347 * @param string $fname Caller name
1348 * @return mixed
1349 * @since 1.28
1350 */
1351 public function onTransactionResolution( callable $callback, $fname = __METHOD__ );
1352
1353 /**
1354 * Run a callback as soon as there is no transaction pending.
1355 * If there is a transaction and it is rolled back, then the callback is cancelled.
1356 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
1357 * Callbacks must commit any transactions that they begin.
1358 *
1359 * This is useful for updates to different systems or when separate transactions are needed.
1360 * For example, one might want to enqueue jobs into a system outside the database, but only
1361 * after the database is updated so that the jobs will see the data when they actually run.
1362 * It can also be used for updates that easily cause deadlocks if locks are held too long.
1363 *
1364 * Updates will execute in the order they were enqueued.
1365 *
1366 * The callback takes one argument:
1367 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_IDLE)
1368 *
1369 * @param callable $callback
1370 * @param string $fname Caller name
1371 * @since 1.20
1372 */
1373 public function onTransactionIdle( callable $callback, $fname = __METHOD__ );
1374
1375 /**
1376 * Run a callback before the current transaction commits or now if there is none.
1377 * If there is a transaction and it is rolled back, then the callback is cancelled.
1378 * Callbacks must not start nor commit any transactions. If no transaction is active,
1379 * then a transaction will wrap the callback.
1380 *
1381 * This is useful for updates that easily cause deadlocks if locks are held too long
1382 * but where atomicity is strongly desired for these updates and some related updates.
1383 *
1384 * Updates will execute in the order they were enqueued.
1385 *
1386 * @param callable $callback
1387 * @param string $fname Caller name
1388 * @since 1.22
1389 */
1390 public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ );
1391
1392 /**
1393 * Run a callback each time any transaction commits or rolls back
1394 *
1395 * The callback takes two arguments:
1396 * - IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK
1397 * - This IDatabase object
1398 * Callbacks must commit any transactions that they begin.
1399 *
1400 * Registering a callback here will not affect writesOrCallbacks() pending
1401 *
1402 * @param string $name Callback name
1403 * @param callable|null $callback Use null to unset a listener
1404 * @return mixed
1405 * @since 1.28
1406 */
1407 public function setTransactionListener( $name, callable $callback = null );
1408
1409 /**
1410 * Begin an atomic section of statements
1411 *
1412 * If a transaction has been started already, just keep track of the given
1413 * section name to make sure the transaction is not committed pre-maturely.
1414 * This function can be used in layers (with sub-sections), so use a stack
1415 * to keep track of the different atomic sections. If there is no transaction,
1416 * start one implicitly.
1417 *
1418 * The goal of this function is to create an atomic section of SQL queries
1419 * without having to start a new transaction if it already exists.
1420 *
1421 * All atomic levels *must* be explicitly closed using IDatabase::endAtomic(),
1422 * and any database transactions cannot be began or committed until all atomic
1423 * levels are closed. There is no such thing as implicitly opening or closing
1424 * an atomic section.
1425 *
1426 * @since 1.23
1427 * @param string $fname
1428 * @throws DBError
1429 */
1430 public function startAtomic( $fname = __METHOD__ );
1431
1432 /**
1433 * Ends an atomic section of SQL statements
1434 *
1435 * Ends the next section of atomic SQL statements and commits the transaction
1436 * if necessary.
1437 *
1438 * @since 1.23
1439 * @see IDatabase::startAtomic
1440 * @param string $fname
1441 * @throws DBError
1442 */
1443 public function endAtomic( $fname = __METHOD__ );
1444
1445 /**
1446 * Run a callback to do an atomic set of updates for this database
1447 *
1448 * The $callback takes the following arguments:
1449 * - This database object
1450 * - The value of $fname
1451 *
1452 * If any exception occurs in the callback, then rollback() will be called and the error will
1453 * be re-thrown. It may also be that the rollback itself fails with an exception before then.
1454 * In any case, such errors are expected to terminate the request, without any outside caller
1455 * attempting to catch errors and commit anyway. Note that any rollback undoes all prior
1456 * atomic section and uncommitted updates, which trashes the current request, requiring an
1457 * error to be displayed.
1458 *
1459 * This can be an alternative to explicit startAtomic()/endAtomic() calls.
1460 *
1461 * @see Database::startAtomic
1462 * @see Database::endAtomic
1463 *
1464 * @param string $fname Caller name (usually __METHOD__)
1465 * @param callable $callback Callback that issues DB updates
1466 * @return mixed $res Result of the callback (since 1.28)
1467 * @throws DBError
1468 * @throws RuntimeException
1469 * @throws UnexpectedValueException
1470 * @since 1.27
1471 */
1472 public function doAtomicSection( $fname, callable $callback );
1473
1474 /**
1475 * Begin a transaction. If a transaction is already in progress,
1476 * that transaction will be committed before the new transaction is started.
1477 *
1478 * Only call this from code with outer transcation scope.
1479 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1480 * Nesting of transactions is not supported.
1481 *
1482 * Note that when the DBO_TRX flag is set (which is usually the case for web
1483 * requests, but not for maintenance scripts), any previous database query
1484 * will have started a transaction automatically.
1485 *
1486 * Nesting of transactions is not supported. Attempts to nest transactions
1487 * will cause a warning, unless the current transaction was started
1488 * automatically because of the DBO_TRX flag.
1489 *
1490 * @param string $fname Calling function name
1491 * @param string $mode A situationally valid IDatabase::TRANSACTION_* constant [optional]
1492 * @throws DBError
1493 */
1494 public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT );
1495
1496 /**
1497 * Commits a transaction previously started using begin().
1498 * If no transaction is in progress, a warning is issued.
1499 *
1500 * Only call this from code with outer transcation scope.
1501 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1502 * Nesting of transactions is not supported.
1503 *
1504 * @param string $fname
1505 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_*
1506 * constant to disable warnings about explicitly committing implicit transactions,
1507 * or calling commit when no transaction is in progress.
1508 *
1509 * This will trigger an exception if there is an ongoing explicit transaction.
1510 *
1511 * Only set the flush flag if you are sure that these warnings are not applicable,
1512 * and no explicit transactions are open.
1513 *
1514 * @throws DBUnexpectedError
1515 */
1516 public function commit( $fname = __METHOD__, $flush = '' );
1517
1518 /**
1519 * Rollback a transaction previously started using begin().
1520 * If no transaction is in progress, a warning is issued.
1521 *
1522 * Only call this from code with outer transcation scope.
1523 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1524 * Nesting of transactions is not supported. If a serious unexpected error occurs,
1525 * throwing an Exception is preferrable, using a pre-installed error handler to trigger
1526 * rollback (in any case, failure to issue COMMIT will cause rollback server-side).
1527 *
1528 * @param string $fname Calling function name
1529 * @param string $flush Flush flag, set to a situationally valid IDatabase::FLUSHING_*
1530 * constant to disable warnings about calling rollback when no transaction is in
1531 * progress. This will silently break any ongoing explicit transaction. Only set the
1532 * flush flag if you are sure that it is safe to ignore these warnings in your context.
1533 * @throws DBUnexpectedError
1534 * @since 1.23 Added $flush parameter
1535 */
1536 public function rollback( $fname = __METHOD__, $flush = '' );
1537
1538 /**
1539 * Commit any transaction but error out if writes or callbacks are pending
1540 *
1541 * This is intended for clearing out REPEATABLE-READ snapshots so that callers can
1542 * see a new point-in-time of the database. This is useful when one of many transaction
1543 * rounds finished and significant time will pass in the script's lifetime. It is also
1544 * useful to call on a replica DB after waiting on replication to catch up to the master.
1545 *
1546 * @param string $fname Calling function name
1547 * @throws DBUnexpectedError
1548 * @since 1.28
1549 */
1550 public function flushSnapshot( $fname = __METHOD__ );
1551
1552 /**
1553 * List all tables on the database
1554 *
1555 * @param string $prefix Only show tables with this prefix, e.g. mw_
1556 * @param string $fname Calling function name
1557 * @throws DBError
1558 * @return array
1559 */
1560 public function listTables( $prefix = null, $fname = __METHOD__ );
1561
1562 /**
1563 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1564 * to the format used for inserting into timestamp fields in this DBMS.
1565 *
1566 * The result is unquoted, and needs to be passed through addQuotes()
1567 * before it can be included in raw SQL.
1568 *
1569 * @param string|int $ts
1570 *
1571 * @return string
1572 */
1573 public function timestamp( $ts = 0 );
1574
1575 /**
1576 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1577 * to the format used for inserting into timestamp fields in this DBMS. If
1578 * NULL is input, it is passed through, allowing NULL values to be inserted
1579 * into timestamp fields.
1580 *
1581 * The result is unquoted, and needs to be passed through addQuotes()
1582 * before it can be included in raw SQL.
1583 *
1584 * @param string|int $ts
1585 *
1586 * @return string
1587 */
1588 public function timestampOrNull( $ts = null );
1589
1590 /**
1591 * Ping the server and try to reconnect if it there is no connection
1592 *
1593 * @param float|null &$rtt Value to store the estimated RTT [optional]
1594 * @return bool Success or failure
1595 */
1596 public function ping( &$rtt = null );
1597
1598 /**
1599 * Get replica DB lag. Currently supported only by MySQL.
1600 *
1601 * Note that this function will generate a fatal error on many
1602 * installations. Most callers should use LoadBalancer::safeGetLag()
1603 * instead.
1604 *
1605 * @return int|bool Database replication lag in seconds or false on error
1606 */
1607 public function getLag();
1608
1609 /**
1610 * Get the replica DB lag when the current transaction started
1611 * or a general lag estimate if not transaction is active
1612 *
1613 * This is useful when transactions might use snapshot isolation
1614 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
1615 * is this lag plus transaction duration. If they don't, it is still
1616 * safe to be pessimistic. In AUTO-COMMIT mode, this still gives an
1617 * indication of the staleness of subsequent reads.
1618 *
1619 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
1620 * @since 1.27
1621 */
1622 public function getSessionLagStatus();
1623
1624 /**
1625 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1626 *
1627 * @return int
1628 */
1629 public function maxListLen();
1630
1631 /**
1632 * Some DBMSs have a special format for inserting into blob fields, they
1633 * don't allow simple quoted strings to be inserted. To insert into such
1634 * a field, pass the data through this function before passing it to
1635 * IDatabase::insert().
1636 *
1637 * @param string $b
1638 * @return string|Blob
1639 */
1640 public function encodeBlob( $b );
1641
1642 /**
1643 * Some DBMSs return a special placeholder object representing blob fields
1644 * in result objects. Pass the object through this function to return the
1645 * original string.
1646 *
1647 * @param string|Blob $b
1648 * @return string
1649 */
1650 public function decodeBlob( $b );
1651
1652 /**
1653 * Override database's default behavior. $options include:
1654 * 'connTimeout' : Set the connection timeout value in seconds.
1655 * May be useful for very long batch queries such as
1656 * full-wiki dumps, where a single query reads out over
1657 * hours or days.
1658 *
1659 * @param array $options
1660 * @return void
1661 */
1662 public function setSessionOptions( array $options );
1663
1664 /**
1665 * Set variables to be used in sourceFile/sourceStream, in preference to the
1666 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
1667 * all. If it's set to false, $GLOBALS will be used.
1668 *
1669 * @param bool|array $vars Mapping variable name to value.
1670 */
1671 public function setSchemaVars( $vars );
1672
1673 /**
1674 * Check to see if a named lock is available (non-blocking)
1675 *
1676 * @param string $lockName Name of lock to poll
1677 * @param string $method Name of method calling us
1678 * @return bool
1679 * @since 1.20
1680 */
1681 public function lockIsFree( $lockName, $method );
1682
1683 /**
1684 * Acquire a named lock
1685 *
1686 * Named locks are not related to transactions
1687 *
1688 * @param string $lockName Name of lock to aquire
1689 * @param string $method Name of the calling method
1690 * @param int $timeout Acquisition timeout in seconds
1691 * @return bool
1692 */
1693 public function lock( $lockName, $method, $timeout = 5 );
1694
1695 /**
1696 * Release a lock
1697 *
1698 * Named locks are not related to transactions
1699 *
1700 * @param string $lockName Name of lock to release
1701 * @param string $method Name of the calling method
1702 *
1703 * @return int Returns 1 if the lock was released, 0 if the lock was not established
1704 * by this thread (in which case the lock is not released), and NULL if the named
1705 * lock did not exist
1706 */
1707 public function unlock( $lockName, $method );
1708
1709 /**
1710 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object
1711 *
1712 * Only call this from outer transcation scope and when only one DB will be affected.
1713 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1714 *
1715 * This is suitiable for transactions that need to be serialized using cooperative locks,
1716 * where each transaction can see each others' changes. Any transaction is flushed to clear
1717 * out stale REPEATABLE-READ snapshot data. Once the returned object falls out of PHP scope,
1718 * the lock will be released unless a transaction is active. If one is active, then the lock
1719 * will be released when it either commits or rolls back.
1720 *
1721 * If the lock acquisition failed, then no transaction flush happens, and null is returned.
1722 *
1723 * @param string $lockKey Name of lock to release
1724 * @param string $fname Name of the calling method
1725 * @param int $timeout Acquisition timeout in seconds
1726 * @return ScopedCallback|null
1727 * @throws DBUnexpectedError
1728 * @since 1.27
1729 */
1730 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
1731
1732 /**
1733 * Check to see if a named lock used by lock() use blocking queues
1734 *
1735 * @return bool
1736 * @since 1.26
1737 */
1738 public function namedLocksEnqueue();
1739
1740 /**
1741 * Find out when 'infinity' is. Most DBMSes support this. This is a special
1742 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
1743 * because "i" sorts after all numbers.
1744 *
1745 * @return string
1746 */
1747 public function getInfinity();
1748
1749 /**
1750 * Encode an expiry time into the DBMS dependent format
1751 *
1752 * @param string $expiry Timestamp for expiry, or the 'infinity' string
1753 * @return string
1754 */
1755 public function encodeExpiry( $expiry );
1756
1757 /**
1758 * Decode an expiry time into a DBMS independent format
1759 *
1760 * @param string $expiry DB timestamp field value for expiry
1761 * @param int $format TS_* constant, defaults to TS_MW
1762 * @return string
1763 */
1764 public function decodeExpiry( $expiry, $format = TS_MW );
1765
1766 /**
1767 * Allow or deny "big selects" for this session only. This is done by setting
1768 * the sql_big_selects session variable.
1769 *
1770 * This is a MySQL-specific feature.
1771 *
1772 * @param bool|string $value True for allow, false for deny, or "default" to
1773 * restore the initial value
1774 */
1775 public function setBigSelects( $value = true );
1776
1777 /**
1778 * @return bool Whether this DB is read-only
1779 * @since 1.27
1780 */
1781 public function isReadOnly();
1782
1783 /**
1784 * Make certain table names use their own database, schema, and table prefix
1785 * when passed into SQL queries pre-escaped and without a qualified database name
1786 *
1787 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
1788 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
1789 *
1790 * Calling this twice will completely clear any old table aliases. Also, note that
1791 * callers are responsible for making sure the schemas and databases actually exist.
1792 *
1793 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
1794 * @since 1.28
1795 */
1796 public function setTableAliases( array $aliases );
1797 }