62 private $sessionAttachedDbs = [];
65 private const VALID_TRX_MODES = [
'',
'DEFERRED',
'IMMEDIATE',
'EXCLUSIVE' ];
68 private const VALID_PRAGMAS = [
70 'synchronous' => [
'EXTRA',
'FULL',
'NORMAL',
'OFF' ],
72 'temp_store' => [
'FILE',
'MEMORY' ],
74 'mmap_size' =>
'integer'
88 if ( isset( $params[
'dbFilePath'] ) ) {
89 $this->dbPath = $params[
'dbFilePath'];
90 if ( !isset( $params[
'dbname'] ) || $params[
'dbname'] ===
'' ) {
91 $params[
'dbname'] = self::generateDatabaseName( $this->dbPath );
93 } elseif ( isset( $params[
'dbDirectory'] ) ) {
94 $this->dbDir = $params[
'dbDirectory'];
97 parent::__construct( $params );
99 $this->trxMode = strtoupper( $params[
'trxMode'] ??
'' );
101 $this->lockMgr = $this->makeLockManager();
105 $this->currentDomain,
109 $params[
'topologyRole'],
117 self::ATTR_DB_IS_FILE =>
true,
118 self::ATTR_DB_LEVEL_LOCKING =>
true
132 $p[
'dbFilePath'] = $filename;
134 $p[
'tablePrefix'] =
'';
136 $db = MediaWikiServices::getInstance()->getDatabaseFactory()->create(
'sqlite', $p );
137 '@phan-var DatabaseSqlite $db';
149 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
150 $this->
close( __METHOD__ );
154 if ( $schema !==
null ) {
158 if ( $this->dbPath !==
null ) {
160 } elseif ( $this->dbDir !==
null ) {
167 if ( !self::isProcessMemoryPath(
$path ) && is_file(
$path ) && !is_readable(
$path ) ) {
169 } elseif ( !in_array( $this->trxMode, self::VALID_TRX_MODES,
true ) ) {
174 PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
178 PDO::ATTR_STRINGIFY_FETCHES =>
true
180 if ( $this->
getFlag( self::DBO_PERSISTENT ) ) {
183 if ( $this->
getFlag( self::DBO_TRX ) || $this->
getFlag( self::DBO_DEFAULT ) ) {
184 $this->logger->warning(
185 __METHOD__ .
": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
189 $attributes[PDO::ATTR_PERSISTENT] =
true;
195 $this->conn =
new PDO(
"sqlite:$path",
null,
null, $attributes );
196 }
catch ( PDOException $e ) {
200 $this->currentDomain =
new DatabaseDomain( $db,
null, $tablePrefix );
201 $this->platform->setPrefix( $tablePrefix );
204 $flags = self::QUERY_CHANGE_TRX | self::QUERY_NO_RETRY;
206 $this->
query(
'PRAGMA case_sensitive_like = 1', __METHOD__, $flags );
208 $pragmas = array_intersect_key( $this->connectionVariables, self::VALID_PRAGMAS );
209 $pragmas += $this->getDefaultPragmas();
210 foreach ( $pragmas as $name => $value ) {
211 $allowed = self::VALID_PRAGMAS[$name];
213 ( is_array( $allowed ) && in_array( $value, $allowed,
true ) ) ||
214 ( is_string( $allowed ) && gettype( $value ) === $allowed )
216 $this->
query(
"PRAGMA $name = $value", __METHOD__, $flags );
219 $this->attachDatabasesFromTableAliases();
220 }
catch ( RuntimeException $e ) {
228 private function getDefaultPragmas() {
231 if ( !$this->cliMode ) {
232 $variables[
'temp_store'] =
'MEMORY';
251 if ( $this->dbPath !==
null && !self::isProcessMemoryPath( $this->dbPath ) ) {
252 return dirname( $this->dbPath ) .
'/locks';
253 } elseif ( $this->dbDir !==
null && !self::isProcessMemoryPath( $this->dbDir ) ) {
254 return $this->dbDir .
'/locks';
267 if ( $lockDirectory !==
null ) {
270 'lockDirectory' => $lockDirectory,
284 $this->lockMgr =
null;
299 } elseif ( self::isProcessMemoryPath( $dir ) ) {
302 __CLASS__ .
": cannot use process memory directory '$dir'"
304 } elseif ( !strlen( $dbName ) ) {
308 return "$dir/$dbName.sqlite";
315 private static function generateDatabaseName(
$path ) {
316 if ( preg_match(
'/^(:memory:$|file::memory:)/',
$path ) ) {
319 } elseif ( preg_match(
'/^file::([^?]+)\?mode=memory(&|$)/',
$path, $m ) ) {
324 return preg_replace(
'/\.sqlite\d?$/',
'', basename(
$path ) );
332 private static function isProcessMemoryPath(
$path ) {
333 return preg_match(
'/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/',
$path );
341 static $cachedResult =
null;
342 if ( $cachedResult !==
null ) {
343 return $cachedResult;
345 $cachedResult =
false;
346 $table =
'dummy_search_test';
348 $db = self::newStandaloneInstance(
':memory:' );
350 "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)",
352 IDatabase::QUERY_SILENCE_ERRORS
354 $cachedResult =
'FTS3';
356 $db->close( __METHOD__ );
358 return $cachedResult;
374 $file = is_string(
$file ) ?
$file : self::generateFileName( $this->dbDir, $name );
375 $encFile = $this->addQuotes(
$file );
378 "ATTACH DATABASE $encFile AS $name",
380 self::QUERY_CHANGE_TRX
385 $conn = $this->getBindingHandle();
387 $res = $conn->query( $sql );
388 $this->lastAffectedRowCount =
$res ?
$res->rowCount() : 0;
402 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
408 if ( $database ===
null ) {
410 $this->currentDomain->getDatabase(),
419 if ( $database !== $this->getDBname() ) {
422 __CLASS__ .
": cannot change database (got '$database')"
427 $this->currentDomain = $domain;
440 return intval( $this->getBindingHandle()->lastInsertId() );
447 if ( is_object( $this->conn ) ) {
448 $e = $this->conn->errorInfo();
450 return $e[2] ?? $this->lastConnectError;
453 return 'No database connection';
460 if ( is_object( $this->conn ) ) {
461 $info = $this->conn->errorInfo();
463 if ( isset( $info[1] ) ) {
475 return $this->lastAffectedRowCount;
479 $tableRaw = $this->tableName( $table,
'raw' );
480 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
484 $encTable = $this->addQuotes( $tableRaw );
486 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable",
488 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
491 return $res->numRows() ?
true :
false;
504 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
505 $sql =
'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) .
')';
506 $res = $this->query( $sql, $fname, self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE );
507 if ( !
$res ||
$res->numRows() == 0 ) {
511 foreach (
$res as $row ) {
512 $info[] = $row->name;
524 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
525 $row = $this->selectRow(
'sqlite_master',
'*',
528 'name' => $this->indexName( $index ),
530 if ( !$row || !isset( $row->sql ) ) {
535 $indexPos = strpos( $row->sql,
'INDEX' );
536 if ( $indexPos ===
false ) {
539 $firstPart = substr( $row->sql, 0, $indexPos );
540 $options = explode(
' ', $firstPart );
542 return in_array(
'UNIQUE', $options );
545 protected function doReplace( $table, array $identityKey, array $rows, $fname ) {
546 $encTable = $this->tableName( $table );
547 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
550 "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples",
552 self::QUERY_CHANGE_ROWS
572 return $this->lastErrno() == 5;
579 return $this->lastErrno() == 8;
595 $this->assertHasConnectionHandle();
597 $path = $this->getDbFilePath();
599 return ( !self::isProcessMemoryPath(
$path ) && !is_writable(
$path ) );
606 return "[{{int:version-db-sqlite-url}} SQLite]";
613 if ( $this->version ===
null ) {
614 $this->version = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
617 return $this->version;
629 $tableRaw = $this->tableName( $table,
'raw' );
631 'PRAGMA table_info(' . $this->addQuotes( $tableRaw ) .
')',
633 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
635 foreach (
$res as $row ) {
636 if ( $row->name == $field ) {
645 if ( $this->trxMode !=
'' ) {
646 $this->query(
"BEGIN {$this->trxMode}", $fname, self::QUERY_CHANGE_TRX );
648 $this->query(
'BEGIN', $fname, self::QUERY_CHANGE_TRX );
657 return substr( $this->addQuotes( $s ), 1, -1 );
665 return new Blob( $b );
673 if ( $b instanceof
Blob ) {
690 if ( $s instanceof
Blob ) {
691 return "x'" . bin2hex( $s->fetch() ) .
"'";
692 } elseif ( is_bool( $s ) ) {
693 return (
string)(int)$s;
694 } elseif ( is_int( $s ) ) {
696 } elseif ( strpos( (
string)$s,
"\0" ) !==
false ) {
706 $this->logger->debug(
708 ': Quoting value containing null byte. ' .
709 'For consistency all binary data should have been ' .
710 'first processed with self::encodeBlob()'
712 return "x'" . bin2hex( (
string)$s ) .
"'";
714 return $this->getBindingHandle()->quote( (
string)$s );
723 public function doLock(
string $lockName,
string $method,
int $timeout ) {
724 $status = $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout );
727 $status->hasMessage(
'lockmanager-fail-openlock' )
729 throw new DBError( $this,
"Cannot create directory \"{$this->getLockFileDirectory()}\"" );
732 return $status->isOK() ? microtime(
true ) :
null;
735 public function doUnlock(
string $lockName,
string $method ) {
736 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
748 $oldName, $newName, $temporary =
false, $fname = __METHOD__
751 "SELECT sql FROM sqlite_master WHERE tbl_name=" .
752 $this->addQuotes( $oldName ) .
" AND type='table'",
754 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
756 $obj =
$res->fetchObject();
758 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
760 $sqlCreateTable = $obj->sql;
761 $sqlCreateTable = preg_replace(
763 preg_quote( trim( $this->platform->addIdentifierQuotes( $oldName ),
'"' ),
'/' ) .
765 $this->platform->addIdentifierQuotes( $newName ),
770 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sqlCreateTable ) ) {
771 $this->logger->debug(
772 "Table $oldName is virtual, can't create a temporary duplicate." );
774 $sqlCreateTable = str_replace(
776 'CREATE TEMPORARY TABLE',
785 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
789 $indexList = $this->query(
790 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) .
')',
792 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
794 foreach ( $indexList as $index ) {
795 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
799 if ( $index->unique ) {
800 $sqlIndex =
'CREATE UNIQUE INDEX';
802 $sqlIndex =
'CREATE INDEX';
805 $indexName = $newName .
'_' . $index->name;
806 $sqlIndex .=
' ' . $this->platform->addIdentifierQuotes( $indexName ) .
807 ' ON ' . $this->platform->addIdentifierQuotes( $newName );
809 $indexInfo = $this->query(
810 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) .
')',
812 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
815 foreach ( $indexInfo as $indexInfoRow ) {
816 $fields[$indexInfoRow->seqno] = $this->addQuotes( $indexInfoRow->name );
819 $sqlIndex .=
'(' . implode(
',', $fields ) .
')';
824 self::QUERY_CHANGE_SCHEMA | self::QUERY_PSEUDO_PERMANENT
839 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
840 $result = $this->query(
841 "SELECT name FROM sqlite_master WHERE type = 'table'",
843 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
848 foreach ( $result as $table ) {
849 $vars = get_object_vars( $table );
850 $table = array_pop( $vars );
852 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
853 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
854 $endArray[] = $table;
863 $this->startAtomic( $fname );
866 foreach ( $tables as $table ) {
868 $sql =
"DELETE FROM " . $this->tableName( $table );
869 $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
871 $encSeqNames[] = $this->addQuotes( $this->tableName( $table,
'raw' ) );
874 $encMasterTable = $this->platform->addIdentifierQuotes(
'sqlite_sequence' );
876 "DELETE FROM $encMasterTable WHERE name IN(" . implode(
',', $encSeqNames ) .
")",
878 self::QUERY_CHANGE_SCHEMA
881 $this->endAtomic( $fname );
885 parent::setTableAliases( $aliases );
886 if ( $this->isOpen() ) {
887 $this->attachDatabasesFromTableAliases();
894 private function attachDatabasesFromTableAliases() {
895 foreach ( $this->platform->getTableAliases() as $params ) {
897 $params[
'dbname'] !== $this->getDBname() &&
898 !isset( $this->sessionAttachedDbs[$params[
'dbname']] )
900 $this->attachDatabase( $params[
'dbname'],
false, __METHOD__ );
901 $this->sessionAttachedDbs[$params[
'dbname']] =
true;
911 $this->sessionAttachedDbs = [];
913 $this->lockMgr =
null;
915 $this->lockMgr = $this->makeLockManager();
920 $this->lockMgr =
null;
922 $this->lockMgr = $this->makeLockManager();
929 return parent::getBindingHandle();
936class_alias( DatabaseSqlite::class,
'DatabaseSqlite' );
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.