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 $alreadyAttached = [];
60 /** @var bool Whether full text is enabled */
61 private static $fulltextEnabled = null;
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 // Set a dummy user to make initConnection() trigger open()
81 parent
::__construct( [ 'user' => '@' ] +
$p );
83 $this->trxMode
= strtoupper( $p['trxMode'] ??
'' );
85 $lockDirectory = $this->getLockFileDirectory();
86 if ( $lockDirectory !== null ) {
87 $this->lockMgr
= new FSLockManager( [
88 'domain' => $this->getDomainID(),
89 'lockDirectory' => $lockDirectory
92 $this->lockMgr
= new NullLockManager( [ 'domain' => $this->getDomainID() ] );
96 protected static function getAttributes() {
97 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
101 * @param string $filename
102 * @param array $p Options map; supports:
103 * - flags : (same as __construct counterpart)
104 * - trxMode : (same as __construct counterpart)
105 * - dbDirectory : (same as __construct counterpart)
106 * @return DatabaseSqlite
109 public static function newStandaloneInstance( $filename, array $p = [] ) {
110 $p['dbFilePath'] = $filename;
112 $p['tablePrefix'] = '';
113 /** @var DatabaseSqlite $db */
114 $db = Database
::factory( 'sqlite', $p );
122 public function getType() {
127 * @todo Check if it should be true like parent class
131 public function implicitGroupby() {
135 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
138 // Note that for SQLite, $server, $user, and $pass are ignored
140 if ( $schema !== null ) {
141 throw new DBExpectedError( $this, __CLASS__
. ": cannot use schemas ('$schema')" );
144 if ( $this->dbPath
!== null ) {
145 $path = $this->dbPath
;
146 } elseif ( $this->dbDir
!== null ) {
147 $path = self
::generateFileName( $this->dbDir
, $dbName );
149 throw new DBExpectedError( $this, __CLASS__
. ": DB path or directory required" );
152 if ( !in_array( $this->trxMode
, [ '', 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ], true ) ) {
153 throw new DBExpectedError(
155 __CLASS__
. ": invalid transaction mode '{$this->trxMode}'"
159 if ( !self
::isProcessMemoryPath( $path ) && !is_readable( $path ) ) {
160 $error = "SQLite database file not readable";
161 $this->connLogger
->error(
162 "Error connecting to {db_server}: {error}",
163 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
165 throw new DBConnectionError( $this, $error );
173 [ PDO
::ATTR_PERSISTENT
=> (bool)( $this->flags
& self
::DBO_PERSISTENT
) ]
175 // Set error codes only, don't raise exceptions
176 $conn->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
177 } catch ( PDOException
$e ) {
178 $error = $e->getMessage();
179 $this->connLogger
->error(
180 "Error connecting to {db_server}: {error}",
181 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
183 throw new DBConnectionError( $this, $error );
187 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
190 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
191 // Enforce LIKE to be case sensitive, just like MySQL
192 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
193 // Apply an optimizations or requirements regarding fsync() usage
194 $sync = $this->connectionVariables
['synchronous'] ??
null;
195 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
196 $this->query( "PRAGMA synchronous = $sync", __METHOD__
, $flags );
198 } catch ( Exception
$e ) {
199 // Connection was not fully initialized and is not safe for use
206 * @return string|null SQLite DB file path
207 * @throws DBUnexpectedError
210 public function getDbFilePath() {
211 return $this->dbPath ?? self
::generateFileName( $this->dbDir
, $this->getDBname() );
215 * @return string|null Lock file directory
217 public function getLockFileDirectory() {
218 if ( $this->dbPath
!== null && !self
::isProcessMemoryPath( $this->dbPath
) ) {
219 return dirname( $this->dbPath
) . '/locks';
220 } elseif ( $this->dbDir
!== null && !self
::isProcessMemoryPath( $this->dbDir
) ) {
221 return $this->dbDir
. '/locks';
228 * Does not actually close the connection, just destroys the reference for GC to do its work
231 protected function closeConnection() {
238 * Generates a database file name. Explicitly public for installer.
239 * @param string $dir Directory where database resides
240 * @param string|bool $dbName Database name (or false from Database::factory, validated here)
242 * @throws DBUnexpectedError
244 public static function generateFileName( $dir, $dbName ) {
246 throw new DBUnexpectedError( null, __CLASS__
. ": no DB directory specified" );
247 } elseif ( self
::isProcessMemoryPath( $dir ) ) {
248 throw new DBUnexpectedError(
250 __CLASS__
. ": cannot use process memory directory '$dir'"
252 } elseif ( !strlen( $dbName ) ) {
253 throw new DBUnexpectedError( null, __CLASS__
. ": no DB name specified" );
256 return "$dir/$dbName.sqlite";
260 * @param string $path
263 private static function generateDatabaseName( $path ) {
264 if ( preg_match( '/^(:memory:$|file::memory:)/', $path ) ) {
265 // E.g. "file::memory:?cache=shared" => ":memory":
267 } elseif ( preg_match( '/^file::([^?]+)\?mode=memory(&|$)/', $path, $m ) ) {
268 // E.g. "file:memdb1?mode=memory" => ":memdb1:"
271 // E.g. "/home/.../some_db.sqlite3" => "some_db"
272 return preg_replace( '/\.sqlite\d?$/', '', basename( $path ) );
277 * @param string $path
280 private static function isProcessMemoryPath( $path ) {
281 return preg_match( '/^(:memory:$|file:(:memory:|[^?]+\?mode=memory(&|$)))/', $path );
285 * Check if the searchindext table is FTS enabled.
286 * @return bool False if not enabled.
288 public function checkForEnabledSearch() {
289 if ( self
::$fulltextEnabled === null ) {
290 self
::$fulltextEnabled = false;
291 $table = $this->tableName( 'searchindex' );
292 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
294 $row = $res->fetchRow();
295 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
299 return self
::$fulltextEnabled;
303 * Returns version of currently supported SQLite fulltext search module or false if none present.
306 static function getFulltextSearchModule() {
307 static $cachedResult = null;
308 if ( $cachedResult !== null ) {
309 return $cachedResult;
311 $cachedResult = false;
312 $table = 'dummy_search_test';
314 $db = self
::newStandaloneInstance( ':memory:' );
315 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
316 $cachedResult = 'FTS3';
320 return $cachedResult;
324 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
327 * @param string $name Database name to be used in queries like
328 * SELECT foo FROM dbname.table
329 * @param bool|string $file Database file name. If omitted, will be generated
330 * using $name and configured data directory
331 * @param string $fname Calling function name
332 * @return IResultWrapper
334 public function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
335 $file = is_string( $file ) ?
$file : self
::generateFileName( $this->dbDir
, $name );
336 $encFile = $this->addQuotes( $file );
338 return $this->query( "ATTACH DATABASE $encFile AS $name", $fname );
341 protected function isWriteQuery( $sql ) {
342 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
345 protected function isTransactableQuery( $sql ) {
346 return parent
::isTransactableQuery( $sql ) && !in_array(
347 $this->getQueryVerb( $sql ),
348 [ 'ATTACH', 'PRAGMA' ],
354 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
357 * @return bool|IResultWrapper
359 protected function doQuery( $sql ) {
360 $res = $this->getBindingHandle()->query( $sql );
361 if ( $res === false ) {
365 $resource = ResultWrapper
::unwrap( $res );
366 $this->lastAffectedRowCount
= $resource->rowCount();
367 $res = new ResultWrapper( $this, $resource->fetchAll() );
373 * @param IResultWrapper|mixed $res
375 function freeResult( $res ) {
376 if ( $res instanceof ResultWrapper
) {
382 * @param IResultWrapper|array $res
383 * @return stdClass|bool
385 function fetchObject( $res ) {
386 $resource =& ResultWrapper
::unwrap( $res );
388 $cur = current( $resource );
389 if ( is_array( $cur ) ) {
392 foreach ( $cur as $k => $v ) {
393 if ( !is_numeric( $k ) ) {
405 * @param IResultWrapper|mixed $res
408 function fetchRow( $res ) {
409 $resource =& ResultWrapper
::unwrap( $res );
410 $cur = current( $resource );
411 if ( is_array( $cur ) ) {
421 * The PDO::Statement class implements the array interface so count() will work
423 * @param IResultWrapper|array|false $res
426 function numRows( $res ) {
427 // false does not implement Countable
428 $resource = ResultWrapper
::unwrap( $res );
430 return is_array( $resource ) ?
count( $resource ) : 0;
434 * @param IResultWrapper $res
437 function numFields( $res ) {
438 $resource = ResultWrapper
::unwrap( $res );
439 if ( is_array( $resource ) && count( $resource ) > 0 ) {
440 // The size of the result array is twice the number of fields. (T67578)
441 return count( $resource[0] ) / 2;
443 // If the result is empty return 0
449 * @param IResultWrapper $res
453 function fieldName( $res, $n ) {
454 $resource = ResultWrapper
::unwrap( $res );
455 if ( is_array( $resource ) ) {
456 $keys = array_keys( $resource[0] );
465 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
467 * @param string $name
468 * @param string $format
471 function tableName( $name, $format = 'quoted' ) {
472 // table names starting with sqlite_ are reserved
473 if ( strpos( $name, 'sqlite_' ) === 0 ) {
477 return str_replace( '"', '', parent
::tableName( $name, $format ) );
481 * This must be called after nextSequenceVal
485 function insertId() {
486 // PDO::lastInsertId yields a string :(
487 return intval( $this->getBindingHandle()->lastInsertId() );
491 * @param IResultWrapper|array $res
494 function dataSeek( $res, $row ) {
495 $resource =& ResultWrapper
::unwrap( $res );
498 for ( $i = 0; $i < $row; $i++
) {
507 function lastError() {
508 if ( !is_object( $this->conn
) ) {
509 return "Cannot return last error, no db connection";
511 $e = $this->conn
->errorInfo();
519 function lastErrno() {
520 if ( !is_object( $this->conn
) ) {
521 return "Cannot return last error, no db connection";
523 $info = $this->conn
->errorInfo();
532 protected function fetchAffectedRowCount() {
533 return $this->lastAffectedRowCount
;
536 function tableExists( $table, $fname = __METHOD__
) {
537 $tableRaw = $this->tableName( $table, 'raw' );
538 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
539 return true; // already known to exist
542 $encTable = $this->addQuotes( $tableRaw );
544 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
546 return $res->numRows() ?
true : false;
550 * Returns information about an index
551 * Returns false if the index does not exist
552 * - if errors are explicitly ignored, returns NULL on failure
554 * @param string $table
555 * @param string $index
556 * @param string $fname
557 * @return array|false
559 function indexInfo( $table, $index, $fname = __METHOD__
) {
560 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
561 $res = $this->query( $sql, $fname );
562 if ( !$res ||
$res->numRows() == 0 ) {
566 foreach ( $res as $row ) {
567 $info[] = $row->name
;
574 * @param string $table
575 * @param string $index
576 * @param string $fname
579 function indexUnique( $table, $index, $fname = __METHOD__
) {
580 $row = $this->selectRow( 'sqlite_master', '*',
583 'name' => $this->indexName( $index ),
585 if ( !$row ||
!isset( $row->sql
) ) {
589 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
590 $indexPos = strpos( $row->sql
, 'INDEX' );
591 if ( $indexPos === false ) {
594 $firstPart = substr( $row->sql
, 0, $indexPos );
595 $options = explode( ' ', $firstPart );
597 return in_array( 'UNIQUE', $options );
601 * Filter the options used in SELECT statements
603 * @param array $options
606 function makeSelectOptions( $options ) {
607 foreach ( $options as $k => $v ) {
608 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
613 return parent
::makeSelectOptions( $options );
617 * @param array $options
620 protected function makeUpdateOptionsArray( $options ) {
621 $options = parent
::makeUpdateOptionsArray( $options );
622 $options = self
::fixIgnore( $options );
628 * @param array $options
631 static function fixIgnore( $options ) {
632 # SQLite uses OR IGNORE not just IGNORE
633 foreach ( $options as $k => $v ) {
634 if ( $v == 'IGNORE' ) {
635 $options[$k] = 'OR IGNORE';
643 * @param array $options
646 function makeInsertOptions( $options ) {
647 $options = self
::fixIgnore( $options );
649 return parent
::makeInsertOptions( $options );
653 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
654 * @param string $table
656 * @param string $fname
657 * @param array $options
660 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
661 if ( !count( $a ) ) {
665 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
666 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
667 $affectedRowCount = 0;
669 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
670 foreach ( $a as $v ) {
671 parent
::insert( $table, $v, "$fname/multi-row", $options );
672 $affectedRowCount +
= $this->affectedRows();
674 $this->endAtomic( $fname );
675 } catch ( Exception
$e ) {
676 $this->cancelAtomic( $fname );
679 $this->affectedRowCount
= $affectedRowCount;
681 parent
::insert( $table, $a, "$fname/single-row", $options );
688 * @param string $table
689 * @param array $uniqueIndexes Unused
690 * @param string|array $rows
691 * @param string $fname
693 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
694 if ( !count( $rows ) ) {
698 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
699 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
700 $affectedRowCount = 0;
702 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
703 foreach ( $rows as $v ) {
704 $this->nativeReplace( $table, $v, "$fname/multi-row" );
705 $affectedRowCount +
= $this->affectedRows();
707 $this->endAtomic( $fname );
708 } catch ( Exception
$e ) {
709 $this->cancelAtomic( $fname );
712 $this->affectedRowCount
= $affectedRowCount;
714 $this->nativeReplace( $table, $rows, "$fname/single-row" );
719 * Returns the size of a text field, or -1 for "unlimited"
720 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
722 * @param string $table
723 * @param string $field
726 function textFieldSize( $table, $field ) {
733 function unionSupportsOrderAndLimit() {
738 * @param string[] $sqls
739 * @param bool $all Whether to "UNION ALL" or not
742 function unionQueries( $sqls, $all ) {
743 $glue = $all ?
' UNION ALL ' : ' UNION ';
745 return implode( $glue, $sqls );
751 function wasDeadlock() {
752 return $this->lastErrno() == 5; // SQLITE_BUSY
758 function wasReadOnlyError() {
759 return $this->lastErrno() == 8; // SQLITE_READONLY;
762 public function wasConnectionError( $errno ) {
763 return $errno == 17; // SQLITE_SCHEMA;
766 protected function wasKnownStatementRollbackError() {
767 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
768 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
769 // https://sqlite.org/lang_createtable.html#uniqueconst
770 // https://sqlite.org/lang_conflict.html
774 public function serverIsReadOnly() {
775 $path = $this->getDbFilePath();
777 return ( !self
::isProcessMemoryPath( $path ) && !is_writable( $path ) );
781 * @return string Wikitext of a link to the server software's web site
783 public function getSoftwareLink() {
784 return "[{{int:version-db-sqlite-url}} SQLite]";
788 * @return string Version information from the database
790 function getServerVersion() {
791 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
797 * Get information about a given field
798 * Returns false if the field does not exist.
800 * @param string $table
801 * @param string $field
802 * @return SQLiteField|bool False on failure
804 function fieldInfo( $table, $field ) {
805 $tableName = $this->tableName( $table );
806 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
807 $res = $this->query( $sql, __METHOD__
);
808 foreach ( $res as $row ) {
809 if ( $row->name
== $field ) {
810 return new SQLiteField( $row, $tableName );
817 protected function doBegin( $fname = '' ) {
818 if ( $this->trxMode
!= '' ) {
819 $this->query( "BEGIN {$this->trxMode}", $fname );
821 $this->query( 'BEGIN', $fname );
829 function strencode( $s ) {
830 return substr( $this->addQuotes( $s ), 1, -1 );
837 function encodeBlob( $b ) {
838 return new Blob( $b );
842 * @param Blob|string $b
845 function decodeBlob( $b ) {
846 if ( $b instanceof Blob
) {
854 * @param string|int|null|bool|Blob $s
857 function addQuotes( $s ) {
858 if ( $s instanceof Blob
) {
859 return "x'" . bin2hex( $s->fetch() ) . "'";
860 } elseif ( is_bool( $s ) ) {
862 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
863 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
864 // This is a known limitation of SQLite's mprintf function which PDO
865 // should work around, but doesn't. I have reported this to php.net as bug #63419:
866 // https://bugs.php.net/bug.php?id=63419
867 // There was already a similar report for SQLite3::escapeString, bug #62361:
868 // https://bugs.php.net/bug.php?id=62361
869 // There is an additional bug regarding sorting this data after insert
870 // on older versions of sqlite shipped with ubuntu 12.04
871 // https://phabricator.wikimedia.org/T74367
872 $this->queryLogger
->debug(
874 ': Quoting value containing null byte. ' .
875 'For consistency all binary data should have been ' .
876 'first processed with self::encodeBlob()'
878 return "x'" . bin2hex( (string)$s ) . "'";
880 return $this->getBindingHandle()->quote( (string)$s );
884 public function buildSubstring( $input, $startPosition, $length = null ) {
885 $this->assertBuildSubstringParams( $startPosition, $length );
886 $params = [ $input, $startPosition ];
887 if ( $length !== null ) {
890 return 'SUBSTR(' . implode( ',', $params ) . ')';
894 * @param string $field Field or column to cast
898 public function buildStringCast( $field ) {
899 return 'CAST ( ' . $field . ' AS TEXT )';
903 * No-op version of deadlockLoop
907 public function deadlockLoop( /*...*/ ) {
908 $args = func_get_args();
909 $function = array_shift( $args );
911 return $function( ...$args );
918 protected function replaceVars( $s ) {
919 $s = parent
::replaceVars( $s );
920 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
921 // CREATE TABLE hacks to allow schema file sharing with MySQL
923 // binary/varbinary column type -> blob
924 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
925 // no such thing as unsigned
926 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
928 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
929 // floating point types -> REAL
931 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
936 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
937 // TEXT normalization
938 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
939 // BLOB normalization
940 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
942 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
944 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
946 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
947 // binary collation type -> nothing
948 $s = preg_replace( '/\bbinary\b/i', '', $s );
949 // auto_increment -> autoincrement
950 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
951 // No explicit options
952 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
953 // AUTOINCREMENT should immedidately follow PRIMARY KEY
954 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
955 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
956 // No truncated indexes
957 $s = preg_replace( '/\(\d+\)/', '', $s );
959 $s = preg_replace( '/\bfulltext\b/i', '', $s );
960 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
961 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
962 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
963 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
964 // INSERT IGNORE --> INSERT OR IGNORE
965 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
971 public function lock( $lockName, $method, $timeout = 5 ) {
972 $status = $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout );
974 $this->lockMgr
instanceof FSLockManager
&&
975 $status->hasMessage( 'lockmanager-fail-openlock' )
977 throw new DBError( $this, "Cannot create directory \"{$this->getLockFileDirectory()}\"" );
980 return $status->isOK();
983 public function unlock( $lockName, $method ) {
984 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isGood();
988 * Build a concatenation list to feed into a SQL query
990 * @param string[] $stringList
993 function buildConcat( $stringList ) {
994 return '(' . implode( ') || (', $stringList ) . ')';
997 public function buildGroupConcatField(
998 $delim, $table, $field, $conds = '', $join_conds = []
1000 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1002 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1006 * @param string $oldName
1007 * @param string $newName
1008 * @param bool $temporary
1009 * @param string $fname
1010 * @return bool|IResultWrapper
1011 * @throws RuntimeException
1013 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1014 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1015 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1016 $obj = $this->fetchObject( $res );
1018 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1021 $sql = preg_replace(
1023 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1025 $this->addIdentifierQuotes( $newName ),
1030 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1031 $this->queryLogger
->debug(
1032 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1034 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1038 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1040 // Take over indexes
1041 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1042 foreach ( $indexList as $index ) {
1043 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1047 if ( $index->unique
) {
1048 $sql = 'CREATE UNIQUE INDEX';
1050 $sql = 'CREATE INDEX';
1052 // Try to come up with a new index name, given indexes have database scope in SQLite
1053 $indexName = $newName . '_' . $index->name
;
1054 $sql .= ' ' . $indexName . ' ON ' . $newName;
1056 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1058 foreach ( $indexInfo as $indexInfoRow ) {
1059 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1062 $sql .= '(' . implode( ',', $fields ) . ')';
1064 $this->query( $sql );
1071 * List all tables on the database
1073 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1074 * @param string $fname Calling function name
1078 function listTables( $prefix = null, $fname = __METHOD__
) {
1079 $result = $this->select(
1087 foreach ( $result as $table ) {
1088 $vars = get_object_vars( $table );
1089 $table = array_pop( $vars );
1091 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1092 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1093 $endArray[] = $table;
1102 * Override due to no CASCADE support
1104 * @param string $tableName
1105 * @param string $fName
1106 * @return bool|IResultWrapper
1107 * @throws DBReadOnlyError
1109 public function dropTable( $tableName, $fName = __METHOD__
) {
1110 if ( !$this->tableExists( $tableName, $fName ) ) {
1113 $sql = "DROP TABLE " . $this->tableName( $tableName );
1115 return $this->query( $sql, $fName );
1118 public function setTableAliases( array $aliases ) {
1119 parent
::setTableAliases( $aliases );
1120 foreach ( $this->tableAliases
as $params ) {
1121 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1124 $this->attachDatabase( $params['dbname'] );
1125 $this->alreadyAttached
[$params['dbname']] = true;
1129 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1130 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1131 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1132 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1135 public function databasesAreIndependent() {
1142 protected function getBindingHandle() {
1143 return parent
::getBindingHandle();
1148 * @deprecated since 1.29
1150 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );