Go to the documentation of this file.
71 if ( isset( $p[
'dbFilePath'] ) ) {
72 $this->dbPath = $p[
'dbFilePath'];
73 if ( !strlen( $p[
'dbname'] ) ) {
76 } elseif ( isset( $p[
'dbDirectory'] ) ) {
77 $this->dbDir = $p[
'dbDirectory'];
80 parent::__construct( $p );
82 $this->trxMode = strtoupper( $p[
'trxMode'] ??
'' );
85 if ( $lockDirectory !==
null ) {
88 'lockDirectory' => $lockDirectory
96 return [ self::ATTR_DB_LEVEL_LOCKING =>
true ];
109 $p[
'dbFilePath'] = $filename;
111 $p[
'tablePrefix'] =
'';
130 if ( $schema !==
null ) {
134 if ( $this->dbPath !==
null ) {
136 } elseif ( $this->dbDir !==
null ) {
144 !self::isProcessMemoryPath(
$path ) &&
145 file_exists(
$path ) &&
146 !is_readable(
$path )
149 } elseif ( !in_array( $this->trxMode, self::$VALID_TRX_MODES,
true ) ) {
158 $this->connLogger->warning(
159 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
163 $attributes[PDO::ATTR_PERSISTENT] =
true;
169 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
170 }
catch ( PDOException $e ) {
174 $this->currentDomain =
new DatabaseDomain( $dbName,
null, $tablePrefix );
177 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY;
179 $this->
query(
'PRAGMA case_sensitive_like = 1', __METHOD__,
$flags );
181 $sync = $this->connectionVariables[
'synchronous'] ??
null;
182 if ( in_array( $sync, [
'EXTRA',
'FULL',
'NORMAL',
'OFF' ],
true ) ) {
183 $this->
query(
"PRAGMA synchronous = $sync", __METHOD__,
$flags );
186 }
catch ( Exception $e ) {
204 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
205 return dirname( $this->dbPath ) .
'/locks';
206 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
207 return $this->dbDir .
'/locks';
233 } elseif ( self::isProcessMemoryPath( $dir ) ) {
236 __CLASS__ .
": cannot use process memory directory '$dir'"
238 } elseif ( !strlen( $dbName ) ) {
242 return "$dir/$dbName.sqlite";
250 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
253 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
258 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
267 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
275 static $cachedResult =
null;
276 if ( $cachedResult !==
null ) {
277 return $cachedResult;
279 $cachedResult =
false;
280 $table =
'dummy_search_test';
283 if ( $db->query(
"CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__,
true ) ) {
284 $cachedResult =
'FTS3';
288 return $cachedResult;
308 "ATTACH DATABASE $encFile AS $name",
310 self::QUERY_IGNORE_DBO_TRX
315 return parent::isWriteQuery( $sql ) && !preg_match(
'/^(ATTACH|PRAGMA)\b/i', $sql );
319 return parent::isTransactableQuery( $sql ) && !in_array(
321 [
'ATTACH',
'PRAGMA' ],
334 if (
$res ===
false ) {
339 $this->lastAffectedRowCount = $resource->rowCount();
361 $cur = current( $resource );
362 if ( is_array( $cur ) ) {
365 foreach ( $cur as $k => $v ) {
366 if ( !is_numeric( $k ) ) {
383 $cur = current( $resource );
384 if ( is_array( $cur ) ) {
403 return is_array( $resource ) ? count( $resource ) : 0;
412 if ( is_array( $resource ) && count( $resource ) > 0 ) {
414 return count( $resource[0] ) / 2;
428 if ( is_array( $resource ) ) {
429 $keys = array_keys( $resource[0] );
441 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
447 if ( $database ===
null ) {
449 $this->currentDomain->getDatabase(),
457 if ( $database !== $this->
getDBname() ) {
460 __CLASS__ .
": cannot change database (got '$database')"
476 if ( strpos( $name,
'sqlite_' ) === 0 ) {
480 return str_replace(
'"',
'', parent::tableName( $name, $format ) );
501 for ( $i = 0; $i < $row; $i++ ) {
511 if ( !is_object( $this->conn ) ) {
512 return "Cannot return last error, no db connection";
514 $e = $this->conn->errorInfo();
523 if ( !is_object( $this->conn ) ) {
524 return "Cannot return last error, no db connection";
526 $info = $this->conn->errorInfo();
540 $tableRaw = $this->
tableName( $table,
'raw' );
541 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
545 $encTable = $this->
addQuotes( $tableRaw );
547 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
549 self::QUERY_IGNORE_DBO_TRX
552 return $res->numRows() ?
true :
false;
565 function indexInfo( $table, $index, $fname = __METHOD__ ) {
567 $res = $this->
query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX );
568 if ( !
$res ||
$res->numRows() == 0 ) {
572 foreach (
$res as $row ) {
573 $info[] = $row->name;
586 $row = $this->
selectRow(
'sqlite_master',
'*',
591 if ( !$row || !isset( $row->sql ) ) {
596 $indexPos = strpos( $row->sql,
'INDEX' );
597 if ( $indexPos ===
false ) {
600 $firstPart = substr( $row->sql, 0, $indexPos );
601 $options = explode(
' ', $firstPart );
603 return in_array(
'UNIQUE', $options );
608 foreach ( $options as $k => $v ) {
609 if ( is_numeric( $k ) && ( $v ===
'FOR UPDATE' || $v ===
'LOCK IN SHARE MODE' ) ) {
614 return parent::makeSelectOptions( $options );
622 $options = parent::makeUpdateOptionsArray( $options );
633 # SQLite uses OR IGNORE not just IGNORE
634 foreach ( $options as $k => $v ) {
635 if ( $v ==
'IGNORE' ) {
636 $options[$k] =
'OR IGNORE';
650 return parent::makeInsertOptions( $options );
661 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
662 if ( !count( $a ) ) {
666 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
667 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
670 $this->
startAtomic( $fname, self::ATOMIC_CANCELABLE );
671 foreach ( $a as $v ) {
672 parent::insert( $table, $v,
"$fname/multi-row", $options );
676 }
catch ( Exception $e ) {
682 parent::insert( $table, $a,
"$fname/single-row", $options );
694 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
695 if ( !count( $rows ) ) {
699 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
700 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
703 $this->
startAtomic( $fname, self::ATOMIC_CANCELABLE );
704 foreach ( $rows as $v ) {
709 }
catch ( Exception $e ) {
744 $glue = $all ?
' UNION ALL ' :
' UNION ';
746 return implode( $glue, $sqls );
780 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
787 return "[{{int:version-db-sqlite-url}} SQLite]";
809 $sql =
'PRAGMA table_info(' . $this->
addQuotes( $tableName ) .
')';
810 $res = $this->
query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
811 foreach (
$res as $row ) {
812 if ( $row->name == $field ) {
821 if ( $this->trxMode !=
'' ) {
822 $this->
query(
"BEGIN {$this->trxMode}", $fname );
824 $this->
query(
'BEGIN', $fname );
841 return new Blob( $b );
849 if ( $b instanceof
Blob ) {
861 if (
$s instanceof
Blob ) {
862 return "x'" . bin2hex(
$s->fetch() ) .
"'";
863 } elseif ( is_bool(
$s ) ) {
865 } elseif ( strpos( (
string)
$s,
"\0" ) !==
false ) {
875 $this->queryLogger->debug(
877 ': Quoting value containing null byte. ' .
878 'For consistency all binary data should have been ' .
879 'first processed with self::encodeBlob()'
881 return "x'" . bin2hex( (
string)
$s ) .
"'";
889 $params = [ $input, $startPosition ];
890 if ( $length !==
null ) {
893 return 'SUBSTR(' . implode(
',', $params ) .
')';
902 return 'CAST ( ' . $field .
' AS TEXT )';
911 $args = func_get_args();
912 $function = array_shift(
$args );
914 return $function( ...
$args );
922 $s = parent::replaceVars(
$s );
923 if ( preg_match(
'/^\s*(CREATE|ALTER) TABLE/i',
$s ) ) {
927 $s = preg_replace(
'/\b(var)?binary(\(\d+\))/i',
'BLOB',
$s );
929 $s = preg_replace(
'/\b(un)?signed\b/i',
'',
$s );
931 $s = preg_replace(
'/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i',
'INTEGER',
$s );
934 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
939 $s = preg_replace(
'/\b(var)?char\s*\(.*?\)/i',
'TEXT',
$s );
941 $s = preg_replace(
'/\b(tiny|medium|long)text\b/i',
'TEXT',
$s );
943 $s = preg_replace(
'/\b(tiny|small|medium|long|)blob\b/i',
'BLOB',
$s );
945 $s = preg_replace(
'/\bbool(ean)?\b/i',
'INTEGER',
$s );
947 $s = preg_replace(
'/\b(datetime|timestamp)\b/i',
'TEXT',
$s );
949 $s = preg_replace(
'/\benum\s*\([^)]*\)/i',
'TEXT',
$s );
951 $s = preg_replace(
'/\bbinary\b/i',
'',
$s );
953 $s = preg_replace(
'/\bauto_increment\b/i',
'AUTOINCREMENT',
$s );
955 $s = preg_replace(
'/\)[^);]*(;?)\s*$/',
')\1',
$s );
957 $s = preg_replace(
'/primary key (.*?) autoincrement/i',
'PRIMARY KEY AUTOINCREMENT $1',
$s );
958 } elseif ( preg_match(
'/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i',
$s ) ) {
960 $s = preg_replace(
'/\(\d+\)/',
'',
$s );
962 $s = preg_replace(
'/\bfulltext\b/i',
'',
$s );
963 } elseif ( preg_match(
'/^\s*DROP INDEX/i',
$s ) ) {
965 $s = preg_replace(
'/\sON\s+[^\s]*/i',
'',
$s );
966 } elseif ( preg_match(
'/^\s*INSERT IGNORE\b/i',
$s ) ) {
968 $s = preg_replace(
'/^\s*INSERT IGNORE\b/i',
'INSERT OR IGNORE',
$s );
974 public function lock( $lockName, $method, $timeout = 5 ) {
978 $status->hasMessage(
'lockmanager-fail-openlock' )
980 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
986 public function unlock( $lockName, $method ) {
997 return '(' . implode(
') || (', $stringList ) .
')';
1001 $delim, $table, $field, $conds =
'', $join_conds = []
1003 $fld =
"group_concat($field," . $this->
addQuotes( $delim ) .
')';
1005 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1017 $res = $this->
query(
"SELECT sql FROM sqlite_master WHERE tbl_name=" .
1018 $this->
addQuotes( $oldName ) .
" AND type='table'", $fname );
1021 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
1024 $sql = preg_replace(
1033 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1034 $this->queryLogger->debug(
1035 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1037 $sql = str_replace(
'CREATE TABLE',
'CREATE TEMPORARY TABLE', $sql );
1041 $res = $this->
query( $sql, $fname, self::QUERY_PSEUDO_PERMANENT );
1044 $indexList = $this->
query(
'PRAGMA INDEX_LIST(' . $this->
addQuotes( $oldName ) .
')' );
1045 foreach ( $indexList as $index ) {
1046 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
1050 if ( $index->unique ) {
1051 $sql =
'CREATE UNIQUE INDEX';
1053 $sql =
'CREATE INDEX';
1056 $indexName = $newName .
'_' . $index->name;
1057 $sql .=
' ' . $indexName .
' ON ' . $newName;
1059 $indexInfo = $this->
query(
'PRAGMA INDEX_INFO(' . $this->
addQuotes( $index->name ) .
')' );
1061 foreach ( $indexInfo as $indexInfoRow ) {
1062 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
1065 $sql .=
'(' . implode(
',', $fields ) .
')';
1067 $this->
query( $sql );
1090 foreach ( $result as $table ) {
1091 $vars = get_object_vars( $table );
1092 $table = array_pop( $vars );
1094 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1095 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
1096 $endArray[] = $table;
1112 public function dropTable( $tableName, $fName = __METHOD__ ) {
1113 if ( !$this->
tableExists( $tableName, $fName ) ) {
1116 $sql =
"DROP TABLE " . $this->
tableName( $tableName );
1118 return $this->
query( $sql, $fName, self::QUERY_IGNORE_DBO_TRX );
1122 parent::setTableAliases( $aliases );
1132 foreach ( $this->tableAliases as $params ) {
1134 $params[
'dbname'] !== $this->
getDBname() &&
1135 !isset( $this->sessionAttachedDbs[$params[
'dbname']] )
1138 $this->sessionAttachedDbs[$params[
'dbname']] =
true;
1147 "DELETE FROM $encTable WHERE name = $encName",
1149 self::QUERY_IGNORE_DBO_TRX
1158 $this->sessionAttachedDbs = [];
1165 return parent::getBindingHandle();
1172 class_alias( DatabaseSqlite::class,
'DatabaseSqlite' );
Class for handling resource locking.
Simple version of LockManager based on using FS lock files.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Simple version of LockManager that only does lock reference counting.
Class to handle database/schema/prefix specifications for IDatabase.