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