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