44 private $sessionAttachedDbs = [];
47 private const VALID_TRX_MODES = [
'',
'DEFERRED',
'IMMEDIATE',
'EXCLUSIVE' ];
50 private const VALID_PRAGMAS = [
52 'synchronous' => [
'EXTRA',
'FULL',
'NORMAL',
'OFF' ],
54 'temp_store' => [
'FILE',
'MEMORY' ],
56 'mmap_size' =>
'integer',
58 'cache_size' =>
'integer',
71 if ( isset( $params[
'dbFilePath'] ) ) {
72 $this->dbPath = $params[
'dbFilePath'];
73 if ( !isset( $params[
'dbname'] ) || $params[
'dbname'] ===
'' ) {
74 $params[
'dbname'] = self::generateDatabaseName( $this->dbPath );
76 } elseif ( isset( $params[
'dbDirectory'] ) ) {
77 $this->dbDir = $params[
'dbDirectory'];
80 parent::__construct( $params );
82 $this->trxMode = strtoupper( $params[
'trxMode'] ??
'' );
84 $this->lockMgr = $this->makeLockManager();
92 $params[
'topologyRole'],
101 self::ATTR_DB_IS_FILE =>
true,
102 self::ATTR_DB_LEVEL_LOCKING => true
116 $p[
'dbFilePath'] = $filename;
118 $p[
'tablePrefix'] =
'';
121 '@phan-var DatabaseSqlite $db';
134 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
135 $this->
close( __METHOD__ );
139 if ( $schema !==
null ) {
143 if ( $this->dbPath !==
null ) {
145 } elseif ( $this->dbDir !==
null ) {
152 if ( !self::isProcessMemoryPath(
$path ) && is_file(
$path ) && !is_readable(
$path ) ) {
154 } elseif ( !in_array( $this->trxMode, self::VALID_TRX_MODES,
true ) ) {
159 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
163 PDO::ATTR_STRINGIFY_FETCHES => true
165 if ( $this->
getFlag( self::DBO_PERSISTENT ) ) {
168 if ( $this->
getFlag( self::DBO_TRX ) || $this->
getFlag( self::DBO_DEFAULT ) ) {
169 $this->logger->warning(
170 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
174 $attributes[PDO::ATTR_PERSISTENT] =
true;
180 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
181 }
catch ( PDOException $e ) {
191 'PRAGMA case_sensitive_like = 1',
192 self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY,
195 $this->
query( $query, __METHOD__ );
198 $pragmas += $this->getDefaultPragmas();
199 foreach ( $pragmas as $name => $value ) {
200 $allowed = self::VALID_PRAGMAS[$name];
202 ( is_array( $allowed ) && in_array( $value, $allowed,
true ) ) ||
203 ( is_string( $allowed ) && gettype( $value ) === $allowed )
206 "PRAGMA $name = $value",
207 self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY,
212 $this->
query( $query, __METHOD__ );
215 $this->attachDatabasesFromTableAliases();
216 }
catch ( RuntimeException $e ) {
224 private function getDefaultPragmas() {
228 $variables[
'temp_store'] =
'MEMORY';
247 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
248 return dirname( $this->dbPath ) .
'/locks';
249 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
250 return $this->dbDir .
'/locks';
263 if ( $lockDirectory !==
null ) {
266 'lockDirectory' => $lockDirectory,
269 return new NullLockManager( [
'domain' => $this->
getDomainID() ] );
280 $this->lockMgr =
null;
295 } elseif ( self::isProcessMemoryPath( $dir ) ) {
298 __CLASS__ .
": cannot use process memory directory '$dir'"
300 } elseif ( !strlen( $dbName ) ) {
304 return "$dir/$dbName.sqlite";
311 private static function generateDatabaseName(
$path ) {
312 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
315 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
320 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
328 private static function isProcessMemoryPath(
$path ) {
329 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
337 static $cachedResult =
null;
338 if ( $cachedResult !==
null ) {
339 return $cachedResult;
341 $cachedResult =
false;
342 $table =
'dummy_search_test';
344 $db = self::newStandaloneInstance(
':memory:' );
346 "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)",
350 $cachedResult =
'FTS3';
352 $db->close( __METHOD__ );
354 return $cachedResult;
370 $file = is_string( $file ) ? $file : self::generateFileName( $this->dbDir, $name );
371 $encFile = $this->addQuotes( $file );
373 "ATTACH DATABASE $encFile AS $name",
374 self::QUERY_CHANGE_TRX,
377 return $this->query( $query, $fname );
381 $res = $this->getBindingHandle()->query( $sql );
385 $res ? $res->rowCount() : 0,
396 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
402 if ( $database ===
null ) {
404 $this->currentDomain->getDatabase(),
408 $this->platform->setCurrentDomain( $this->currentDomain );
413 if ( $database !== $this->getDBname() ) {
416 __CLASS__ .
": cannot change database (got '$database')"
421 $this->currentDomain = $domain;
422 $this->platform->setCurrentDomain( $domain );
430 return (
int)$this->getBindingHandle()->lastInsertId();
437 if ( is_object( $this->conn ) ) {
438 $e = $this->conn->errorInfo();
440 return $e[2] ?? $this->lastConnectError;
443 return 'No database connection';
450 if ( is_object( $this->conn ) ) {
451 $info = $this->conn->errorInfo();
453 if ( isset( $info[1] ) ) {
463 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
464 if ( isset( $this->sessionTempTables[$db][$pt] ) ) {
468 $encTable = $this->addQuotes( $pt );
470 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
471 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
474 $res = $this->query( $query, __METHOD__ );
476 return (
bool)$res->numRows();
480 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
481 $components = $this->platform->qualifiedTableComponents( $table );
482 $tableRaw = end( $components );
484 'PRAGMA index_list(' . $this->addQuotes( $tableRaw ) .
')',
485 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
488 $res = $this->query( $query, $fname );
490 foreach ( $res as $row ) {
491 if ( $row->name === $index ) {
492 return [
'unique' => (bool)$row->unique ];
501 $components = $this->platform->qualifiedTableComponents( $table );
502 $tableRaw = end( $components );
504 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
505 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
508 $res = $this->query( $query, $fname );
511 foreach ( $res as $row ) {
512 if ( isset( $row->pk ) && (
int)$row->pk > 0 ) {
513 $pkBySeq[(int)$row->pk] = (
string)$row->name;
519 return array_values( $pkBySeq );
523 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
524 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
528 $encTable = $this->tableName( $table );
529 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
534 "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples",
535 self::QUERY_CHANGE_ROWS,
539 $this->query( $query, $fname );
558 $this->assertHasConnectionHandle();
560 $path = $this->getDbFilePath();
562 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
569 return "[{{int:version-db-sqlite-url}} SQLite]";
576 if ( $this->version ===
null ) {
577 $this->version = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
580 return $this->version;
592 $components = $this->platform->qualifiedTableComponents( $table );
593 $tableRaw = end( $components );
595 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
596 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
599 $res = $this->query( $query, __METHOD__ );
600 foreach ( $res as $row ) {
601 if ( $row->name == $field ) {
611 if ( $this->trxMode !=
'' ) {
612 $sql =
"BEGIN {$this->trxMode}";
616 $query =
new Query( $sql, self::QUERY_CHANGE_TRX,
'BEGIN' );
617 $this->query( $query, $fname );
625 return substr( $this->addQuotes( $s ), 1, -1 );
633 return new Blob( $b );
641 if ( $b instanceof
Blob ) {
658 if ( $s instanceof
Blob ) {
659 return "x'" . bin2hex( $s->fetch() ) .
"'";
660 } elseif ( is_bool( $s ) ) {
661 return (
string)(int)$s;
662 } elseif ( is_int( $s ) ) {
664 } elseif ( str_contains( (
string)$s,
"\0" ) ) {
674 $this->logger->debug(
676 ': Quoting value containing null byte. ' .
677 'For consistency all binary data should have been ' .
678 'first processed with self::encodeBlob()'
680 return "x'" . bin2hex( (
string)$s ) .
"'";
682 return $this->getBindingHandle()->quote( (
string)$s );
693 public function doLock(
string $lockName,
string $method,
int $timeout ) {
694 $status = $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout );
697 $status->hasMessage(
'lockmanager-fail-openlock' )
699 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
702 return $status->isOK() ? microtime(
true ) :
null;
706 public function doUnlock(
string $lockName,
string $method ) {
707 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
719 $oldName, $newName, $temporary =
false, $fname = __METHOD__
722 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
723 $this->addQuotes( $oldName ) .
" AND type='table'",
724 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
727 $res = $this->query( $query, $fname );
728 $obj = $res->fetchObject();
730 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
732 $sqlCreateTable = $obj->sql;
733 $sqlCreateTable = preg_replace(
735 preg_quote( trim( $this->platform->addIdentifierQuotes( $oldName ),
'"' ),
'/' ) .
737 $this->platform->addIdentifierQuotes( $newName ),
741 $flags = self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT;
743 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sqlCreateTable ) ) {
744 $this->logger->debug(
745 "Table $oldName is virtual, can't create a temporary duplicate." );
747 $sqlCreateTable = str_replace(
749 'CREATE TEMPORARY TABLE',
758 $temporary ?
'CREATE TEMPORARY' :
'CREATE',
762 $res = $this->query( $query, $fname );
765 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) .
')',
766 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
770 $indexList = $this->query( $query, $fname );
771 foreach ( $indexList as $index ) {
772 if ( str_starts_with( $index->name,
'sqlite_autoindex' ) ) {
776 if ( $index->unique ) {
777 $sqlIndex =
'CREATE UNIQUE INDEX';
779 $sqlIndex =
'CREATE INDEX';
782 $indexName = $newName .
'_' . $index->name;
783 $sqlIndex .=
' ' . $this->platform->addIdentifierQuotes( $indexName ) .
784 ' ON ' . $this->platform->addIdentifierQuotes( $newName );
787 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) .
')',
788 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
791 $indexInfo = $this->query( $query, $fname );
793 foreach ( $indexInfo as $indexInfoRow ) {
794 $fields[$indexInfoRow->seqno] = $this->addQuotes( $indexInfoRow->name );
797 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
801 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT,
805 $this->query( $query, __METHOD__ );
819 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
821 "SELECT name FROM sqlite_master WHERE type = 'table'",
822 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
825 $result = $this->query( $query, $fname );
829 foreach ( $result as $table ) {
830 $vars = get_object_vars( $table );
831 $table = array_pop( $vars );
833 if ( !$prefix || str_starts_with( $table, $prefix ) ) {
834 if ( !str_starts_with( $table,
'sqlite_' ) ) {
835 $endArray[] = $table;
845 $this->startAtomic( $fname );
848 "DELETE FROM " . $this->tableName( $table ),
849 self::QUERY_CHANGE_SCHEMA,
853 $this->query( $query, $fname );
855 $encMasterTable = $this->platform->addIdentifierQuotes(
'sqlite_sequence' );
856 $encSequenceName = $this->addQuotes( $this->tableName( $table,
'raw' ) );
858 "DELETE FROM $encMasterTable WHERE name = $encSequenceName",
859 self::QUERY_CHANGE_SCHEMA,
863 $this->query( $query, $fname );
865 $this->endAtomic( $fname );
869 parent::setTableAliases( $aliases );
870 if ( $this->isOpen() ) {
871 $this->attachDatabasesFromTableAliases();
878 private function attachDatabasesFromTableAliases() {
879 foreach ( $this->platform->getTableAliases() as $params ) {
881 $params[
'dbname'] !== $this->getDBname() &&
882 !isset( $this->sessionAttachedDbs[$params[
'dbname']] )
884 $this->attachDatabase( $params[
'dbname'],
false, __METHOD__ );
885 $this->sessionAttachedDbs[$params[
'dbname']] =
true;
896 $this->sessionAttachedDbs = [];
898 $this->lockMgr =
null;
900 $this->lockMgr = $this->makeLockManager();
906 $this->lockMgr =
null;
908 $this->lockMgr = $this->makeLockManager();
915 return parent::getBindingHandle();
920 $components = $this->platform->qualifiedTableComponents( $table );
921 $tableRaw = end( $components );
923 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
924 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
927 $res = $this->query( $query, __METHOD__ );
928 foreach ( $res as $row ) {
929 if ( $row->pk && strtolower( $row->type ) ===
'integer' ) {
Class to handle database/schema/prefix specifications for IDatabase.