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'
84 if ( isset( $params[
'dbFilePath'] ) ) {
85 $this->dbPath = $params[
'dbFilePath'];
86 if ( !isset( $params[
'dbname'] ) || $params[
'dbname'] ===
'' ) {
87 $params[
'dbname'] = self::generateDatabaseName( $this->dbPath );
89 } elseif ( isset( $params[
'dbDirectory'] ) ) {
90 $this->dbDir = $params[
'dbDirectory'];
93 parent::__construct( $params );
95 $this->trxMode = strtoupper( $params[
'trxMode'] ??
'' );
97 $this->lockMgr = $this->makeLockManager();
101 $this->currentDomain,
105 $params[
'topologyRole'],
113 self::ATTR_DB_IS_FILE =>
true,
114 self::ATTR_DB_LEVEL_LOCKING =>
true
128 $p[
'dbFilePath'] = $filename;
130 $p[
'tablePrefix'] =
'';
133 '@phan-var DatabaseSqlite $db';
145 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
146 $this->
close( __METHOD__ );
150 if ( $schema !==
null ) {
154 if ( $this->dbPath !==
null ) {
156 } elseif ( $this->dbDir !==
null ) {
163 if ( !self::isProcessMemoryPath(
$path ) && is_file(
$path ) && !is_readable(
$path ) ) {
165 } elseif ( !in_array( $this->trxMode, self::VALID_TRX_MODES,
true ) ) {
170 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
174 PDO::ATTR_STRINGIFY_FETCHES =>
true
180 $this->logger->warning(
181 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
185 $attributes[PDO::ATTR_PERSISTENT] =
true;
191 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
192 }
catch ( PDOException $e ) {
196 $this->currentDomain =
new DatabaseDomain( $db,
null, $tablePrefix );
197 $this->platform->setPrefix( $tablePrefix );
200 $flags = self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY;
202 $this->
query(
'PRAGMA case_sensitive_like = 1', __METHOD__, $flags );
204 $pragmas = array_intersect_key( $this->connectionVariables, self::VALID_PRAGMAS );
205 $pragmas += $this->getDefaultPragmas();
206 foreach ( $pragmas as $name => $value ) {
207 $allowed = self::VALID_PRAGMAS[$name];
209 ( is_array( $allowed ) && in_array( $value, $allowed,
true ) ) ||
210 ( is_string( $allowed ) && gettype( $value ) === $allowed )
212 $this->
query(
"PRAGMA $name = $value", __METHOD__, $flags );
215 $this->attachDatabasesFromTableAliases();
216 }
catch ( RuntimeException $e ) {
224 private function getDefaultPragmas() {
227 if ( !$this->cliMode ) {
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,
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)",
348 IDatabase::QUERY_SILENCE_ERRORS
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 );
374 "ATTACH DATABASE $encFile AS $name",
376 self::QUERY_CHANGE_TRX
381 $res = $this->getBindingHandle()->query( $sql );
385 $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;
428 return (
int)$this->getBindingHandle()->lastInsertId();
435 if ( is_object( $this->conn ) ) {
436 $e = $this->conn->errorInfo();
438 return $e[2] ?? $this->lastConnectError;
441 return 'No database connection';
448 if ( is_object( $this->conn ) ) {
449 $info = $this->conn->errorInfo();
451 if ( isset( $info[1] ) ) {
460 $tableRaw = $this->tableName( $table,
'raw' );
461 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
465 $encTable = $this->addQuotes( $tableRaw );
467 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
469 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
472 return (
bool)$res->numRows();
485 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
486 $sql =
'PRAGMA index_info(' . $this->addQuotes( $this->platform->indexName( $index ) ) .
')';
487 $res = $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE );
488 if ( !$res || $res->numRows() == 0 ) {
492 foreach ( $res as $row ) {
493 $info[] = $row->name;
505 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
506 $row = $this->selectRow(
'sqlite_master',
'*',
509 'name' => $this->platform->indexName( $index ),
511 if ( !$row || !isset( $row->sql ) ) {
516 $indexPos = strpos( $row->sql,
'INDEX' );
517 if ( $indexPos ===
false ) {
520 $firstPart = substr( $row->sql, 0, $indexPos );
521 $options = explode(
' ', $firstPart );
523 return in_array(
'UNIQUE', $options );
526 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
527 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
531 $encTable = $this->tableName( $table );
532 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
537 "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples",
539 self::QUERY_CHANGE_ROWS
559 return $this->lastErrno() == 5;
566 return $this->lastErrno() == 8;
582 $this->assertHasConnectionHandle();
584 $path = $this->getDbFilePath();
586 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
593 return "[{{int:version-db-sqlite-url}} SQLite]";
600 if ( $this->version ===
null ) {
601 $this->version = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
604 return $this->version;
616 $tableRaw = $this->tableName( $table,
'raw' );
618 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
620 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
622 foreach ( $res as $row ) {
623 if ( $row->name == $field ) {
632 if ( $this->trxMode !=
'' ) {
633 $this->query(
"BEGIN {$this->trxMode}", $fname, self::QUERY_CHANGE_TRX );
635 $this->query(
'BEGIN', $fname, self::QUERY_CHANGE_TRX );
644 return substr( $this->addQuotes( $s ), 1, -1 );
652 return new Blob( $b );
660 if ( $b instanceof
Blob ) {
677 if ( $s instanceof
Blob ) {
678 return "x'" . bin2hex( $s->fetch() ) .
"'";
679 } elseif ( is_bool( $s ) ) {
680 return (
string)(int)$s;
681 } elseif ( is_int( $s ) ) {
683 } elseif ( strpos( (
string)$s,
"\0" ) !==
false ) {
693 $this->logger->debug(
695 ': Quoting value containing null byte. ' .
696 'For consistency all binary data should have been ' .
697 'first processed with self::encodeBlob()'
699 return "x'" . bin2hex( (
string)$s ) .
"'";
701 return $this->getBindingHandle()->quote( (
string)$s );
710 public function doLock(
string $lockName,
string $method,
int $timeout ) {
714 $status->hasMessage(
'lockmanager-fail-openlock' )
716 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
719 return $status->isOK() ? microtime(
true ) :
null;
722 public function doUnlock(
string $lockName,
string $method ) {
735 $oldName, $newName, $temporary =
false, $fname = __METHOD__
738 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
739 $this->addQuotes( $oldName ) .
" AND type='table'",
741 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
743 $obj = $res->fetchObject();
745 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
747 $sqlCreateTable = $obj->sql;
748 $sqlCreateTable = preg_replace(
750 preg_quote( trim( $this->platform->addIdentifierQuotes( $oldName ),
'"' ),
'/' ) .
752 $this->platform->addIdentifierQuotes( $newName ),
757 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sqlCreateTable ) ) {
758 $this->logger->debug(
759 "Table $oldName is virtual, can't create a temporary duplicate." );
761 $sqlCreateTable = str_replace(
763 'CREATE TEMPORARY TABLE',
772 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
776 $indexList = $this->query(
777 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) .
')',
779 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
781 foreach ( $indexList as $index ) {
782 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
786 if ( $index->unique ) {
787 $sqlIndex =
'CREATE UNIQUE INDEX';
789 $sqlIndex =
'CREATE INDEX';
792 $indexName = $newName .
'_' . $index->name;
793 $sqlIndex .=
' ' . $this->platform->addIdentifierQuotes( $indexName ) .
794 ' ON ' . $this->platform->addIdentifierQuotes( $newName );
796 $indexInfo = $this->query(
797 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) .
')',
799 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
802 foreach ( $indexInfo as $indexInfoRow ) {
803 $fields[$indexInfoRow->seqno] = $this->addQuotes( $indexInfoRow->name );
806 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
811 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
826 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
827 $result = $this->query(
828 "SELECT name FROM sqlite_master WHERE type = 'table'",
830 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
835 foreach ( $result as $table ) {
836 $vars = get_object_vars( $table );
837 $table = array_pop( $vars );
839 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
840 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
841 $endArray[] = $table;
850 $this->startAtomic( $fname );
853 foreach ( $tables as $table ) {
855 $sql =
"DELETE FROM " . $this->tableName( $table );
856 $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
858 $encSeqNames[] = $this->addQuotes( $this->tableName( $table,
'raw' ) );
861 $encMasterTable = $this->platform->addIdentifierQuotes(
'sqlite_sequence' );
863 "DELETE FROM $encMasterTable WHERE name IN(" . implode(
',', $encSeqNames ) .
")",
865 self::QUERY_CHANGE_SCHEMA
868 $this->endAtomic( $fname );
872 parent::setTableAliases( $aliases );
873 if ( $this->isOpen() ) {
874 $this->attachDatabasesFromTableAliases();
881 private function attachDatabasesFromTableAliases() {
882 foreach ( $this->platform->getTableAliases() as $params ) {
884 $params[
'dbname'] !== $this->getDBname() &&
885 !isset( $this->sessionAttachedDbs[$params[
'dbname']] )
887 $this->attachDatabase( $params[
'dbname'],
false, __METHOD__ );
888 $this->sessionAttachedDbs[$params[
'dbname']] =
true;
898 $this->sessionAttachedDbs = [];
900 $this->lockMgr =
null;
902 $this->lockMgr = $this->makeLockManager();
907 $this->lockMgr =
null;
909 $this->lockMgr = $this->makeLockManager();
916 return parent::getBindingHandle();
920 $tableRaw = $this->tableName( $table,
'raw' );
922 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
924 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
926 foreach ( $res as $row ) {
927 if ( $row->pk && strtolower( $row->type ) ===
'integer' ) {
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.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.