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',
86 if ( isset(
$params[
'dbFilePath'] ) ) {
87 $this->dbPath =
$params[
'dbFilePath'];
89 $params[
'dbname'] = self::generateDatabaseName( $this->dbPath );
91 } elseif ( isset(
$params[
'dbDirectory'] ) ) {
92 $this->dbDir =
$params[
'dbDirectory'];
97 $this->trxMode = strtoupper(
$params[
'trxMode'] ??
'' );
99 $this->lockMgr = $this->makeLockManager();
115 self::ATTR_DB_IS_FILE =>
true,
116 self::ATTR_DB_LEVEL_LOCKING => true
130 $p[
'dbFilePath'] = $filename;
132 $p[
'tablePrefix'] =
'';
135 '@phan-var DatabaseSqlite $db';
147 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
148 $this->
close( __METHOD__ );
152 if ( $schema !==
null ) {
156 if ( $this->dbPath !==
null ) {
158 } elseif ( $this->dbDir !==
null ) {
165 if ( !self::isProcessMemoryPath(
$path ) && is_file(
$path ) && !is_readable(
$path ) ) {
167 } elseif ( !in_array( $this->trxMode, self::VALID_TRX_MODES,
true ) ) {
172 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
176 PDO::ATTR_STRINGIFY_FETCHES => true
178 if ( $this->
getFlag( self::DBO_PERSISTENT ) ) {
181 if ( $this->
getFlag( self::DBO_TRX ) || $this->
getFlag( self::DBO_DEFAULT ) ) {
182 $this->logger->warning(
183 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
187 $attributes[PDO::ATTR_PERSISTENT] =
true;
193 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
194 }
catch ( PDOException $e ) {
204 'PRAGMA case_sensitive_like = 1',
205 self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY,
208 $this->
query( $query, __METHOD__ );
211 $pragmas += $this->getDefaultPragmas();
212 foreach ( $pragmas as $name => $value ) {
213 $allowed = self::VALID_PRAGMAS[$name];
215 ( is_array( $allowed ) && in_array( $value, $allowed,
true ) ) ||
216 ( is_string( $allowed ) && gettype( $value ) === $allowed )
219 "PRAGMA $name = $value",
220 self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY,
225 $this->
query( $query, __METHOD__ );
228 $this->attachDatabasesFromTableAliases();
229 }
catch ( RuntimeException $e ) {
237 private function getDefaultPragmas() {
241 $variables[
'temp_store'] =
'MEMORY';
260 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
261 return dirname( $this->dbPath ) .
'/locks';
262 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
263 return $this->dbDir .
'/locks';
276 if ( $lockDirectory !==
null ) {
279 'lockDirectory' => $lockDirectory,
293 $this->lockMgr =
null;
308 } elseif ( self::isProcessMemoryPath( $dir ) ) {
311 __CLASS__ .
": cannot use process memory directory '$dir'"
313 } elseif ( !strlen( $dbName ) ) {
317 return "$dir/$dbName.sqlite";
324 private static function generateDatabaseName(
$path ) {
325 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
328 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
333 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
341 private static function isProcessMemoryPath(
$path ) {
342 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
350 static $cachedResult =
null;
351 if ( $cachedResult !==
null ) {
352 return $cachedResult;
354 $cachedResult =
false;
355 $table =
'dummy_search_test';
357 $db = self::newStandaloneInstance(
':memory:' );
359 "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)",
363 $cachedResult =
'FTS3';
365 $db->close( __METHOD__ );
367 return $cachedResult;
383 $file = is_string( $file ) ? $file : self::generateFileName( $this->dbDir, $name );
384 $encFile = $this->addQuotes( $file );
386 "ATTACH DATABASE $encFile AS $name",
387 self::QUERY_CHANGE_TRX,
390 return $this->query( $query, $fname );
394 $res = $this->getBindingHandle()->query( $sql );
398 $res ? $res->rowCount() : 0,
408 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
414 if ( $database ===
null ) {
416 $this->currentDomain->getDatabase(),
420 $this->platform->setCurrentDomain( $this->currentDomain );
425 if ( $database !== $this->getDBname() ) {
428 __CLASS__ .
": cannot change database (got '$database')"
433 $this->currentDomain = $domain;
434 $this->platform->setCurrentDomain( $domain );
441 return (
int)$this->getBindingHandle()->lastInsertId();
448 if ( is_object( $this->conn ) ) {
449 $e = $this->conn->errorInfo();
451 return $e[2] ?? $this->lastConnectError;
454 return 'No database connection';
461 if ( is_object( $this->conn ) ) {
462 $info = $this->conn->errorInfo();
464 if ( isset( $info[1] ) ) {
473 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
474 if ( isset( $this->sessionTempTables[$db][$pt] ) ) {
478 $encTable = $this->addQuotes( $pt );
480 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
481 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
484 $res = $this->query( $query, __METHOD__ );
486 return (
bool)$res->numRows();
489 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
490 $indexName = $this->platform->indexName( $index );
491 $components = $this->platform->qualifiedTableComponents( $table );
492 $tableRaw = end( $components );
494 'PRAGMA index_list(' . $this->addQuotes( $tableRaw ) .
')',
495 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
498 $res = $this->query( $query, $fname );
500 foreach ( $res as $row ) {
501 if ( $row->name === $indexName ) {
502 return [
'unique' => (bool)$row->unique ];
509 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
510 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
514 $encTable = $this->tableName( $table );
515 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
520 "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples",
521 self::QUERY_CHANGE_ROWS,
525 $this->query( $query, $fname );
541 $this->assertHasConnectionHandle();
543 $path = $this->getDbFilePath();
545 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
552 return "[{{int:version-db-sqlite-url}} SQLite]";
559 if ( $this->version ===
null ) {
560 $this->version = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
563 return $this->version;
575 $components = $this->platform->qualifiedTableComponents( $table );
576 $tableRaw = end( $components );
578 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
579 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
582 $res = $this->query( $query, __METHOD__ );
583 foreach ( $res as $row ) {
584 if ( $row->name == $field ) {
593 if ( $this->trxMode !=
'' ) {
594 $sql =
"BEGIN {$this->trxMode}";
598 $query =
new Query( $sql, self::QUERY_CHANGE_TRX,
'BEGIN' );
599 $this->query( $query, $fname );
607 return substr( $this->addQuotes( $s ), 1, -1 );
615 return new Blob( $b );
623 if ( $b instanceof
Blob ) {
639 if ( $s instanceof
Blob ) {
640 return "x'" . bin2hex( $s->fetch() ) .
"'";
641 } elseif ( is_bool( $s ) ) {
642 return (
string)(int)$s;
643 } elseif ( is_int( $s ) ) {
645 } elseif ( strpos( (
string)$s,
"\0" ) !==
false ) {
655 $this->logger->debug(
657 ': Quoting value containing null byte. ' .
658 'For consistency all binary data should have been ' .
659 'first processed with self::encodeBlob()'
661 return "x'" . bin2hex( (
string)$s ) .
"'";
663 return $this->getBindingHandle()->quote( (
string)$s );
672 public function doLock(
string $lockName,
string $method,
int $timeout ) {
673 $status = $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout );
676 $status->hasMessage(
'lockmanager-fail-openlock' )
678 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
681 return $status->isOK() ? microtime(
true ) :
null;
684 public function doUnlock(
string $lockName,
string $method ) {
685 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
697 $oldName, $newName, $temporary =
false, $fname = __METHOD__
700 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
701 $this->addQuotes( $oldName ) .
" AND type='table'",
702 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
705 $res = $this->query( $query, $fname );
706 $obj = $res->fetchObject();
708 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
710 $sqlCreateTable = $obj->sql;
711 $sqlCreateTable = preg_replace(
713 preg_quote( trim( $this->platform->addIdentifierQuotes( $oldName ),
'"' ),
'/' ) .
715 $this->platform->addIdentifierQuotes( $newName ),
719 $flags = self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT;
721 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sqlCreateTable ) ) {
722 $this->logger->debug(
723 "Table $oldName is virtual, can't create a temporary duplicate." );
725 $sqlCreateTable = str_replace(
727 'CREATE TEMPORARY TABLE',
736 $temporary ?
'CREATE TEMPORARY' :
'CREATE',
740 $res = $this->query( $query, $fname );
743 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) .
')',
744 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
748 $indexList = $this->query( $query, $fname );
749 foreach ( $indexList as $index ) {
750 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
754 if ( $index->unique ) {
755 $sqlIndex =
'CREATE UNIQUE INDEX';
757 $sqlIndex =
'CREATE INDEX';
760 $indexName = $newName .
'_' . $index->name;
761 $sqlIndex .=
' ' . $this->platform->addIdentifierQuotes( $indexName ) .
762 ' ON ' . $this->platform->addIdentifierQuotes( $newName );
765 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) .
')',
766 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
769 $indexInfo = $this->query( $query, $fname );
771 foreach ( $indexInfo as $indexInfoRow ) {
772 $fields[$indexInfoRow->seqno] = $this->addQuotes( $indexInfoRow->name );
775 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
779 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT,
783 $this->query( $query, __METHOD__ );
797 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
799 "SELECT name FROM sqlite_master WHERE type = 'table'",
800 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
803 $result = $this->query( $query, $fname );
807 foreach ( $result as $table ) {
808 $vars = get_object_vars( $table );
809 $table = array_pop( $vars );
811 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
812 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
813 $endArray[] = $table;
822 $this->startAtomic( $fname );
825 "DELETE FROM " . $this->tableName( $table ),
826 self::QUERY_CHANGE_SCHEMA,
830 $this->query( $query, $fname );
832 $encMasterTable = $this->platform->addIdentifierQuotes(
'sqlite_sequence' );
833 $encSequenceName = $this->addQuotes( $this->tableName( $table,
'raw' ) );
835 "DELETE FROM $encMasterTable WHERE name = $encSequenceName",
836 self::QUERY_CHANGE_SCHEMA,
840 $this->query( $query, $fname );
842 $this->endAtomic( $fname );
846 parent::setTableAliases( $aliases );
847 if ( $this->isOpen() ) {
848 $this->attachDatabasesFromTableAliases();
855 private function attachDatabasesFromTableAliases() {
856 foreach ( $this->platform->getTableAliases() as
$params ) {
858 $params[
'dbname'] !== $this->getDBname() &&
859 !isset( $this->sessionAttachedDbs[
$params[
'dbname']] )
861 $this->attachDatabase(
$params[
'dbname'],
false, __METHOD__ );
862 $this->sessionAttachedDbs[
$params[
'dbname']] =
true;
872 $this->sessionAttachedDbs = [];
874 $this->lockMgr =
null;
876 $this->lockMgr = $this->makeLockManager();
881 $this->lockMgr =
null;
883 $this->lockMgr = $this->makeLockManager();
890 return parent::getBindingHandle();
894 $components = $this->platform->qualifiedTableComponents( $table );
895 $tableRaw = end( $components );
897 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
898 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
901 $res = $this->query( $query, __METHOD__ );
902 foreach ( $res as $row ) {
903 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.