Add CollationFa
[lhc/web/wiklou.git] / includes / db / Database.php
index c065ee9..3dc6e92 100644 (file)
@@ -52,10 +52,14 @@ abstract class DatabaseBase implements IDatabase {
        protected $mConn = null;
        protected $mOpened = false;
 
-       /** @var callable[] */
+       /** @var array[] List of (callable, method name) */
        protected $mTrxIdleCallbacks = [];
-       /** @var callable[] */
+       /** @var array[] List of (callable, method name) */
        protected $mTrxPreCommitCallbacks = [];
+       /** @var array[] List of (callable, method name) */
+       protected $mTrxEndCallbacks = [];
+       /** @var bool Whether to suppress triggering of post-commit callbacks */
+       protected $suppressPostCommitCallbacks = false;
 
        protected $mTablePrefix;
        protected $mSchema;
@@ -692,9 +696,6 @@ abstract class DatabaseBase implements IDatabase {
        }
 
        public function close() {
-               if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
-                       throw new MWException( "Transaction idle callbacks still pending." );
-               }
                if ( $this->mConn ) {
                        if ( $this->trxLevel() ) {
                                if ( !$this->mTrxAutomatic ) {
@@ -707,6 +708,8 @@ abstract class DatabaseBase implements IDatabase {
 
                        $closed = $this->closeConnection();
                        $this->mConn = false;
+               } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
+                       throw new MWException( "Transaction callbacks still pending." );
                } else {
                        $closed = true;
                }
@@ -1226,6 +1229,7 @@ abstract class DatabaseBase implements IDatabase {
                return '';
        }
 
+       // See IDatabase::select for the docs for this function
        public function select( $table, $vars, $conds = '', $fname = __METHOD__,
                $options = [], $join_conds = [] ) {
                $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
@@ -1668,6 +1672,8 @@ abstract class DatabaseBase implements IDatabase {
         * themselves. Pass the canonical name to such functions. This is only needed
         * when calling query() directly.
         *
+        * @note This function does not sanitize user input. It is not safe to use
+        *   this function to escape user input.
         * @param string $name Database table name
         * @param string $format One of:
         *   quoted - Automatically pass the table name through addIdentifierQuotes()
@@ -1844,7 +1850,7 @@ abstract class DatabaseBase implements IDatabase {
                if ( !$alias || (string)$alias === (string)$name ) {
                        return $name;
                } else {
-                       return $name . ' AS ' . $alias; // PostgreSQL needs AS
+                       return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
                }
        }
 
@@ -1981,6 +1987,8 @@ abstract class DatabaseBase implements IDatabase {
         * Returns if the given identifier looks quoted or not according to
         * the database convention for quoting identifiers .
         *
+        * @note Do not use this to determine if untrusted input is safe.
+        *   A malicious user can trick this function.
         * @param string $name
         * @return bool
         */
@@ -2380,14 +2388,19 @@ abstract class DatabaseBase implements IDatabase {
         * queries. If a deadlock occurs during the processing, the transaction
         * will be rolled back and the callback function will be called again.
         *
+        * Avoid using this method outside of Job or Maintenance classes.
+        *
         * Usage:
         *   $dbw->deadlockLoop( callback, ... );
         *
         * Extra arguments are passed through to the specified callback function.
+        * This method requires that no transactions are already active to avoid
+        * causing premature commits or exceptions.
         *
         * Returns whatever the callback function returned on its successful,
         * iteration, or false on error, for example if the retry limit was
         * reached.
+        *
         * @return mixed
         * @throws DBUnexpectedError
         * @throws Exception
@@ -2443,38 +2456,80 @@ abstract class DatabaseBase implements IDatabase {
                return false;
        }
 
-       final public function onTransactionIdle( $callback ) {
+       public function serverIsReadOnly() {
+               return false;
+       }
+
+       final public function onTransactionResolution( callable $callback ) {
+               if ( !$this->mTrxLevel ) {
+                       throw new DBUnexpectedError( $this, "No transaction is active." );
+               }
+               $this->mTrxEndCallbacks[] = [ $callback, wfGetCaller() ];
+       }
+
+       final public function onTransactionIdle( callable $callback ) {
                $this->mTrxIdleCallbacks[] = [ $callback, wfGetCaller() ];
                if ( !$this->mTrxLevel ) {
-                       $this->runOnTransactionIdleCallbacks();
+                       $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
                }
        }
 
-       final public function onTransactionPreCommitOrIdle( $callback ) {
+       final public function onTransactionPreCommitOrIdle( callable $callback ) {
                if ( $this->mTrxLevel ) {
                        $this->mTrxPreCommitCallbacks[] = [ $callback, wfGetCaller() ];
                } else {
-                       $this->onTransactionIdle( $callback ); // this will trigger immediately
+                       // If no transaction is active, then make one for this callback
+                       $this->begin( __METHOD__ );
+                       try {
+                               call_user_func( $callback );
+                               $this->commit( __METHOD__ );
+                       } catch ( Exception $e ) {
+                               $this->rollback( __METHOD__ );
+                               throw $e;
+                       }
                }
        }
 
        /**
-        * Actually any "on transaction idle" callbacks.
+        * Whether to disable running of post-commit callbacks
+        *
+        * This method should not be used outside of Database/LoadBalancer
+        *
+        * @param bool $suppress
+        * @since 1.28
+        */
+       final public function setPostCommitCallbackSupression( $suppress ) {
+               $this->suppressPostCommitCallbacks = $suppress;
+       }
+
+       /**
+        * Actually run and consume any "on transaction idle/resolution" callbacks.
         *
+        * This method should not be used outside of Database/LoadBalancer
+        *
+        * @param integer $trigger IDatabase::TRIGGER_* constant
         * @since 1.20
         */
-       protected function runOnTransactionIdleCallbacks() {
+       public function runOnTransactionIdleCallbacks( $trigger ) {
+               if ( $this->suppressPostCommitCallbacks ) {
+                       return;
+               }
+
                $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
 
                $e = $ePrior = null; // last exception
                do { // callbacks may add callbacks :)
-                       $callbacks = $this->mTrxIdleCallbacks;
-                       $this->mTrxIdleCallbacks = []; // recursion guard
+                       $callbacks = array_merge(
+                               $this->mTrxIdleCallbacks,
+                               $this->mTrxEndCallbacks // include "transaction resolution" callbacks
+                       );
+                       $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
+                       $this->mTrxEndCallbacks = []; // consumed (recursion guard)
                        foreach ( $callbacks as $callback ) {
                                try {
                                        list( $phpCallback ) = $callback;
                                        $this->clearFlag( DBO_TRX ); // make each query its own transaction
-                                       call_user_func( $phpCallback );
+                                       call_user_func_array( $phpCallback, [ $trigger ] );
                                        if ( $autoTrx ) {
                                                $this->setFlag( DBO_TRX ); // restore automatic begin()
                                        } else {
@@ -2500,15 +2555,17 @@ abstract class DatabaseBase implements IDatabase {
        }
 
        /**
-        * Actually any "on transaction pre-commit" callbacks.
+        * Actually run and consume any "on transaction pre-commit" callbacks.
+        *
+        * This method should not be used outside of Database/LoadBalancer
         *
         * @since 1.22
         */
-       protected function runOnTransactionPreCommitCallbacks() {
+       public function runOnTransactionPreCommitCallbacks() {
                $e = $ePrior = null; // last exception
                do { // callbacks may add callbacks :)
                        $callbacks = $this->mTrxPreCommitCallbacks;
-                       $this->mTrxPreCommitCallbacks = []; // recursion guard
+                       $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
                        foreach ( $callbacks as $callback ) {
                                try {
                                        list( $phpCallback ) = $callback;
@@ -2543,12 +2600,12 @@ abstract class DatabaseBase implements IDatabase {
 
        final public function endAtomic( $fname = __METHOD__ ) {
                if ( !$this->mTrxLevel ) {
-                       throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
+                       throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
                }
                if ( !$this->mTrxAtomicLevels ||
                        array_pop( $this->mTrxAtomicLevels ) !== $fname
                ) {
-                       throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
+                       throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
                }
 
                if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
@@ -2556,11 +2613,7 @@ abstract class DatabaseBase implements IDatabase {
                }
        }
 
-       final public function doAtomicSection( $fname, $callback ) {
-               if ( !is_callable( $callback ) ) {
-                       throw new UnexpectedValueException( "Invalid callback." );
-               };
-
+       final public function doAtomicSection( $fname, callable $callback ) {
                $this->startAtomic( $fname );
                try {
                        call_user_func_array( $callback, [ $this, $fname ] );
@@ -2584,19 +2637,15 @@ abstract class DatabaseBase implements IDatabase {
                        } elseif ( !$this->mTrxAutomatic ) {
                                // We want to warn about inadvertently nested begin/commit pairs, but not about
                                // auto-committing implicit transactions that were started by query() via DBO_TRX
-                               $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
-                                       " performing implicit commit!";
-                               wfWarn( $msg );
-                               wfLogDBError( $msg,
-                                       $this->getLogContext( [
-                                               'method' => __METHOD__,
-                                               'fname' => $fname,
-                                       ] )
+                               throw new DBUnexpectedError(
+                                       $this,
+                                       "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
+                                               " performing implicit commit!"
                                );
                        } else {
-                               // if the transaction was automatic and has done write operations
+                               // The transaction was automatic and has done write operations
                                if ( $this->mTrxDoneWrites ) {
-                                       wfDebug( "$fname: Automatic transaction with writes in progress" .
+                                       wfLogDBError( "$fname: Automatic transaction with writes in progress" .
                                                " (from {$this->mTrxFname}), performing implicit commit!\n"
                                        );
                                }
@@ -2610,10 +2659,11 @@ abstract class DatabaseBase implements IDatabase {
                                $this->getTransactionProfiler()->transactionWritingOut(
                                        $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
                        }
-                       $this->runOnTransactionIdleCallbacks();
+
+                       $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
                }
 
-               # Avoid fatals if close() was called
+               // Avoid fatals if close() was called
                $this->assertOpen();
 
                $this->doBegin( $fname );
@@ -2623,8 +2673,6 @@ abstract class DatabaseBase implements IDatabase {
                $this->mTrxAutomatic = false;
                $this->mTrxAutomaticAtomic = false;
                $this->mTrxAtomicLevels = [];
-               $this->mTrxIdleCallbacks = [];
-               $this->mTrxPreCommitCallbacks = [];
                $this->mTrxShortId = wfRandomString( 12 );
                $this->mTrxWriteDuration = 0.0;
                $this->mTrxWriteCallers = [];
@@ -2674,7 +2722,7 @@ abstract class DatabaseBase implements IDatabase {
                        }
                }
 
-               # Avoid fatals if close() was called
+               // Avoid fatals if close() was called
                $this->assertOpen();
 
                $this->runOnTransactionPreCommitCallbacks();
@@ -2685,7 +2733,8 @@ abstract class DatabaseBase implements IDatabase {
                        $this->getTransactionProfiler()->transactionWritingOut(
                                $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
                }
-               $this->runOnTransactionIdleCallbacks();
+
+               $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
        }
 
        /**
@@ -2713,17 +2762,19 @@ abstract class DatabaseBase implements IDatabase {
                        }
                }
 
-               # Avoid fatals if close() was called
+               // Avoid fatals if close() was called
                $this->assertOpen();
 
                $this->doRollback( $fname );
-               $this->mTrxIdleCallbacks = []; // cancel
-               $this->mTrxPreCommitCallbacks = []; // cancel
                $this->mTrxAtomicLevels = [];
                if ( $this->mTrxDoneWrites ) {
                        $this->getTransactionProfiler()->transactionWritingOut(
                                $this->mServer, $this->mDBname, $this->mTrxShortId );
                }
+
+               $this->mTrxIdleCallbacks = []; // clear
+               $this->mTrxPreCommitCallbacks = []; // clear
+               $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
        }
 
        /**
@@ -3297,9 +3348,14 @@ abstract class DatabaseBase implements IDatabase {
                if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
                        trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
                }
-               if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
+               $danglingCallbacks = array_merge(
+                       $this->mTrxIdleCallbacks,
+                       $this->mTrxPreCommitCallbacks,
+                       $this->mTrxEndCallbacks
+               );
+               if ( $danglingCallbacks ) {
                        $callers = [];
-                       foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
+                       foreach ( $danglingCallbacks as $callbackInfo ) {
                                $callers[] = $callbackInfo[1];
                        }
                        $callers = implode( ', ', $callers );