62 private const VALID_TRX_MODES = [
'',
'DEFERRED',
'IMMEDIATE',
'EXCLUSIVE' ];
65 private const VALID_PRAGMAS = [
67 'synchronous' => [
'EXTRA',
'FULL',
'NORMAL',
'OFF' ],
69 'temp_store' => [
'FILE',
'MEMORY' ]
83 if ( isset( $params[
'dbFilePath'] ) ) {
84 $this->dbPath = $params[
'dbFilePath'];
85 if ( !strlen( $params[
'dbname'] ) ) {
88 } elseif ( isset( $params[
'dbDirectory'] ) ) {
89 $this->dbDir = $params[
'dbDirectory'];
92 parent::__construct( $params );
94 $this->trxMode = strtoupper( $params[
'trxMode'] ??
'' );
102 self::ATTR_DB_IS_FILE =>
true,
103 self::ATTR_DB_LEVEL_LOCKING =>
true
117 $p[
'dbFilePath'] = $filename;
119 $p[
'tablePrefix'] =
'';
122 '@phan-var DatabaseSqlite $db';
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 ) ) {
158 $attributes = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT ];
163 $this->connLogger->warning(
164 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
168 $attributes[PDO::ATTR_PERSISTENT] =
true;
174 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
175 }
catch ( PDOException $e ) {
179 $this->currentDomain =
new DatabaseDomain( $db,
null, $tablePrefix );
182 $flags = self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY;
184 $this->
query(
'PRAGMA case_sensitive_like = 1', __METHOD__,
$flags );
186 $pragmas = array_intersect_key( $this->connectionVariables, self::VALID_PRAGMAS );
188 foreach ( $pragmas as $name => $value ) {
189 $allowed = self::VALID_PRAGMAS[$name];
190 if ( in_array( $value, $allowed,
true ) ) {
191 $this->
query(
"PRAGMA $name = $value", __METHOD__,
$flags );
195 }
catch ( RuntimeException $e ) {
206 if ( !$this->cliMode ) {
207 $variables[
'temp_store'] =
'MEMORY';
226 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
227 return dirname( $this->dbPath ) .
'/locks';
228 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
229 return $this->dbDir .
'/locks';
242 if ( $lockDirectory !==
null ) {
245 'lockDirectory' => $lockDirectory,
259 $this->lockMgr =
null;
274 } elseif ( self::isProcessMemoryPath( $dir ) ) {
277 __CLASS__ .
": cannot use process memory directory '$dir'"
279 } elseif ( !strlen( $dbName ) ) {
283 return "$dir/$dbName.sqlite";
291 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
294 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
299 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
308 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
316 static $cachedResult =
null;
317 if ( $cachedResult !==
null ) {
318 return $cachedResult;
320 $cachedResult =
false;
321 $table =
'dummy_search_test';
323 $db = self::newStandaloneInstance(
':memory:' );
325 "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)",
327 IDatabase::QUERY_SILENCE_ERRORS
329 $cachedResult =
'FTS3';
331 $db->close( __METHOD__ );
333 return $cachedResult;
349 $file = is_string(
$file ) ?
$file : self::generateFileName( $this->dbDir, $name );
350 $encFile = $this->addQuotes(
$file );
353 "ATTACH DATABASE $encFile AS $name",
355 self::QUERY_CHANGE_TRX
360 return parent::isWriteQuery( $sql, $flags ) && !preg_match(
'/^(ATTACH|PRAGMA)\b/i', $sql );
364 return parent::isTransactableQuery( $sql ) && !in_array(
365 $this->getQueryVerb( $sql ),
366 [
'ATTACH',
'PRAGMA' ],
376 $res = $this->getBindingHandle()->query( $sql );
377 if (
$res ===
false ) {
381 $this->lastAffectedRowCount =
$res->rowCount();
389 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
395 if ( $database ===
null ) {
397 $this->currentDomain->getDatabase(),
405 if ( $database !== $this->getDBname() ) {
408 __CLASS__ .
": cannot change database (got '$database')"
422 public function tableName( $name, $format =
'quoted' ) {
424 if ( strpos( $name,
'sqlite_' ) === 0 ) {
428 return str_replace(
'"',
'', parent::tableName( $name, $format ) );
438 return intval( $this->getBindingHandle()->lastInsertId() );
445 if ( is_object( $this->conn ) ) {
446 $e = $this->conn->errorInfo();
450 return 'No database connection';
457 if ( is_object( $this->conn ) ) {
458 $info = $this->conn->errorInfo();
460 if ( isset( $info[1] ) ) {
471 return $this->lastAffectedRowCount;
475 $tableRaw = $this->tableName( $table,
'raw' );
476 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
480 $encTable = $this->addQuotes( $tableRaw );
482 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
484 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
487 return $res->numRows() ?
true :
false;
500 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
501 $sql =
'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) .
')';
502 $res = $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE );
503 if ( !
$res ||
$res->numRows() == 0 ) {
507 foreach (
$res as $row ) {
508 $info[] = $row->name;
520 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
521 $row = $this->selectRow(
'sqlite_master',
'*',
524 'name' => $this->indexName( $index ),
526 if ( !$row || !isset( $row->sql ) ) {
531 $indexPos = strpos( $row->sql,
'INDEX' );
532 if ( $indexPos ===
false ) {
535 $firstPart = substr( $row->sql, 0, $indexPos );
536 $options = explode(
' ', $firstPart );
538 return in_array(
'UNIQUE', $options );
543 foreach ( $options as $k => $v ) {
544 if ( is_numeric( $k ) && ( $v ===
'FOR UPDATE' || $v ===
'LOCK IN SHARE MODE' ) ) {
549 return parent::makeSelectOptions( $options );
557 $options = parent::makeUpdateOptionsArray( $options );
558 $options = $this->rewriteIgnoreKeyword( $options );
568 # SQLite uses OR IGNORE not just IGNORE
569 foreach ( $options as $k => $v ) {
570 if ( $v ==
'IGNORE' ) {
571 $options[$k] =
'OR IGNORE';
579 return [
'INSERT OR IGNORE INTO',
'' ];
582 protected function doReplace( $table, array $identityKey, array $rows, $fname ) {
583 $encTable = $this->tableName( $table );
584 list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
587 "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples",
589 self::QUERY_CHANGE_ROWS
609 return $this->lastErrno() == 5;
616 return $this->lastErrno() == 8;
637 $this->assertHasConnectionHandle();
639 $path = $this->getDbFilePath();
641 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
648 return "[{{int:version-db-sqlite-url}} SQLite]";
655 if ( $this->version ===
null ) {
656 $this->version = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
659 return $this->version;
671 $tableName = $this->tableName( $table );
673 'PRAGMA table_info(' . $this->addQuotes( $tableName ) .
')',
675 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
677 foreach (
$res as $row ) {
678 if ( $row->name == $field ) {
687 if ( $this->trxMode !=
'' ) {
688 $this->query(
"BEGIN {$this->trxMode}", $fname, self::QUERY_CHANGE_TRX );
690 $this->query(
'BEGIN', $fname, self::QUERY_CHANGE_TRX );
699 return substr( $this->addQuotes(
$s ), 1, -1 );
707 return new Blob( $b );
715 if ( $b instanceof
Blob ) {
727 if (
$s instanceof
Blob ) {
728 return "x'" . bin2hex(
$s->fetch() ) .
"'";
729 } elseif ( is_bool(
$s ) ) {
730 return (
string)(int)
$s;
731 } elseif ( is_int(
$s ) ) {
733 } elseif ( strpos( (
string)
$s,
"\0" ) !==
false ) {
743 $this->queryLogger->debug(
745 ': Quoting value containing null byte. ' .
746 'For consistency all binary data should have been ' .
747 'first processed with self::encodeBlob()'
749 return "x'" . bin2hex( (
string)
$s ) .
"'";
751 return $this->getBindingHandle()->quote( (
string)
$s );
762 $function = array_shift(
$args );
764 return $function( ...
$args );
772 $s = parent::replaceVars(
$s );
773 if ( preg_match(
'/^\s*(CREATE|ALTER) TABLE/i',
$s ) ) {
777 $s = preg_replace(
'/\b(var)?binary(\(\d+\))/i',
'BLOB',
$s );
779 $s = preg_replace(
'/\b(un)?signed\b/i',
'',
$s );
781 $s = preg_replace(
'/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i',
'INTEGER',
$s );
784 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
789 $s = preg_replace(
'/\b(var)?char\s*\(.*?\)/i',
'TEXT',
$s );
791 $s = preg_replace(
'/\b(tiny|medium|long)text\b/i',
'TEXT',
$s );
793 $s = preg_replace(
'/\b(tiny|small|medium|long|)blob\b/i',
'BLOB',
$s );
795 $s = preg_replace(
'/\bbool(ean)?\b/i',
'INTEGER',
$s );
797 $s = preg_replace(
'/\b(datetime|timestamp)\b/i',
'TEXT',
$s );
799 $s = preg_replace(
'/\benum\s*\([^)]*\)/i',
'TEXT',
$s );
801 $s = preg_replace(
'/\bbinary\b/i',
'',
$s );
803 $s = preg_replace(
'/\bauto_increment\b/i',
'AUTOINCREMENT',
$s );
805 $s = preg_replace(
'/\)[^);]*(;?)\s*$/',
')\1',
$s );
807 $s = preg_replace(
'/primary key (.*?) autoincrement/i',
'PRIMARY KEY AUTOINCREMENT $1',
$s );
808 } elseif ( preg_match(
'/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i',
$s ) ) {
810 $s = preg_replace(
'/\(\d+\)/',
'',
$s );
812 $s = preg_replace(
'/\bfulltext\b/i',
'',
$s );
813 } elseif ( preg_match(
'/^\s*DROP INDEX/i',
$s ) ) {
815 $s = preg_replace(
'/\sON\s+[^\s]*/i',
'',
$s );
816 } elseif ( preg_match(
'/^\s*INSERT IGNORE\b/i',
$s ) ) {
818 $s = preg_replace(
'/^\s*INSERT IGNORE\b/i',
'INSERT OR IGNORE',
$s );
829 public function doLock(
string $lockName,
string $method,
int $timeout ) {
833 $status->hasMessage(
'lockmanager-fail-openlock' )
835 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
838 return $status->isOK() ? microtime(
true ) :
null;
841 public function doUnlock(
string $lockName,
string $method ) {
846 $delim, $table, $field, $conds =
'', $join_conds = []
848 $fld =
"group_concat($field," . $this->addQuotes( $delim ) .
')';
850 return '(' . $this->selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
862 $oldName, $newName, $temporary =
false, $fname = __METHOD__
865 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
866 $this->addQuotes( $oldName ) .
" AND type='table'",
868 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
870 $obj =
$res->fetchObject();
872 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
874 $sqlCreateTable = $obj->sql;
875 $sqlCreateTable = preg_replace(
877 preg_quote( trim( $this->platform->addIdentifierQuotes( $oldName ),
'"' ),
'/' ) .
879 $this->platform->addIdentifierQuotes( $newName ),
884 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sqlCreateTable ) ) {
885 $this->queryLogger->debug(
886 "Table $oldName is virtual, can't create a temporary duplicate." );
888 $sqlCreateTable = str_replace(
890 'CREATE TEMPORARY TABLE',
900 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
904 $indexList = $this->query(
905 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) .
')',
907 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
909 foreach ( $indexList as $index ) {
910 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
914 if ( $index->unique ) {
915 $sqlIndex =
'CREATE UNIQUE INDEX';
917 $sqlIndex =
'CREATE INDEX';
920 $indexName = $newName .
'_' . $index->name;
921 $sqlIndex .=
' ' . $this->platform->addIdentifierQuotes( $indexName ) .
922 ' ON ' . $this->platform->addIdentifierQuotes( $newName );
924 $indexInfo = $this->query(
925 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) .
')',
927 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
930 foreach ( $indexInfo as $indexInfoRow ) {
931 $fields[$indexInfoRow->seqno] = $this->addQuotes( $indexInfoRow->name );
934 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
939 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
954 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
955 $result = $this->query(
956 "SELECT name FROM sqlite_master WHERE type = 'table'",
958 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
963 foreach ( $result as $table ) {
964 $vars = get_object_vars( $table );
965 $table = array_pop( $vars );
967 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
968 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
969 $endArray[] = $table;
977 public function dropTable( $table, $fname = __METHOD__ ) {
978 if ( !$this->tableExists( $table, $fname ) ) {
983 $sql =
"DROP TABLE " . $this->tableName( $table );
984 $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
990 $this->startAtomic( $fname );
993 foreach ( $tables as $table ) {
995 $sql =
"DELETE FROM " . $this->tableName( $table );
996 $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
998 $encSeqNames[] = $this->addQuotes( $this->tableName( $table,
'raw' ) );
1001 $encMasterTable = $this->platform->addIdentifierQuotes(
'sqlite_sequence' );
1003 "DELETE FROM $encMasterTable WHERE name IN(" . implode(
',', $encSeqNames ) .
")",
1005 self::QUERY_CHANGE_SCHEMA
1008 $this->endAtomic( $fname );
1012 parent::setTableAliases( $aliases );
1013 if ( $this->isOpen() ) {
1014 $this->attachDatabasesFromTableAliases();
1022 foreach ( $this->tableAliases as $params ) {
1024 $params[
'dbname'] !== $this->getDBname() &&
1025 !isset( $this->sessionAttachedDbs[$params[
'dbname']] )
1027 $this->attachDatabase( $params[
'dbname'],
false, __METHOD__ );
1028 $this->sessionAttachedDbs[$params[
'dbname']] =
true;
1038 $this->sessionAttachedDbs = [];
1040 $this->lockMgr =
null;
1042 $this->lockMgr = $this->makeLockManager();
1047 $this->lockMgr =
null;
1049 $this->lockMgr = $this->makeLockManager();
1056 return parent::getBindingHandle();
1063 class_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.