60 private $sessionAttachedDbs = [];
63 private const VALID_TRX_MODES = [
'',
'DEFERRED',
'IMMEDIATE',
'EXCLUSIVE' ];
66 private const VALID_PRAGMAS = [
68 'synchronous' => [
'EXTRA',
'FULL',
'NORMAL',
'OFF' ],
70 'temp_store' => [
'FILE',
'MEMORY' ],
72 'mmap_size' =>
'integer'
86 if ( isset( $params[
'dbFilePath'] ) ) {
87 $this->dbPath = $params[
'dbFilePath'];
88 if ( !isset( $params[
'dbname'] ) || $params[
'dbname'] ===
'' ) {
89 $params[
'dbname'] = self::generateDatabaseName( $this->dbPath );
91 } elseif ( isset( $params[
'dbDirectory'] ) ) {
92 $this->dbDir = $params[
'dbDirectory'];
95 parent::__construct( $params );
97 $this->trxMode = strtoupper( $params[
'trxMode'] ??
'' );
99 $this->lockMgr = $this->makeLockManager();
102 $params[
'queryLogger'],
103 $this->currentDomain,
110 self::ATTR_DB_IS_FILE =>
true,
111 self::ATTR_DB_LEVEL_LOCKING =>
true
125 $p[
'dbFilePath'] = $filename;
127 $p[
'tablePrefix'] =
'';
129 $db = Database::factory(
'sqlite', $p );
130 '@phan-var DatabaseSqlite $db';
143 $this->
close( __METHOD__ );
147 if ( $schema !==
null ) {
151 if ( $this->dbPath !==
null ) {
153 } elseif ( $this->dbDir !==
null ) {
160 if ( !self::isProcessMemoryPath(
$path ) && is_file(
$path ) && !is_readable(
$path ) ) {
162 } elseif ( !in_array( $this->trxMode, self::VALID_TRX_MODES,
true ) ) {
167 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
171 PDO::ATTR_STRINGIFY_FETCHES =>
true
173 if ( $this->
getFlag( self::DBO_PERSISTENT ) ) {
176 if ( $this->
getFlag( self::DBO_TRX ) || $this->
getFlag( self::DBO_DEFAULT ) ) {
177 $this->connLogger->warning(
178 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
182 $attributes[PDO::ATTR_PERSISTENT] =
true;
188 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
189 }
catch ( PDOException $e ) {
193 $this->currentDomain =
new DatabaseDomain( $db,
null, $tablePrefix );
194 $this->platform->setPrefix( $tablePrefix );
197 $flags = self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY;
199 $this->
query(
'PRAGMA case_sensitive_like = 1', __METHOD__,
$flags );
201 $pragmas = array_intersect_key( $this->connectionVariables, self::VALID_PRAGMAS );
202 $pragmas += $this->getDefaultPragmas();
203 foreach ( $pragmas as $name => $value ) {
204 $allowed = self::VALID_PRAGMAS[$name];
206 ( is_array( $allowed ) && in_array( $value, $allowed,
true ) ) ||
207 ( is_string( $allowed ) && gettype( $value ) === $allowed )
209 $this->
query(
"PRAGMA $name = $value", __METHOD__,
$flags );
212 $this->attachDatabasesFromTableAliases();
213 }
catch ( RuntimeException $e ) {
221 private function getDefaultPragmas() {
224 if ( !$this->cliMode ) {
225 $variables[
'temp_store'] =
'MEMORY';
244 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
245 return dirname( $this->dbPath ) .
'/locks';
246 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
247 return $this->dbDir .
'/locks';
260 if ( $lockDirectory !==
null ) {
263 'lockDirectory' => $lockDirectory,
277 $this->lockMgr =
null;
292 } elseif ( self::isProcessMemoryPath( $dir ) ) {
295 __CLASS__ .
": cannot use process memory directory '$dir'"
297 } elseif ( !strlen( $dbName ) ) {
301 return "$dir/$dbName.sqlite";
308 private static function generateDatabaseName(
$path ) {
309 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
312 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
317 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
325 private static function isProcessMemoryPath(
$path ) {
326 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
334 static $cachedResult =
null;
335 if ( $cachedResult !==
null ) {
336 return $cachedResult;
338 $cachedResult =
false;
339 $table =
'dummy_search_test';
341 $db = self::newStandaloneInstance(
':memory:' );
343 "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)",
345 IDatabase::QUERY_SILENCE_ERRORS
347 $cachedResult =
'FTS3';
349 $db->close( __METHOD__ );
351 return $cachedResult;
367 $file = is_string(
$file ) ?
$file : self::generateFileName( $this->dbDir, $name );
368 $encFile = $this->addQuotes(
$file );
371 "ATTACH DATABASE $encFile AS $name",
373 self::QUERY_CHANGE_TRX
378 $conn = $this->getBindingHandle();
380 $res = $conn->query( $sql );
381 $this->lastAffectedRowCount =
$res ?
$res->rowCount() : 0;
395 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
401 if ( $database ===
null ) {
403 $this->currentDomain->getDatabase(),
412 if ( $database !== $this->getDBname() ) {
415 __CLASS__ .
": cannot change database (got '$database')"
420 $this->currentDomain = $domain;
433 return intval( $this->getBindingHandle()->lastInsertId() );
440 if ( is_object( $this->conn ) ) {
441 $e = $this->conn->errorInfo();
445 return 'No database connection';
452 if ( is_object( $this->conn ) ) {
453 $info = $this->conn->errorInfo();
455 if ( isset( $info[1] ) ) {
466 return $this->lastAffectedRowCount;
470 $tableRaw = $this->tableName( $table,
'raw' );
471 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
475 $encTable = $this->addQuotes( $tableRaw );
477 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
479 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
482 return $res->numRows() ?
true :
false;
495 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
496 $sql =
'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) .
')';
497 $res = $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE );
498 if ( !
$res ||
$res->numRows() == 0 ) {
502 foreach (
$res as $row ) {
503 $info[] = $row->name;
515 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
516 $row = $this->selectRow(
'sqlite_master',
'*',
519 'name' => $this->indexName( $index ),
521 if ( !$row || !isset( $row->sql ) ) {
526 $indexPos = strpos( $row->sql,
'INDEX' );
527 if ( $indexPos ===
false ) {
530 $firstPart = substr( $row->sql, 0, $indexPos );
531 $options = explode(
' ', $firstPart );
533 return in_array(
'UNIQUE', $options );
536 protected function doReplace( $table, array $identityKey, array $rows, $fname ) {
537 $encTable = $this->tableName( $table );
538 list( $sqlColumns, $sqlTuples ) = $this->platform->makeInsertLists( $rows );
541 "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples",
543 self::QUERY_CHANGE_ROWS
563 return $this->lastErrno() == 5;
570 return $this->lastErrno() == 8;
591 $this->assertHasConnectionHandle();
593 $path = $this->getDbFilePath();
595 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
602 return "[{{int:version-db-sqlite-url}} SQLite]";
609 if ( $this->version ===
null ) {
610 $this->version = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
613 return $this->version;
625 $tableRaw = $this->tableName( $table,
'raw' );
627 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
629 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
631 foreach (
$res as $row ) {
632 if ( $row->name == $field ) {
641 if ( $this->trxMode !=
'' ) {
642 $this->query(
"BEGIN {$this->trxMode}", $fname, self::QUERY_CHANGE_TRX );
644 $this->query(
'BEGIN', $fname, self::QUERY_CHANGE_TRX );
653 return substr( $this->addQuotes(
$s ), 1, -1 );
661 return new Blob( $b );
669 if ( $b instanceof
Blob ) {
686 if (
$s instanceof
Blob ) {
687 return "x'" . bin2hex(
$s->fetch() ) .
"'";
688 } elseif ( is_bool(
$s ) ) {
689 return (
string)(int)
$s;
690 } elseif ( is_int(
$s ) ) {
692 } elseif ( strpos( (
string)
$s,
"\0" ) !==
false ) {
702 $this->queryLogger->debug(
704 ': Quoting value containing null byte. ' .
705 'For consistency all binary data should have been ' .
706 'first processed with self::encodeBlob()'
708 return "x'" . bin2hex( (
string)
$s ) .
"'";
710 return $this->getBindingHandle()->quote( (
string)
$s );
721 $function = array_shift(
$args );
723 return $function( ...
$args );
731 public function doLock(
string $lockName,
string $method,
int $timeout ) {
732 $status = $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout );
735 $status->hasMessage(
'lockmanager-fail-openlock' )
737 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
740 return $status->isOK() ? microtime(
true ) :
null;
743 public function doUnlock(
string $lockName,
string $method ) {
744 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
756 $oldName, $newName, $temporary =
false, $fname = __METHOD__
759 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
760 $this->addQuotes( $oldName ) .
" AND type='table'",
762 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
764 $obj =
$res->fetchObject();
766 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
768 $sqlCreateTable = $obj->sql;
769 $sqlCreateTable = preg_replace(
771 preg_quote( trim( $this->platform->addIdentifierQuotes( $oldName ),
'"' ),
'/' ) .
773 $this->platform->addIdentifierQuotes( $newName ),
778 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sqlCreateTable ) ) {
779 $this->queryLogger->debug(
780 "Table $oldName is virtual, can't create a temporary duplicate." );
782 $sqlCreateTable = str_replace(
784 'CREATE TEMPORARY TABLE',
793 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
797 $indexList = $this->query(
798 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) .
')',
800 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
802 foreach ( $indexList as $index ) {
803 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
807 if ( $index->unique ) {
808 $sqlIndex =
'CREATE UNIQUE INDEX';
810 $sqlIndex =
'CREATE INDEX';
813 $indexName = $newName .
'_' . $index->name;
814 $sqlIndex .=
' ' . $this->platform->addIdentifierQuotes( $indexName ) .
815 ' ON ' . $this->platform->addIdentifierQuotes( $newName );
817 $indexInfo = $this->query(
818 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) .
')',
820 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
823 foreach ( $indexInfo as $indexInfoRow ) {
824 $fields[$indexInfoRow->seqno] = $this->addQuotes( $indexInfoRow->name );
827 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
832 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
847 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
848 $result = $this->query(
849 "SELECT name FROM sqlite_master WHERE type = 'table'",
851 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
856 foreach ( $result as $table ) {
857 $vars = get_object_vars( $table );
858 $table = array_pop( $vars );
860 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
861 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
862 $endArray[] = $table;
871 $this->startAtomic( $fname );
874 foreach ( $tables as $table ) {
876 $sql =
"DELETE FROM " . $this->tableName( $table );
877 $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
879 $encSeqNames[] = $this->addQuotes( $this->tableName( $table,
'raw' ) );
882 $encMasterTable = $this->platform->addIdentifierQuotes(
'sqlite_sequence' );
884 "DELETE FROM $encMasterTable WHERE name IN(" . implode(
',', $encSeqNames ) .
")",
886 self::QUERY_CHANGE_SCHEMA
889 $this->endAtomic( $fname );
893 parent::setTableAliases( $aliases );
894 if ( $this->isOpen() ) {
895 $this->attachDatabasesFromTableAliases();
902 private function attachDatabasesFromTableAliases() {
903 foreach ( $this->platform->getTableAliases() as $params ) {
905 $params[
'dbname'] !== $this->getDBname() &&
906 !isset( $this->sessionAttachedDbs[$params[
'dbname']] )
908 $this->attachDatabase( $params[
'dbname'],
false, __METHOD__ );
909 $this->sessionAttachedDbs[$params[
'dbname']] =
true;
919 $this->sessionAttachedDbs = [];
921 $this->lockMgr =
null;
923 $this->lockMgr = $this->makeLockManager();
928 $this->lockMgr =
null;
930 $this->lockMgr = $this->makeLockManager();
937 return parent::getBindingHandle();
944class_alias( DatabaseSqlite::class,
'DatabaseSqlite' );
Simple version of LockManager based on using FS lock files.
Class for handling resource locking.
Simple version of LockManager that only does lock reference counting.
Class to handle database/schema/prefix specifications for IDatabase.
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.