65 'synchronous' => [
'EXTRA',
'FULL',
'NORMAL',
'OFF' ],
67 'temp_store' => [
'FILE',
'MEMORY' ]
78 if ( isset( $params[
'dbFilePath'] ) ) {
79 $this->dbPath = $params[
'dbFilePath'];
80 if ( !isset( $params[
'dbname'] ) || $params[
'dbname'] ===
'' ) {
83 } elseif ( isset( $params[
'dbDirectory'] ) ) {
84 $this->dbDir = $params[
'dbDirectory'];
87 parent::__construct( $params );
89 $this->trxMode = strtoupper( $params[
'trxMode'] ??
'' );
92 if ( $lockDirectory !==
null ) {
95 'lockDirectory' => $lockDirectory
104 self::ATTR_DB_IS_FILE =>
true,
105 self::ATTR_DB_LEVEL_LOCKING =>
true
119 $p[
'dbFilePath'] = $filename;
121 $p[
'tablePrefix'] =
'';
136 $this->
close( __METHOD__ );
140 if ( $schema !==
null ) {
144 if ( $this->dbPath !==
null ) {
146 } elseif ( $this->dbDir !==
null ) {
153 if ( !self::isProcessMemoryPath(
$path ) && is_file(
$path ) && !is_readable(
$path ) ) {
155 } elseif ( !in_array( $this->trxMode, self::$VALID_TRX_MODES,
true ) ) {
160 if ( $this->
getFlag( self::DBO_PERSISTENT ) ) {
163 if ( $this->
getFlag( self::DBO_TRX ) || $this->
getFlag( self::DBO_DEFAULT ) ) {
164 $this->connLogger->warning(
165 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
169 $attributes[PDO::ATTR_PERSISTENT] =
true;
175 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
176 }
catch ( PDOException $e ) {
180 $this->currentDomain =
new DatabaseDomain( $db,
null, $tablePrefix );
183 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY;
185 $this->
query(
'PRAGMA case_sensitive_like = 1', __METHOD__,
$flags );
187 $pragmas = array_intersect_key( $this->connectionVariables, self::$VALID_PRAGMAS );
189 foreach ( $pragmas as $name => $value ) {
190 $allowed = self::$VALID_PRAGMAS[$name];
191 if ( in_array( $value, $allowed,
true ) ) {
192 $this->
query(
"PRAGMA $name = $value", __METHOD__,
$flags );
196 }
catch ( RuntimeException $e ) {
207 if ( !$this->cliMode ) {
208 $variables[
'temp_store'] =
'MEMORY';
227 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
228 return dirname( $this->dbPath ) .
'/locks';
229 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
230 return $this->dbDir .
'/locks';
256 } elseif ( self::isProcessMemoryPath( $dir ) ) {
259 __CLASS__ .
": cannot use process memory directory '$dir'"
261 } elseif ( !strlen( $dbName ) ) {
265 return "$dir/$dbName.sqlite";
273 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
276 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
281 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
290 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
298 static $cachedResult =
null;
299 if ( $cachedResult !==
null ) {
300 return $cachedResult;
302 $cachedResult =
false;
303 $table =
'dummy_search_test';
307 "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)",
309 IDatabase::QUERY_SILENCE_ERRORS
311 $cachedResult =
'FTS3';
313 $db->close( __METHOD__ );
315 return $cachedResult;
335 "ATTACH DATABASE $encFile AS $name",
337 self::QUERY_IGNORE_DBO_TRX
342 return parent::isWriteQuery( $sql,
$flags ) && !preg_match(
'/^(ATTACH|PRAGMA)\b/i', $sql );
346 return parent::isTransactableQuery( $sql ) && !in_array(
348 [
'ATTACH',
'PRAGMA' ],
359 if (
$res ===
false ) {
363 $this->lastAffectedRowCount =
$res->rowCount();
371 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
377 if ( $database ===
null ) {
379 $this->currentDomain->getDatabase(),
387 if ( $database !== $this->
getDBname() ) {
390 __CLASS__ .
": cannot change database (got '$database')"
404 public function tableName( $name, $format =
'quoted' ) {
406 if ( strpos( $name,
'sqlite_' ) === 0 ) {
410 return str_replace(
'"',
'', parent::tableName( $name, $format ) );
427 if ( !is_object( $this->conn ) ) {
428 return "Cannot return last error, no db connection";
430 $e = $this->conn->errorInfo();
439 if ( !is_object( $this->conn ) ) {
440 return "Cannot return last error, no db connection";
442 $info = $this->conn->errorInfo();
456 $tableRaw = $this->
tableName( $table,
'raw' );
457 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
461 $encTable = $this->
addQuotes( $tableRaw );
463 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
465 self::QUERY_IGNORE_DBO_TRX
468 return $res->numRows() ?
true :
false;
481 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
483 $res = $this->
query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
484 if ( !
$res ||
$res->numRows() == 0 ) {
488 foreach (
$res as $row ) {
489 $info[] = $row->name;
501 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
502 $row = $this->
selectRow(
'sqlite_master',
'*',
507 if ( !$row || !isset( $row->sql ) ) {
512 $indexPos = strpos( $row->sql,
'INDEX' );
513 if ( $indexPos ===
false ) {
516 $firstPart = substr( $row->sql, 0, $indexPos );
517 $options = explode(
' ', $firstPart );
519 return in_array(
'UNIQUE', $options );
524 foreach ( $options as $k => $v ) {
525 if ( is_numeric( $k ) && ( $v ===
'FOR UPDATE' || $v ===
'LOCK IN SHARE MODE' ) ) {
530 return parent::makeSelectOptions( $options );
538 $options = parent::makeUpdateOptionsArray( $options );
549 # SQLite uses OR IGNORE not just IGNORE
550 foreach ( $options as $k => $v ) {
551 if ( $v ==
'IGNORE' ) {
552 $options[$k] =
'OR IGNORE';
560 return [
'INSERT OR IGNORE INTO',
'' ];
563 protected function doReplace( $table, array $identityKey, array $rows, $fname ) {
567 $this->
query(
"REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples", $fname );
595 $glue = $all ?
' UNION ALL ' :
' UNION ';
597 return implode( $glue, $sqls );
636 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
643 return "[{{int:version-db-sqlite-url}} SQLite]";
650 if ( $this->version ===
null ) {
651 $this->version = $this->
getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
667 $sql =
'PRAGMA table_info(' . $this->
addQuotes( $tableName ) .
')';
668 $res = $this->
query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
669 foreach (
$res as $row ) {
670 if ( $row->name == $field ) {
679 if ( $this->trxMode !=
'' ) {
680 $this->
query(
"BEGIN {$this->trxMode}", $fname );
682 $this->
query(
'BEGIN', $fname );
699 return new Blob( $b );
707 if ( $b instanceof
Blob ) {
719 if (
$s instanceof
Blob ) {
720 return "x'" . bin2hex(
$s->fetch() ) .
"'";
721 } elseif ( is_bool(
$s ) ) {
722 return (
string)(int)
$s;
723 } elseif ( is_int(
$s ) ) {
725 } elseif ( strpos( (
string)
$s,
"\0" ) !==
false ) {
735 $this->queryLogger->debug(
737 ': Quoting value containing null byte. ' .
738 'For consistency all binary data should have been ' .
739 'first processed with self::encodeBlob()'
741 return "x'" . bin2hex( (
string)
$s ) .
"'";
749 $params = [ $input, $startPosition ];
750 if ( $length !==
null ) {
753 return 'SUBSTR(' . implode(
',', $params ) .
')';
762 return 'CAST ( ' . $field .
' AS TEXT )';
772 $function = array_shift(
$args );
774 return $function( ...
$args );
782 $s = parent::replaceVars(
$s );
783 if ( preg_match(
'/^\s*(CREATE|ALTER) TABLE/i',
$s ) ) {
787 $s = preg_replace(
'/\b(var)?binary(\(\d+\))/i',
'BLOB',
$s );
789 $s = preg_replace(
'/\b(un)?signed\b/i',
'',
$s );
791 $s = preg_replace(
'/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i',
'INTEGER',
$s );
794 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
799 $s = preg_replace(
'/\b(var)?char\s*\(.*?\)/i',
'TEXT',
$s );
801 $s = preg_replace(
'/\b(tiny|medium|long)text\b/i',
'TEXT',
$s );
803 $s = preg_replace(
'/\b(tiny|small|medium|long|)blob\b/i',
'BLOB',
$s );
805 $s = preg_replace(
'/\bbool(ean)?\b/i',
'INTEGER',
$s );
807 $s = preg_replace(
'/\b(datetime|timestamp)\b/i',
'TEXT',
$s );
809 $s = preg_replace(
'/\benum\s*\([^)]*\)/i',
'TEXT',
$s );
811 $s = preg_replace(
'/\bbinary\b/i',
'',
$s );
813 $s = preg_replace(
'/\bauto_increment\b/i',
'AUTOINCREMENT',
$s );
815 $s = preg_replace(
'/\)[^);]*(;?)\s*$/',
')\1',
$s );
817 $s = preg_replace(
'/primary key (.*?) autoincrement/i',
'PRIMARY KEY AUTOINCREMENT $1',
$s );
818 } elseif ( preg_match(
'/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i',
$s ) ) {
820 $s = preg_replace(
'/\(\d+\)/',
'',
$s );
822 $s = preg_replace(
'/\bfulltext\b/i',
'',
$s );
823 } elseif ( preg_match(
'/^\s*DROP INDEX/i',
$s ) ) {
825 $s = preg_replace(
'/\sON\s+[^\s]*/i',
'',
$s );
826 } elseif ( preg_match(
'/^\s*INSERT IGNORE\b/i',
$s ) ) {
828 $s = preg_replace(
'/^\s*INSERT IGNORE\b/i',
'INSERT OR IGNORE',
$s );
839 public function doLock(
string $lockName,
string $method,
int $timeout ) {
843 $status->hasMessage(
'lockmanager-fail-openlock' )
845 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
848 return $status->isOK() ? microtime(
true ) :
null;
851 public function doUnlock(
string $lockName,
string $method ) {
862 return '(' . implode(
') || (', $stringList ) .
')';
866 $delim, $table, $field, $conds =
'', $join_conds = []
868 $fld =
"group_concat($field," . $this->
addQuotes( $delim ) .
')';
870 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
890 $oldName, $newName, $temporary =
false, $fname = __METHOD__
892 $queryFlags = self::QUERY_PSEUDO_PERMANENT | self::QUERY_IGNORE_DBO_TRX;
895 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
896 $this->
addQuotes( $oldName ) .
" AND type='table'",
902 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
914 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
915 $this->queryLogger->debug(
916 "Table $oldName is virtual, can't create a temporary duplicate." );
918 $sql = str_replace(
'CREATE TABLE',
'CREATE TEMPORARY TABLE', $sql );
923 $res = $this->
query( $sql, $fname, $queryFlags );
926 $indexList = $this->
query(
927 'PRAGMA INDEX_LIST(' . $this->
addQuotes( $oldName ) .
')',
931 foreach ( $indexList as $index ) {
932 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
936 if ( $index->unique ) {
937 $sqlIndex =
'CREATE UNIQUE INDEX';
939 $sqlIndex =
'CREATE INDEX';
942 $indexName = $newName .
'_' . $index->name;
946 $indexInfo = $this->
query(
947 'PRAGMA INDEX_INFO(' . $this->
addQuotes( $index->name ) .
')',
952 foreach ( $indexInfo as $indexInfoRow ) {
953 $fields[$indexInfoRow->seqno] = $this->
addQuotes( $indexInfoRow->name );
956 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
958 $this->
query( $sqlIndex, __METHOD__ );
972 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
973 $result = $this->
query(
974 "SELECT name FROM sqlite_master WHERE type = 'table'",
976 self::QUERY_IGNORE_DBO_TRX
981 foreach ( $result as $table ) {
982 $vars = get_object_vars( $table );
983 $table = array_pop( $vars );
985 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
986 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
987 $endArray[] = $table;
995 public function dropTable( $table, $fname = __METHOD__ ) {
1001 $sql =
"DROP TABLE " . $this->
tableName( $table );
1002 $this->
query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
1011 foreach ( $tables as $table ) {
1013 $sql =
"DELETE FROM " . $this->
tableName( $table );
1014 $this->
query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
1021 "DELETE FROM $encMasterTable WHERE name IN(" . implode(
',', $encSeqNames ) .
")",
1023 self::QUERY_CHANGE_SCHEMA
1030 parent::setTableAliases( $aliases );
1040 foreach ( $this->tableAliases as $params ) {
1042 $params[
'dbname'] !== $this->
getDBname() &&
1043 !isset( $this->sessionAttachedDbs[$params[
'dbname']] )
1046 $this->sessionAttachedDbs[$params[
'dbname']] =
true;
1056 $this->sessionAttachedDbs = [];
1063 return parent::getBindingHandle();
1070class_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.