rdbms: Add IDatabase::cancelAtomic()
[lhc/web/wiklou.git] / includes / libs / rdbms / database / IDatabase.php
index d59bee3..47954b6 100644 (file)
@@ -19,6 +19,7 @@
  */
 namespace Wikimedia\Rdbms;
 
+use InvalidArgumentException;
 use Wikimedia\ScopedCallback;
 use RuntimeException;
 use UnexpectedValueException;
@@ -356,7 +357,7 @@ interface IDatabase {
        public function getType();
 
        /**
-        * Open a connection to the database. Usually aborts on failure
+        * Open a new connection to the database (closing any existing one)
         *
         * @param string $server Database server host
         * @param string $user Database user name
@@ -491,8 +492,11 @@ interface IDatabase {
        public function getServerVersion();
 
        /**
-        * Closes a database connection.
-        * if it is open : commits any open transactions
+        * Close the database connection
+        *
+        * This should only be called after any transactions have been resolved,
+        * aside from read-only transactions (assuming no callbacks are registered).
+        * If a transaction is still open anyway, it will be committed if possible.
         *
         * @throws DBError
         * @return bool Operation success. true if already closed.
@@ -509,6 +513,10 @@ interface IDatabase {
         * Run an SQL query and return the result. Normally throws a DBQueryError
         * on failure. If errors are ignored, returns false instead.
         *
+        * If a connection loss is detected, then an attempt to reconnect will be made.
+        * For queries that involve no larger transactions or locks, they will be re-issued
+        * for convenience, provided the connection was re-established.
+        *
         * In new code, the query wrappers select(), insert(), update(), delete(),
         * etc. should be used where possible, since they give much better DBMS
         * independence and automatically quote or validate user input in a variety
@@ -620,6 +628,11 @@ interface IDatabase {
         * This includes the user table in the query, with the alias "a" available
         * for use in field names (e.g. a.user_name).
         *
+        * A derived table, defined by the result of selectSQLText(), requires an alias
+        * key and a Subquery instance value which wraps the SQL query, for example:
+        *
+        *    [ 'c' => new Subquery( 'SELECT ...' ) ]
+        *
         * Joins using parentheses for grouping (since MediaWiki 1.31) may be
         * constructed using nested arrays. For example,
         *
@@ -769,15 +782,15 @@ interface IDatabase {
         * doing UNION queries, where the SQL text of each query is needed. In general,
         * however, callers outside of Database classes should just use select().
         *
+        * @see IDatabase::select()
+        *
         * @param string|array $table Table name
         * @param string|array $vars Field names
         * @param string|array $conds Conditions
         * @param string $fname Caller function name
         * @param string|array $options Query options
         * @param string|array $join_conds Join conditions
-        *
-        * @return string SQL query string.
-        * @see IDatabase::select()
+        * @return string SQL query string
         */
        public function selectSQLText(
                $table, $vars, $conds = '', $fname = __METHOD__,
@@ -817,15 +830,16 @@ interface IDatabase {
         * Takes the same arguments as IDatabase::select().
         *
         * @param string $table Table name
-        * @param string $vars Unused
+        * @param string $var Column for which NULL values are not counted [default "*"]
         * @param array|string $conds Filters on the table
         * @param string $fname Function name for profiling
         * @param array $options Options for select
+        * @param array|string $join_conds Join conditions
         * @return int Row count
         * @throws DBError
         */
        public function estimateRowCount(
-               $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
+               $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
        );
 
        /**
@@ -838,7 +852,7 @@ interface IDatabase {
         * @since 1.27 Added $join_conds parameter
         *
         * @param array|string $tables Table names
-        * @param string $vars Unused
+        * @param string $var Column for which NULL values are not counted [default "*"]
         * @param array|string $conds Filters on the table
         * @param string $fname Function name for profiling
         * @param array $options Options for select
@@ -847,7 +861,7 @@ interface IDatabase {
         * @throws DBError
         */
        public function selectRowCount(
-               $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
+               $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
        );
 
        /**
@@ -962,11 +976,11 @@ interface IDatabase {
         * Example usage:
         * @code
         *     $sql = $db->makeList( [
-        *         'rev_user' => $id,
+        *         'rev_page' => $id,
         *         $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] )
         *     ], $db::LIST_AND );
         * @endcode
-        * This would set $sql to "rev_user = '$id' AND (rev_minor = '1' OR rev_len < '500')"
+        * This would set $sql to "rev_page = '$id' AND (rev_minor = '1' OR rev_len < '500')"
         *
         * @param array $a Containing the data
         * @param int $mode IDatabase class constant:
@@ -1050,6 +1064,20 @@ interface IDatabase {
                $delim, $table, $field, $conds = '', $join_conds = []
        );
 
+       /**
+        * Build a SUBSTRING function.
+        *
+        * Behavior for non-ASCII values is undefined.
+        *
+        * @param string $input Field name
+        * @param int $startPosition Positive integer
+        * @param int|null $length Non-negative integer length or null for no limit
+        * @throws InvalidArgumentException
+        * @return string SQL text
+        * @since 1.31
+        */
+       public function buildSubString( $input, $startPosition, $length = null );
+
        /**
         * @param string $field Field or column to cast
         * @return string
@@ -1057,6 +1085,32 @@ interface IDatabase {
         */
        public function buildStringCast( $field );
 
+       /**
+        * @param string $field Field or column to cast
+        * @return string
+        * @since 1.31
+        */
+       public function buildIntegerCast( $field );
+
+       /**
+        * Equivalent to IDatabase::selectSQLText() except wraps the result in Subqyery
+        *
+        * @see IDatabase::selectSQLText()
+        *
+        * @param string|array $table Table name
+        * @param string|array $vars Field names
+        * @param string|array $conds Conditions
+        * @param string $fname Caller function name
+        * @param string|array $options Query options
+        * @param string|array $join_conds Join conditions
+        * @return Subquery
+        * @since 1.31
+        */
+       public function buildSelectSubquery(
+               $table, $vars, $conds = '', $fname = __METHOD__,
+               $options = [], $join_conds = []
+       );
+
        /**
         * Returns true if DBs are assumed to be on potentially different servers
         *
@@ -1276,7 +1330,9 @@ interface IDatabase {
         * @param string $fname The function name of the caller, from __METHOD__
         *
         * @param array $insertOptions Options for the INSERT part of the query, see
-        *    IDatabase::insert() for details.
+        *    IDatabase::insert() for details. Also, one additional option is
+        *    available: pass 'NO_AUTO_COLUMNS' to hint that the query does not use
+        *    an auto-increment or sequence to determine any column values.
         * @param array $selectOptions Options for the SELECT part of the query, see
         *    IDatabase::select() for details.
         * @param array $selectJoinConds Join conditions for the SELECT part of the query, see
@@ -1372,6 +1428,8 @@ interface IDatabase {
        /**
         * Determines if the last failure was due to a deadlock
         *
+        * Note that during a deadlock, the prior transaction will have been lost
+        *
         * @return bool
         */
        public function wasDeadlock();
@@ -1379,17 +1437,21 @@ interface IDatabase {
        /**
         * Determines if the last failure was due to a lock timeout
         *
+        * Note that during a lock wait timeout, the prior transaction will have been lost
+        *
         * @return bool
         */
        public function wasLockTimeout();
 
        /**
-        * Determines if the last query error was due to a dropped connection and should
-        * be dealt with by pinging the connection and reissuing the query.
+        * Determines if the last query error was due to a dropped connection
+        *
+        * Note that during a connection loss, the prior transaction will have been lost
         *
         * @return bool
+        * @since 1.31
         */
-       public function wasErrorReissuable();
+       public function wasConnectionLoss();
 
        /**
         * Determines if the last failure was due to the database being read-only.
@@ -1398,6 +1460,15 @@ interface IDatabase {
         */
        public function wasReadOnlyError();
 
+       /**
+        * Determines if the last query error was due to something outside of the query itself
+        *
+        * Note that the transaction may have been lost, discarding prior writes and results
+        *
+        * @return bool
+        */
+       public function wasErrorReissuable();
+
        /**
         * Wait for the replica DB to catch up to a given master position
         *
@@ -1509,19 +1580,19 @@ interface IDatabase {
        /**
         * Begin an atomic section of statements
         *
-        * If a transaction has been started already, just keep track of the given
-        * section name to make sure the transaction is not committed pre-maturely.
-        * This function can be used in layers (with sub-sections), so use a stack
-        * to keep track of the different atomic sections. If there is no transaction,
-        * start one implicitly.
+        * If a transaction has been started already, sets a savepoint and tracks
+        * the given section name to make sure the transaction is not committed
+        * pre-maturely. This function can be used in layers (with sub-sections),
+        * so use a stack to keep track of the different atomic sections. If there
+        * is no transaction, one is started implicitly.
         *
         * The goal of this function is to create an atomic section of SQL queries
         * without having to start a new transaction if it already exists.
         *
-        * All atomic levels *must* be explicitly closed using IDatabase::endAtomic(),
-        * and any database transactions cannot be began or committed until all atomic
-        * levels are closed. There is no such thing as implicitly opening or closing
-        * an atomic section.
+        * All atomic levels *must* be explicitly closed using IDatabase::endAtomic()
+        * or IDatabase::cancelAtomic(), and any database transactions cannot be
+        * began or committed until all atomic levels are closed. There is no such
+        * thing as implicitly opening or closing an atomic section.
         *
         * @since 1.23
         * @param string $fname
@@ -1542,6 +1613,26 @@ interface IDatabase {
         */
        public function endAtomic( $fname = __METHOD__ );
 
+       /**
+        * Cancel an atomic section of SQL statements
+        *
+        * This will roll back only the statements executed since the start of the
+        * most recent atomic section, and close that section. If a transaction was
+        * open before the corresponding startAtomic() call, any statements before
+        * that call are *not* rolled back and the transaction remains open. If the
+        * corresponding startAtomic() implicitly started a transaction, that
+        * transaction is rolled back.
+        *
+        * Note that a call to IDatabase::rollback() will also roll back any open
+        * atomic sections.
+        *
+        * @since 1.31
+        * @see IDatabase::startAtomic
+        * @param string $fname
+        * @throws DBError
+        */
+       public function cancelAtomic( $fname = __METHOD__ );
+
        /**
         * Run a callback to do an atomic set of updates for this database
         *
@@ -1549,17 +1640,18 @@ interface IDatabase {
         *   - This database object
         *   - The value of $fname
         *
-        * If any exception occurs in the callback, then rollback() will be called and the error will
-        * be re-thrown. It may also be that the rollback itself fails with an exception before then.
-        * In any case, such errors are expected to terminate the request, without any outside caller
-        * attempting to catch errors and commit anyway. Note that any rollback undoes all prior
-        * atomic section and uncommitted updates, which trashes the current request, requiring an
-        * error to be displayed.
+        * If any exception occurs in the callback, then cancelAtomic() will be
+        * called to back out any statements executed by the callback and the error
+        * will be re-thrown. It may also be that the cancel itself fails with an
+        * exception before then. In any case, such errors are expected to
+        * terminate the request, without any outside caller attempting to catch
+        * errors and commit anyway.
         *
-        * This can be an alternative to explicit startAtomic()/endAtomic() calls.
+        * This can be an alternative to explicit startAtomic()/endAtomic()/cancelAtomic() calls.
         *
         * @see Database::startAtomic
         * @see Database::endAtomic
+        * @see Database::cancelAtomic
         *
         * @param string $fname Caller name (usually __METHOD__)
         * @param callable $callback Callback that issues DB updates
@@ -1567,7 +1659,9 @@ interface IDatabase {
         * @throws DBError
         * @throws RuntimeException
         * @throws UnexpectedValueException
-        * @since 1.27
+        * @since 1.27; prior to 1.31 this did a rollback() instead of
+        *  cancelAtomic(), and assumed no callers up the stack would ever try to
+        *  catch the exception.
         */
        public function doAtomicSection( $fname, callable $callback );
 
@@ -1903,6 +1997,21 @@ interface IDatabase {
         * @since 1.28
         */
        public function setTableAliases( array $aliases );
+
+       /**
+        * Convert certain index names to alternative names before querying the DB
+        *
+        * Note that this applies to indexes regardless of the table they belong to.
+        *
+        * This can be employed when an index was renamed X => Y in code, but the new Y-named
+        * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
+        * the aliases can be removed, and then the old X-named indexes dropped.
+        *
+        * @param string[] $aliases
+        * @return mixed
+        * @since 1.31
+        */
+       public function setIndexAliases( array $aliases );
 }
 
 class_alias( IDatabase::class, 'IDatabase' );