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
;
31 use InvalidArgumentException
;
38 class DatabaseSqlite
extends Database
{
39 /** @var bool Whether full text is enabled */
40 private static $fulltextEnabled = null;
42 /** @var string Directory */
44 /** @var string File name for SQLite database file */
46 /** @var string Transaction mode */
49 /** @var int The number of rows affected as an integer */
50 protected $lastAffectedRowCount;
52 protected $lastResultHandle;
57 /** @var FSLockManager (hopefully on the same server as the DB) */
60 /** @var array List of shared database already attached to this connection */
61 private $alreadyAttached = [];
64 * Additional params include:
65 * - dbDirectory : directory containing the DB and the lock file directory
66 * [defaults to $wgSQLiteDataDir]
67 * - dbFilePath : use this to force the path of the DB file
68 * - trxMode : one of (deferred, immediate, exclusive)
71 function __construct( array $p ) {
72 if ( isset( $p['dbFilePath'] ) ) {
73 $this->dbPath
= $p['dbFilePath'];
74 $lockDomain = md5( $this->dbPath
);
75 // Use "X" for things like X.sqlite and ":memory:" for RAM-only DBs
76 if ( !isset( $p['dbname'] ) ||
!strlen( $p['dbname'] ) ) {
77 $p['dbname'] = preg_replace( '/\.sqlite\d?$/', '', basename( $this->dbPath
) );
79 } elseif ( isset( $p['dbDirectory'] ) ) {
80 $this->dbDir
= $p['dbDirectory'];
81 $lockDomain = $p['dbname'];
83 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
86 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
87 if ( $this->trxMode
&&
88 !in_array( $this->trxMode
, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
90 $this->trxMode
= null;
91 $this->queryLogger
->warning( "Invalid SQLite transaction mode provided." );
94 $this->lockMgr
= new FSLockManager( [
95 'domain' => $lockDomain,
96 'lockDirectory' => "{$this->dbDir}/locks"
99 parent
::__construct( $p );
102 protected static function getAttributes() {
103 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
107 * @param string $filename
108 * @param array $p Options map; supports:
109 * - flags : (same as __construct counterpart)
110 * - trxMode : (same as __construct counterpart)
111 * - dbDirectory : (same as __construct counterpart)
112 * @return DatabaseSqlite
115 public static function newStandaloneInstance( $filename, array $p = [] ) {
116 $p['dbFilePath'] = $filename;
118 $p['tablePrefix'] = '';
119 /** @var DatabaseSqlite $db */
120 $db = Database
::factory( 'sqlite', $p );
125 protected function doInitConnection() {
126 if ( $this->dbPath
!== null ) {
127 // Standalone .sqlite file mode.
130 $this->connectionParams
['dbname'],
131 $this->connectionParams
['tablePrefix']
133 } elseif ( $this->dbDir
!== null ) {
134 // Stock wiki mode using standard file names per DB
135 if ( strlen( $this->connectionParams
['dbname'] ) ) {
137 $this->connectionParams
['host'],
138 $this->connectionParams
['user'],
139 $this->connectionParams
['password'],
140 $this->connectionParams
['dbname'],
141 $this->connectionParams
['schema'],
142 $this->connectionParams
['tablePrefix']
145 // Caller will manually call open() later?
146 $this->connLogger
->debug( __METHOD__
. ': no database opened.' );
149 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
161 * @todo Check if it should be true like parent class
165 function implicitGroupby() {
169 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
172 if ( $schema !== null ) {
173 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
176 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
177 $this->openFile( self
::generateFileName( $this->dbDir
, $dbName ), $dbName, $tablePrefix );
181 * Opens a database file
183 * @param string $fileName
184 * @param string $dbName
185 * @param string $tablePrefix
186 * @throws DBConnectionError
188 protected function openFile( $fileName, $dbName, $tablePrefix ) {
189 if ( !$this->hasMemoryPath() && !is_readable( $fileName ) ) {
190 $error = "SQLite database file not readable";
191 $this->connLogger
->error(
192 "Error connecting to {db_server}: {error}",
193 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
195 throw new DBConnectionError( $this, $error );
198 $this->dbPath
= $fileName;
200 $this->conn
= new PDO(
204 [ PDO
::ATTR_PERSISTENT
=> (bool)( $this->flags
& self
::DBO_PERSISTENT
) ]
206 $error = 'unknown error';
207 } catch ( PDOException
$e ) {
208 $error = $e->getMessage();
211 if ( !$this->conn
) {
212 $this->connLogger
->error(
213 "Error connecting to {db_server}: {error}",
214 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
216 throw new DBConnectionError( $this, $error );
220 // Set error codes only, don't raise exceptions
221 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
223 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
225 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
226 // Enforce LIKE to be case sensitive, just like MySQL
227 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
228 // Apply an optimizations or requirements regarding fsync() usage
229 $sync = $this->connectionVariables
['synchronous'] ??
null;
230 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
231 $this->query( "PRAGMA synchronous = $sync", __METHOD__
);
233 } catch ( Exception
$e ) {
234 // Connection was not fully initialized and is not safe for use
241 * @return string SQLite DB file path
244 public function getDbFilePath() {
245 return $this->dbPath
;
249 * Does not actually close the connection, just destroys the reference for GC to do its work
252 protected function closeConnection() {
259 * Generates a database file name. Explicitly public for installer.
260 * @param string $dir Directory where database resides
261 * @param string $dbName Database name
264 public static function generateFileName( $dir, $dbName ) {
265 return "$dir/$dbName.sqlite";
269 * Check if the searchindext table is FTS enabled.
270 * @return bool False if not enabled.
272 public function checkForEnabledSearch() {
273 if ( self
::$fulltextEnabled === null ) {
274 self
::$fulltextEnabled = false;
275 $table = $this->tableName( 'searchindex' );
276 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
278 $row = $res->fetchRow();
279 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
283 return self
::$fulltextEnabled;
287 * Returns version of currently supported SQLite fulltext search module or false if none present.
290 static function getFulltextSearchModule() {
291 static $cachedResult = null;
292 if ( $cachedResult !== null ) {
293 return $cachedResult;
295 $cachedResult = false;
296 $table = 'dummy_search_test';
298 $db = self
::newStandaloneInstance( ':memory:' );
299 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
300 $cachedResult = 'FTS3';
304 return $cachedResult;
308 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
311 * @param string $name Database name to be used in queries like
312 * SELECT foo FROM dbname.table
313 * @param bool|string $file Database file name. If omitted, will be generated
314 * using $name and configured data directory
315 * @param string $fname Calling function name
316 * @return IResultWrapper
318 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
320 $file = self
::generateFileName( $this->dbDir
, $name );
322 $file = $this->addQuotes( $file );
324 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
327 protected function isWriteQuery( $sql ) {
328 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
331 protected function isTransactableQuery( $sql ) {
332 return parent
::isTransactableQuery( $sql ) && !in_array(
333 $this->getQueryVerb( $sql ),
334 [ 'ATTACH', 'PRAGMA' ],
340 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
343 * @return bool|IResultWrapper
345 protected function doQuery( $sql ) {
346 $res = $this->getBindingHandle()->query( $sql );
347 if ( $res === false ) {
351 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
352 $this->lastAffectedRowCount
= $r->rowCount();
353 $res = new ResultWrapper( $this, $r->fetchAll() );
359 * @param IResultWrapper|mixed $res
361 function freeResult( $res ) {
362 if ( $res instanceof ResultWrapper
) {
370 * @param IResultWrapper|array $res
371 * @return stdClass|bool
373 function fetchObject( $res ) {
374 if ( $res instanceof ResultWrapper
) {
380 $cur = current( $r );
381 if ( is_array( $cur ) ) {
384 foreach ( $cur as $k => $v ) {
385 if ( !is_numeric( $k ) ) {
397 * @param IResultWrapper|mixed $res
400 function fetchRow( $res ) {
401 if ( $res instanceof ResultWrapper
) {
406 $cur = current( $r );
407 if ( is_array( $cur ) ) {
417 * The PDO::Statement class implements the array interface so count() will work
419 * @param IResultWrapper|array|false $res
422 function numRows( $res ) {
423 // false does not implement Countable
424 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
426 return is_array( $r ) ?
count( $r ) : 0;
430 * @param IResultWrapper $res
433 function numFields( $res ) {
434 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
435 if ( is_array( $r ) && count( $r ) > 0 ) {
436 // The size of the result array is twice the number of fields. (T67578)
437 return count( $r[0] ) / 2;
439 // If the result is empty return 0
445 * @param IResultWrapper $res
449 function fieldName( $res, $n ) {
450 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
451 if ( is_array( $r ) ) {
452 $keys = array_keys( $r[0] );
461 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
463 * @param string $name
464 * @param string $format
467 function tableName( $name, $format = 'quoted' ) {
468 // table names starting with sqlite_ are reserved
469 if ( strpos( $name, 'sqlite_' ) === 0 ) {
473 return str_replace( '"', '', parent
::tableName( $name, $format ) );
477 * This must be called after nextSequenceVal
481 function insertId() {
482 // PDO::lastInsertId yields a string :(
483 return intval( $this->getBindingHandle()->lastInsertId() );
487 * @param IResultWrapper|array $res
490 function dataSeek( $res, $row ) {
491 if ( $res instanceof ResultWrapper
) {
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 return ( !$this->hasMemoryPath() && !is_writable( $this->dbPath
) );
781 private function hasMemoryPath() {
782 return ( strpos( $this->dbPath
, ':memory:' ) === 0 );
786 * @return string Wikitext of a link to the server software's web site
788 public function getSoftwareLink() {
789 return "[{{int:version-db-sqlite-url}} SQLite]";
793 * @return string Version information from the database
795 function getServerVersion() {
796 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
802 * Get information about a given field
803 * Returns false if the field does not exist.
805 * @param string $table
806 * @param string $field
807 * @return SQLiteField|bool False on failure
809 function fieldInfo( $table, $field ) {
810 $tableName = $this->tableName( $table );
811 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
812 $res = $this->query( $sql, __METHOD__
);
813 foreach ( $res as $row ) {
814 if ( $row->name
== $field ) {
815 return new SQLiteField( $row, $tableName );
822 protected function doBegin( $fname = '' ) {
823 if ( $this->trxMode
) {
824 $this->query( "BEGIN {$this->trxMode}", $fname );
826 $this->query( 'BEGIN', $fname );
834 function strencode( $s ) {
835 return substr( $this->addQuotes( $s ), 1, -1 );
842 function encodeBlob( $b ) {
843 return new Blob( $b );
847 * @param Blob|string $b
850 function decodeBlob( $b ) {
851 if ( $b instanceof Blob
) {
859 * @param string|int|null|bool|Blob $s
862 function addQuotes( $s ) {
863 if ( $s instanceof Blob
) {
864 return "x'" . bin2hex( $s->fetch() ) . "'";
865 } elseif ( is_bool( $s ) ) {
867 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
868 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
869 // This is a known limitation of SQLite's mprintf function which PDO
870 // should work around, but doesn't. I have reported this to php.net as bug #63419:
871 // https://bugs.php.net/bug.php?id=63419
872 // There was already a similar report for SQLite3::escapeString, bug #62361:
873 // https://bugs.php.net/bug.php?id=62361
874 // There is an additional bug regarding sorting this data after insert
875 // on older versions of sqlite shipped with ubuntu 12.04
876 // https://phabricator.wikimedia.org/T74367
877 $this->queryLogger
->debug(
879 ': Quoting value containing null byte. ' .
880 'For consistency all binary data should have been ' .
881 'first processed with self::encodeBlob()'
883 return "x'" . bin2hex( (string)$s ) . "'";
885 return $this->getBindingHandle()->quote( (string)$s );
889 public function buildSubstring( $input, $startPosition, $length = null ) {
890 $this->assertBuildSubstringParams( $startPosition, $length );
891 $params = [ $input, $startPosition ];
892 if ( $length !== null ) {
895 return 'SUBSTR(' . implode( ',', $params ) . ')';
899 * @param string $field Field or column to cast
903 public function buildStringCast( $field ) {
904 return 'CAST ( ' . $field . ' AS TEXT )';
908 * No-op version of deadlockLoop
912 public function deadlockLoop( /*...*/ ) {
913 $args = func_get_args();
914 $function = array_shift( $args );
916 return $function( ...$args );
923 protected function replaceVars( $s ) {
924 $s = parent
::replaceVars( $s );
925 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
926 // CREATE TABLE hacks to allow schema file sharing with MySQL
928 // binary/varbinary column type -> blob
929 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
930 // no such thing as unsigned
931 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
933 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
934 // floating point types -> REAL
936 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
941 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
942 // TEXT normalization
943 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
944 // BLOB normalization
945 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
947 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
949 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
951 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
952 // binary collation type -> nothing
953 $s = preg_replace( '/\bbinary\b/i', '', $s );
954 // auto_increment -> autoincrement
955 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
956 // No explicit options
957 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
958 // AUTOINCREMENT should immedidately follow PRIMARY KEY
959 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
960 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
961 // No truncated indexes
962 $s = preg_replace( '/\(\d+\)/', '', $s );
964 $s = preg_replace( '/\bfulltext\b/i', '', $s );
965 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
966 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
967 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
968 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
969 // INSERT IGNORE --> INSERT OR IGNORE
970 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
976 public function lock( $lockName, $method, $timeout = 5 ) {
977 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
978 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
979 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
983 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
986 public function unlock( $lockName, $method ) {
987 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
991 * Build a concatenation list to feed into a SQL query
993 * @param string[] $stringList
996 function buildConcat( $stringList ) {
997 return '(' . implode( ') || (', $stringList ) . ')';
1000 public function buildGroupConcatField(
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 ) . ')';
1009 * @param string $oldName
1010 * @param string $newName
1011 * @param bool $temporary
1012 * @param string $fname
1013 * @return bool|IResultWrapper
1014 * @throws RuntimeException
1016 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1017 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1018 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1019 $obj = $this->fetchObject( $res );
1021 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1024 $sql = preg_replace(
1026 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1028 $this->addIdentifierQuotes( $newName ),
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
);
1043 // Take over indexes
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';
1055 // Try to come up with a new index name, given indexes have database scope in SQLite
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 );
1074 * List all tables on the database
1076 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1077 * @param string $fname Calling function name
1081 function listTables( $prefix = null, $fname = __METHOD__
) {
1082 $result = $this->select(
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;
1105 * Override due to no CASCADE support
1107 * @param string $tableName
1108 * @param string $fName
1109 * @return bool|IResultWrapper
1110 * @throws DBReadOnlyError
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 );
1121 public function setTableAliases( array $aliases ) {
1122 parent
::setTableAliases( $aliases );
1123 foreach ( $this->tableAliases
as $params ) {
1124 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1127 $this->attachDatabase( $params['dbname'] );
1128 $this->alreadyAttached
[$params['dbname']] = true;
1132 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1133 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1134 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1135 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1138 public function databasesAreIndependent() {
1145 protected function getBindingHandle() {
1146 return parent
::getBindingHandle();
1151 * @deprecated since 1.29
1153 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );