Move mssql class to /libs
[mediawiki.git] / includes / libs / rdbms / database / IDatabase.php
blobf1613ebc5a4c5f00e078b732771acce7d449c786
1 <?php
2 /**
3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Database
26 use Wikimedia\ScopedCallback;
27 use Wikimedia\Rdbms\LikeMatch;
29 /**
30 * Basic database interface for live and lazy-loaded relation database handles
32 * @note: IDatabase and DBConnRef should be updated to reflect any changes
33 * @ingroup Database
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;
43 /** @var string Transaction is requested by regular caller outside of the DB layer */
44 const TRANSACTION_EXPLICIT = '';
45 /** @var string Transaction is requested internally via DBO_TRX/startAtomic() */
46 const TRANSACTION_INTERNAL = 'implicit';
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';
53 /** @var string Do not remember the prior flags */
54 const REMEMBER_NOTHING = '';
55 /** @var string Remember the prior flags */
56 const REMEMBER_PRIOR = 'remember';
57 /** @var string Restore to the prior flag state */
58 const RESTORE_PRIOR = 'prior';
59 /** @var string Restore to the initial flag state */
60 const RESTORE_INITIAL = 'initial';
62 /** @var string Estimate total time (RTT, scanning, waiting on locks, applying) */
63 const ESTIMATE_TOTAL = 'total';
64 /** @var string Estimate time to apply (scanning, applying) */
65 const ESTIMATE_DB_APPLY = 'apply';
67 /** @var int Combine list with comma delimeters */
68 const LIST_COMMA = 0;
69 /** @var int Combine list with AND clauses */
70 const LIST_AND = 1;
71 /** @var int Convert map into a SET clause */
72 const LIST_SET = 2;
73 /** @var int Treat as field name and do not apply value escaping */
74 const LIST_NAMES = 3;
75 /** @var int Combine list with OR clauses */
76 const LIST_OR = 4;
78 /** @var int Enable debug logging */
79 const DBO_DEBUG = 1;
80 /** @var int Disable query buffering (only one result set can be iterated at a time) */
81 const DBO_NOBUFFER = 2;
82 /** @var int Ignore query errors (internal use only!) */
83 const DBO_IGNORE = 4;
84 /** @var int Autoatically start transaction on first query (work with ILoadBalancer rounds) */
85 const DBO_TRX = 8;
86 /** @var int Use DBO_TRX in non-CLI mode */
87 const DBO_DEFAULT = 16;
88 /** @var int Use DB persistent connections if possible */
89 const DBO_PERSISTENT = 32;
90 /** @var int DBA session mode; mostly for Oracle */
91 const DBO_SYSDBA = 64;
92 /** @var int Schema file mode; mostly for Oracle */
93 const DBO_DDLMODE = 128;
94 /** @var int Enable SSL/TLS in connection protocol */
95 const DBO_SSL = 256;
96 /** @var int Enable compression in connection protocol */
97 const DBO_COMPRESS = 512;
99 /**
100 * A string describing the current software version, and possibly
101 * other details in a user-friendly way. Will be listed on Special:Version, etc.
102 * Use getServerVersion() to get machine-friendly information.
104 * @return string Version information from the database server
106 public function getServerInfo();
109 * Turns buffering of SQL result sets on (true) or off (false). Default is "on".
111 * Unbuffered queries are very troublesome in MySQL:
113 * - If another query is executed while the first query is being read
114 * out, the first query is killed. This means you can't call normal
115 * Database functions while you are reading an unbuffered query result
116 * from a normal Database connection.
118 * - Unbuffered queries cause the MySQL server to use large amounts of
119 * memory and to hold broad locks which block other queries.
121 * If you want to limit client-side memory, it's almost always better to
122 * split up queries into batches using a LIMIT clause than to switch off
123 * buffering.
125 * @param null|bool $buffer
126 * @return null|bool The previous value of the flag
128 public function bufferResults( $buffer = null );
131 * Gets the current transaction level.
133 * Historically, transactions were allowed to be "nested". This is no
134 * longer supported, so this function really only returns a boolean.
136 * @return int The previous value
138 public function trxLevel();
141 * Get the UNIX timestamp of the time that the transaction was established
143 * This can be used to reason about the staleness of SELECT data
144 * in REPEATABLE-READ transaction isolation level.
146 * @return float|null Returns null if there is not active transaction
147 * @since 1.25
149 public function trxTimestamp();
152 * @return bool Whether an explicit transaction or atomic sections are still open
153 * @since 1.28
155 public function explicitTrxActive();
158 * Get/set the table prefix.
159 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
160 * @return string The previous table prefix.
162 public function tablePrefix( $prefix = null );
165 * Get/set the db schema.
166 * @param string $schema The database schema to set, or omitted to leave it unchanged.
167 * @return string The previous db schema.
169 public function dbSchema( $schema = null );
172 * Get properties passed down from the server info array of the load
173 * balancer.
175 * @param string $name The entry of the info array to get, or null to get the
176 * whole array
178 * @return array|mixed|null
180 public function getLBInfo( $name = null );
183 * Set the LB info array, or a member of it. If called with one parameter,
184 * the LB info array is set to that parameter. If it is called with two
185 * parameters, the member with the given name is set to the given value.
187 * @param string $name
188 * @param array $value
190 public function setLBInfo( $name, $value = null );
193 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
195 * @param IDatabase $conn
196 * @since 1.27
198 public function setLazyMasterHandle( IDatabase $conn );
201 * Returns true if this database does an implicit sort when doing GROUP BY
203 * @return bool
205 public function implicitGroupby();
208 * Returns true if this database does an implicit order by when the column has an index
209 * For example: SELECT page_title FROM page LIMIT 1
211 * @return bool
213 public function implicitOrderby();
216 * Return the last query that went through IDatabase::query()
217 * @return string
219 public function lastQuery();
222 * Returns true if the connection may have been used for write queries.
223 * Should return true if unsure.
225 * @return bool
227 public function doneWrites();
230 * Returns the last time the connection may have been used for write queries.
231 * Should return a timestamp if unsure.
233 * @return int|float UNIX timestamp or false
234 * @since 1.24
236 public function lastDoneWrites();
239 * @return bool Whether there is a transaction open with possible write queries
240 * @since 1.27
242 public function writesPending();
245 * Returns true if there is a transaction open with possible write
246 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
247 * This does *not* count recurring callbacks, e.g. from setTransactionListener().
249 * @return bool
251 public function writesOrCallbacksPending();
254 * Get the time spend running write queries for this transaction
256 * High times could be due to scanning, updates, locking, and such
258 * @param string $type IDatabase::ESTIMATE_* constant [default: ESTIMATE_ALL]
259 * @return float|bool Returns false if not transaction is active
260 * @since 1.26
262 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL );
265 * Get the list of method names that did write queries for this transaction
267 * @return array
268 * @since 1.27
270 public function pendingWriteCallers();
273 * Is a connection to the database open?
274 * @return bool
276 public function isOpen();
279 * Set a flag for this connection
281 * @param int $flag DBO_* constants from Defines.php:
282 * - DBO_DEBUG: output some debug info (same as debug())
283 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
284 * - DBO_TRX: automatically start transactions
285 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
286 * and removes it in command line mode
287 * - DBO_PERSISTENT: use persistant database connection
288 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
290 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING );
293 * Clear a flag for this connection
295 * @param int $flag DBO_* constants from Defines.php:
296 * - DBO_DEBUG: output some debug info (same as debug())
297 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
298 * - DBO_TRX: automatically start transactions
299 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
300 * and removes it in command line mode
301 * - DBO_PERSISTENT: use persistant database connection
302 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING]
304 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING );
307 * Restore the flags to their prior state before the last setFlag/clearFlag call
309 * @param string $state IDatabase::RESTORE_* constant. [default: RESTORE_PRIOR]
310 * @since 1.28
312 public function restoreFlags( $state = self::RESTORE_PRIOR );
315 * Returns a boolean whether the flag $flag is set for this connection
317 * @param int $flag DBO_* constants from Defines.php:
318 * - DBO_DEBUG: output some debug info (same as debug())
319 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
320 * - DBO_TRX: automatically start transactions
321 * - DBO_PERSISTENT: use persistant database connection
322 * @return bool
324 public function getFlag( $flag );
327 * @return string
329 public function getDomainID();
332 * Alias for getDomainID()
334 * @return string
336 public function getWikiID();
339 * Get the type of the DBMS, as it appears in $wgDBtype.
341 * @return string
343 public function getType();
346 * Open a connection to the database. Usually aborts on failure
348 * @param string $server Database server host
349 * @param string $user Database user name
350 * @param string $password Database user password
351 * @param string $dbName Database name
352 * @return bool
353 * @throws DBConnectionError
355 public function open( $server, $user, $password, $dbName );
358 * Fetch the next row from the given result object, in object form.
359 * Fields can be retrieved with $row->fieldname, with fields acting like
360 * member variables.
361 * If no more rows are available, false is returned.
363 * @param ResultWrapper|stdClass $res Object as returned from IDatabase::query(), etc.
364 * @return stdClass|bool
365 * @throws DBUnexpectedError Thrown if the database returns an error
367 public function fetchObject( $res );
370 * Fetch the next row from the given result object, in associative array
371 * form. Fields are retrieved with $row['fieldname'].
372 * If no more rows are available, false is returned.
374 * @param ResultWrapper $res Result object as returned from IDatabase::query(), etc.
375 * @return array|bool
376 * @throws DBUnexpectedError Thrown if the database returns an error
378 public function fetchRow( $res );
381 * Get the number of rows in a result object
383 * @param mixed $res A SQL result
384 * @return int
386 public function numRows( $res );
389 * Get the number of fields in a result object
390 * @see https://secure.php.net/mysql_num_fields
392 * @param mixed $res A SQL result
393 * @return int
395 public function numFields( $res );
398 * Get a field name in a result object
399 * @see https://secure.php.net/mysql_field_name
401 * @param mixed $res A SQL result
402 * @param int $n
403 * @return string
405 public function fieldName( $res, $n );
408 * Get the inserted value of an auto-increment row
410 * The value inserted should be fetched from nextSequenceValue()
412 * Example:
413 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
414 * $dbw->insert( 'page', [ 'page_id' => $id ] );
415 * $id = $dbw->insertId();
417 * @return int
419 public function insertId();
422 * Change the position of the cursor in a result object
423 * @see https://secure.php.net/mysql_data_seek
425 * @param mixed $res A SQL result
426 * @param int $row
428 public function dataSeek( $res, $row );
431 * Get the last error number
432 * @see https://secure.php.net/mysql_errno
434 * @return int
436 public function lastErrno();
439 * Get a description of the last error
440 * @see https://secure.php.net/mysql_error
442 * @return string
444 public function lastError();
447 * mysql_fetch_field() wrapper
448 * Returns false if the field doesn't exist
450 * @param string $table Table name
451 * @param string $field Field name
453 * @return Field
455 public function fieldInfo( $table, $field );
458 * Get the number of rows affected by the last write query
459 * @see https://secure.php.net/mysql_affected_rows
461 * @return int
463 public function affectedRows();
466 * Returns a wikitext link to the DB's website, e.g.,
467 * return "[https://www.mysql.com/ MySQL]";
468 * Should at least contain plain text, if for some reason
469 * your database has no website.
471 * @return string Wikitext of a link to the server software's web site
473 public function getSoftwareLink();
476 * A string describing the current software version, like from
477 * mysql_get_server_info().
479 * @return string Version information from the database server.
481 public function getServerVersion();
484 * Closes a database connection.
485 * if it is open : commits any open transactions
487 * @throws DBError
488 * @return bool Operation success. true if already closed.
490 public function close();
493 * @param string $error Fallback error message, used if none is given by DB
494 * @throws DBConnectionError
496 public function reportConnectionError( $error = 'Unknown error' );
499 * Run an SQL query and return the result. Normally throws a DBQueryError
500 * on failure. If errors are ignored, returns false instead.
502 * In new code, the query wrappers select(), insert(), update(), delete(),
503 * etc. should be used where possible, since they give much better DBMS
504 * independence and automatically quote or validate user input in a variety
505 * of contexts. This function is generally only useful for queries which are
506 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
507 * as CREATE TABLE.
509 * However, the query wrappers themselves should call this function.
511 * @param string $sql SQL query
512 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
513 * comment (you can use __METHOD__ or add some extra info)
514 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
515 * maybe best to catch the exception instead?
516 * @throws DBError
517 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
518 * for a successful read query, or false on failure if $tempIgnore set
520 public function query( $sql, $fname = __METHOD__, $tempIgnore = false );
523 * Report a query error. Log the error, and if neither the object ignore
524 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
526 * @param string $error
527 * @param int $errno
528 * @param string $sql
529 * @param string $fname
530 * @param bool $tempIgnore
531 * @throws DBQueryError
533 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false );
536 * Free a result object returned by query() or select(). It's usually not
537 * necessary to call this, just use unset() or let the variable holding
538 * the result object go out of scope.
540 * @param mixed $res A SQL result
542 public function freeResult( $res );
545 * A SELECT wrapper which returns a single field from a single result row.
547 * Usually throws a DBQueryError on failure. If errors are explicitly
548 * ignored, returns false on failure.
550 * If no result rows are returned from the query, false is returned.
552 * @param string|array $table Table name. See IDatabase::select() for details.
553 * @param string $var The field name to select. This must be a valid SQL
554 * fragment: do not use unvalidated user input.
555 * @param string|array $cond The condition array. See IDatabase::select() for details.
556 * @param string $fname The function name of the caller.
557 * @param string|array $options The query options. See IDatabase::select() for details.
559 * @return bool|mixed The value from the field, or false on failure.
561 public function selectField(
562 $table, $var, $cond = '', $fname = __METHOD__, $options = []
566 * A SELECT wrapper which returns a list of single field values from result rows.
568 * Usually throws a DBQueryError on failure. If errors are explicitly
569 * ignored, returns false on failure.
571 * If no result rows are returned from the query, false is returned.
573 * @param string|array $table Table name. See IDatabase::select() for details.
574 * @param string $var The field name to select. This must be a valid SQL
575 * fragment: do not use unvalidated user input.
576 * @param string|array $cond The condition array. See IDatabase::select() for details.
577 * @param string $fname The function name of the caller.
578 * @param string|array $options The query options. See IDatabase::select() for details.
580 * @return bool|array The values from the field, or false on failure
581 * @since 1.25
583 public function selectFieldValues(
584 $table, $var, $cond = '', $fname = __METHOD__, $options = []
588 * Execute a SELECT query constructed using the various parameters provided.
589 * See below for full details of the parameters.
591 * @param string|array $table Table name
592 * @param string|array $vars Field names
593 * @param string|array $conds Conditions
594 * @param string $fname Caller function name
595 * @param array $options Query options
596 * @param array $join_conds Join conditions
599 * @param string|array $table
601 * May be either an array of table names, or a single string holding a table
602 * name. If an array is given, table aliases can be specified, for example:
604 * [ 'a' => 'user' ]
606 * This includes the user table in the query, with the alias "a" available
607 * for use in field names (e.g. a.user_name).
609 * All of the table names given here are automatically run through
610 * Database::tableName(), which causes the table prefix (if any) to be
611 * added, and various other table name mappings to be performed.
613 * Do not use untrusted user input as a table name. Alias names should
614 * not have characters outside of the Basic multilingual plane.
616 * @param string|array $vars
618 * May be either a field name or an array of field names. The field names
619 * can be complete fragments of SQL, for direct inclusion into the SELECT
620 * query. If an array is given, field aliases can be specified, for example:
622 * [ 'maxrev' => 'MAX(rev_id)' ]
624 * This includes an expression with the alias "maxrev" in the query.
626 * If an expression is given, care must be taken to ensure that it is
627 * DBMS-independent.
629 * Untrusted user input must not be passed to this parameter.
631 * @param string|array $conds
633 * May be either a string containing a single condition, or an array of
634 * conditions. If an array is given, the conditions constructed from each
635 * element are combined with AND.
637 * Array elements may take one of two forms:
639 * - Elements with a numeric key are interpreted as raw SQL fragments.
640 * - Elements with a string key are interpreted as equality conditions,
641 * where the key is the field name.
642 * - If the value of such an array element is a scalar (such as a
643 * string), it will be treated as data and thus quoted appropriately.
644 * If it is null, an IS NULL clause will be added.
645 * - If the value is an array, an IN (...) clause will be constructed
646 * from its non-null elements, and an IS NULL clause will be added
647 * if null is present, such that the field may match any of the
648 * elements in the array. The non-null elements will be quoted.
650 * Note that expressions are often DBMS-dependent in their syntax.
651 * DBMS-independent wrappers are provided for constructing several types of
652 * expression commonly used in condition queries. See:
653 * - IDatabase::buildLike()
654 * - IDatabase::conditional()
656 * Untrusted user input is safe in the values of string keys, however untrusted
657 * input must not be used in the array key names or in the values of numeric keys.
658 * Escaping of untrusted input used in values of numeric keys should be done via
659 * IDatabase::addQuotes()
661 * @param string|array $options
663 * Optional: Array of query options. Boolean options are specified by
664 * including them in the array as a string value with a numeric key, for
665 * example:
667 * [ 'FOR UPDATE' ]
669 * The supported options are:
671 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
672 * with LIMIT can theoretically be used for paging through a result set,
673 * but this is discouraged for performance reasons.
675 * - LIMIT: Integer: return at most this many rows. The rows are sorted
676 * and then the first rows are taken until the limit is reached. LIMIT
677 * is applied to a result set after OFFSET.
679 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
680 * changed until the next COMMIT.
682 * - DISTINCT: Boolean: return only unique result rows.
684 * - GROUP BY: May be either an SQL fragment string naming a field or
685 * expression to group by, or an array of such SQL fragments.
687 * - HAVING: May be either an string containing a HAVING clause or an array of
688 * conditions building the HAVING clause. If an array is given, the conditions
689 * constructed from each element are combined with AND.
691 * - ORDER BY: May be either an SQL fragment giving a field name or
692 * expression to order by, or an array of such SQL fragments.
694 * - USE INDEX: This may be either a string giving the index name to use
695 * for the query, or an array. If it is an associative array, each key
696 * gives the table name (or alias), each value gives the index name to
697 * use for that table. All strings are SQL fragments and so should be
698 * validated by the caller.
700 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
701 * instead of SELECT.
703 * And also the following boolean MySQL extensions, see the MySQL manual
704 * for documentation:
706 * - LOCK IN SHARE MODE
707 * - STRAIGHT_JOIN
708 * - HIGH_PRIORITY
709 * - SQL_BIG_RESULT
710 * - SQL_BUFFER_RESULT
711 * - SQL_SMALL_RESULT
712 * - SQL_CALC_FOUND_ROWS
713 * - SQL_CACHE
714 * - SQL_NO_CACHE
717 * @param string|array $join_conds
719 * Optional associative array of table-specific join conditions. In the
720 * most common case, this is unnecessary, since the join condition can be
721 * in $conds. However, it is useful for doing a LEFT JOIN.
723 * The key of the array contains the table name or alias. The value is an
724 * array with two elements, numbered 0 and 1. The first gives the type of
725 * join, the second is the same as the $conds parameter. Thus it can be
726 * an SQL fragment, or an array where the string keys are equality and the
727 * numeric keys are SQL fragments all AND'd together. For example:
729 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
731 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
732 * with no rows in it will be returned. If there was a query error, a
733 * DBQueryError exception will be thrown, except if the "ignore errors"
734 * option was set, in which case false will be returned.
736 public function select(
737 $table, $vars, $conds = '', $fname = __METHOD__,
738 $options = [], $join_conds = []
742 * The equivalent of IDatabase::select() except that the constructed SQL
743 * is returned, instead of being immediately executed. This can be useful for
744 * doing UNION queries, where the SQL text of each query is needed. In general,
745 * however, callers outside of Database classes should just use select().
747 * @param string|array $table Table name
748 * @param string|array $vars Field names
749 * @param string|array $conds Conditions
750 * @param string $fname Caller function name
751 * @param string|array $options Query options
752 * @param string|array $join_conds Join conditions
754 * @return string SQL query string.
755 * @see IDatabase::select()
757 public function selectSQLText(
758 $table, $vars, $conds = '', $fname = __METHOD__,
759 $options = [], $join_conds = []
763 * Single row SELECT wrapper. Equivalent to IDatabase::select(), except
764 * that a single row object is returned. If the query returns no rows,
765 * false is returned.
767 * @param string|array $table Table name
768 * @param string|array $vars Field names
769 * @param array $conds Conditions
770 * @param string $fname Caller function name
771 * @param string|array $options Query options
772 * @param array|string $join_conds Join conditions
774 * @return stdClass|bool
776 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
777 $options = [], $join_conds = []
781 * Estimate the number of rows in dataset
783 * MySQL allows you to estimate the number of rows that would be returned
784 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
785 * index cardinality statistics, and is notoriously inaccurate, especially
786 * when large numbers of rows have recently been added or deleted.
788 * For DBMSs that don't support fast result size estimation, this function
789 * will actually perform the SELECT COUNT(*).
791 * Takes the same arguments as IDatabase::select().
793 * @param string $table Table name
794 * @param string $vars Unused
795 * @param array|string $conds Filters on the table
796 * @param string $fname Function name for profiling
797 * @param array $options Options for select
798 * @return int Row count
800 public function estimateRowCount(
801 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
805 * Get the number of rows in dataset
807 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
809 * Takes the same arguments as IDatabase::select().
811 * @since 1.27 Added $join_conds parameter
813 * @param array|string $tables Table names
814 * @param string $vars Unused
815 * @param array|string $conds Filters on the table
816 * @param string $fname Function name for profiling
817 * @param array $options Options for select
818 * @param array $join_conds Join conditions (since 1.27)
819 * @return int Row count
821 public function selectRowCount(
822 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
826 * Determines whether a field exists in a table
828 * @param string $table Table name
829 * @param string $field Filed to check on that table
830 * @param string $fname Calling function name (optional)
831 * @return bool Whether $table has filed $field
833 public function fieldExists( $table, $field, $fname = __METHOD__ );
836 * Determines whether an index exists
837 * Usually throws a DBQueryError on failure
838 * If errors are explicitly ignored, returns NULL on failure
840 * @param string $table
841 * @param string $index
842 * @param string $fname
843 * @return bool|null
845 public function indexExists( $table, $index, $fname = __METHOD__ );
848 * Query whether a given table exists
850 * @param string $table
851 * @param string $fname
852 * @return bool
854 public function tableExists( $table, $fname = __METHOD__ );
857 * Determines if a given index is unique
859 * @param string $table
860 * @param string $index
862 * @return bool
864 public function indexUnique( $table, $index );
867 * INSERT wrapper, inserts an array into a table.
869 * $a may be either:
871 * - A single associative array. The array keys are the field names, and
872 * the values are the values to insert. The values are treated as data
873 * and will be quoted appropriately. If NULL is inserted, this will be
874 * converted to a database NULL.
875 * - An array with numeric keys, holding a list of associative arrays.
876 * This causes a multi-row INSERT on DBMSs that support it. The keys in
877 * each subarray must be identical to each other, and in the same order.
879 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
880 * returns success.
882 * $options is an array of options, with boolean options encoded as values
883 * with numeric keys, in the same style as $options in
884 * IDatabase::select(). Supported options are:
886 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
887 * any rows which cause duplicate key errors are not inserted. It's
888 * possible to determine how many rows were successfully inserted using
889 * IDatabase::affectedRows().
891 * @param string $table Table name. This will be passed through
892 * Database::tableName().
893 * @param array $a Array of rows to insert
894 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
895 * @param array $options Array of options
897 * @return bool
899 public function insert( $table, $a, $fname = __METHOD__, $options = [] );
902 * UPDATE wrapper. Takes a condition array and a SET array.
904 * @param string $table Name of the table to UPDATE. This will be passed through
905 * Database::tableName().
906 * @param array $values An array of values to SET. For each array element,
907 * the key gives the field name, and the value gives the data to set
908 * that field to. The data will be quoted by IDatabase::addQuotes().
909 * @param array $conds An array of conditions (WHERE). See
910 * IDatabase::select() for the details of the format of condition
911 * arrays. Use '*' to update all rows.
912 * @param string $fname The function name of the caller (from __METHOD__),
913 * for logging and profiling.
914 * @param array $options An array of UPDATE options, can be:
915 * - IGNORE: Ignore unique key conflicts
916 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
917 * @return bool
919 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] );
922 * Makes an encoded list of strings from an array
924 * These can be used to make conjunctions or disjunctions on SQL condition strings
925 * derived from an array (see IDatabase::select() $conds documentation).
927 * Example usage:
928 * @code
929 * $sql = $db->makeList( [
930 * 'rev_user' => $id,
931 * $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] )
932 * ], $db::LIST_AND );
933 * @endcode
934 * This would set $sql to "rev_user = '$id' AND (rev_minor = '1' OR rev_len < '500')"
936 * @param array $a Containing the data
937 * @param int $mode IDatabase class constant:
938 * - IDatabase::LIST_COMMA: Comma separated, no field names
939 * - IDatabase::LIST_AND: ANDed WHERE clause (without the WHERE).
940 * - IDatabase::LIST_OR: ORed WHERE clause (without the WHERE)
941 * - IDatabase::LIST_SET: Comma separated with field names, like a SET clause
942 * - IDatabase::LIST_NAMES: Comma separated field names
943 * @throws DBError
944 * @return string
946 public function makeList( $a, $mode = self::LIST_COMMA );
949 * Build a partial where clause from a 2-d array such as used for LinkBatch.
950 * The keys on each level may be either integers or strings.
952 * @param array $data Organized as 2-d
953 * [ baseKeyVal => [ subKeyVal => [ignored], ... ], ... ]
954 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
955 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
956 * @return string|bool SQL fragment, or false if no items in array
958 public function makeWhereFrom2d( $data, $baseKey, $subKey );
961 * Return aggregated value alias
963 * @param array $valuedata
964 * @param string $valuename
966 * @return string
968 public function aggregateValue( $valuedata, $valuename = 'value' );
971 * @param string $field
972 * @return string
974 public function bitNot( $field );
977 * @param string $fieldLeft
978 * @param string $fieldRight
979 * @return string
981 public function bitAnd( $fieldLeft, $fieldRight );
984 * @param string $fieldLeft
985 * @param string $fieldRight
986 * @return string
988 public function bitOr( $fieldLeft, $fieldRight );
991 * Build a concatenation list to feed into a SQL query
992 * @param array $stringList List of raw SQL expressions; caller is
993 * responsible for any quoting
994 * @return string
996 public function buildConcat( $stringList );
999 * Build a GROUP_CONCAT or equivalent statement for a query.
1001 * This is useful for combining a field for several rows into a single string.
1002 * NULL values will not appear in the output, duplicated values will appear,
1003 * and the resulting delimiter-separated values have no defined sort order.
1004 * Code using the results may need to use the PHP unique() or sort() methods.
1006 * @param string $delim Glue to bind the results together
1007 * @param string|array $table Table name
1008 * @param string $field Field name
1009 * @param string|array $conds Conditions
1010 * @param string|array $join_conds Join conditions
1011 * @return string SQL text
1012 * @since 1.23
1014 public function buildGroupConcatField(
1015 $delim, $table, $field, $conds = '', $join_conds = []
1019 * @param string $field Field or column to cast
1020 * @return string
1021 * @since 1.28
1023 public function buildStringCast( $field );
1026 * Change the current database
1028 * @param string $db
1029 * @return bool Success or failure
1031 public function selectDB( $db );
1034 * Get the current DB name
1035 * @return string
1037 public function getDBname();
1040 * Get the server hostname or IP address
1041 * @return string
1043 public function getServer();
1046 * Adds quotes and backslashes.
1048 * @param string|int|null|bool|Blob $s
1049 * @return string|int
1051 public function addQuotes( $s );
1054 * LIKE statement wrapper, receives a variable-length argument list with
1055 * parts of pattern to match containing either string literals that will be
1056 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
1057 * the function could be provided with an array of aforementioned
1058 * parameters.
1060 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
1061 * a LIKE clause that searches for subpages of 'My page title'.
1062 * Alternatively:
1063 * $pattern = [ 'My_page_title/', $dbr->anyString() ];
1064 * $query .= $dbr->buildLike( $pattern );
1066 * @since 1.16
1067 * @return string Fully built LIKE statement
1069 public function buildLike();
1072 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1074 * @return LikeMatch
1076 public function anyChar();
1079 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1081 * @return LikeMatch
1083 public function anyString();
1086 * Returns an appropriately quoted sequence value for inserting a new row.
1087 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1088 * subclass will return an integer, and save the value for insertId()
1090 * Any implementation of this function should *not* involve reusing
1091 * sequence numbers created for rolled-back transactions.
1092 * See https://bugs.mysql.com/bug.php?id=30767 for details.
1093 * @param string $seqName
1094 * @return null|int
1096 public function nextSequenceValue( $seqName );
1099 * REPLACE query wrapper.
1101 * REPLACE is a very handy MySQL extension, which functions like an INSERT
1102 * except that when there is a duplicate key error, the old row is deleted
1103 * and the new row is inserted in its place.
1105 * We simulate this with standard SQL with a DELETE followed by INSERT. To
1106 * perform the delete, we need to know what the unique indexes are so that
1107 * we know how to find the conflicting rows.
1109 * It may be more efficient to leave off unique indexes which are unlikely
1110 * to collide. However if you do this, you run the risk of encountering
1111 * errors which wouldn't have occurred in MySQL.
1113 * @param string $table The table to replace the row(s) in.
1114 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
1115 * a field name or an array of field names
1116 * @param array $rows Can be either a single row to insert, or multiple rows,
1117 * in the same format as for IDatabase::insert()
1118 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1120 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ );
1123 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
1125 * This updates any conflicting rows (according to the unique indexes) using
1126 * the provided SET clause and inserts any remaining (non-conflicted) rows.
1128 * $rows may be either:
1129 * - A single associative array. The array keys are the field names, and
1130 * the values are the values to insert. The values are treated as data
1131 * and will be quoted appropriately. If NULL is inserted, this will be
1132 * converted to a database NULL.
1133 * - An array with numeric keys, holding a list of associative arrays.
1134 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1135 * each subarray must be identical to each other, and in the same order.
1137 * It may be more efficient to leave off unique indexes which are unlikely
1138 * to collide. However if you do this, you run the risk of encountering
1139 * errors which wouldn't have occurred in MySQL.
1141 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1142 * returns success.
1144 * @since 1.22
1146 * @param string $table Table name. This will be passed through Database::tableName().
1147 * @param array $rows A single row or list of rows to insert
1148 * @param array $uniqueIndexes List of single field names or field name tuples
1149 * @param array $set An array of values to SET. For each array element, the
1150 * key gives the field name, and the value gives the data to set that
1151 * field to. The data will be quoted by IDatabase::addQuotes().
1152 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1153 * @throws Exception
1154 * @return bool
1156 public function upsert(
1157 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
1161 * DELETE where the condition is a join.
1163 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
1164 * we use sub-selects
1166 * For safety, an empty $conds will not delete everything. If you want to
1167 * delete all rows where the join condition matches, set $conds='*'.
1169 * DO NOT put the join condition in $conds.
1171 * @param string $delTable The table to delete from.
1172 * @param string $joinTable The other table.
1173 * @param string $delVar The variable to join on, in the first table.
1174 * @param string $joinVar The variable to join on, in the second table.
1175 * @param array $conds Condition array of field names mapped to variables,
1176 * ANDed together in the WHERE clause
1177 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1178 * @throws DBUnexpectedError
1180 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
1181 $fname = __METHOD__
1185 * DELETE query wrapper.
1187 * @param string $table Table name
1188 * @param string|array $conds Array of conditions. See $conds in IDatabase::select()
1189 * for the format. Use $conds == "*" to delete all rows
1190 * @param string $fname Name of the calling function
1191 * @throws DBUnexpectedError
1192 * @return bool|ResultWrapper
1194 public function delete( $table, $conds, $fname = __METHOD__ );
1197 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
1198 * into another table.
1200 * @param string $destTable The table name to insert into
1201 * @param string|array $srcTable May be either a table name, or an array of table names
1202 * to include in a join.
1204 * @param array $varMap Must be an associative array of the form
1205 * [ 'dest1' => 'source1', ... ]. Source items may be literals
1206 * rather than field names, but strings should be quoted with
1207 * IDatabase::addQuotes()
1209 * @param array $conds Condition array. See $conds in IDatabase::select() for
1210 * the details of the format of condition arrays. May be "*" to copy the
1211 * whole table.
1213 * @param string $fname The function name of the caller, from __METHOD__
1215 * @param array $insertOptions Options for the INSERT part of the query, see
1216 * IDatabase::insert() for details.
1217 * @param array $selectOptions Options for the SELECT part of the query, see
1218 * IDatabase::select() for details.
1220 * @return ResultWrapper
1222 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
1223 $fname = __METHOD__,
1224 $insertOptions = [], $selectOptions = []
1228 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1229 * within the UNION construct.
1230 * @return bool
1232 public function unionSupportsOrderAndLimit();
1235 * Construct a UNION query
1236 * This is used for providing overload point for other DB abstractions
1237 * not compatible with the MySQL syntax.
1238 * @param array $sqls SQL statements to combine
1239 * @param bool $all Use UNION ALL
1240 * @return string SQL fragment
1242 public function unionQueries( $sqls, $all );
1245 * Returns an SQL expression for a simple conditional. This doesn't need
1246 * to be overridden unless CASE isn't supported in your DBMS.
1248 * @param string|array $cond SQL expression which will result in a boolean value
1249 * @param string $trueVal SQL expression to return if true
1250 * @param string $falseVal SQL expression to return if false
1251 * @return string SQL fragment
1253 public function conditional( $cond, $trueVal, $falseVal );
1256 * Returns a comand for str_replace function in SQL query.
1257 * Uses REPLACE() in MySQL
1259 * @param string $orig Column to modify
1260 * @param string $old Column to seek
1261 * @param string $new Column to replace with
1263 * @return string
1265 public function strreplace( $orig, $old, $new );
1268 * Determines how long the server has been up
1270 * @return int
1272 public function getServerUptime();
1275 * Determines if the last failure was due to a deadlock
1277 * @return bool
1279 public function wasDeadlock();
1282 * Determines if the last failure was due to a lock timeout
1284 * @return bool
1286 public function wasLockTimeout();
1289 * Determines if the last query error was due to a dropped connection and should
1290 * be dealt with by pinging the connection and reissuing the query.
1292 * @return bool
1294 public function wasErrorReissuable();
1297 * Determines if the last failure was due to the database being read-only.
1299 * @return bool
1301 public function wasReadOnlyError();
1304 * Wait for the replica DB to catch up to a given master position
1306 * @param DBMasterPos $pos
1307 * @param int $timeout The maximum number of seconds to wait for synchronisation
1308 * @return int|null Zero if the replica DB was past that position already,
1309 * greater than zero if we waited for some period of time, less than
1310 * zero if it timed out, and null on error
1312 public function masterPosWait( DBMasterPos $pos, $timeout );
1315 * Get the replication position of this replica DB
1317 * @return DBMasterPos|bool False if this is not a replica DB.
1319 public function getReplicaPos();
1322 * Get the position of this master
1324 * @return DBMasterPos|bool False if this is not a master
1326 public function getMasterPos();
1329 * @return bool Whether the DB is marked as read-only server-side
1330 * @since 1.28
1332 public function serverIsReadOnly();
1335 * Run a callback as soon as the current transaction commits or rolls back.
1336 * An error is thrown if no transaction is pending. Queries in the function will run in
1337 * AUTO-COMMIT mode unless there are begin() calls. Callbacks must commit any transactions
1338 * that they begin.
1340 * This is useful for combining cooperative locks and DB transactions.
1342 * The callback takes one argument:
1343 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK)
1345 * @param callable $callback
1346 * @param string $fname Caller name
1347 * @return mixed
1348 * @since 1.28
1350 public function onTransactionResolution( callable $callback, $fname = __METHOD__ );
1353 * Run a callback as soon as there is no transaction pending.
1354 * If there is a transaction and it is rolled back, then the callback is cancelled.
1355 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
1356 * Callbacks must commit any transactions that they begin.
1358 * This is useful for updates to different systems or when separate transactions are needed.
1359 * For example, one might want to enqueue jobs into a system outside the database, but only
1360 * after the database is updated so that the jobs will see the data when they actually run.
1361 * It can also be used for updates that easily cause deadlocks if locks are held too long.
1363 * Updates will execute in the order they were enqueued.
1365 * The callback takes one argument:
1366 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_IDLE)
1368 * @param callable $callback
1369 * @param string $fname Caller name
1370 * @since 1.20
1372 public function onTransactionIdle( callable $callback, $fname = __METHOD__ );
1375 * Run a callback before the current transaction commits or now if there is none.
1376 * If there is a transaction and it is rolled back, then the callback is cancelled.
1377 * Callbacks must not start nor commit any transactions. If no transaction is active,
1378 * then a transaction will wrap the callback.
1380 * This is useful for updates that easily cause deadlocks if locks are held too long
1381 * but where atomicity is strongly desired for these updates and some related updates.
1383 * Updates will execute in the order they were enqueued.
1385 * @param callable $callback
1386 * @param string $fname Caller name
1387 * @since 1.22
1389 public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ );
1392 * Run a callback each time any transaction commits or rolls back
1394 * The callback takes two arguments:
1395 * - IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK
1396 * - This IDatabase object
1397 * Callbacks must commit any transactions that they begin.
1399 * Registering a callback here will not affect writesOrCallbacks() pending
1401 * @param string $name Callback name
1402 * @param callable|null $callback Use null to unset a listener
1403 * @return mixed
1404 * @since 1.28
1406 public function setTransactionListener( $name, callable $callback = null );
1409 * Begin an atomic section of statements
1411 * If a transaction has been started already, just keep track of the given
1412 * section name to make sure the transaction is not committed pre-maturely.
1413 * This function can be used in layers (with sub-sections), so use a stack
1414 * to keep track of the different atomic sections. If there is no transaction,
1415 * start one implicitly.
1417 * The goal of this function is to create an atomic section of SQL queries
1418 * without having to start a new transaction if it already exists.
1420 * All atomic levels *must* be explicitly closed using IDatabase::endAtomic(),
1421 * and any database transactions cannot be began or committed until all atomic
1422 * levels are closed. There is no such thing as implicitly opening or closing
1423 * an atomic section.
1425 * @since 1.23
1426 * @param string $fname
1427 * @throws DBError
1429 public function startAtomic( $fname = __METHOD__ );
1432 * Ends an atomic section of SQL statements
1434 * Ends the next section of atomic SQL statements and commits the transaction
1435 * if necessary.
1437 * @since 1.23
1438 * @see IDatabase::startAtomic
1439 * @param string $fname
1440 * @throws DBError
1442 public function endAtomic( $fname = __METHOD__ );
1445 * Run a callback to do an atomic set of updates for this database
1447 * The $callback takes the following arguments:
1448 * - This database object
1449 * - The value of $fname
1451 * If any exception occurs in the callback, then rollback() will be called and the error will
1452 * be re-thrown. It may also be that the rollback itself fails with an exception before then.
1453 * In any case, such errors are expected to terminate the request, without any outside caller
1454 * attempting to catch errors and commit anyway. Note that any rollback undoes all prior
1455 * atomic section and uncommitted updates, which trashes the current request, requiring an
1456 * error to be displayed.
1458 * This can be an alternative to explicit startAtomic()/endAtomic() calls.
1460 * @see Database::startAtomic
1461 * @see Database::endAtomic
1463 * @param string $fname Caller name (usually __METHOD__)
1464 * @param callable $callback Callback that issues DB updates
1465 * @return mixed $res Result of the callback (since 1.28)
1466 * @throws DBError
1467 * @throws RuntimeException
1468 * @throws UnexpectedValueException
1469 * @since 1.27
1471 public function doAtomicSection( $fname, callable $callback );
1474 * Begin a transaction. If a transaction is already in progress,
1475 * that transaction will be committed before the new transaction is started.
1477 * Only call this from code with outer transcation scope.
1478 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1479 * Nesting of transactions is not supported.
1481 * Note that when the DBO_TRX flag is set (which is usually the case for web
1482 * requests, but not for maintenance scripts), any previous database query
1483 * will have started a transaction automatically.
1485 * Nesting of transactions is not supported. Attempts to nest transactions
1486 * will cause a warning, unless the current transaction was started
1487 * automatically because of the DBO_TRX flag.
1489 * @param string $fname Calling function name
1490 * @param string $mode A situationally valid IDatabase::TRANSACTION_* constant [optional]
1491 * @throws DBError
1493 public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT );
1496 * Commits a transaction previously started using begin().
1497 * If no transaction is in progress, a warning is issued.
1499 * Only call this from code with outer transcation scope.
1500 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1501 * Nesting of transactions is not supported.
1503 * @param string $fname
1504 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_*
1505 * constant to disable warnings about explicitly committing implicit transactions,
1506 * or calling commit when no transaction is in progress.
1508 * This will trigger an exception if there is an ongoing explicit transaction.
1510 * Only set the flush flag if you are sure that these warnings are not applicable,
1511 * and no explicit transactions are open.
1513 * @throws DBUnexpectedError
1515 public function commit( $fname = __METHOD__, $flush = '' );
1518 * Rollback a transaction previously started using begin().
1519 * If no transaction is in progress, a warning is issued.
1521 * Only call this from code with outer transcation scope.
1522 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1523 * Nesting of transactions is not supported. If a serious unexpected error occurs,
1524 * throwing an Exception is preferrable, using a pre-installed error handler to trigger
1525 * rollback (in any case, failure to issue COMMIT will cause rollback server-side).
1527 * @param string $fname Calling function name
1528 * @param string $flush Flush flag, set to a situationally valid IDatabase::FLUSHING_*
1529 * constant to disable warnings about calling rollback when no transaction is in
1530 * progress. This will silently break any ongoing explicit transaction. Only set the
1531 * flush flag if you are sure that it is safe to ignore these warnings in your context.
1532 * @throws DBUnexpectedError
1533 * @since 1.23 Added $flush parameter
1535 public function rollback( $fname = __METHOD__, $flush = '' );
1538 * Commit any transaction but error out if writes or callbacks are pending
1540 * This is intended for clearing out REPEATABLE-READ snapshots so that callers can
1541 * see a new point-in-time of the database. This is useful when one of many transaction
1542 * rounds finished and significant time will pass in the script's lifetime. It is also
1543 * useful to call on a replica DB after waiting on replication to catch up to the master.
1545 * @param string $fname Calling function name
1546 * @throws DBUnexpectedError
1547 * @since 1.28
1549 public function flushSnapshot( $fname = __METHOD__ );
1552 * List all tables on the database
1554 * @param string $prefix Only show tables with this prefix, e.g. mw_
1555 * @param string $fname Calling function name
1556 * @throws DBError
1557 * @return array
1559 public function listTables( $prefix = null, $fname = __METHOD__ );
1562 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1563 * to the format used for inserting into timestamp fields in this DBMS.
1565 * The result is unquoted, and needs to be passed through addQuotes()
1566 * before it can be included in raw SQL.
1568 * @param string|int $ts
1570 * @return string
1572 public function timestamp( $ts = 0 );
1575 * Convert a timestamp in one of the formats accepted by wfTimestamp()
1576 * to the format used for inserting into timestamp fields in this DBMS. If
1577 * NULL is input, it is passed through, allowing NULL values to be inserted
1578 * into timestamp fields.
1580 * The result is unquoted, and needs to be passed through addQuotes()
1581 * before it can be included in raw SQL.
1583 * @param string|int $ts
1585 * @return string
1587 public function timestampOrNull( $ts = null );
1590 * Ping the server and try to reconnect if it there is no connection
1592 * @param float|null &$rtt Value to store the estimated RTT [optional]
1593 * @return bool Success or failure
1595 public function ping( &$rtt = null );
1598 * Get replica DB lag. Currently supported only by MySQL.
1600 * Note that this function will generate a fatal error on many
1601 * installations. Most callers should use LoadBalancer::safeGetLag()
1602 * instead.
1604 * @return int|bool Database replication lag in seconds or false on error
1606 public function getLag();
1609 * Get the replica DB lag when the current transaction started
1610 * or a general lag estimate if not transaction is active
1612 * This is useful when transactions might use snapshot isolation
1613 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
1614 * is this lag plus transaction duration. If they don't, it is still
1615 * safe to be pessimistic. In AUTO-COMMIT mode, this still gives an
1616 * indication of the staleness of subsequent reads.
1618 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
1619 * @since 1.27
1621 public function getSessionLagStatus();
1624 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1626 * @return int
1628 public function maxListLen();
1631 * Some DBMSs have a special format for inserting into blob fields, they
1632 * don't allow simple quoted strings to be inserted. To insert into such
1633 * a field, pass the data through this function before passing it to
1634 * IDatabase::insert().
1636 * @param string $b
1637 * @return string|Blob
1639 public function encodeBlob( $b );
1642 * Some DBMSs return a special placeholder object representing blob fields
1643 * in result objects. Pass the object through this function to return the
1644 * original string.
1646 * @param string|Blob $b
1647 * @return string
1649 public function decodeBlob( $b );
1652 * Override database's default behavior. $options include:
1653 * 'connTimeout' : Set the connection timeout value in seconds.
1654 * May be useful for very long batch queries such as
1655 * full-wiki dumps, where a single query reads out over
1656 * hours or days.
1658 * @param array $options
1659 * @return void
1661 public function setSessionOptions( array $options );
1664 * Set variables to be used in sourceFile/sourceStream, in preference to the
1665 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
1666 * all. If it's set to false, $GLOBALS will be used.
1668 * @param bool|array $vars Mapping variable name to value.
1670 public function setSchemaVars( $vars );
1673 * Check to see if a named lock is available (non-blocking)
1675 * @param string $lockName Name of lock to poll
1676 * @param string $method Name of method calling us
1677 * @return bool
1678 * @since 1.20
1680 public function lockIsFree( $lockName, $method );
1683 * Acquire a named lock
1685 * Named locks are not related to transactions
1687 * @param string $lockName Name of lock to aquire
1688 * @param string $method Name of the calling method
1689 * @param int $timeout Acquisition timeout in seconds
1690 * @return bool
1692 public function lock( $lockName, $method, $timeout = 5 );
1695 * Release a lock
1697 * Named locks are not related to transactions
1699 * @param string $lockName Name of lock to release
1700 * @param string $method Name of the calling method
1702 * @return int Returns 1 if the lock was released, 0 if the lock was not established
1703 * by this thread (in which case the lock is not released), and NULL if the named
1704 * lock did not exist
1706 public function unlock( $lockName, $method );
1709 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object
1711 * Only call this from outer transcation scope and when only one DB will be affected.
1712 * See https://www.mediawiki.org/wiki/Database_transactions for details.
1714 * This is suitiable for transactions that need to be serialized using cooperative locks,
1715 * where each transaction can see each others' changes. Any transaction is flushed to clear
1716 * out stale REPEATABLE-READ snapshot data. Once the returned object falls out of PHP scope,
1717 * the lock will be released unless a transaction is active. If one is active, then the lock
1718 * will be released when it either commits or rolls back.
1720 * If the lock acquisition failed, then no transaction flush happens, and null is returned.
1722 * @param string $lockKey Name of lock to release
1723 * @param string $fname Name of the calling method
1724 * @param int $timeout Acquisition timeout in seconds
1725 * @return ScopedCallback|null
1726 * @throws DBUnexpectedError
1727 * @since 1.27
1729 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
1732 * Check to see if a named lock used by lock() use blocking queues
1734 * @return bool
1735 * @since 1.26
1737 public function namedLocksEnqueue();
1740 * Find out when 'infinity' is. Most DBMSes support this. This is a special
1741 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
1742 * because "i" sorts after all numbers.
1744 * @return string
1746 public function getInfinity();
1749 * Encode an expiry time into the DBMS dependent format
1751 * @param string $expiry Timestamp for expiry, or the 'infinity' string
1752 * @return string
1754 public function encodeExpiry( $expiry );
1757 * Decode an expiry time into a DBMS independent format
1759 * @param string $expiry DB timestamp field value for expiry
1760 * @param int $format TS_* constant, defaults to TS_MW
1761 * @return string
1763 public function decodeExpiry( $expiry, $format = TS_MW );
1766 * Allow or deny "big selects" for this session only. This is done by setting
1767 * the sql_big_selects session variable.
1769 * This is a MySQL-specific feature.
1771 * @param bool|string $value True for allow, false for deny, or "default" to
1772 * restore the initial value
1774 public function setBigSelects( $value = true );
1777 * @return bool Whether this DB is read-only
1778 * @since 1.27
1780 public function isReadOnly();
1783 * Make certain table names use their own database, schema, and table prefix
1784 * when passed into SQL queries pre-escaped and without a qualified database name
1786 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
1787 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
1789 * Calling this twice will completely clear any old table aliases. Also, note that
1790 * callers are responsible for making sure the schemas and databases actually exist.
1792 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
1793 * @since 1.28
1795 public function setTableAliases( array $aliases );