4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
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.
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.
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
29 * Basic database interface for live and lazy-loaded DB handles
31 * @todo: loosen up DB classes from MWException
32 * @note: IDatabase and DBConnRef should be updated to reflect any changes
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 interally 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';
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.
58 * @return string Version information from the database server
60 public function getServerInfo();
63 * Turns buffering of SQL result sets on (true) or off (false). Default is
66 * Unbuffered queries are very troublesome in MySQL:
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.
73 * - Unbuffered queries cause the MySQL server to use large amounts of
74 * memory and to hold broad locks which block other queries.
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
80 * @param null|bool $buffer
81 * @return null|bool The previous value of the flag
83 public function bufferResults( $buffer = null );
86 * Gets the current transaction level.
88 * Historically, transactions were allowed to be "nested". This is no
89 * longer supported, so this function really only returns a boolean.
91 * @return int The previous value
93 public function trxLevel();
96 * Get the UNIX timestamp of the time that the transaction was established
98 * This can be used to reason about the staleness of SELECT data
99 * in REPEATABLE-READ transaction isolation level.
101 * @return float|null Returns null if there is not active transaction
104 public function trxTimestamp();
107 * @return bool Whether an explicit transaction or atomic sections are still open
110 public function explicitTrxActive();
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.
117 public function tablePrefix( $prefix = null );
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.
124 public function dbSchema( $schema = null );
127 * Get properties passed down from the server info array of the load
130 * @param string $name The entry of the info array to get, or null to get the
133 * @return array|mixed|null
135 public function getLBInfo( $name = null );
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.
142 * @param string $name
143 * @param array $value
145 public function setLBInfo( $name, $value = null );
148 * Returns true if this database does an implicit sort when doing GROUP BY
152 public function implicitGroupby();
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
160 public function implicitOrderby();
163 * Return the last query that went through IDatabase::query()
166 public function lastQuery();
169 * Returns true if the connection may have been used for write queries.
170 * Should return true if unsure.
174 public function doneWrites();
177 * Returns the last time the connection may have been used for write queries.
178 * Should return a timestamp if unsure.
180 * @return int|float UNIX timestamp or false
183 public function lastDoneWrites();
186 * @return bool Whether there is a transaction open with possible write queries
189 public function writesPending();
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.
197 public function writesOrCallbacksPending();
200 * Get the time spend running write queries for this transaction
202 * High times could be due to scanning, updates, locking, and such
204 * @return float|bool Returns false if not transaction is active
207 public function pendingWriteQueryDuration();
210 * Get the list of method names that did write queries for this transaction
215 public function pendingWriteCallers();
218 * Is a connection to the database open?
221 public function isOpen();
224 * Set a flag for this connection
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
234 public function setFlag( $flag );
237 * Clear a flag for this connection
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
247 public function clearFlag( $flag );
250 * Returns a boolean whether the flag $flag is set for this connection
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
259 public function getFlag( $flag );
262 * General read-only accessor
264 * @param string $name
267 public function getProperty( $name );
272 public function getWikiID();
275 * Get the type of the DBMS, as it appears in $wgDBtype.
279 public function getType();
282 * Open a connection to the database. Usually aborts on failure
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
289 * @throws DBConnectionError
291 public function open( $server, $user, $password, $dbName );
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
297 * If no more rows are available, false is returned.
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
303 public function fetchObject( $res );
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.
310 * @param ResultWrapper $res Result object as returned from IDatabase::query(), etc.
312 * @throws DBUnexpectedError Thrown if the database returns an error
314 public function fetchRow( $res );
317 * Get the number of rows in a result object
319 * @param mixed $res A SQL result
322 public function numRows( $res );
325 * Get the number of fields in a result object
326 * @see http://www.php.net/mysql_num_fields
328 * @param mixed $res A SQL result
331 public function numFields( $res );
334 * Get a field name in a result object
335 * @see http://www.php.net/mysql_field_name
337 * @param mixed $res A SQL result
341 public function fieldName( $res, $n );
344 * Get the inserted value of an auto-increment row
346 * The value inserted should be fetched from nextSequenceValue()
349 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
350 * $dbw->insert( 'page', [ 'page_id' => $id ] );
351 * $id = $dbw->insertId();
355 public function insertId();
358 * Change the position of the cursor in a result object
359 * @see http://www.php.net/mysql_data_seek
361 * @param mixed $res A SQL result
364 public function dataSeek( $res, $row );
367 * Get the last error number
368 * @see http://www.php.net/mysql_errno
372 public function lastErrno();
375 * Get a description of the last error
376 * @see http://www.php.net/mysql_error
380 public function lastError();
383 * mysql_fetch_field() wrapper
384 * Returns false if the field doesn't exist
386 * @param string $table Table name
387 * @param string $field Field name
391 public function fieldInfo( $table, $field );
394 * Get the number of rows affected by the last write query
395 * @see http://www.php.net/mysql_affected_rows
399 public function affectedRows();
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.
407 * @return string Wikitext of a link to the server software's web site
409 public function getSoftwareLink();
412 * A string describing the current software version, like from
413 * mysql_get_server_info().
415 * @return string Version information from the database server.
417 public function getServerVersion();
420 * Closes a database connection.
421 * if it is open : commits any open transactions
423 * @throws MWException
424 * @return bool Operation success. true if already closed.
426 public function close();
429 * @param string $error Fallback error message, used if none is given by DB
430 * @throws DBConnectionError
432 public function reportConnectionError( $error = 'Unknown error' );
435 * Run an SQL query and return the result. Normally throws a DBQueryError
436 * on failure. If errors are ignored, returns false instead.
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
445 * However, the query wrappers themselves should call this function.
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
456 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false );
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.
462 * @param string $error
465 * @param string $fname
466 * @param bool $tempIgnore
467 * @throws DBQueryError
469 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false );
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.
476 * @param mixed $res A SQL result
478 public function freeResult( $res );
481 * A SELECT wrapper which returns a single field from a single result row.
483 * Usually throws a DBQueryError on failure. If errors are explicitly
484 * ignored, returns false on failure.
486 * If no result rows are returned from the query, false is returned.
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.
495 * @return bool|mixed The value from the field, or false on failure.
497 public function selectField(
498 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
502 * A SELECT wrapper which returns a list of single field values from result rows.
504 * Usually throws a DBQueryError on failure. If errors are explicitly
505 * ignored, returns false on failure.
507 * If no result rows are returned from the query, false is returned.
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.
516 * @return bool|array The values from the field, or false on failure
519 public function selectFieldValues(
520 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
524 * Execute a SELECT query constructed using the various parameters provided.
525 * See below for full details of the parameters.
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
535 * @param string|array $table
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:
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).
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.
549 * Do not use untrusted user input as a table name. Alias names should
550 * not have characters outside of the Basic multilingual plane.
552 * @param string|array $vars
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:
558 * [ 'maxrev' => 'MAX(rev_id)' ]
560 * This includes an expression with the alias "maxrev" in the query.
562 * If an expression is given, care must be taken to ensure that it is
565 * Untrusted user input must not be passed to this parameter.
567 * @param string|array $conds
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.
573 * Array elements may take one of two forms:
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.
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()
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()
597 * @param string|array $options
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
605 * The supported options are:
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.
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.
615 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
616 * changed until the next COMMIT.
618 * - DISTINCT: Boolean: return only unique result rows.
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.
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.
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.
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.
636 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
639 * And also the following boolean MySQL extensions, see the MySQL manual
642 * - LOCK IN SHARE MODE
646 * - SQL_BUFFER_RESULT
648 * - SQL_CALC_FOUND_ROWS
653 * @param string|array $join_conds
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.
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:
665 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ]
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.
672 public function select(
673 $table, $vars, $conds = '', $fname = __METHOD__
,
674 $options = [], $join_conds = []
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().
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
690 * @return string SQL query string.
691 * @see IDatabase::select()
693 public function selectSQLText(
694 $table, $vars, $conds = '', $fname = __METHOD__
,
695 $options = [], $join_conds = []
699 * Single row SELECT wrapper. Equivalent to IDatabase::select(), except
700 * that a single row object is returned. If the query returns no rows,
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
710 * @return stdClass|bool
712 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
713 $options = [], $join_conds = []
717 * Estimate the number of rows in dataset
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.
724 * For DBMSs that don't support fast result size estimation, this function
725 * will actually perform the SELECT COUNT(*).
727 * Takes the same arguments as IDatabase::select().
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
736 public function estimateRowCount(
737 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
741 * Get the number of rows in dataset
743 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
745 * Takes the same arguments as IDatabase::select().
747 * @since 1.27 Added $join_conds parameter
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
757 public function selectRowCount(
758 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
762 * Determines whether a field exists in a table
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
769 public function fieldExists( $table, $field, $fname = __METHOD__
);
772 * Determines whether an index exists
773 * Usually throws a DBQueryError on failure
774 * If errors are explicitly ignored, returns NULL on failure
776 * @param string $table
777 * @param string $index
778 * @param string $fname
781 public function indexExists( $table, $index, $fname = __METHOD__
);
784 * Query whether a given table exists
786 * @param string $table
787 * @param string $fname
790 public function tableExists( $table, $fname = __METHOD__
);
793 * Determines if a given index is unique
795 * @param string $table
796 * @param string $index
800 public function indexUnique( $table, $index );
803 * INSERT wrapper, inserts an array into a table.
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.
815 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
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:
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().
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
835 public function insert( $table, $a, $fname = __METHOD__
, $options = [] );
838 * UPDATE wrapper. Takes a condition array and a SET array.
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.
855 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] );
858 * Makes an encoded list of strings from an array
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
871 public function makeList( $a, $mode = LIST_COMMA
);
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.
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
883 public function makeWhereFrom2d( $data, $baseKey, $subKey );
886 * @param string $field
889 public function bitNot( $field );
892 * @param string $fieldLeft
893 * @param string $fieldRight
896 public function bitAnd( $fieldLeft, $fieldRight );
899 * @param string $fieldLeft
900 * @param string $fieldRight
903 public function bitOr( $fieldLeft, $fieldRight );
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
911 public function buildConcat( $stringList );
914 * Build a GROUP_CONCAT or equivalent statement for a query.
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.
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
929 public function buildGroupConcatField(
930 $delim, $table, $field, $conds = '', $join_conds = []
934 * Change the current database
937 * @return bool Success or failure
939 public function selectDB( $db );
942 * Get the current DB name
945 public function getDBname();
948 * Get the server hostname or IP address
951 public function getServer();
954 * Adds quotes and backslashes.
956 * @param string|Blob $s
959 public function addQuotes( $s );
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
968 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
969 * a LIKE clause that searches for subpages of 'My page title'.
971 * $pattern = [ 'My_page_title/', $dbr->anyString() ];
972 * $query .= $dbr->buildLike( $pattern );
975 * @return string Fully built LIKE statement
977 public function buildLike();
980 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
984 public function anyChar();
987 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
991 public function anyString();
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()
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
1004 public function nextSequenceValue( $seqName );
1007 * REPLACE query wrapper.
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.
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.
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.
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
1028 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
);
1031 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
1033 * This updates any conflicting rows (according to the unique indexes) using
1034 * the provided SET clause and inserts any remaining (non-conflicted) rows.
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.
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.
1049 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
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
1064 public function upsert(
1065 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
1069 * DELETE where the condition is a join.
1071 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
1072 * we use sub-selects
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='*'.
1077 * DO NOT put the join condition in $conds.
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
1088 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
1093 * DELETE query wrapper.
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
1102 public function delete( $table, $conds, $fname = __METHOD__
);
1105 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
1106 * into another table.
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.
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()
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
1121 * @param string $fname The function name of the caller, from __METHOD__
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.
1128 * @return ResultWrapper
1130 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
1131 $fname = __METHOD__
,
1132 $insertOptions = [], $selectOptions = []
1136 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1137 * within the UNION construct.
1140 public function unionSupportsOrderAndLimit();
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
1150 public function unionQueries( $sqls, $all );
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.
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
1161 public function conditional( $cond, $trueVal, $falseVal );
1164 * Returns a comand for str_replace function in SQL query.
1165 * Uses REPLACE() in MySQL
1167 * @param string $orig Column to modify
1168 * @param string $old Column to seek
1169 * @param string $new Column to replace with
1173 public function strreplace( $orig, $old, $new );
1176 * Determines how long the server has been up
1180 public function getServerUptime();
1183 * Determines if the last failure was due to a deadlock
1187 public function wasDeadlock();
1190 * Determines if the last failure was due to a lock timeout
1194 public function wasLockTimeout();
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.
1202 public function wasErrorReissuable();
1205 * Determines if the last failure was due to the database being read-only.
1209 public function wasReadOnlyError();
1212 * Wait for the slave to catch up to a given master position
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
1220 public function masterPosWait( DBMasterPos
$pos, $timeout );
1223 * Get the replication position of this slave
1225 * @return DBMasterPos|bool False if this is not a slave.
1227 public function getSlavePos();
1230 * Get the position of this master
1232 * @return DBMasterPos|bool False if this is not a master
1234 public function getMasterPos();
1237 * @return bool Whether the DB is marked as read-only server-side
1240 public function serverIsReadOnly();
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
1248 * This is useful for combining cooperative locks and DB transactions.
1250 * The callback takes one argument:
1251 * How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK)
1253 * @param callable $callback
1257 public function onTransactionResolution( callable
$callback );
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.
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.
1270 * Updates will execute in the order they were enqueued.
1272 * The callback takes one argument:
1273 * How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_IDLE)
1275 * @param callable $callback
1278 public function onTransactionIdle( callable
$callback );
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.
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.
1289 * Updates will execute in the order they were enqueued.
1291 * @param callable $callback
1294 public function onTransactionPreCommitOrIdle( callable
$callback );
1297 * Begin an atomic section of statements
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.
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.
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.
1317 * @param string $fname
1320 public function startAtomic( $fname = __METHOD__
);
1323 * Ends an atomic section of SQL statements
1325 * Ends the next section of atomic SQL statements and commits the transaction
1329 * @see IDatabase::startAtomic
1330 * @param string $fname
1333 public function endAtomic( $fname = __METHOD__
);
1336 * Run a callback to do an atomic set of updates for this database
1338 * The $callback takes the following arguments:
1339 * - This database object
1340 * - The value of $fname
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.
1349 * This can be an alternative to explicit startAtomic()/endAtomic() calls.
1351 * @see DatabaseBase::startAtomic
1352 * @see DatabaseBase::endAtomic
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)
1358 * @throws RuntimeException
1359 * @throws UnexpectedValueException
1362 public function doAtomicSection( $fname, callable
$callback );
1365 * Begin a transaction. If a transaction is already in progress,
1366 * that transaction will be committed before the new transaction is started.
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.
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.
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.
1380 * @param string $fname
1381 * @param string $mode A situationally valid IDatabase::TRANSACTION_* constant [optional]
1384 public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
);
1387 * Commits a transaction previously started using begin().
1388 * If no transaction is in progress, a warning is issued.
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.
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.
1399 * This will trigger an exception if there is an ongoing explicit transaction.
1401 * Only set the flush flag if you are sure that these warnings are not applicable,
1402 * and no explicit transactions are open.
1404 * @throws DBUnexpectedError
1406 public function commit( $fname = __METHOD__
, $flush = '' );
1409 * Rollback a transaction previously started using begin().
1410 * If no transaction is in progress, a warning is issued.
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).
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
1426 public function rollback( $fname = __METHOD__
, $flush = '' );
1429 * List all tables on the database
1431 * @param string $prefix Only show tables with this prefix, e.g. mw_
1432 * @param string $fname Calling function name
1433 * @throws MWException
1436 public function listTables( $prefix = null, $fname = __METHOD__
);
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.
1442 * The result is unquoted, and needs to be passed through addQuotes()
1443 * before it can be included in raw SQL.
1445 * @param string|int $ts
1449 public function timestamp( $ts = 0 );
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.
1457 * The result is unquoted, and needs to be passed through addQuotes()
1458 * before it can be included in raw SQL.
1460 * @param string|int $ts
1464 public function timestampOrNull( $ts = null );
1467 * Ping the server and try to reconnect if it there is no connection
1469 * @return bool Success or failure
1471 public function ping();
1474 * Get slave lag. Currently supported only by MySQL.
1476 * Note that this function will generate a fatal error on many
1477 * installations. Most callers should use LoadBalancer::safeGetLag()
1480 * @return int|bool Database replication lag in seconds or false on error
1482 public function getLag();
1485 * Get the slave lag when the current transaction started
1486 * or a general lag estimate if not transaction is active
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.
1494 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
1497 public function getSessionLagStatus();
1500 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1504 public function maxListLen();
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().
1515 public function encodeBlob( $b );
1518 * Some DBMSs return a special placeholder object representing blob fields
1519 * in result objects. Pass the object through this function to return the
1522 * @param string|Blob $b
1525 public function decodeBlob( $b );
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
1534 * @param array $options
1537 public function setSessionOptions( array $options );
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.
1544 * @param bool|array $vars Mapping variable name to value.
1546 public function setSchemaVars( $vars );
1549 * Check to see if a named lock is available (non-blocking)
1551 * @param string $lockName Name of lock to poll
1552 * @param string $method Name of method calling us
1556 public function lockIsFree( $lockName, $method );
1559 * Acquire a named lock
1561 * Named locks are not related to transactions
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
1568 public function lock( $lockName, $method, $timeout = 5 );
1573 * Named locks are not related to transactions
1575 * @param string $lockName Name of lock to release
1576 * @param string $method Name of the calling method
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
1582 public function unlock( $lockName, $method );
1585 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object
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.
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.
1596 * If the lock acquisition failed, then no transaction flush happens, and null is returned.
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
1605 public function getScopedLockAndFlush( $lockKey, $fname, $timeout );
1608 * Check to see if a named lock used by lock() use blocking queues
1613 public function namedLocksEnqueue();
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.
1622 public function getInfinity();
1625 * Encode an expiry time into the DBMS dependent format
1627 * @param string $expiry Timestamp for expiry, or the 'infinity' string
1630 public function encodeExpiry( $expiry );
1633 * Decode an expiry time into a DBMS independent format
1635 * @param string $expiry DB timestamp field value for expiry
1636 * @param int $format TS_* constant, defaults to TS_MW
1639 public function decodeExpiry( $expiry, $format = TS_MW
);
1642 * Allow or deny "big selects" for this session only. This is done by setting
1643 * the sql_big_selects session variable.
1645 * This is a MySQL-specific feature.
1647 * @param bool|string $value True for allow, false for deny, or "default" to
1648 * restore the initial value
1650 public function setBigSelects( $value = true );
1653 * @return bool Whether this DB is read-only
1656 public function isReadOnly();