Merge "resourceloader: Compile documentElement.className server-side"
[lhc/web/wiklou.git] / includes / objectcache / SqlBagOStuff.php
index d9fe319..d713396 100644 (file)
@@ -22,6 +22,7 @@
  */
 
 use MediaWiki\MediaWikiServices;
+use Wikimedia\AtEase\AtEase;
 use Wikimedia\Rdbms\Database;
 use Wikimedia\Rdbms\IDatabase;
 use Wikimedia\Rdbms\DBError;
@@ -30,6 +31,7 @@ use Wikimedia\Rdbms\DBConnectionError;
 use Wikimedia\Rdbms\IMaintainableDatabase;
 use Wikimedia\Rdbms\LoadBalancer;
 use Wikimedia\ScopedCallback;
+use Wikimedia\Timestamp\ConvertibleTimestamp;
 use Wikimedia\WaitConditionLoop;
 
 /**
@@ -43,7 +45,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        /** @var string[] (server index => tag/host name) */
        protected $serverTags;
        /** @var int */
-       protected $numServers;
+       protected $numServerShards;
        /** @var int UNIX timestamp */
        protected $lastGarbageCollect = 0;
        /** @var int */
@@ -51,7 +53,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        /** @var int */
        protected $purgeLimit = 100;
        /** @var int */
-       protected $shards = 1;
+       protected $numTableShards = 1;
        /** @var string */
        protected $tableName = 'objectcache';
        /** @var bool */
@@ -126,7 +128,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                if ( isset( $params['servers'] ) ) {
                        $this->serverInfos = [];
                        $this->serverTags = [];
-                       $this->numServers = count( $params['servers'] );
+                       $this->numServerShards = count( $params['servers'] );
                        $index = 0;
                        foreach ( $params['servers'] as $tag => $info ) {
                                $this->serverInfos[$index] = $info;
@@ -139,11 +141,11 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                        }
                } elseif ( isset( $params['server'] ) ) {
                        $this->serverInfos = [ $params['server'] ];
-                       $this->numServers = count( $this->serverInfos );
+                       $this->numServerShards = count( $this->serverInfos );
                } else {
                        // Default to using the main wiki's database servers
-                       $this->serverInfos = false;
-                       $this->numServers = 1;
+                       $this->serverInfos = [];
+                       $this->numServerShards = 1;
                        $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
                }
                if ( isset( $params['purgePeriod'] ) ) {
@@ -156,7 +158,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                        $this->tableName = $params['tableName'];
                }
                if ( isset( $params['shards'] ) ) {
-                       $this->shards = intval( $params['shards'] );
+                       $this->numTableShards = intval( $params['shards'] );
                }
                // Backwards-compatibility for < 1.34
                $this->replicaOnly = $params['replicaOnly'] ?? ( $params['slaveOnly'] ?? false );
@@ -165,52 +167,54 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        /**
         * Get a connection to the specified database
         *
-        * @param int $serverIndex
+        * @param int $shardIndex
         * @return IMaintainableDatabase
         * @throws MWException
         */
-       protected function getDB( $serverIndex ) {
-               if ( $serverIndex >= $this->numServers ) {
-                       throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
+       private function getConnection( $shardIndex ) {
+               if ( $shardIndex >= $this->numServerShards ) {
+                       throw new MWException( __METHOD__ . ": Invalid server index \"$shardIndex\"" );
                }
 
                # Don't keep timing out trying to connect for each call if the DB is down
                if (
-                       isset( $this->connFailureErrors[$serverIndex] ) &&
-                       ( $this->getCurrentTime() - $this->connFailureTimes[$serverIndex] ) < 60
+                       isset( $this->connFailureErrors[$shardIndex] ) &&
+                       ( $this->getCurrentTime() - $this->connFailureTimes[$shardIndex] ) < 60
                ) {
-                       throw $this->connFailureErrors[$serverIndex];
+                       throw $this->connFailureErrors[$shardIndex];
                }
 
                if ( $this->serverInfos ) {
-                       if ( !isset( $this->conns[$serverIndex] ) ) {
+                       if ( !isset( $this->conns[$shardIndex] ) ) {
                                // Use custom database defined by server connection info
-                               $info = $this->serverInfos[$serverIndex];
+                               $info = $this->serverInfos[$shardIndex];
                                $type = $info['type'] ?? 'mysql';
                                $host = $info['host'] ?? '[unknown]';
                                $this->logger->debug( __CLASS__ . ": connecting to $host" );
-                               $db = Database::factory( $type, $info );
-                               $db->clearFlag( DBO_TRX ); // auto-commit mode
-                               $this->conns[$serverIndex] = $db;
+                               $conn = Database::factory( $type, $info );
+                               $conn->clearFlag( DBO_TRX ); // auto-commit mode
+                               $this->conns[$shardIndex] = $conn;
                        }
-                       $db = $this->conns[$serverIndex];
+                       $conn = $this->conns[$shardIndex];
                } else {
                        // Use the main LB database
                        $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
                        $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
-                       if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
-                               // Keep a separate connection to avoid contention and deadlocks
-                               $db = $lb->getConnectionRef( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
-                       } else {
-                               // However, SQLite has the opposite behavior due to DB-level locking.
-                               // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
-                               $db = $lb->getConnectionRef( $index );
+                       // If the RDBMS has row-level locking, use the autocommit connection to avoid
+                       // contention and deadlocks. Do not do this if it only has DB-level locking since
+                       // that would just cause deadlocks.
+                       $attribs = $lb->getServerAttributes( $lb->getWriterIndex() );
+                       $flags = $attribs[Database::ATTR_DB_LEVEL_LOCKING] ? 0 : $lb::CONN_TRX_AUTOCOMMIT;
+                       $conn = $lb->getMaintenanceConnectionRef( $index, [], false, $flags );
+                       // Automatically create the objectcache table for sqlite as needed
+                       if ( $conn->getType() === 'sqlite' ) {
+                               $this->initSqliteDatabase( $conn );
                        }
                }
 
-               $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
+               $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $conn ) );
 
-               return $db;
+               return $conn;
        }
 
        /**
@@ -218,22 +222,22 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         * @param string $key
         * @return array Server index and table name
         */
-       protected function getTableByKey( $key ) {
-               if ( $this->shards > 1 ) {
+       private function getTableByKey( $key ) {
+               if ( $this->numTableShards > 1 ) {
                        $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
-                       $tableIndex = $hash % $this->shards;
+                       $tableIndex = $hash % $this->numTableShards;
                } else {
                        $tableIndex = 0;
                }
-               if ( $this->numServers > 1 ) {
+               if ( $this->numServerShards > 1 ) {
                        $sortedServers = $this->serverTags;
                        ArrayUtils::consistentHashSort( $sortedServers, $key );
                        reset( $sortedServers );
-                       $serverIndex = key( $sortedServers );
+                       $shardIndex = key( $sortedServers );
                } else {
-                       $serverIndex = 0;
+                       $shardIndex = 0;
                }
-               return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
+               return [ $shardIndex, $this->getTableNameByShard( $tableIndex ) ];
        }
 
        /**
@@ -241,9 +245,9 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         * @param int $index
         * @return string
         */
-       protected function getTableNameByShard( $index ) {
-               if ( $this->shards > 1 ) {
-                       $decimals = strlen( $this->shards - 1 );
+       private function getTableNameByShard( $index ) {
+               if ( $this->numTableShards > 1 ) {
+                       $decimals = strlen( $this->numTableShards - 1 );
                        return $this->tableName .
                                sprintf( "%0{$decimals}d", $index );
                } else {
@@ -278,19 +282,19 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                return $values;
        }
 
-       protected function fetchBlobMulti( array $keys, $flags = 0 ) {
+       private function fetchBlobMulti( array $keys, $flags = 0 ) {
                $values = []; // array of (key => value)
 
                $keysByTable = [];
                foreach ( $keys as $key ) {
-                       list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
-                       $keysByTable[$serverIndex][$tableName][] = $key;
+                       list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
+                       $keysByTable[$shardIndex][$tableName][] = $key;
                }
 
                $dataRows = [];
-               foreach ( $keysByTable as $serverIndex => $serverKeys ) {
+               foreach ( $keysByTable as $shardIndex => $serverKeys ) {
                        try {
-                               $db = $this->getDB( $serverIndex );
+                               $db = $this->getConnection( $shardIndex );
                                foreach ( $serverKeys as $tableName => $tableKeys ) {
                                        $res = $db->select( $tableName,
                                                [ 'keyname', 'value', 'exptime' ],
@@ -305,13 +309,13 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                                continue;
                                        }
                                        foreach ( $res as $row ) {
-                                               $row->serverIndex = $serverIndex;
+                                               $row->shardIndex = $shardIndex;
                                                $row->tableName = $tableName;
                                                $dataRows[$row->keyname] = $row;
                                        }
                                }
                        } catch ( DBError $e ) {
-                               $this->handleReadError( $e, $serverIndex );
+                               $this->handleReadError( $e, $shardIndex );
                        }
                }
 
@@ -321,14 +325,14 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
                                $db = null; // in case of connection failure
                                try {
-                                       $db = $this->getDB( $row->serverIndex );
+                                       $db = $this->getConnection( $row->shardIndex );
                                        if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
                                                $this->debug( "get: key has expired" );
                                        } else { // HIT
                                                $values[$key] = $db->decodeBlob( $row->value );
                                        }
                                } catch ( DBQueryError $e ) {
-                                       $this->handleWriteError( $e, $db, $row->serverIndex );
+                                       $this->handleWriteError( $e, $db, $row->shardIndex );
                                }
                        } else { // MISS
                                $this->debug( 'get: no matching rows' );
@@ -352,8 +356,8 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        private function modifyMulti( array $data, $exptime, $flags, $op ) {
                $keysByTable = [];
                foreach ( $data as $key => $value ) {
-                       list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
-                       $keysByTable[$serverIndex][$tableName][] = $key;
+                       list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
+                       $keysByTable[$shardIndex][$tableName][] = $key;
                }
 
                $exptime = $this->getExpirationAsTimestamp( $exptime );
@@ -361,14 +365,14 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                $result = true;
                /** @noinspection PhpUnusedLocalVariableInspection */
                $silenceScope = $this->silenceTransactionProfiler();
-               foreach ( $keysByTable as $serverIndex => $serverKeys ) {
+               foreach ( $keysByTable as $shardIndex => $serverKeys ) {
                        $db = null; // in case of connection failure
                        try {
-                               $db = $this->getDB( $serverIndex );
+                               $db = $this->getConnection( $shardIndex );
                                $this->occasionallyGarbageCollect( $db ); // expire old entries if any
                                $dbExpiry = $exptime ? $db->timestamp( $exptime ) : $this->getMaxDateTime( $db );
                        } catch ( DBError $e ) {
-                               $this->handleWriteError( $e, $db, $serverIndex );
+                               $this->handleWriteError( $e, $db, $shardIndex );
                                $result = false;
                                continue;
                        }
@@ -384,14 +388,14 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                                $dbExpiry
                                        ) && $result;
                                } catch ( DBError $e ) {
-                                       $this->handleWriteError( $e, $db, $serverIndex );
+                                       $this->handleWriteError( $e, $db, $shardIndex );
                                        $result = false;
                                }
 
                        }
                }
 
-               if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
+               if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
                        $result = $this->waitForReplication() && $result;
                }
 
@@ -472,14 +476,14 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        }
 
        protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
-               list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
+               list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
                $exptime = $this->getExpirationAsTimestamp( $exptime );
 
                /** @noinspection PhpUnusedLocalVariableInspection */
                $silenceScope = $this->silenceTransactionProfiler();
                $db = null; // in case of connection failure
                try {
-                       $db = $this->getDB( $serverIndex );
+                       $db = $this->getConnection( $shardIndex );
                        // (T26425) use a replace if the db supports it instead of
                        // delete/insert to avoid clashes with conflicting keynames
                        $db->update(
@@ -499,12 +503,17 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                __METHOD__
                        );
                } catch ( DBQueryError $e ) {
-                       $this->handleWriteError( $e, $db, $serverIndex );
+                       $this->handleWriteError( $e, $db, $shardIndex );
 
                        return false;
                }
 
-               return (bool)$db->affectedRows();
+               $success = (bool)$db->affectedRows();
+               if ( $this->fieldHasFlags( $flags, self::WRITE_SYNC ) ) {
+                       $success = $this->waitForReplication() && $success;
+               }
+
+               return $success;
        }
 
        protected function doDeleteMulti( array $keys, $flags = 0 ) {
@@ -520,15 +529,15 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                return $this->modifyMulti( [ $key => null ], 0, $flags, self::$OP_DELETE );
        }
 
-       public function incr( $key, $step = 1 ) {
-               list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
+       public function incr( $key, $step = 1, $flags = 0 ) {
+               list( $shardIndex, $tableName ) = $this->getTableByKey( $key );
 
                $newCount = false;
                /** @noinspection PhpUnusedLocalVariableInspection */
                $silenceScope = $this->silenceTransactionProfiler();
                $db = null; // in case of connection failure
                try {
-                       $db = $this->getDB( $serverIndex );
+                       $db = $this->getConnection( $shardIndex );
                        $encTimestamp = $db->addQuotes( $db->timestamp() );
                        $db->update(
                                $tableName,
@@ -548,19 +557,14 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                }
                        }
                } catch ( DBError $e ) {
-                       $this->handleWriteError( $e, $db, $serverIndex );
+                       $this->handleWriteError( $e, $db, $shardIndex );
                }
 
                return $newCount;
        }
 
-       public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
-               $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
-               if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
-                       $ok = $this->waitForReplication() && $ok;
-               }
-
-               return $ok;
+       public function decr( $key, $value = 1, $flags = 0 ) {
+               return $this->incr( $key, -$value, $flags );
        }
 
        public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
@@ -581,10 +585,10 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         * @param string $exptime
         * @return bool
         */
-       protected function isExpired( $db, $exptime ) {
+       private function isExpired( IDatabase $db, $exptime ) {
                return (
                        $exptime != $this->getMaxDateTime( $db ) &&
-                       wfTimestamp( TS_UNIX, $exptime ) < $this->getCurrentTime()
+                       ConvertibleTimestamp::convert( TS_UNIX, $exptime ) < $this->getCurrentTime()
                );
        }
 
@@ -592,7 +596,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         * @param IDatabase $db
         * @return string
         */
-       protected function getMaxDateTime( $db ) {
+       private function getMaxDateTime( $db ) {
                if ( (int)$this->getCurrentTime() > 0x7fffffff ) {
                        return $db->timestamp( 1 << 62 );
                } else {
@@ -604,7 +608,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         * @param IDatabase $db
         * @throws DBError
         */
-       protected function occasionallyGarbageCollect( IDatabase $db ) {
+       private function occasionallyGarbageCollect( IDatabase $db ) {
                if (
                        // Random purging is enabled
                        $this->purgePeriod &&
@@ -642,16 +646,16 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                /** @noinspection PhpUnusedLocalVariableInspection */
                $silenceScope = $this->silenceTransactionProfiler();
 
-               $serverIndexes = range( 0, $this->numServers - 1 );
-               shuffle( $serverIndexes );
+               $shardIndexes = range( 0, $this->numServerShards - 1 );
+               shuffle( $shardIndexes );
 
                $ok = true;
 
                $keysDeletedCount = 0;
-               foreach ( $serverIndexes as $numServersDone => $serverIndex ) {
+               foreach ( $shardIndexes as $numServersDone => $shardIndex ) {
                        $db = null; // in case of connection failure
                        try {
-                               $db = $this->getDB( $serverIndex );
+                               $db = $this->getConnection( $shardIndex );
                                $this->deleteServerObjectsExpiringBefore(
                                        $db,
                                        $timestamp,
@@ -661,7 +665,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                        $keysDeletedCount
                                );
                        } catch ( DBError $e ) {
-                               $this->handleWriteError( $e, $db, $serverIndex );
+                               $this->handleWriteError( $e, $db, $shardIndex );
                                $ok = false;
                        }
                }
@@ -686,8 +690,8 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                $serversDoneCount = 0,
                &$keysDeletedCount = 0
        ) {
-               $cutoffUnix = wfTimestamp( TS_UNIX, $timestamp );
-               $shardIndexes = range( 0, $this->shards - 1 );
+               $cutoffUnix = ConvertibleTimestamp::convert( TS_UNIX, $timestamp );
+               $shardIndexes = range( 0, $this->numTableShards - 1 );
                shuffle( $shardIndexes );
 
                foreach ( $shardIndexes as $numShardsDone => $shardIndex ) {
@@ -708,7 +712,8 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                if ( $res->numRows() ) {
                                        $row = $res->current();
                                        if ( $lag === null ) {
-                                               $lag = max( $cutoffUnix - wfTimestamp( TS_UNIX, $row->exptime ), 1 );
+                                               $rowExpUnix = ConvertibleTimestamp::convert( TS_UNIX, $row->exptime );
+                                               $lag = max( $cutoffUnix - $rowExpUnix, 1 );
                                        }
 
                                        $keys = [];
@@ -730,15 +735,16 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
 
                                if ( is_callable( $progressCallback ) ) {
                                        if ( $lag ) {
-                                               $remainingLag = $cutoffUnix - wfTimestamp( TS_UNIX, $continue );
+                                               $continueUnix = ConvertibleTimestamp::convert( TS_UNIX, $continue );
+                                               $remainingLag = $cutoffUnix - $continueUnix;
                                                $processedLag = max( $lag - $remainingLag, 0 );
-                                               $doneRatio = ( $numShardsDone + $processedLag / $lag ) / $this->shards;
+                                               $doneRatio = ( $numShardsDone + $processedLag / $lag ) / $this->numTableShards;
                                        } else {
                                                $doneRatio = 1;
                                        }
 
-                                       $overallRatio = ( $doneRatio / $this->numServers )
-                                               + ( $serversDoneCount / $this->numServers );
+                                       $overallRatio = ( $doneRatio / $this->numServerShards )
+                                               + ( $serversDoneCount / $this->numServerShards );
                                        call_user_func( $progressCallback, $overallRatio * 100 );
                                }
                        } while ( $res->numRows() && $keysDeletedCount < $limit );
@@ -753,15 +759,15 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        public function deleteAll() {
                /** @noinspection PhpUnusedLocalVariableInspection */
                $silenceScope = $this->silenceTransactionProfiler();
-               for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
+               for ( $shardIndex = 0; $shardIndex < $this->numServerShards; $shardIndex++ ) {
                        $db = null; // in case of connection failure
                        try {
-                               $db = $this->getDB( $serverIndex );
-                               for ( $i = 0; $i < $this->shards; $i++ ) {
+                               $db = $this->getConnection( $shardIndex );
+                               for ( $i = 0; $i < $this->numTableShards; $i++ ) {
                                        $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
                                }
                        } catch ( DBError $e ) {
-                               $this->handleWriteError( $e, $db, $serverIndex );
+                               $this->handleWriteError( $e, $db, $shardIndex );
                                return false;
                        }
                }
@@ -779,11 +785,11 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                        }
                }
 
-               list( $serverIndex ) = $this->getTableByKey( $key );
+               list( $shardIndex ) = $this->getTableByKey( $key );
 
                $db = null; // in case of connection failure
                try {
-                       $db = $this->getDB( $serverIndex );
+                       $db = $this->getConnection( $shardIndex );
                        $ok = $db->lock( $key, __METHOD__, $timeout );
                        if ( $ok ) {
                                $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
@@ -796,7 +802,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
 
                        return $ok;
                } catch ( DBError $e ) {
-                       $this->handleWriteError( $e, $db, $serverIndex );
+                       $this->handleWriteError( $e, $db, $shardIndex );
                        $ok = false;
                }
 
@@ -811,11 +817,11 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                if ( --$this->locks[$key]['depth'] <= 0 ) {
                        unset( $this->locks[$key] );
 
-                       list( $serverIndex ) = $this->getTableByKey( $key );
+                       list( $shardIndex ) = $this->getTableByKey( $key );
 
                        $db = null; // in case of connection failure
                        try {
-                               $db = $this->getDB( $serverIndex );
+                               $db = $this->getConnection( $shardIndex );
                                $ok = $db->unlock( $key, __METHOD__ );
                                if ( !$ok ) {
                                        $this->logger->warning(
@@ -824,7 +830,7 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                                        );
                                }
                        } catch ( DBError $e ) {
-                               $this->handleWriteError( $e, $db, $serverIndex );
+                               $this->handleWriteError( $e, $db, $shardIndex );
                                $ok = false;
                        }
 
@@ -866,9 +872,9 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
                }
 
                if ( function_exists( 'gzinflate' ) ) {
-                       Wikimedia\suppressWarnings();
+                       AtEase::suppressWarnings();
                        $decomp = gzinflate( $serial );
-                       Wikimedia\restoreWarnings();
+                       AtEase::restoreWarnings();
 
                        if ( $decomp !== false ) {
                                $serial = $decomp;
@@ -882,11 +888,11 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         * Handle a DBError which occurred during a read operation.
         *
         * @param DBError $exception
-        * @param int $serverIndex
+        * @param int $shardIndex
         */
-       protected function handleReadError( DBError $exception, $serverIndex ) {
+       private function handleReadError( DBError $exception, $shardIndex ) {
                if ( $exception instanceof DBConnectionError ) {
-                       $this->markServerDown( $exception, $serverIndex );
+                       $this->markServerDown( $exception, $shardIndex );
                }
 
                $this->setAndLogDBError( $exception );
@@ -897,12 +903,12 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         *
         * @param DBError $exception
         * @param IDatabase|null $db DB handle or null if connection failed
-        * @param int $serverIndex
+        * @param int $shardIndex
         * @throws Exception
         */
-       protected function handleWriteError( DBError $exception, $db, $serverIndex ) {
+       private function handleWriteError( DBError $exception, $db, $shardIndex ) {
                if ( !( $db instanceof IDatabase ) ) {
-                       $this->markServerDown( $exception, $serverIndex );
+                       $this->markServerDown( $exception, $shardIndex );
                }
 
                $this->setAndLogDBError( $exception );
@@ -926,41 +932,68 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
         * Mark a server down due to a DBConnectionError exception
         *
         * @param DBError $exception
-        * @param int $serverIndex
+        * @param int $shardIndex
         */
-       protected function markServerDown( DBError $exception, $serverIndex ) {
-               unset( $this->conns[$serverIndex] ); // bug T103435
+       private function markServerDown( DBError $exception, $shardIndex ) {
+               unset( $this->conns[$shardIndex] ); // bug T103435
 
                $now = $this->getCurrentTime();
-               if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
-                       if ( $now - $this->connFailureTimes[$serverIndex] >= 60 ) {
-                               unset( $this->connFailureTimes[$serverIndex] );
-                               unset( $this->connFailureErrors[$serverIndex] );
+               if ( isset( $this->connFailureTimes[$shardIndex] ) ) {
+                       if ( $now - $this->connFailureTimes[$shardIndex] >= 60 ) {
+                               unset( $this->connFailureTimes[$shardIndex] );
+                               unset( $this->connFailureErrors[$shardIndex] );
                        } else {
-                               $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
+                               $this->logger->debug( __METHOD__ . ": Server #$shardIndex already down" );
                                return;
                        }
                }
-               $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
-               $this->connFailureTimes[$serverIndex] = $now;
-               $this->connFailureErrors[$serverIndex] = $exception;
+               $this->logger->info( __METHOD__ . ": Server #$shardIndex down until " . ( $now + 60 ) );
+               $this->connFailureTimes[$shardIndex] = $now;
+               $this->connFailureErrors[$shardIndex] = $exception;
        }
 
        /**
-        * Create shard tables. For use from eval.php.
+        * @param IMaintainableDatabase $db
+        * @throws DBError
         */
-       public function createTables() {
-               for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
-                       $db = $this->getDB( $serverIndex );
-                       if ( $db->getType() !== 'mysql' ) {
-                               throw new MWException( __METHOD__ . ' is not supported on this DB server' );
-                       }
+       private function initSqliteDatabase( IMaintainableDatabase $db ) {
+               if ( $db->tableExists( 'objectcache' ) ) {
+                       return;
+               }
+               // Use one table for SQLite; sharding does not seem to have much benefit
+               $db->query( "PRAGMA journal_mode=WAL" ); // this is permanent
+               $db->startAtomic( __METHOD__ ); // atomic DDL
+               try {
+                       $encTable = $db->tableName( 'objectcache' );
+                       $encExptimeIndex = $db->addIdentifierQuotes( $db->tablePrefix() . 'exptime' );
+                       $db->query(
+                               "CREATE TABLE $encTable (\n" .
+                               "       keyname BLOB NOT NULL default '' PRIMARY KEY,\n" .
+                               "       value BLOB,\n" .
+                               "       exptime TEXT\n" .
+                               ")",
+                               __METHOD__
+                       );
+                       $db->query( "CREATE INDEX $encExptimeIndex ON $encTable (exptime)" );
+                       $db->endAtomic( __METHOD__ );
+               } catch ( DBError $e ) {
+                       $db->rollback( __METHOD__ );
+                       throw $e;
+               }
+       }
 
-                       for ( $i = 0; $i < $this->shards; $i++ ) {
-                               $db->query(
-                                       'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
-                                       ' LIKE ' . $db->tableName( 'objectcache' ),
-                                       __METHOD__ );
+       /**
+        * Create the shard tables on all databases (e.g. via eval.php/shell.php)
+        */
+       public function createTables() {
+               for ( $shardIndex = 0; $shardIndex < $this->numServerShards; $shardIndex++ ) {
+                       $db = $this->getConnection( $shardIndex );
+                       if ( in_array( $db->getType(), [ 'mysql', 'postgres' ], true ) ) {
+                               for ( $i = 0; $i < $this->numTableShards; $i++ ) {
+                                       $encBaseTable = $db->tableName( 'objectcache' );
+                                       $encShardTable = $db->tableName( $this->getTableNameByShard( $i ) );
+                                       $db->query( "CREATE TABLE $encShardTable LIKE $encBaseTable" );
+                               }
                        }
                }
        }
@@ -968,11 +1001,11 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        /**
         * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
         */
-       protected function usesMainDB() {
+       private function usesMainDB() {
                return !$this->serverInfos;
        }
 
-       protected function waitForReplication() {
+       private function waitForReplication() {
                if ( !$this->usesMainDB() ) {
                        // Custom DB server list; probably doesn't use replication
                        return true;
@@ -1007,12 +1040,17 @@ class SqlBagOStuff extends MediumSpecificBagOStuff {
        }
 
        /**
-        * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
-        * destroyed on the end of a scope, for example on return or throw
-        * @return ScopedCallback
-        * @since 1.32
+        * Silence the transaction profiler until the return value falls out of scope
+        *
+        * @return ScopedCallback|null
         */
-       protected function silenceTransactionProfiler() {
+       private function silenceTransactionProfiler() {
+               if ( !$this->usesMainDB() ) {
+                       // Custom DB is configured which either has no TransactionProfiler injected,
+                       // or has one specific for cache use, which we shouldn't silence
+                       return null;
+               }
+
                $trxProfiler = Profiler::instance()->getTransactionProfiler();
                $oldSilenced = $trxProfiler->setSilenced( true );
                return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {