Merge "CologneBlue rewrite: fix talkLink() to use generic nav links"
[lhc/web/wiklou.git] / includes / db / Database.php
index 5344b12..48aac9d 100644 (file)
@@ -228,7 +228,10 @@ abstract class DatabaseBase implements DatabaseType {
        protected $mConn = null;
        protected $mOpened = false;
 
-       /** @var Array */
+       /**
+        * @since 1.20
+        * @var array of callable
+        */
        protected $trxIdleCallbacks = array();
 
        protected $mTablePrefix;
@@ -247,7 +250,7 @@ abstract class DatabaseBase implements DatabaseType {
        protected $delimiter = ';';
 
        /**
-        * Remembers the function name given for starting the most recent transaction via the begin() method.
+        * Remembers the function name given for starting the most recent transaction via begin().
         * Used to provide additional context for error reporting.
         *
         * @var String
@@ -255,6 +258,22 @@ abstract class DatabaseBase implements DatabaseType {
         */
        private $mTrxFname = null;
 
+       /**
+        * Record if possible write queries were done in the last transaction started
+        *
+        * @var Bool
+        * @see DatabaseBase::mTrxLevel
+        */
+       private $mTrxDoneWrites = false;
+
+       /**
+        * Record if the current transaction was started implicitly due to DBO_TRX being set.
+        *
+        * @var Bool
+        * @see DatabaseBase::mTrxLevel
+        */
+       private $mTrxAutomatic = false;
+
 # ------------------------------------------------------------------------------
 # Accessors
 # ------------------------------------------------------------------------------
@@ -734,8 +753,14 @@ abstract class DatabaseBase implements DatabaseType {
                $this->mOpened = false;
                if ( $this->mConn ) {
                        if ( $this->trxLevel() ) {
-                               $this->commit( __METHOD__ );
+                               if ( !$this->mTrxAutomatic ) {
+                                       wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
+                                               " performing implicit commit before closing connection!" );
+                               }
+
+                               $this->commit( __METHOD__, 'flush' );
                        }
+
                        $ret = $this->closeConnection();
                        $this->mConn = false;
                        return $ret;
@@ -753,6 +778,7 @@ abstract class DatabaseBase implements DatabaseType {
 
        /**
         * @param $error String: fallback error message, used if none is given by DB
+        * @throws DBConnectionError
         */
        function reportConnectionError( $error = 'Unknown error' ) {
                $myError = $this->lastError();
@@ -802,9 +828,9 @@ abstract class DatabaseBase implements DatabaseType {
         *     comment (you can use __METHOD__ or add some extra info)
         * @param  $tempIgnore Boolean:   Whether to avoid throwing an exception on errors...
         *     maybe best to catch the exception instead?
+        * @throws MWException
         * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
         *     for a successful read query, or false on failure if $tempIgnore set
-        * @throws DBQueryError Thrown when the database returns an error of any kind
         */
        public function query( $sql, $fname = '', $tempIgnore = false ) {
                $isMaster = !is_null( $this->getLBInfo( 'master' ) );
@@ -845,9 +871,10 @@ abstract class DatabaseBase implements DatabaseType {
                $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
 
                # If DBO_TRX is set, start a transaction
-               if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
-                       $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
-                       # avoid establishing transactions for SHOW and SET statements too -
+               if ( ( $this->mFlags & DBO_TRX ) && !$this->mTrxLevel &&
+                       $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
+               {
+                       # Avoid establishing transactions for SHOW and SET statements too -
                        # that would delay transaction initializations to once connection
                        # is really used by application
                        $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
@@ -857,9 +884,15 @@ abstract class DatabaseBase implements DatabaseType {
                                        wfDebug("Implicit transaction start.\n");
                                }
                                $this->begin( __METHOD__ . " ($fname)" );
+                               $this->mTrxAutomatic = true;
                        }
                }
 
+               # Keep track of whether the transaction has write queries pending
+               if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $this->isWriteQuery( $sql ) ) {
+                       $this->mTrxDoneWrites = true;
+               }
+
                if ( $this->debug() ) {
                        static $cnt = 0;
 
@@ -886,6 +919,7 @@ abstract class DatabaseBase implements DatabaseType {
                if ( false === $ret && $this->wasErrorReissuable() ) {
                        # Transaction is gone, like it or not
                        $this->mTrxLevel = 0;
+                       $this->trxIdleCallbacks = array(); // cancel
                        wfDebug( "Connection lost, reconnecting...\n" );
 
                        if ( $this->ping() ) {
@@ -925,6 +959,7 @@ abstract class DatabaseBase implements DatabaseType {
         * @param $sql String
         * @param $fname String
         * @param $tempIgnore Boolean
+        * @throws DBQueryError
         */
        public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
                # Ignore errors during error handling to avoid infinite recursion
@@ -1011,6 +1046,7 @@ abstract class DatabaseBase implements DatabaseType {
         * while we're doing this.
         *
         * @param $matches Array
+        * @throws DBUnexpectedError
         * @return String
         */
        protected function fillPreparedArg( $matches ) {
@@ -1726,7 +1762,7 @@ abstract class DatabaseBase implements DatabaseType {
        /**
         * Makes an encoded list of strings from an array
         * @param $a Array containing the data
-        * @param $mode int Constant
+        * @param int $mode Constant
         *      - LIST_COMMA:          comma separated, no field names
         *      - LIST_AND:            ANDed WHERE clause (without the WHERE). See
         *        the documentation for $conds in DatabaseBase::select().
@@ -1734,6 +1770,7 @@ abstract class DatabaseBase implements DatabaseType {
         *      - LIST_SET:            comma separated with field names, like a SET clause
         *      - LIST_NAMES:          comma separated field names
         *
+        * @throws MWException|DBUnexpectedError
         * @return string
         */
        public function makeList( $a, $mode = LIST_COMMA ) {
@@ -2435,6 +2472,7 @@ abstract class DatabaseBase implements DatabaseType {
         *                    ANDed together in the WHERE clause
         * @param $fname      String: Calling function name (use __METHOD__) for
         *                    logs/profiling
+        * @throws DBUnexpectedError
         */
        public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
                $fname = 'DatabaseBase::deleteJoin' )
@@ -2500,6 +2538,7 @@ abstract class DatabaseBase implements DatabaseType {
         *               the format. Use $conds == "*" to delete all rows
         * @param $fname String name of the calling function
         *
+        * @throws DBUnexpectedError
         * @return bool
         */
        public function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
@@ -2598,6 +2637,7 @@ abstract class DatabaseBase implements DatabaseType {
         * @param $limit Integer the SQL limit
         * @param $offset Integer|bool the SQL offset (default false)
         *
+        * @throws DBUnexpectedError
         * @return string
         */
        public function limitResult( $sql, $limit, $offset = false ) {
@@ -2846,8 +2886,9 @@ abstract class DatabaseBase implements DatabaseType {
         *
         * This is useful for updates to different systems or separate transactions are needed.
         *
+        * @since 1.20
+        *
         * @param Closure $callback
-        * @return void
         */
        final public function onTransactionIdle( Closure $callback ) {
                if ( $this->mTrxLevel ) {
@@ -2858,7 +2899,9 @@ abstract class DatabaseBase implements DatabaseType {
        }
 
        /**
-        * Actually run the "on transaction idle" callbacks
+        * Actually run the "on transaction idle" callbacks.
+        *
+        * @since 1.20
         */
        protected function runOnTransactionIdleCallbacks() {
                $e = null; // last exception
@@ -2878,22 +2921,50 @@ abstract class DatabaseBase implements DatabaseType {
        }
 
        /**
-        * Begin a transaction
+        * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
+        * new transaction is started.
+        *
+        * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
+        * any previous database query will have started a transaction automatically.
+        *
+        * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
+        * transaction was started automatically because of the DBO_TRX flag.
         *
         * @param $fname string
         */
        final public function begin( $fname = 'DatabaseBase::begin' ) {
+               global $wgDebugDBTransactions;
+
                if ( $this->mTrxLevel ) { // implicit commit
-                       wfWarn( "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
-                               " performing implicit commit!" );
+                       if ( !$this->mTrxAutomatic ) {
+                               // We want to warn about inadvertently nested begin/commit pairs, but not about auto-committing
+                               // implicit transactions that were started by query() because DBO_TRX was set.
+
+                               wfWarn( "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
+                                       " performing implicit commit!" );
+                       } else {
+                               // if the transaction was automatic and has done write operations,
+                               // log it if $wgDebugDBTransactions is enabled.
+
+                               if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
+                                       wfDebug( "$fname: Automatic transaction with writes in progress (from {$this->mTrxFname}), " .
+                                               " performing implicit commit!\n" );
+                               }
+                       }
+
                        $this->doCommit( $fname );
                        $this->runOnTransactionIdleCallbacks();
                }
+
                $this->doBegin( $fname );
                $this->mTrxFname = $fname;
+               $this->mTrxDoneWrites = false;
+               $this->mTrxAutomatic = false;
        }
 
        /**
+        * Issues the BEGIN command to the database server.
+        *
         * @see DatabaseBase::begin()
         * @param type $fname
         */
@@ -2903,19 +2974,39 @@ abstract class DatabaseBase implements DatabaseType {
        }
 
        /**
-        * End a transaction
+        * Commits a transaction previously started using begin().
+        * If no transaction is in progress, a warning is issued.
+        *
+        * Nesting of transactions is not supported.
         *
         * @param $fname string
-        */
-       final public function commit( $fname = 'DatabaseBase::commit' ) {
-               if ( !$this->mTrxLevel ) {
-                       wfWarn( "$fname: No transaction to commit, something got out of sync!" );
+        * @param $flush String Flush flag, set to 'flush' to disable warnings about explicitly committing implicit
+        *        transactions, or calling commit when no transaction is in progress.
+        *        This will silently break any ongoing explicit transaction. Only set the flush flag if you are sure
+        *        that it is safe to ignore these warnings in your context.
+        */
+       final public function commit( $fname = 'DatabaseBase::commit', $flush = '' ) {
+               if ( $flush != 'flush' ) {
+                       if ( !$this->mTrxLevel ) {
+                               wfWarn( "$fname: No transaction to commit, something got out of sync!" );
+                       } elseif( $this->mTrxAutomatic ) {
+                               wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
+                       }
+               } else {
+                       if ( !$this->mTrxLevel ) {
+                               return; // nothing to do
+                       } elseif( !$this->mTrxAutomatic ) {
+                               wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
+                       }
                }
+
                $this->doCommit( $fname );
                $this->runOnTransactionIdleCallbacks();
        }
 
        /**
+        * Issues the COMMIT command to the database server.
+        *
         * @see DatabaseBase::commit()
         * @param type $fname
         */
@@ -2927,7 +3018,9 @@ abstract class DatabaseBase implements DatabaseType {
        }
 
        /**
-        * Rollback a transaction.
+        * Rollback a transaction previously started using begin().
+        * If no transaction is in progress, a warning is issued.
+        *
         * No-op on non-transactional databases.
         *
         * @param $fname string
@@ -2941,6 +3034,8 @@ abstract class DatabaseBase implements DatabaseType {
        }
 
        /**
+        * Issues the ROLLBACK command to the database server.
+        *
         * @see DatabaseBase::rollback()
         * @param type $fname
         */
@@ -2963,6 +3058,7 @@ abstract class DatabaseBase implements DatabaseType {
         * @param $newName String: name of table to be created
         * @param $temporary Boolean: whether the new table should be temporary
         * @param $fname String: calling function name
+        * @throws MWException
         * @return Boolean: true if operation was successful
         */
        public function duplicateTableStructure( $oldName, $newName, $temporary = false,
@@ -2977,6 +3073,7 @@ abstract class DatabaseBase implements DatabaseType {
         *
         * @param $prefix string Only show tables with this prefix, e.g. mw_
         * @param $fname String: calling function name
+        * @throws MWException
         */
        function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
                throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
@@ -3120,10 +3217,11 @@ abstract class DatabaseBase implements DatabaseType {
         * on object's error ignore settings).
         *
         * @param $filename String: File name to open
-        * @param $lineCallback Callback: Optional function called before reading each line
-        * @param $resultCallback Callback: Optional function called for each MySQL result
-        * @param $fname String: Calling function name or false if name should be
+        * @param bool|callable $lineCallback Optional function called before reading each line
+        * @param bool|callable $resultCallback Optional function called for each MySQL result
+        * @param bool|string $fname Calling function name or false if name should be
         *      generated dynamically using $filename
+        * @throws MWException
         * @return bool|string
         */
        public function sourceFile(