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