3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 namespace Wikimedia\Rdbms
;
38 class DatabaseSqlite
extends Database
{
39 /** @var string|null Directory for SQLite database files listed under their DB name */
41 /** @var string|null Explicit path for the SQLite database file */
43 /** @var string Transaction mode */
46 /** @var int The number of rows affected as an integer */
47 protected $lastAffectedRowCount;
49 protected $lastResultHandle;
54 /** @var FSLockManager (hopefully on the same server as the DB) */
57 /** @var array List of shared database already attached to this connection */
58 private $sessionAttachedDbs = [];
60 /** @var string[] See https://www.sqlite.org/lang_transaction.html */
61 private static $VALID_TRX_MODES = [ '', 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ];
64 * Additional params include:
65 * - dbDirectory : directory containing the DB and the lock file directory
66 * - dbFilePath : use this to force the path of the DB file
67 * - trxMode : one of (deferred, immediate, exclusive)
70 public function __construct( array $p ) {
71 if ( isset( $p['dbFilePath'] ) ) {
72 $this->dbPath
= $p['dbFilePath'];
73 if ( !strlen( $p['dbname'] ) ) {
74 $p['dbname'] = self
::generateDatabaseName( $this->dbPath
);
76 } elseif ( isset( $p['dbDirectory'] ) ) {
77 $this->dbDir
= $p['dbDirectory'];
80 parent
::__construct( $p );
82 $this->trxMode
= strtoupper( $p['trxMode'] ??
'' );
84 $lockDirectory = $this->getLockFileDirectory();
85 if ( $lockDirectory !== null ) {
86 $this->lockMgr
= new FSLockManager( [
87 'domain' => $this->getDomainID(),
88 'lockDirectory' => $lockDirectory
91 $this->lockMgr
= new NullLockManager( [ 'domain' => $this->getDomainID() ] );
95 protected static function getAttributes() {
96 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
100 * @param string $filename
101 * @param array $p Options map; supports:
102 * - flags : (same as __construct counterpart)
103 * - trxMode : (same as __construct counterpart)
104 * - dbDirectory : (same as __construct counterpart)
105 * @return DatabaseSqlite
108 public static function newStandaloneInstance( $filename, array $p = [] ) {
109 $p['dbFilePath'] = $filename;
111 $p['tablePrefix'] = '';
112 /** @var DatabaseSqlite $db */
113 $db = Database
::factory( 'sqlite', $p );
121 public function getType() {
125 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
128 // Note that for SQLite, $server, $user, and $pass are ignored
130 if ( $schema !== null ) {
131 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
134 if ( $this->dbPath
!== null ) {
135 $path = $this->dbPath
;
136 } elseif ( $this->dbDir
!== null ) {
137 $path = self
::generateFileName( $this->dbDir
, $dbName );
139 throw $this->newExceptionAfterConnectError( "DB path or directory required" );
142 // Check if the database file already exists but is non-readable
144 !self
::isProcessMemoryPath( $path ) &&
145 file_exists( $path ) &&
146 !is_readable( $path )
148 throw $this->newExceptionAfterConnectError( 'SQLite database file is not readable' );
149 } elseif ( !in_array( $this->trxMode
, self
::$VALID_TRX_MODES, true ) ) {
150 throw $this->newExceptionAfterConnectError( "Got mode '{$this->trxMode}' for BEGIN" );
154 if ( $this->getFlag( self
::DBO_PERSISTENT
) ) {
155 // Persistent connections can avoid some schema index reading overhead.
156 // On the other hand, they can cause horrible contention with DBO_TRX.
157 if ( $this->getFlag( self
::DBO_TRX
) ||
$this->getFlag( self
::DBO_DEFAULT
) ) {
158 $this->connLogger
->warning(
159 __METHOD__
. ": ignoring DBO_PERSISTENT due to DBO_TRX or DBO_DEFAULT",
160 $this->getLogContext()
163 $attributes[PDO
::ATTR_PERSISTENT
] = true;
168 // Open the database file, creating it if it does not yet exist
169 $this->conn
= new PDO( "sqlite:$path", null, null, $attributes );
170 } catch ( PDOException
$e ) {
171 throw $this->newExceptionAfterConnectError( $e->getMessage() );
174 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
177 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
178 // Enforce LIKE to be case sensitive, just like MySQL
179 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
180 // Apply optimizations or requirements regarding fsync() usage
181 $sync = $this->connectionVariables
['synchronous'] ??
null;
182 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
183 $this->query( "PRAGMA synchronous = $sync", __METHOD__
, $flags );
185 $this->attachDatabasesFromTableAliases();
186 } catch ( Exception
$e ) {
187 throw $this->newExceptionAfterConnectError( $e->getMessage() );
192 * @return string|null SQLite DB file path
193 * @throws DBUnexpectedError
196 public function getDbFilePath() {
197 return $this->dbPath ?? self
::generateFileName( $this->dbDir
, $this->getDBname() );
201 * @return string|null Lock file directory
203 public function getLockFileDirectory() {
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';
214 * Does not actually close the connection, just destroys the reference for GC to do its work
217 protected function closeConnection() {
224 * Generates a database file name. Explicitly public for installer.
225 * @param string $dir Directory where database resides
226 * @param string|bool $dbName Database name (or false from Database::factory, validated here)
228 * @throws DBUnexpectedError
230 public static function generateFileName( $dir, $dbName ) {
232 throw new DBUnexpectedError( null, __CLASS__
. ": no DB directory specified" );
233 } elseif ( self
::isProcessMemoryPath( $dir ) ) {
234 throw new DBUnexpectedError(
236 __CLASS__
. ": cannot use process memory directory '$dir'"
238 } elseif ( !strlen( $dbName ) ) {
239 throw new DBUnexpectedError( null, __CLASS__
. ": no DB name specified" );
242 return "$dir/$dbName.sqlite";
246 * @param string $path
249 private static function generateDatabaseName( $path ) {
250 if ( preg_match( '/^(:memory:$|file::memory:)/', $path ) ) {
251 // E.g. "file::memory:?cache=shared" => ":memory":
253 } elseif ( preg_match( '/^file::([^?]+)\?mode=memory(&|$)/', $path, $m ) ) {
254 // E.g. "file:memdb1?mode=memory" => ":memdb1:"
257 // E.g. "/home/.../some_db.sqlite3" => "some_db"
258 return preg_replace( '/\.sqlite\d?$/', '', basename( $path ) );
263 * @param string $path
266 private static function isProcessMemoryPath( $path ) {
267 return preg_match( '/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/', $path );
271 * Returns version of currently supported SQLite fulltext search module or false if none present.
274 static function getFulltextSearchModule() {
275 static $cachedResult = null;
276 if ( $cachedResult !== null ) {
277 return $cachedResult;
279 $cachedResult = false;
280 $table = 'dummy_search_test';
282 $db = self
::newStandaloneInstance( ':memory:' );
283 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
284 $cachedResult = 'FTS3';
288 return $cachedResult;
292 * Attaches external database to the connection handle
294 * @see https://sqlite.org/lang_attach.html
296 * @param string $name Database name to be used in queries like
297 * SELECT foo FROM dbname.table
298 * @param bool|string $file Database file name. If omitted, will be generated
299 * using $name and configured data directory
300 * @param string $fname Calling function name
301 * @return IResultWrapper
303 public function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
304 $file = is_string( $file ) ?
$file : self
::generateFileName( $this->dbDir
, $name );
305 $encFile = $this->addQuotes( $file );
308 "ATTACH DATABASE $encFile AS $name",
310 self
::QUERY_IGNORE_DBO_TRX
314 protected function isWriteQuery( $sql ) {
315 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
318 protected function isTransactableQuery( $sql ) {
319 return parent
::isTransactableQuery( $sql ) && !in_array(
320 $this->getQueryVerb( $sql ),
321 [ 'ATTACH', 'PRAGMA' ],
327 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
330 * @return bool|IResultWrapper
332 protected function doQuery( $sql ) {
333 $res = $this->getBindingHandle()->query( $sql );
334 if ( $res === false ) {
338 $resource = ResultWrapper
::unwrap( $res );
339 $this->lastAffectedRowCount
= $resource->rowCount();
340 $res = new ResultWrapper( $this, $resource->fetchAll() );
346 * @param IResultWrapper|mixed $res
348 function freeResult( $res ) {
349 if ( $res instanceof ResultWrapper
) {
355 * @param IResultWrapper|array $res
356 * @return stdClass|bool
358 function fetchObject( $res ) {
359 $resource =& ResultWrapper
::unwrap( $res );
361 $cur = current( $resource );
362 if ( is_array( $cur ) ) {
365 foreach ( $cur as $k => $v ) {
366 if ( !is_numeric( $k ) ) {
378 * @param IResultWrapper|mixed $res
381 function fetchRow( $res ) {
382 $resource =& ResultWrapper
::unwrap( $res );
383 $cur = current( $resource );
384 if ( is_array( $cur ) ) {
394 * The PDO::Statement class implements the array interface so count() will work
396 * @param IResultWrapper|array|false $res
399 function numRows( $res ) {
400 // false does not implement Countable
401 $resource = ResultWrapper
::unwrap( $res );
403 return is_array( $resource ) ?
count( $resource ) : 0;
407 * @param IResultWrapper $res
410 function numFields( $res ) {
411 $resource = ResultWrapper
::unwrap( $res );
412 if ( is_array( $resource ) && count( $resource ) > 0 ) {
413 // The size of the result array is twice the number of fields. (T67578)
414 return count( $resource[0] ) / 2;
416 // If the result is empty return 0
422 * @param IResultWrapper $res
426 function fieldName( $res, $n ) {
427 $resource = ResultWrapper
::unwrap( $res );
428 if ( is_array( $resource ) ) {
429 $keys = array_keys( $resource[0] );
437 protected function doSelectDomain( DatabaseDomain
$domain ) {
438 if ( $domain->getSchema() !== null ) {
439 throw new DBExpectedError(
441 __CLASS__
. ": domain '{$domain->getId()}' has a schema component"
445 $database = $domain->getDatabase();
446 // A null database means "don't care" so leave it as is and update the table prefix
447 if ( $database === null ) {
448 $this->currentDomain
= new DatabaseDomain(
449 $this->currentDomain
->getDatabase(),
451 $domain->getTablePrefix()
457 if ( $database !== $this->getDBname() ) {
458 throw new DBExpectedError(
460 __CLASS__
. ": cannot change database (got '$database')"
468 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
470 * @param string $name
471 * @param string $format
474 function tableName( $name, $format = 'quoted' ) {
475 // table names starting with sqlite_ are reserved
476 if ( strpos( $name, 'sqlite_' ) === 0 ) {
480 return str_replace( '"', '', parent
::tableName( $name, $format ) );
484 * This must be called after nextSequenceVal
488 function insertId() {
489 // PDO::lastInsertId yields a string :(
490 return intval( $this->getBindingHandle()->lastInsertId() );
494 * @param IResultWrapper|array $res
497 function dataSeek( $res, $row ) {
498 $resource =& ResultWrapper
::unwrap( $res );
501 for ( $i = 0; $i < $row; $i++
) {
510 function lastError() {
511 if ( !is_object( $this->conn
) ) {
512 return "Cannot return last error, no db connection";
514 $e = $this->conn
->errorInfo();
522 function lastErrno() {
523 if ( !is_object( $this->conn
) ) {
524 return "Cannot return last error, no db connection";
526 $info = $this->conn
->errorInfo();
535 protected function fetchAffectedRowCount() {
536 return $this->lastAffectedRowCount
;
539 function tableExists( $table, $fname = __METHOD__
) {
540 $tableRaw = $this->tableName( $table, 'raw' );
541 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
542 return true; // already known to exist
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;
556 * Returns information about an index
557 * Returns false if the index does not exist
558 * - if errors are explicitly ignored, returns NULL on failure
560 * @param string $table
561 * @param string $index
562 * @param string $fname
563 * @return array|false
565 function indexInfo( $table, $index, $fname = __METHOD__
) {
566 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
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
;
580 * @param string $table
581 * @param string $index
582 * @param string $fname
585 function indexUnique( $table, $index, $fname = __METHOD__
) {
586 $row = $this->selectRow( 'sqlite_master', '*',
589 'name' => $this->indexName( $index ),
591 if ( !$row ||
!isset( $row->sql
) ) {
595 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
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 );
607 * Filter the options used in SELECT statements
609 * @param array $options
612 function makeSelectOptions( $options ) {
613 foreach ( $options as $k => $v ) {
614 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
619 return parent
::makeSelectOptions( $options );
623 * @param array $options
626 protected function makeUpdateOptionsArray( $options ) {
627 $options = parent
::makeUpdateOptionsArray( $options );
628 $options = self
::fixIgnore( $options );
634 * @param array $options
637 static function fixIgnore( $options ) {
638 # SQLite uses OR IGNORE not just IGNORE
639 foreach ( $options as $k => $v ) {
640 if ( $v == 'IGNORE' ) {
641 $options[$k] = 'OR IGNORE';
649 * @param array $options
652 function makeInsertOptions( $options ) {
653 $options = self
::fixIgnore( $options );
655 return parent
::makeInsertOptions( $options );
659 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
660 * @param string $table
662 * @param string $fname
663 * @param array $options
666 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
667 if ( !count( $a ) ) {
671 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
672 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
673 $affectedRowCount = 0;
675 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
676 foreach ( $a as $v ) {
677 parent
::insert( $table, $v, "$fname/multi-row", $options );
678 $affectedRowCount +
= $this->affectedRows();
680 $this->endAtomic( $fname );
681 } catch ( Exception
$e ) {
682 $this->cancelAtomic( $fname );
685 $this->affectedRowCount
= $affectedRowCount;
687 parent
::insert( $table, $a, "$fname/single-row", $options );
694 * @param string $table
695 * @param array $uniqueIndexes Unused
696 * @param string|array $rows
697 * @param string $fname
699 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
700 if ( !count( $rows ) ) {
704 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
705 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
706 $affectedRowCount = 0;
708 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
709 foreach ( $rows as $v ) {
710 $this->nativeReplace( $table, $v, "$fname/multi-row" );
711 $affectedRowCount +
= $this->affectedRows();
713 $this->endAtomic( $fname );
714 } catch ( Exception
$e ) {
715 $this->cancelAtomic( $fname );
718 $this->affectedRowCount
= $affectedRowCount;
720 $this->nativeReplace( $table, $rows, "$fname/single-row" );
725 * Returns the size of a text field, or -1 for "unlimited"
726 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
728 * @param string $table
729 * @param string $field
732 function textFieldSize( $table, $field ) {
739 function unionSupportsOrderAndLimit() {
744 * @param string[] $sqls
745 * @param bool $all Whether to "UNION ALL" or not
748 function unionQueries( $sqls, $all ) {
749 $glue = $all ?
' UNION ALL ' : ' UNION ';
751 return implode( $glue, $sqls );
757 function wasDeadlock() {
758 return $this->lastErrno() == 5; // SQLITE_BUSY
764 function wasReadOnlyError() {
765 return $this->lastErrno() == 8; // SQLITE_READONLY;
768 public function wasConnectionError( $errno ) {
769 return $errno == 17; // SQLITE_SCHEMA;
772 protected function wasKnownStatementRollbackError() {
773 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
774 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
775 // https://sqlite.org/lang_createtable.html#uniqueconst
776 // https://sqlite.org/lang_conflict.html
780 public function serverIsReadOnly() {
781 $this->assertHasConnectionHandle();
783 $path = $this->getDbFilePath();
785 return ( !self
::isProcessMemoryPath( $path ) && !is_writable( $path ) );
789 * @return string Wikitext of a link to the server software's web site
791 public function getSoftwareLink() {
792 return "[{{int:version-db-sqlite-url}} SQLite]";
796 * @return string Version information from the database
798 function getServerVersion() {
799 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
805 * Get information about a given field
806 * Returns false if the field does not exist.
808 * @param string $table
809 * @param string $field
810 * @return SQLiteField|bool False on failure
812 function fieldInfo( $table, $field ) {
813 $tableName = $this->tableName( $table );
814 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
815 $res = $this->query( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
816 foreach ( $res as $row ) {
817 if ( $row->name
== $field ) {
818 return new SQLiteField( $row, $tableName );
825 protected function doBegin( $fname = '' ) {
826 if ( $this->trxMode
!= '' ) {
827 $this->query( "BEGIN {$this->trxMode}", $fname );
829 $this->query( 'BEGIN', $fname );
837 function strencode( $s ) {
838 return substr( $this->addQuotes( $s ), 1, -1 );
845 function encodeBlob( $b ) {
846 return new Blob( $b );
850 * @param Blob|string $b
853 function decodeBlob( $b ) {
854 if ( $b instanceof Blob
) {
862 * @param string|int|null|bool|Blob $s
865 function addQuotes( $s ) {
866 if ( $s instanceof Blob
) {
867 return "x'" . bin2hex( $s->fetch() ) . "'";
868 } elseif ( is_bool( $s ) ) {
870 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
871 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
872 // This is a known limitation of SQLite's mprintf function which PDO
873 // should work around, but doesn't. I have reported this to php.net as bug #63419:
874 // https://bugs.php.net/bug.php?id=63419
875 // There was already a similar report for SQLite3::escapeString, bug #62361:
876 // https://bugs.php.net/bug.php?id=62361
877 // There is an additional bug regarding sorting this data after insert
878 // on older versions of sqlite shipped with ubuntu 12.04
879 // https://phabricator.wikimedia.org/T74367
880 $this->queryLogger
->debug(
882 ': Quoting value containing null byte. ' .
883 'For consistency all binary data should have been ' .
884 'first processed with self::encodeBlob()'
886 return "x'" . bin2hex( (string)$s ) . "'";
888 return $this->getBindingHandle()->quote( (string)$s );
892 public function buildSubstring( $input, $startPosition, $length = null ) {
893 $this->assertBuildSubstringParams( $startPosition, $length );
894 $params = [ $input, $startPosition ];
895 if ( $length !== null ) {
898 return 'SUBSTR(' . implode( ',', $params ) . ')';
902 * @param string $field Field or column to cast
906 public function buildStringCast( $field ) {
907 return 'CAST ( ' . $field . ' AS TEXT )';
911 * No-op version of deadlockLoop
915 public function deadlockLoop( /*...*/ ) {
916 $args = func_get_args();
917 $function = array_shift( $args );
919 return $function( ...$args );
926 protected function replaceVars( $s ) {
927 $s = parent
::replaceVars( $s );
928 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
929 // CREATE TABLE hacks to allow schema file sharing with MySQL
931 // binary/varbinary column type -> blob
932 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
933 // no such thing as unsigned
934 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
936 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
937 // floating point types -> REAL
939 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
944 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
945 // TEXT normalization
946 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
947 // BLOB normalization
948 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
950 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
952 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
954 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
955 // binary collation type -> nothing
956 $s = preg_replace( '/\bbinary\b/i', '', $s );
957 // auto_increment -> autoincrement
958 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
959 // No explicit options
960 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
961 // AUTOINCREMENT should immedidately follow PRIMARY KEY
962 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
963 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
964 // No truncated indexes
965 $s = preg_replace( '/\(\d+\)/', '', $s );
967 $s = preg_replace( '/\bfulltext\b/i', '', $s );
968 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
969 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
970 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
971 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
972 // INSERT IGNORE --> INSERT OR IGNORE
973 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
979 public function lock( $lockName, $method, $timeout = 5 ) {
980 $status = $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout );
982 $this->lockMgr
instanceof FSLockManager
&&
983 $status->hasMessage( 'lockmanager-fail-openlock' )
985 throw new DBError( $this, "Cannot create directory \"{$this->getLockFileDirectory()}\"" );
988 return $status->isOK();
991 public function unlock( $lockName, $method ) {
992 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isGood();
996 * Build a concatenation list to feed into a SQL query
998 * @param string[] $stringList
1001 function buildConcat( $stringList ) {
1002 return '(' . implode( ') || (', $stringList ) . ')';
1005 public function buildGroupConcatField(
1006 $delim, $table, $field, $conds = '', $join_conds = []
1008 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1010 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1014 * @param string $oldName
1015 * @param string $newName
1016 * @param bool $temporary
1017 * @param string $fname
1018 * @return bool|IResultWrapper
1019 * @throws RuntimeException
1021 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1022 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1023 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1024 $obj = $this->fetchObject( $res );
1026 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1029 $sql = preg_replace(
1031 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1033 $this->addIdentifierQuotes( $newName ),
1038 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1039 $this->queryLogger
->debug(
1040 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1042 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1046 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1048 // Take over indexes
1049 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1050 foreach ( $indexList as $index ) {
1051 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1055 if ( $index->unique
) {
1056 $sql = 'CREATE UNIQUE INDEX';
1058 $sql = 'CREATE INDEX';
1060 // Try to come up with a new index name, given indexes have database scope in SQLite
1061 $indexName = $newName . '_' . $index->name
;
1062 $sql .= ' ' . $indexName . ' ON ' . $newName;
1064 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1066 foreach ( $indexInfo as $indexInfoRow ) {
1067 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1070 $sql .= '(' . implode( ',', $fields ) . ')';
1072 $this->query( $sql );
1079 * List all tables on the database
1081 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1082 * @param string $fname Calling function name
1086 function listTables( $prefix = null, $fname = __METHOD__
) {
1087 $result = $this->select(
1095 foreach ( $result as $table ) {
1096 $vars = get_object_vars( $table );
1097 $table = array_pop( $vars );
1099 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1100 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1101 $endArray[] = $table;
1110 * Override due to no CASCADE support
1112 * @param string $tableName
1113 * @param string $fName
1114 * @return bool|IResultWrapper
1115 * @throws DBReadOnlyError
1117 public function dropTable( $tableName, $fName = __METHOD__
) {
1118 if ( !$this->tableExists( $tableName, $fName ) ) {
1121 $sql = "DROP TABLE " . $this->tableName( $tableName );
1123 return $this->query( $sql, $fName, self
::QUERY_IGNORE_DBO_TRX
);
1126 public function setTableAliases( array $aliases ) {
1127 parent
::setTableAliases( $aliases );
1128 if ( $this->isOpen() ) {
1129 $this->attachDatabasesFromTableAliases();
1134 * Issue ATTATCH statements for all unattached foreign DBs in table aliases
1136 private function attachDatabasesFromTableAliases() {
1137 foreach ( $this->tableAliases
as $params ) {
1139 $params['dbname'] !== $this->getDBname() &&
1140 !isset( $this->sessionAttachedDbs
[$params['dbname']] )
1142 $this->attachDatabase( $params['dbname'] );
1143 $this->sessionAttachedDbs
[$params['dbname']] = true;
1148 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1149 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1150 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1152 "DELETE FROM $encTable WHERE name = $encName",
1154 self
::QUERY_IGNORE_DBO_TRX
1158 public function databasesAreIndependent() {
1162 protected function doHandleSessionLossPreconnect() {
1163 $this->sessionAttachedDbs
= [];
1169 protected function getBindingHandle() {
1170 return parent
::getBindingHandle();
1175 * @deprecated since 1.29
1177 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );