Remove Profiler::isStub()
[lhc/web/wiklou.git] / includes / db / Database.php
index 18cd39f..a805fa5 100644 (file)
@@ -798,6 +798,23 @@ abstract class DatabaseBase implements IDatabase {
                $this->mPHPError = $errstr;
        }
 
+       /**
+        * Create a log context to pass to wfLogDBError or other logging functions.
+        *
+        * @param array $extras Additional data to add to context
+        * @return array
+        */
+       protected function getLogContext( array $extras = array() ) {
+               return array_merge(
+                       array(
+                               'db_server' => $this->mServer,
+                               'db_name' => $this->mDBname,
+                               'db_user' => $this->mUser,
+                       ),
+                       $extras
+               );
+       }
+
        /**
         * Closes a database connection.
         * if it is open : commits any open transactions
@@ -945,7 +962,8 @@ abstract class DatabaseBase implements IDatabase {
                $totalProf = '';
                $isMaster = !is_null( $this->getLBInfo( 'master' ) );
 
-               if ( !Profiler::instance()->isStub() ) {
+               $profiler = Profiler::instance();
+               if ( !$profiler instanceof ProfilerStub ) {
                        # generalizeSQL will probably cut down the query to reasonable
                        # logging size most of the time. The substr is really just a sanity check.
                        if ( $isMaster ) {
@@ -958,9 +976,8 @@ abstract class DatabaseBase implements IDatabase {
                        # Include query transaction state
                        $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
 
-                       $trx = $this->mTrxLevel ? 'TRX=yes' : 'TRX=no';
-                       wfProfileIn( $totalProf );
-                       wfProfileIn( $queryProf );
+                       $totalProfSection = $profiler->scopedProfileIn( $totalProf );
+                       $queryProfSection = $profiler->scopedProfileIn( $queryProf );
                }
 
                if ( $this->debug() ) {
@@ -983,12 +1000,15 @@ abstract class DatabaseBase implements IDatabase {
                }
 
                # Log the query time and feed it into the DB trx profiler
-               $queryStartTime = microtime( true );
-               $queryProfile = new ScopedCallback( function() use ( $queryStartTime, $queryProf ) {
-                       $elapsed = microtime( true ) - $queryStartTime;
-                       $trxProfiler = Profiler::instance()->getTransactionProfiler();
-                       $trxProfiler->recordFunctionCompletion( $queryProf, $elapsed );
-               } );
+               if ( $queryProf != '' ) {
+                       $queryStartTime = microtime( true );
+                       $queryProfile = new ScopedCallback(
+                               function() use ( $queryStartTime, $queryProf, $isMaster ) {
+                                       $trxProfiler = Profiler::instance()->getTransactionProfiler();
+                                       $trxProfiler->recordQueryCompletion( $queryProf, $queryStartTime, $isMaster );
+                               }
+                       );
+               }
 
                # Do the query and handle errors
                $ret = $this->doQuery( $commentedSql );
@@ -1007,16 +1027,11 @@ abstract class DatabaseBase implements IDatabase {
                        $lastError = $this->lastError();
                        $lastErrno = $this->lastErrno();
                        if ( $this->ping() ) {
-                               global $wgRequestTime;
                                wfDebug( "Reconnected\n" );
-                               $sqlx = $wgDebugDumpSqlLength ? substr( $commentedSql, 0, $wgDebugDumpSqlLength )
-                                       : $commentedSql;
-                               $sqlx = strtr( $sqlx, "\t\n", '  ' );
-                               $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
-                               if ( $elapsed < 300 ) {
-                                       # Not a database error to lose a transaction after a minute or two
-                                       wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx" );
-                               }
+                               $server = $this->getServer();
+                               $msg = __METHOD__ . ": lost connection to $server; reconnected";
+                               wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
+
                                if ( $hadTrx ) {
                                        # Leave $ret as false and let an error be reported.
                                        # Callers may catch the exception and continue to use the DB.
@@ -1034,11 +1049,6 @@ abstract class DatabaseBase implements IDatabase {
                        $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
                }
 
-               if ( !Profiler::instance()->isStub() ) {
-                       wfProfileOut( $queryProf );
-                       wfProfileOut( $totalProf );
-               }
-
                return $this->resultObject( $ret );
        }
 
@@ -1063,7 +1073,16 @@ abstract class DatabaseBase implements IDatabase {
                        $this->ignoreErrors( $ignore );
                } else {
                        $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
-                       wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line" );
+                       wfLogDBError(
+                               "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
+                               $this->getLogContext( array(
+                                       'method' => __METHOD__,
+                                       'errno' => $errno,
+                                       'error' => $error,
+                                       'sql1line' => $sql1line,
+                                       'fname' => $fname,
+                               ) )
+                       );
                        wfDebug( "SQL ERROR: " . $error . "\n" );
                        throw new DBQueryError( $this, $error, $errno, $sql, $fname );
                }
@@ -3338,7 +3357,12 @@ abstract class DatabaseBase implements IDatabase {
                                $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
                                        " performing implicit commit!";
                                wfWarn( $msg );
-                               wfLogDBError( $msg );
+                               wfLogDBError( $msg,
+                                       $this->getLogContext( array(
+                                               'method' => __METHOD__,
+                                               'fname' => $fname,
+                                       ) )
+                               );
                        } else {
                                // if the transaction was automatic and has done write operations,
                                // log it if $wgDebugDBTransactions is enabled.
@@ -3872,47 +3896,49 @@ abstract class DatabaseBase implements IDatabase {
         *
         * - '{$var}' should be used for text and is passed through the database's
         *   addQuotes method.
-        * - `{$var}` should be used for identifiers (eg: table and database names),
-        *   it is passed through the database's addIdentifierQuotes method which
+        * - `{$var}` should be used for identifiers (e.g. table and database names).
+        *   It is passed through the database's addIdentifierQuotes method which
         *   can be overridden if the database uses something other than backticks.
-        * - / *$var* / is just encoded, besides traditional table prefix and
-        *   table options its use should be avoided.
+        * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
+        *   database's tableName method.
+        * - / *i* / passes the name that follows through the database's indexName method.
+        * - In all other cases, / *$var* / is left unencoded. Except for table options,
+        *   its use should be avoided. In 1.24 and older, string encoding was applied.
         *
         * @param string $ins SQL statement to replace variables in
         * @return string The new SQL statement with variables replaced
         */
-       protected function replaceSchemaVars( $ins ) {
-               $vars = $this->getSchemaVars();
-               foreach ( $vars as $var => $value ) {
-                       // replace '{$var}'
-                       $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
-                       // replace `{$var}`
-                       $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
-                       // replace /*$var*/
-                       $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
-               }
-
-               return $ins;
-       }
-
-       /**
-        * Replace variables in sourced SQL
-        *
-        * @param string $ins
-        * @return string
-        */
        protected function replaceVars( $ins ) {
-               $ins = $this->replaceSchemaVars( $ins );
-
-               // Table prefixes
-               $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
-                       array( $this, 'tableNameCallback' ), $ins );
-
-               // Index names
-               $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
-                       array( $this, 'indexNameCallback' ), $ins );
-
-               return $ins;
+               $that = $this;
+               $vars = $this->getSchemaVars();
+               return preg_replace_callback(
+                       '!
+                               /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
+                               \'\{\$ (\w+) }\'                  | # 3. addQuotes
+                               `\{\$ (\w+) }`                    | # 4. addIdentifierQuotes
+                               /\*\$ (\w+) \*/                     # 5. leave unencoded
+                       !x',
+                       function ( $m ) use ( $that, $vars ) {
+                               // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
+                               // check for both nonexistent keys *and* the empty string.
+                               if ( isset( $m[1] ) && $m[1] !== '' ) {
+                                       if ( $m[1] === 'i' ) {
+                                               return $that->indexName( $m[2] );
+                                       } else {
+                                               return $that->tableName( $m[2] );
+                                       }
+                               } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
+                                       return $that->addQuotes( $vars[$m[3]] );
+                               } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
+                                       return $that->addIdentifierQuotes( $vars[$m[4]] );
+                               } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
+                                       return $vars[$m[5]];
+                               } else {
+                                       return $m[0];
+                               }
+                       },
+                       $ins
+               );
        }
 
        /**
@@ -3941,26 +3967,6 @@ abstract class DatabaseBase implements IDatabase {
                return array();
        }
 
-       /**
-        * Table name callback
-        *
-        * @param array $matches
-        * @return string
-        */
-       protected function tableNameCallback( $matches ) {
-               return $this->tableName( $matches[1] );
-       }
-
-       /**
-        * Index name callback
-        *
-        * @param array $matches
-        * @return string
-        */
-       protected function indexNameCallback( $matches ) {
-               return $this->indexName( $matches[1] );
-       }
-
        /**
         * Check to see if a named lock is available. This is non-blocking.
         *