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 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
177 if ( !is_readable( $fileName ) ) {
178 $error = "SQLite database file not readable";
179 $this->connLogger
->error(
180 "Error connecting to {db_server}: {error}",
181 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
183 throw new DBConnectionError( $this, $error );
186 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
187 $this->openFile( $fileName, $dbName, $tablePrefix );
191 * Opens a database file
193 * @param string $fileName
194 * @param string $dbName
195 * @param string $tablePrefix
196 * @throws DBConnectionError
198 protected function openFile( $fileName, $dbName, $tablePrefix ) {
199 $this->dbPath
= $fileName;
201 $this->conn
= new PDO(
205 [ PDO
::ATTR_PERSISTENT
=> (bool)( $this->flags
& self
::DBO_PERSISTENT
) ]
207 $error = 'unknown error';
208 } catch ( PDOException
$e ) {
209 $error = $e->getMessage();
212 if ( !$this->conn
) {
213 $this->connLogger
->error(
214 "Error connecting to {db_server}: {error}",
215 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
217 throw new DBConnectionError( $this, $error );
221 // Set error codes only, don't raise exceptions
222 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
224 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
226 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
227 // Enforce LIKE to be case sensitive, just like MySQL
228 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
229 // Apply an optimizations or requirements regarding fsync() usage
230 $sync = $this->connectionVariables
['synchronous'] ??
null;
231 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
232 $this->query( "PRAGMA synchronous = $sync", __METHOD__
);
234 } catch ( Exception
$e ) {
235 // Connection was not fully initialized and is not safe for use
242 * @return string SQLite DB file path
245 public function getDbFilePath() {
246 return $this->dbPath
;
250 * Does not actually close the connection, just destroys the reference for GC to do its work
253 protected function closeConnection() {
260 * Generates a database file name. Explicitly public for installer.
261 * @param string $dir Directory where database resides
262 * @param string $dbName Database name
265 public static function generateFileName( $dir, $dbName ) {
266 return "$dir/$dbName.sqlite";
270 * Check if the searchindext table is FTS enabled.
271 * @return bool False if not enabled.
273 public function checkForEnabledSearch() {
274 if ( self
::$fulltextEnabled === null ) {
275 self
::$fulltextEnabled = false;
276 $table = $this->tableName( 'searchindex' );
277 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
279 $row = $res->fetchRow();
280 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
284 return self
::$fulltextEnabled;
288 * Returns version of currently supported SQLite fulltext search module or false if none present.
291 static function getFulltextSearchModule() {
292 static $cachedResult = null;
293 if ( $cachedResult !== null ) {
294 return $cachedResult;
296 $cachedResult = false;
297 $table = 'dummy_search_test';
299 $db = self
::newStandaloneInstance( ':memory:' );
300 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
301 $cachedResult = 'FTS3';
305 return $cachedResult;
309 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
312 * @param string $name Database name to be used in queries like
313 * SELECT foo FROM dbname.table
314 * @param bool|string $file Database file name. If omitted, will be generated
315 * using $name and configured data directory
316 * @param string $fname Calling function name
317 * @return IResultWrapper
319 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
321 $file = self
::generateFileName( $this->dbDir
, $name );
323 $file = $this->addQuotes( $file );
325 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
328 protected function isWriteQuery( $sql ) {
329 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
332 protected function isTransactableQuery( $sql ) {
333 return parent
::isTransactableQuery( $sql ) && !in_array(
334 $this->getQueryVerb( $sql ),
335 [ 'ATTACH', 'PRAGMA' ],
341 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
344 * @return bool|IResultWrapper
346 protected function doQuery( $sql ) {
347 $res = $this->getBindingHandle()->query( $sql );
348 if ( $res === false ) {
352 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
353 $this->lastAffectedRowCount
= $r->rowCount();
354 $res = new ResultWrapper( $this, $r->fetchAll() );
360 * @param IResultWrapper|mixed $res
362 function freeResult( $res ) {
363 if ( $res instanceof ResultWrapper
) {
371 * @param IResultWrapper|array $res
372 * @return stdClass|bool
374 function fetchObject( $res ) {
375 if ( $res instanceof ResultWrapper
) {
381 $cur = current( $r );
382 if ( is_array( $cur ) ) {
385 foreach ( $cur as $k => $v ) {
386 if ( !is_numeric( $k ) ) {
398 * @param IResultWrapper|mixed $res
401 function fetchRow( $res ) {
402 if ( $res instanceof ResultWrapper
) {
407 $cur = current( $r );
408 if ( is_array( $cur ) ) {
418 * The PDO::Statement class implements the array interface so count() will work
420 * @param IResultWrapper|array|false $res
423 function numRows( $res ) {
424 // false does not implement Countable
425 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
427 return is_array( $r ) ?
count( $r ) : 0;
431 * @param IResultWrapper $res
434 function numFields( $res ) {
435 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
436 if ( is_array( $r ) && count( $r ) > 0 ) {
437 // The size of the result array is twice the number of fields. (T67578)
438 return count( $r[0] ) / 2;
440 // If the result is empty return 0
446 * @param IResultWrapper $res
450 function fieldName( $res, $n ) {
451 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
452 if ( is_array( $r ) ) {
453 $keys = array_keys( $r[0] );
462 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
464 * @param string $name
465 * @param string $format
468 function tableName( $name, $format = 'quoted' ) {
469 // table names starting with sqlite_ are reserved
470 if ( strpos( $name, 'sqlite_' ) === 0 ) {
474 return str_replace( '"', '', parent
::tableName( $name, $format ) );
478 * This must be called after nextSequenceVal
482 function insertId() {
483 // PDO::lastInsertId yields a string :(
484 return intval( $this->getBindingHandle()->lastInsertId() );
488 * @param IResultWrapper|array $res
491 function dataSeek( $res, $row ) {
492 if ( $res instanceof ResultWrapper
) {
499 for ( $i = 0; $i < $row; $i++
) {
508 function lastError() {
509 if ( !is_object( $this->conn
) ) {
510 return "Cannot return last error, no db connection";
512 $e = $this->conn
->errorInfo();
520 function lastErrno() {
521 if ( !is_object( $this->conn
) ) {
522 return "Cannot return last error, no db connection";
524 $info = $this->conn
->errorInfo();
533 protected function fetchAffectedRowCount() {
534 return $this->lastAffectedRowCount
;
537 function tableExists( $table, $fname = __METHOD__
) {
538 $tableRaw = $this->tableName( $table, 'raw' );
539 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
540 return true; // already known to exist
543 $encTable = $this->addQuotes( $tableRaw );
545 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
547 return $res->numRows() ?
true : false;
551 * Returns information about an index
552 * Returns false if the index does not exist
553 * - if errors are explicitly ignored, returns NULL on failure
555 * @param string $table
556 * @param string $index
557 * @param string $fname
558 * @return array|false
560 function indexInfo( $table, $index, $fname = __METHOD__
) {
561 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
562 $res = $this->query( $sql, $fname );
563 if ( !$res ||
$res->numRows() == 0 ) {
567 foreach ( $res as $row ) {
568 $info[] = $row->name
;
575 * @param string $table
576 * @param string $index
577 * @param string $fname
580 function indexUnique( $table, $index, $fname = __METHOD__
) {
581 $row = $this->selectRow( 'sqlite_master', '*',
584 'name' => $this->indexName( $index ),
586 if ( !$row ||
!isset( $row->sql
) ) {
590 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
591 $indexPos = strpos( $row->sql
, 'INDEX' );
592 if ( $indexPos === false ) {
595 $firstPart = substr( $row->sql
, 0, $indexPos );
596 $options = explode( ' ', $firstPart );
598 return in_array( 'UNIQUE', $options );
602 * Filter the options used in SELECT statements
604 * @param array $options
607 function makeSelectOptions( $options ) {
608 foreach ( $options as $k => $v ) {
609 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
614 return parent
::makeSelectOptions( $options );
618 * @param array $options
621 protected function makeUpdateOptionsArray( $options ) {
622 $options = parent
::makeUpdateOptionsArray( $options );
623 $options = self
::fixIgnore( $options );
629 * @param array $options
632 static function fixIgnore( $options ) {
633 # SQLite uses OR IGNORE not just IGNORE
634 foreach ( $options as $k => $v ) {
635 if ( $v == 'IGNORE' ) {
636 $options[$k] = 'OR IGNORE';
644 * @param array $options
647 function makeInsertOptions( $options ) {
648 $options = self
::fixIgnore( $options );
650 return parent
::makeInsertOptions( $options );
654 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
655 * @param string $table
657 * @param string $fname
658 * @param array $options
661 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
662 if ( !count( $a ) ) {
666 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
667 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
668 $affectedRowCount = 0;
670 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
671 foreach ( $a as $v ) {
672 parent
::insert( $table, $v, "$fname/multi-row", $options );
673 $affectedRowCount +
= $this->affectedRows();
675 $this->endAtomic( $fname );
676 } catch ( Exception
$e ) {
677 $this->cancelAtomic( $fname );
680 $this->affectedRowCount
= $affectedRowCount;
682 parent
::insert( $table, $a, "$fname/single-row", $options );
689 * @param string $table
690 * @param array $uniqueIndexes Unused
691 * @param string|array $rows
692 * @param string $fname
694 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
695 if ( !count( $rows ) ) {
699 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
700 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
701 $affectedRowCount = 0;
703 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
704 foreach ( $rows as $v ) {
705 $this->nativeReplace( $table, $v, "$fname/multi-row" );
706 $affectedRowCount +
= $this->affectedRows();
708 $this->endAtomic( $fname );
709 } catch ( Exception
$e ) {
710 $this->cancelAtomic( $fname );
713 $this->affectedRowCount
= $affectedRowCount;
715 $this->nativeReplace( $table, $rows, "$fname/single-row" );
720 * Returns the size of a text field, or -1 for "unlimited"
721 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
723 * @param string $table
724 * @param string $field
727 function textFieldSize( $table, $field ) {
734 function unionSupportsOrderAndLimit() {
739 * @param string[] $sqls
740 * @param bool $all Whether to "UNION ALL" or not
743 function unionQueries( $sqls, $all ) {
744 $glue = $all ?
' UNION ALL ' : ' UNION ';
746 return implode( $glue, $sqls );
752 function wasDeadlock() {
753 return $this->lastErrno() == 5; // SQLITE_BUSY
759 function wasReadOnlyError() {
760 return $this->lastErrno() == 8; // SQLITE_READONLY;
763 public function wasConnectionError( $errno ) {
764 return $errno == 17; // SQLITE_SCHEMA;
767 protected function wasKnownStatementRollbackError() {
768 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
769 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
770 // https://sqlite.org/lang_createtable.html#uniqueconst
771 // https://sqlite.org/lang_conflict.html
776 * @return string Wikitext of a link to the server software's web site
778 public function getSoftwareLink() {
779 return "[{{int:version-db-sqlite-url}} SQLite]";
783 * @return string Version information from the database
785 function getServerVersion() {
786 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
792 * Get information about a given field
793 * Returns false if the field does not exist.
795 * @param string $table
796 * @param string $field
797 * @return SQLiteField|bool False on failure
799 function fieldInfo( $table, $field ) {
800 $tableName = $this->tableName( $table );
801 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
802 $res = $this->query( $sql, __METHOD__
);
803 foreach ( $res as $row ) {
804 if ( $row->name
== $field ) {
805 return new SQLiteField( $row, $tableName );
812 protected function doBegin( $fname = '' ) {
813 if ( $this->trxMode
) {
814 $this->query( "BEGIN {$this->trxMode}", $fname );
816 $this->query( 'BEGIN', $fname );
825 function strencode( $s ) {
826 return substr( $this->addQuotes( $s ), 1, -1 );
833 function encodeBlob( $b ) {
834 return new Blob( $b );
838 * @param Blob|string $b
841 function decodeBlob( $b ) {
842 if ( $b instanceof Blob
) {
850 * @param string|int|null|bool|Blob $s
853 function addQuotes( $s ) {
854 if ( $s instanceof Blob
) {
855 return "x'" . bin2hex( $s->fetch() ) . "'";
856 } elseif ( is_bool( $s ) ) {
858 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
859 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
860 // This is a known limitation of SQLite's mprintf function which PDO
861 // should work around, but doesn't. I have reported this to php.net as bug #63419:
862 // https://bugs.php.net/bug.php?id=63419
863 // There was already a similar report for SQLite3::escapeString, bug #62361:
864 // https://bugs.php.net/bug.php?id=62361
865 // There is an additional bug regarding sorting this data after insert
866 // on older versions of sqlite shipped with ubuntu 12.04
867 // https://phabricator.wikimedia.org/T74367
868 $this->queryLogger
->debug(
870 ': Quoting value containing null byte. ' .
871 'For consistency all binary data should have been ' .
872 'first processed with self::encodeBlob()'
874 return "x'" . bin2hex( (string)$s ) . "'";
876 return $this->getBindingHandle()->quote( (string)$s );
880 public function buildSubstring( $input, $startPosition, $length = null ) {
881 $this->assertBuildSubstringParams( $startPosition, $length );
882 $params = [ $input, $startPosition ];
883 if ( $length !== null ) {
886 return 'SUBSTR(' . implode( ',', $params ) . ')';
890 * @param string $field Field or column to cast
894 public function buildStringCast( $field ) {
895 return 'CAST ( ' . $field . ' AS TEXT )';
899 * No-op version of deadlockLoop
903 public function deadlockLoop( /*...*/ ) {
904 $args = func_get_args();
905 $function = array_shift( $args );
907 return $function( ...$args );
914 protected function replaceVars( $s ) {
915 $s = parent
::replaceVars( $s );
916 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
917 // CREATE TABLE hacks to allow schema file sharing with MySQL
919 // binary/varbinary column type -> blob
920 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
921 // no such thing as unsigned
922 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
924 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
925 // floating point types -> REAL
927 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
932 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
933 // TEXT normalization
934 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
935 // BLOB normalization
936 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
938 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
940 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
942 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
943 // binary collation type -> nothing
944 $s = preg_replace( '/\bbinary\b/i', '', $s );
945 // auto_increment -> autoincrement
946 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
947 // No explicit options
948 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
949 // AUTOINCREMENT should immedidately follow PRIMARY KEY
950 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
951 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
952 // No truncated indexes
953 $s = preg_replace( '/\(\d+\)/', '', $s );
955 $s = preg_replace( '/\bfulltext\b/i', '', $s );
956 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
957 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
958 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
959 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
960 // INSERT IGNORE --> INSERT OR IGNORE
961 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
967 public function lock( $lockName, $method, $timeout = 5 ) {
968 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
969 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
970 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
974 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
977 public function unlock( $lockName, $method ) {
978 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
982 * Build a concatenation list to feed into a SQL query
984 * @param string[] $stringList
987 function buildConcat( $stringList ) {
988 return '(' . implode( ') || (', $stringList ) . ')';
991 public function buildGroupConcatField(
992 $delim, $table, $field, $conds = '', $join_conds = []
994 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
996 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1000 * @param string $oldName
1001 * @param string $newName
1002 * @param bool $temporary
1003 * @param string $fname
1004 * @return bool|IResultWrapper
1005 * @throws RuntimeException
1007 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1008 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1009 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1010 $obj = $this->fetchObject( $res );
1012 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1015 $sql = preg_replace(
1017 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1019 $this->addIdentifierQuotes( $newName ),
1024 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1025 $this->queryLogger
->debug(
1026 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1028 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1032 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1034 // Take over indexes
1035 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1036 foreach ( $indexList as $index ) {
1037 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1041 if ( $index->unique
) {
1042 $sql = 'CREATE UNIQUE INDEX';
1044 $sql = 'CREATE INDEX';
1046 // Try to come up with a new index name, given indexes have database scope in SQLite
1047 $indexName = $newName . '_' . $index->name
;
1048 $sql .= ' ' . $indexName . ' ON ' . $newName;
1050 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1052 foreach ( $indexInfo as $indexInfoRow ) {
1053 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1056 $sql .= '(' . implode( ',', $fields ) . ')';
1058 $this->query( $sql );
1065 * List all tables on the database
1067 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1068 * @param string $fname Calling function name
1072 function listTables( $prefix = null, $fname = __METHOD__
) {
1073 $result = $this->select(
1081 foreach ( $result as $table ) {
1082 $vars = get_object_vars( $table );
1083 $table = array_pop( $vars );
1085 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1086 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1087 $endArray[] = $table;
1096 * Override due to no CASCADE support
1098 * @param string $tableName
1099 * @param string $fName
1100 * @return bool|IResultWrapper
1101 * @throws DBReadOnlyError
1103 public function dropTable( $tableName, $fName = __METHOD__
) {
1104 if ( !$this->tableExists( $tableName, $fName ) ) {
1107 $sql = "DROP TABLE " . $this->tableName( $tableName );
1109 return $this->query( $sql, $fName );
1112 public function setTableAliases( array $aliases ) {
1113 parent
::setTableAliases( $aliases );
1114 foreach ( $this->tableAliases
as $params ) {
1115 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1118 $this->attachDatabase( $params['dbname'] );
1119 $this->alreadyAttached
[$params['dbname']] = true;
1123 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1124 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1125 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1126 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1129 public function databasesAreIndependent() {
1136 protected function getBindingHandle() {
1137 return parent
::getBindingHandle();
1142 * @deprecated since 1.29
1144 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );