58 private $sessionAttachedDbs = [];
61 private const VALID_TRX_MODES = [
'',
'DEFERRED',
'IMMEDIATE',
'EXCLUSIVE' ];
64 private const VALID_PRAGMAS = [
66 'synchronous' => [
'EXTRA',
'FULL',
'NORMAL',
'OFF' ],
68 'temp_store' => [
'FILE',
'MEMORY' ],
70 'mmap_size' =>
'integer',
72 'cache_size' =>
'integer',
85 if ( isset(
$params[
'dbFilePath'] ) ) {
86 $this->dbPath =
$params[
'dbFilePath'];
88 $params[
'dbname'] = self::generateDatabaseName( $this->dbPath );
90 } elseif ( isset(
$params[
'dbDirectory'] ) ) {
91 $this->dbDir =
$params[
'dbDirectory'];
96 $this->trxMode = strtoupper(
$params[
'trxMode'] ??
'' );
98 $this->lockMgr = $this->makeLockManager();
114 self::ATTR_DB_IS_FILE =>
true,
115 self::ATTR_DB_LEVEL_LOCKING => true
129 $p[
'dbFilePath'] = $filename;
131 $p[
'tablePrefix'] =
'';
134 '@phan-var DatabaseSqlite $db';
146 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
147 $this->
close( __METHOD__ );
151 if ( $schema !==
null ) {
155 if ( $this->dbPath !==
null ) {
157 } elseif ( $this->dbDir !==
null ) {
164 if ( !self::isProcessMemoryPath(
$path ) && is_file(
$path ) && !is_readable(
$path ) ) {
166 } elseif ( !in_array( $this->trxMode, self::VALID_TRX_MODES,
true ) ) {
171 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
175 PDO::ATTR_STRINGIFY_FETCHES => true
177 if ( $this->
getFlag( self::DBO_PERSISTENT ) ) {
180 if ( $this->
getFlag( self::DBO_TRX ) || $this->
getFlag( self::DBO_DEFAULT ) ) {
181 $this->logger->warning(
182 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
186 $attributes[PDO::ATTR_PERSISTENT] =
true;
192 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
193 }
catch ( PDOException $e ) {
203 'PRAGMA case_sensitive_like = 1',
204 self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY,
207 $this->
query( $query, __METHOD__ );
210 $pragmas += $this->getDefaultPragmas();
211 foreach ( $pragmas as $name => $value ) {
212 $allowed = self::VALID_PRAGMAS[$name];
214 ( is_array( $allowed ) && in_array( $value, $allowed,
true ) ) ||
215 ( is_string( $allowed ) && gettype( $value ) === $allowed )
218 "PRAGMA $name = $value",
219 self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY,
224 $this->
query( $query, __METHOD__ );
227 $this->attachDatabasesFromTableAliases();
228 }
catch ( RuntimeException $e ) {
236 private function getDefaultPragmas() {
240 $variables[
'temp_store'] =
'MEMORY';
259 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
260 return dirname( $this->dbPath ) .
'/locks';
261 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
262 return $this->dbDir .
'/locks';
275 if ( $lockDirectory !==
null ) {
278 'lockDirectory' => $lockDirectory,
292 $this->lockMgr =
null;
307 } elseif ( self::isProcessMemoryPath( $dir ) ) {
310 __CLASS__ .
": cannot use process memory directory '$dir'"
312 } elseif ( !strlen( $dbName ) ) {
316 return "$dir/$dbName.sqlite";
323 private static function generateDatabaseName(
$path ) {
324 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
327 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
332 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
340 private static function isProcessMemoryPath(
$path ) {
341 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
349 static $cachedResult =
null;
350 if ( $cachedResult !==
null ) {
351 return $cachedResult;
353 $cachedResult =
false;
354 $table =
'dummy_search_test';
356 $db = self::newStandaloneInstance(
':memory:' );
358 "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)",
362 $cachedResult =
'FTS3';
364 $db->close( __METHOD__ );
366 return $cachedResult;
382 $file = is_string( $file ) ? $file : self::generateFileName( $this->dbDir, $name );
383 $encFile = $this->addQuotes( $file );
385 "ATTACH DATABASE $encFile AS $name",
386 self::QUERY_CHANGE_TRX,
389 return $this->query( $query, $fname );
393 $res = $this->getBindingHandle()->query( $sql );
397 $res ? $res->rowCount() : 0,
407 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
413 if ( $database ===
null ) {
415 $this->currentDomain->getDatabase(),
419 $this->platform->setCurrentDomain( $this->currentDomain );
424 if ( $database !== $this->getDBname() ) {
427 __CLASS__ .
": cannot change database (got '$database')"
432 $this->currentDomain = $domain;
433 $this->platform->setCurrentDomain( $domain );
440 return (
int)$this->getBindingHandle()->lastInsertId();
447 if ( is_object( $this->conn ) ) {
448 $e = $this->conn->errorInfo();
450 return $e[2] ?? $this->lastConnectError;
453 return 'No database connection';
460 if ( is_object( $this->conn ) ) {
461 $info = $this->conn->errorInfo();
463 if ( isset( $info[1] ) ) {
472 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
473 if ( isset( $this->sessionTempTables[$db][$pt] ) ) {
477 $encTable = $this->addQuotes( $pt );
479 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
480 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
483 $res = $this->query( $query, __METHOD__ );
485 return (
bool)$res->numRows();
488 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
489 $indexName = $this->platform->indexName( $index );
490 $components = $this->platform->qualifiedTableComponents( $table );
491 $tableRaw = end( $components );
493 'PRAGMA index_list(' . $this->addQuotes( $tableRaw ) .
')',
494 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
497 $res = $this->query( $query, $fname );
499 foreach ( $res as $row ) {
500 if ( $row->name === $indexName ) {
501 return [
'unique' => (bool)$row->unique ];
508 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
509 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
513 $encTable = $this->tableName( $table );
514 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
519 "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples",
520 self::QUERY_CHANGE_ROWS,
524 $this->query( $query, $fname );
540 $this->assertHasConnectionHandle();
542 $path = $this->getDbFilePath();
544 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
551 return "[{{int:version-db-sqlite-url}} SQLite]";
558 if ( $this->version ===
null ) {
559 $this->version = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
562 return $this->version;
574 $components = $this->platform->qualifiedTableComponents( $table );
575 $tableRaw = end( $components );
577 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
578 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
581 $res = $this->query( $query, __METHOD__ );
582 foreach ( $res as $row ) {
583 if ( $row->name == $field ) {
592 if ( $this->trxMode !=
'' ) {
593 $sql =
"BEGIN {$this->trxMode}";
597 $query =
new Query( $sql, self::QUERY_CHANGE_TRX,
'BEGIN' );
598 $this->query( $query, $fname );
606 return substr( $this->addQuotes( $s ), 1, -1 );
614 return new Blob( $b );
622 if ( $b instanceof
Blob ) {
638 if ( $s instanceof
Blob ) {
639 return "x'" . bin2hex( $s->fetch() ) .
"'";
640 } elseif ( is_bool( $s ) ) {
641 return (
string)(int)$s;
642 } elseif ( is_int( $s ) ) {
644 } elseif ( strpos( (
string)$s,
"\0" ) !==
false ) {
654 $this->logger->debug(
656 ': Quoting value containing null byte. ' .
657 'For consistency all binary data should have been ' .
658 'first processed with self::encodeBlob()'
660 return "x'" . bin2hex( (
string)$s ) .
"'";
662 return $this->getBindingHandle()->quote( (
string)$s );
671 public function doLock(
string $lockName,
string $method,
int $timeout ) {
672 $status = $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout );
675 $status->hasMessage(
'lockmanager-fail-openlock' )
677 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
680 return $status->isOK() ? microtime(
true ) :
null;
683 public function doUnlock(
string $lockName,
string $method ) {
684 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
696 $oldName, $newName, $temporary =
false, $fname = __METHOD__
699 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
700 $this->addQuotes( $oldName ) .
" AND type='table'",
701 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
704 $res = $this->query( $query, $fname );
705 $obj = $res->fetchObject();
707 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
709 $sqlCreateTable = $obj->sql;
710 $sqlCreateTable = preg_replace(
712 preg_quote( trim( $this->platform->addIdentifierQuotes( $oldName ),
'"' ),
'/' ) .
714 $this->platform->addIdentifierQuotes( $newName ),
718 $flags = self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT;
720 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sqlCreateTable ) ) {
721 $this->logger->debug(
722 "Table $oldName is virtual, can't create a temporary duplicate." );
724 $sqlCreateTable = str_replace(
726 'CREATE TEMPORARY TABLE',
735 $temporary ?
'CREATE TEMPORARY' :
'CREATE',
739 $res = $this->query( $query, $fname );
742 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) .
')',
743 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
747 $indexList = $this->query( $query, $fname );
748 foreach ( $indexList as $index ) {
749 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
753 if ( $index->unique ) {
754 $sqlIndex =
'CREATE UNIQUE INDEX';
756 $sqlIndex =
'CREATE INDEX';
759 $indexName = $newName .
'_' . $index->name;
760 $sqlIndex .=
' ' . $this->platform->addIdentifierQuotes( $indexName ) .
761 ' ON ' . $this->platform->addIdentifierQuotes( $newName );
764 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) .
')',
765 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
768 $indexInfo = $this->query( $query, $fname );
770 foreach ( $indexInfo as $indexInfoRow ) {
771 $fields[$indexInfoRow->seqno] = $this->addQuotes( $indexInfoRow->name );
774 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
778 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT,
782 $this->query( $query, __METHOD__ );
796 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
798 "SELECT name FROM sqlite_master WHERE type = 'table'",
799 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
802 $result = $this->query( $query, $fname );
806 foreach ( $result as $table ) {
807 $vars = get_object_vars( $table );
808 $table = array_pop( $vars );
810 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
811 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
812 $endArray[] = $table;
821 $this->startAtomic( $fname );
824 "DELETE FROM " . $this->tableName( $table ),
825 self::QUERY_CHANGE_SCHEMA,
829 $this->query( $query, $fname );
831 $encMasterTable = $this->platform->addIdentifierQuotes(
'sqlite_sequence' );
832 $encSequenceName = $this->addQuotes( $this->tableName( $table,
'raw' ) );
834 "DELETE FROM $encMasterTable WHERE name = $encSequenceName",
835 self::QUERY_CHANGE_SCHEMA,
839 $this->query( $query, $fname );
841 $this->endAtomic( $fname );
845 parent::setTableAliases( $aliases );
846 if ( $this->isOpen() ) {
847 $this->attachDatabasesFromTableAliases();
854 private function attachDatabasesFromTableAliases() {
855 foreach ( $this->platform->getTableAliases() as
$params ) {
857 $params[
'dbname'] !== $this->getDBname() &&
858 !isset( $this->sessionAttachedDbs[
$params[
'dbname']] )
860 $this->attachDatabase(
$params[
'dbname'],
false, __METHOD__ );
861 $this->sessionAttachedDbs[
$params[
'dbname']] =
true;
871 $this->sessionAttachedDbs = [];
873 $this->lockMgr =
null;
875 $this->lockMgr = $this->makeLockManager();
880 $this->lockMgr =
null;
882 $this->lockMgr = $this->makeLockManager();
889 return parent::getBindingHandle();
893 $components = $this->platform->qualifiedTableComponents( $table );
894 $tableRaw = end( $components );
896 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
897 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
900 $res = $this->query( $query, __METHOD__ );
901 foreach ( $res as $row ) {
902 if ( $row->pk && strtolower( $row->type ) ===
'integer' ) {
array $params
The job parameters.
Simple lock management based on server-local temporary files.
Resource locking handling.
Simple lock management based on in-process reference counting.
Class to handle database/schema/prefix specifications for IDatabase.