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
;
32 use InvalidArgumentException
;
39 class DatabaseSqlite
extends Database
{
40 /** @var bool Whether full text is enabled */
41 private static $fulltextEnabled = null;
43 /** @var string|null Directory */
45 /** @var string File name for SQLite database file */
47 /** @var string Transaction mode */
50 /** @var int The number of rows affected as an integer */
51 protected $lastAffectedRowCount;
53 protected $lastResultHandle;
58 /** @var FSLockManager (hopefully on the same server as the DB) */
61 /** @var array List of shared database already attached to this connection */
62 private $alreadyAttached = [];
65 * Additional params include:
66 * - dbDirectory : directory containing the DB and the lock file directory
67 * [defaults to $wgSQLiteDataDir]
68 * - dbFilePath : use this to force the path of the DB file
69 * - trxMode : one of (deferred, immediate, exclusive)
72 function __construct( array $p ) {
73 if ( isset( $p['dbFilePath'] ) ) {
74 $this->dbPath
= $p['dbFilePath'];
75 $lockDomain = md5( $this->dbPath
);
76 // Use "X" for things like X.sqlite and ":memory:" for RAM-only DBs
77 if ( !isset( $p['dbname'] ) ||
!strlen( $p['dbname'] ) ) {
78 $p['dbname'] = preg_replace( '/\.sqlite\d?$/', '', basename( $this->dbPath
) );
80 } elseif ( isset( $p['dbDirectory'] ) ) {
81 $this->dbDir
= $p['dbDirectory'];
82 $lockDomain = $p['dbname'];
84 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
87 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
88 if ( $this->trxMode
&&
89 !in_array( $this->trxMode
, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
91 $this->trxMode
= null;
92 $this->queryLogger
->warning( "Invalid SQLite transaction mode provided." );
95 if ( $this->hasProcessMemoryPath() ) {
96 $this->lockMgr
= new NullLockManager( [ 'domain' => $lockDomain ] );
98 $this->lockMgr
= new FSLockManager( [
99 'domain' => $lockDomain,
100 'lockDirectory' => is_string( $this->dbDir
)
101 ?
"{$this->dbDir}/locks"
102 : dirname( $this->dbPath
) . "/locks"
106 parent
::__construct( $p );
109 protected static function getAttributes() {
110 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
114 * @param string $filename
115 * @param array $p Options map; supports:
116 * - flags : (same as __construct counterpart)
117 * - trxMode : (same as __construct counterpart)
118 * - dbDirectory : (same as __construct counterpart)
119 * @return DatabaseSqlite
122 public static function newStandaloneInstance( $filename, array $p = [] ) {
123 $p['dbFilePath'] = $filename;
125 $p['tablePrefix'] = '';
126 /** @var DatabaseSqlite $db */
127 $db = Database
::factory( 'sqlite', $p );
132 protected function doInitConnection() {
133 if ( $this->dbPath
!== null ) {
134 // Standalone .sqlite file mode.
137 $this->connectionParams
['dbname'],
138 $this->connectionParams
['tablePrefix']
140 } elseif ( $this->dbDir
!== null ) {
141 // Stock wiki mode using standard file names per DB
142 if ( strlen( $this->connectionParams
['dbname'] ) ) {
144 $this->connectionParams
['host'],
145 $this->connectionParams
['user'],
146 $this->connectionParams
['password'],
147 $this->connectionParams
['dbname'],
148 $this->connectionParams
['schema'],
149 $this->connectionParams
['tablePrefix']
152 // Caller will manually call open() later?
153 $this->connLogger
->debug( __METHOD__
. ': no database opened.' );
156 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
168 * @todo Check if it should be true like parent class
172 function implicitGroupby() {
176 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
179 if ( $schema !== null ) {
180 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
183 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
184 $this->openFile( self
::generateFileName( $this->dbDir
, $dbName ), $dbName, $tablePrefix );
188 * Opens a database file
190 * @param string $fileName
191 * @param string $dbName
192 * @param string $tablePrefix
193 * @throws DBConnectionError
195 protected function openFile( $fileName, $dbName, $tablePrefix ) {
196 if ( !$this->hasProcessMemoryPath() && !is_readable( $fileName ) ) {
197 $error = "SQLite database file not readable";
198 $this->connLogger
->error(
199 "Error connecting to {db_server}: {error}",
200 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
202 throw new DBConnectionError( $this, $error );
205 $this->dbPath
= $fileName;
207 $this->conn
= new PDO(
211 [ PDO
::ATTR_PERSISTENT
=> (bool)( $this->flags
& self
::DBO_PERSISTENT
) ]
213 $error = 'unknown error';
214 } catch ( PDOException
$e ) {
215 $error = $e->getMessage();
218 if ( !$this->conn
) {
219 $this->connLogger
->error(
220 "Error connecting to {db_server}: {error}",
221 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
223 throw new DBConnectionError( $this, $error );
227 // Set error codes only, don't raise exceptions
228 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
230 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
232 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
;
233 // Enforce LIKE to be case sensitive, just like MySQL
234 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__
, $flags );
235 // Apply an optimizations or requirements regarding fsync() usage
236 $sync = $this->connectionVariables
['synchronous'] ??
null;
237 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
238 $this->query( "PRAGMA synchronous = $sync", __METHOD__
);
240 } catch ( Exception
$e ) {
241 // Connection was not fully initialized and is not safe for use
248 * @return string SQLite DB file path
251 public function getDbFilePath() {
252 return $this->dbPath
;
256 * Does not actually close the connection, just destroys the reference for GC to do its work
259 protected function closeConnection() {
266 * Generates a database file name. Explicitly public for installer.
267 * @param string $dir Directory where database resides
268 * @param string $dbName Database name
271 public static function generateFileName( $dir, $dbName ) {
272 return "$dir/$dbName.sqlite";
276 * Check if the searchindext table is FTS enabled.
277 * @return bool False if not enabled.
279 public function checkForEnabledSearch() {
280 if ( self
::$fulltextEnabled === null ) {
281 self
::$fulltextEnabled = false;
282 $table = $this->tableName( 'searchindex' );
283 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
285 $row = $res->fetchRow();
286 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
290 return self
::$fulltextEnabled;
294 * Returns version of currently supported SQLite fulltext search module or false if none present.
297 static function getFulltextSearchModule() {
298 static $cachedResult = null;
299 if ( $cachedResult !== null ) {
300 return $cachedResult;
302 $cachedResult = false;
303 $table = 'dummy_search_test';
305 $db = self
::newStandaloneInstance( ':memory:' );
306 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
307 $cachedResult = 'FTS3';
311 return $cachedResult;
315 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
318 * @param string $name Database name to be used in queries like
319 * SELECT foo FROM dbname.table
320 * @param bool|string $file Database file name. If omitted, will be generated
321 * using $name and configured data directory
322 * @param string $fname Calling function name
323 * @return IResultWrapper
325 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
327 $file = self
::generateFileName( $this->dbDir
, $name );
329 $file = $this->addQuotes( $file );
331 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
334 protected function isWriteQuery( $sql ) {
335 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
338 protected function isTransactableQuery( $sql ) {
339 return parent
::isTransactableQuery( $sql ) && !in_array(
340 $this->getQueryVerb( $sql ),
341 [ 'ATTACH', 'PRAGMA' ],
347 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
350 * @return bool|IResultWrapper
352 protected function doQuery( $sql ) {
353 $res = $this->getBindingHandle()->query( $sql );
354 if ( $res === false ) {
358 $resource = ResultWrapper
::unwrap( $res );
359 $this->lastAffectedRowCount
= $resource->rowCount();
360 $res = new ResultWrapper( $this, $resource->fetchAll() );
366 * @param IResultWrapper|mixed $res
368 function freeResult( $res ) {
369 if ( $res instanceof ResultWrapper
) {
375 * @param IResultWrapper|array $res
376 * @return stdClass|bool
378 function fetchObject( $res ) {
379 $resource =& ResultWrapper
::unwrap( $res );
381 $cur = current( $resource );
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 $resource =& ResultWrapper
::unwrap( $res );
403 $cur = current( $resource );
404 if ( is_array( $cur ) ) {
414 * The PDO::Statement class implements the array interface so count() will work
416 * @param IResultWrapper|array|false $res
419 function numRows( $res ) {
420 // false does not implement Countable
421 $resource = ResultWrapper
::unwrap( $res );
423 return is_array( $resource ) ?
count( $resource ) : 0;
427 * @param IResultWrapper $res
430 function numFields( $res ) {
431 $resource = ResultWrapper
::unwrap( $res );
432 if ( is_array( $resource ) && count( $resource ) > 0 ) {
433 // The size of the result array is twice the number of fields. (T67578)
434 return count( $resource[0] ) / 2;
436 // If the result is empty return 0
442 * @param IResultWrapper $res
446 function fieldName( $res, $n ) {
447 $resource = ResultWrapper
::unwrap( $res );
448 if ( is_array( $resource ) ) {
449 $keys = array_keys( $resource[0] );
458 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
460 * @param string $name
461 * @param string $format
464 function tableName( $name, $format = 'quoted' ) {
465 // table names starting with sqlite_ are reserved
466 if ( strpos( $name, 'sqlite_' ) === 0 ) {
470 return str_replace( '"', '', parent
::tableName( $name, $format ) );
474 * This must be called after nextSequenceVal
478 function insertId() {
479 // PDO::lastInsertId yields a string :(
480 return intval( $this->getBindingHandle()->lastInsertId() );
484 * @param IResultWrapper|array $res
487 function dataSeek( $res, $row ) {
488 $resource =& ResultWrapper
::unwrap( $res );
491 for ( $i = 0; $i < $row; $i++
) {
500 function lastError() {
501 if ( !is_object( $this->conn
) ) {
502 return "Cannot return last error, no db connection";
504 $e = $this->conn
->errorInfo();
512 function lastErrno() {
513 if ( !is_object( $this->conn
) ) {
514 return "Cannot return last error, no db connection";
516 $info = $this->conn
->errorInfo();
525 protected function fetchAffectedRowCount() {
526 return $this->lastAffectedRowCount
;
529 function tableExists( $table, $fname = __METHOD__
) {
530 $tableRaw = $this->tableName( $table, 'raw' );
531 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
532 return true; // already known to exist
535 $encTable = $this->addQuotes( $tableRaw );
537 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
539 return $res->numRows() ?
true : false;
543 * Returns information about an index
544 * Returns false if the index does not exist
545 * - if errors are explicitly ignored, returns NULL on failure
547 * @param string $table
548 * @param string $index
549 * @param string $fname
550 * @return array|false
552 function indexInfo( $table, $index, $fname = __METHOD__
) {
553 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
554 $res = $this->query( $sql, $fname );
555 if ( !$res ||
$res->numRows() == 0 ) {
559 foreach ( $res as $row ) {
560 $info[] = $row->name
;
567 * @param string $table
568 * @param string $index
569 * @param string $fname
572 function indexUnique( $table, $index, $fname = __METHOD__
) {
573 $row = $this->selectRow( 'sqlite_master', '*',
576 'name' => $this->indexName( $index ),
578 if ( !$row ||
!isset( $row->sql
) ) {
582 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
583 $indexPos = strpos( $row->sql
, 'INDEX' );
584 if ( $indexPos === false ) {
587 $firstPart = substr( $row->sql
, 0, $indexPos );
588 $options = explode( ' ', $firstPart );
590 return in_array( 'UNIQUE', $options );
594 * Filter the options used in SELECT statements
596 * @param array $options
599 function makeSelectOptions( $options ) {
600 foreach ( $options as $k => $v ) {
601 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
606 return parent
::makeSelectOptions( $options );
610 * @param array $options
613 protected function makeUpdateOptionsArray( $options ) {
614 $options = parent
::makeUpdateOptionsArray( $options );
615 $options = self
::fixIgnore( $options );
621 * @param array $options
624 static function fixIgnore( $options ) {
625 # SQLite uses OR IGNORE not just IGNORE
626 foreach ( $options as $k => $v ) {
627 if ( $v == 'IGNORE' ) {
628 $options[$k] = 'OR IGNORE';
636 * @param array $options
639 function makeInsertOptions( $options ) {
640 $options = self
::fixIgnore( $options );
642 return parent
::makeInsertOptions( $options );
646 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
647 * @param string $table
649 * @param string $fname
650 * @param array $options
653 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
654 if ( !count( $a ) ) {
658 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
659 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
660 $affectedRowCount = 0;
662 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
663 foreach ( $a as $v ) {
664 parent
::insert( $table, $v, "$fname/multi-row", $options );
665 $affectedRowCount +
= $this->affectedRows();
667 $this->endAtomic( $fname );
668 } catch ( Exception
$e ) {
669 $this->cancelAtomic( $fname );
672 $this->affectedRowCount
= $affectedRowCount;
674 parent
::insert( $table, $a, "$fname/single-row", $options );
681 * @param string $table
682 * @param array $uniqueIndexes Unused
683 * @param string|array $rows
684 * @param string $fname
686 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
687 if ( !count( $rows ) ) {
691 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
692 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
693 $affectedRowCount = 0;
695 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
696 foreach ( $rows as $v ) {
697 $this->nativeReplace( $table, $v, "$fname/multi-row" );
698 $affectedRowCount +
= $this->affectedRows();
700 $this->endAtomic( $fname );
701 } catch ( Exception
$e ) {
702 $this->cancelAtomic( $fname );
705 $this->affectedRowCount
= $affectedRowCount;
707 $this->nativeReplace( $table, $rows, "$fname/single-row" );
712 * Returns the size of a text field, or -1 for "unlimited"
713 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
715 * @param string $table
716 * @param string $field
719 function textFieldSize( $table, $field ) {
726 function unionSupportsOrderAndLimit() {
731 * @param string[] $sqls
732 * @param bool $all Whether to "UNION ALL" or not
735 function unionQueries( $sqls, $all ) {
736 $glue = $all ?
' UNION ALL ' : ' UNION ';
738 return implode( $glue, $sqls );
744 function wasDeadlock() {
745 return $this->lastErrno() == 5; // SQLITE_BUSY
751 function wasReadOnlyError() {
752 return $this->lastErrno() == 8; // SQLITE_READONLY;
755 public function wasConnectionError( $errno ) {
756 return $errno == 17; // SQLITE_SCHEMA;
759 protected function wasKnownStatementRollbackError() {
760 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
761 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
762 // https://sqlite.org/lang_createtable.html#uniqueconst
763 // https://sqlite.org/lang_conflict.html
767 public function serverIsReadOnly() {
768 return ( !$this->hasProcessMemoryPath() && !is_writable( $this->dbPath
) );
774 private function hasProcessMemoryPath() {
775 return ( strpos( $this->dbPath
, ':memory:' ) === 0 );
779 * @return string Wikitext of a link to the server software's web site
781 public function getSoftwareLink() {
782 return "[{{int:version-db-sqlite-url}} SQLite]";
786 * @return string Version information from the database
788 function getServerVersion() {
789 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
795 * Get information about a given field
796 * Returns false if the field does not exist.
798 * @param string $table
799 * @param string $field
800 * @return SQLiteField|bool False on failure
802 function fieldInfo( $table, $field ) {
803 $tableName = $this->tableName( $table );
804 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
805 $res = $this->query( $sql, __METHOD__
);
806 foreach ( $res as $row ) {
807 if ( $row->name
== $field ) {
808 return new SQLiteField( $row, $tableName );
815 protected function doBegin( $fname = '' ) {
816 if ( $this->trxMode
) {
817 $this->query( "BEGIN {$this->trxMode}", $fname );
819 $this->query( 'BEGIN', $fname );
827 function strencode( $s ) {
828 return substr( $this->addQuotes( $s ), 1, -1 );
835 function encodeBlob( $b ) {
836 return new Blob( $b );
840 * @param Blob|string $b
843 function decodeBlob( $b ) {
844 if ( $b instanceof Blob
) {
852 * @param string|int|null|bool|Blob $s
855 function addQuotes( $s ) {
856 if ( $s instanceof Blob
) {
857 return "x'" . bin2hex( $s->fetch() ) . "'";
858 } elseif ( is_bool( $s ) ) {
860 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
861 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
862 // This is a known limitation of SQLite's mprintf function which PDO
863 // should work around, but doesn't. I have reported this to php.net as bug #63419:
864 // https://bugs.php.net/bug.php?id=63419
865 // There was already a similar report for SQLite3::escapeString, bug #62361:
866 // https://bugs.php.net/bug.php?id=62361
867 // There is an additional bug regarding sorting this data after insert
868 // on older versions of sqlite shipped with ubuntu 12.04
869 // https://phabricator.wikimedia.org/T74367
870 $this->queryLogger
->debug(
872 ': Quoting value containing null byte. ' .
873 'For consistency all binary data should have been ' .
874 'first processed with self::encodeBlob()'
876 return "x'" . bin2hex( (string)$s ) . "'";
878 return $this->getBindingHandle()->quote( (string)$s );
882 public function buildSubstring( $input, $startPosition, $length = null ) {
883 $this->assertBuildSubstringParams( $startPosition, $length );
884 $params = [ $input, $startPosition ];
885 if ( $length !== null ) {
888 return 'SUBSTR(' . implode( ',', $params ) . ')';
892 * @param string $field Field or column to cast
896 public function buildStringCast( $field ) {
897 return 'CAST ( ' . $field . ' AS TEXT )';
901 * No-op version of deadlockLoop
905 public function deadlockLoop( /*...*/ ) {
906 $args = func_get_args();
907 $function = array_shift( $args );
909 return $function( ...$args );
916 protected function replaceVars( $s ) {
917 $s = parent
::replaceVars( $s );
918 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
919 // CREATE TABLE hacks to allow schema file sharing with MySQL
921 // binary/varbinary column type -> blob
922 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
923 // no such thing as unsigned
924 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
926 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
927 // floating point types -> REAL
929 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
934 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
935 // TEXT normalization
936 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
937 // BLOB normalization
938 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
940 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
942 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
944 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
945 // binary collation type -> nothing
946 $s = preg_replace( '/\bbinary\b/i', '', $s );
947 // auto_increment -> autoincrement
948 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
949 // No explicit options
950 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
951 // AUTOINCREMENT should immedidately follow PRIMARY KEY
952 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
953 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
954 // No truncated indexes
955 $s = preg_replace( '/\(\d+\)/', '', $s );
957 $s = preg_replace( '/\bfulltext\b/i', '', $s );
958 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
959 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
960 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
961 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
962 // INSERT IGNORE --> INSERT OR IGNORE
963 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
969 public function lock( $lockName, $method, $timeout = 5 ) {
970 // Give better error message for permission problems than just returning false
972 !is_dir( "{$this->dbDir}/locks" ) &&
973 ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) )
975 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
978 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
981 public function unlock( $lockName, $method ) {
982 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isGood();
986 * Build a concatenation list to feed into a SQL query
988 * @param string[] $stringList
991 function buildConcat( $stringList ) {
992 return '(' . implode( ') || (', $stringList ) . ')';
995 public function buildGroupConcatField(
996 $delim, $table, $field, $conds = '', $join_conds = []
998 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1000 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1004 * @param string $oldName
1005 * @param string $newName
1006 * @param bool $temporary
1007 * @param string $fname
1008 * @return bool|IResultWrapper
1009 * @throws RuntimeException
1011 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1012 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1013 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1014 $obj = $this->fetchObject( $res );
1016 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1019 $sql = preg_replace(
1021 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1023 $this->addIdentifierQuotes( $newName ),
1028 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1029 $this->queryLogger
->debug(
1030 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1032 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1036 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1038 // Take over indexes
1039 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1040 foreach ( $indexList as $index ) {
1041 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1045 if ( $index->unique
) {
1046 $sql = 'CREATE UNIQUE INDEX';
1048 $sql = 'CREATE INDEX';
1050 // Try to come up with a new index name, given indexes have database scope in SQLite
1051 $indexName = $newName . '_' . $index->name
;
1052 $sql .= ' ' . $indexName . ' ON ' . $newName;
1054 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1056 foreach ( $indexInfo as $indexInfoRow ) {
1057 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1060 $sql .= '(' . implode( ',', $fields ) . ')';
1062 $this->query( $sql );
1069 * List all tables on the database
1071 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1072 * @param string $fname Calling function name
1076 function listTables( $prefix = null, $fname = __METHOD__
) {
1077 $result = $this->select(
1085 foreach ( $result as $table ) {
1086 $vars = get_object_vars( $table );
1087 $table = array_pop( $vars );
1089 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1090 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1091 $endArray[] = $table;
1100 * Override due to no CASCADE support
1102 * @param string $tableName
1103 * @param string $fName
1104 * @return bool|IResultWrapper
1105 * @throws DBReadOnlyError
1107 public function dropTable( $tableName, $fName = __METHOD__
) {
1108 if ( !$this->tableExists( $tableName, $fName ) ) {
1111 $sql = "DROP TABLE " . $this->tableName( $tableName );
1113 return $this->query( $sql, $fName );
1116 public function setTableAliases( array $aliases ) {
1117 parent
::setTableAliases( $aliases );
1118 foreach ( $this->tableAliases
as $params ) {
1119 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1122 $this->attachDatabase( $params['dbname'] );
1123 $this->alreadyAttached
[$params['dbname']] = true;
1127 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1128 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1129 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1130 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1133 public function databasesAreIndependent() {
1140 protected function getBindingHandle() {
1141 return parent
::getBindingHandle();
1146 * @deprecated since 1.29
1148 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );