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 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
359 $this->lastAffectedRowCount
= $r->rowCount();
360 $res = new ResultWrapper( $this, $r->fetchAll() );
366 * @param IResultWrapper|mixed $res
368 function freeResult( $res ) {
369 if ( $res instanceof ResultWrapper
) {
377 * @param IResultWrapper|array $res
378 * @return stdClass|bool
380 function fetchObject( $res ) {
381 if ( $res instanceof ResultWrapper
) {
387 $cur = current( $r );
388 if ( is_array( $cur ) ) {
391 foreach ( $cur as $k => $v ) {
392 if ( !is_numeric( $k ) ) {
404 * @param IResultWrapper|mixed $res
407 function fetchRow( $res ) {
408 if ( $res instanceof ResultWrapper
) {
413 $cur = current( $r );
414 if ( is_array( $cur ) ) {
424 * The PDO::Statement class implements the array interface so count() will work
426 * @param IResultWrapper|array|false $res
429 function numRows( $res ) {
430 // false does not implement Countable
431 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
433 return is_array( $r ) ?
count( $r ) : 0;
437 * @param IResultWrapper $res
440 function numFields( $res ) {
441 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
442 if ( is_array( $r ) && count( $r ) > 0 ) {
443 // The size of the result array is twice the number of fields. (T67578)
444 return count( $r[0] ) / 2;
446 // If the result is empty return 0
452 * @param IResultWrapper $res
456 function fieldName( $res, $n ) {
457 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
458 if ( is_array( $r ) ) {
459 $keys = array_keys( $r[0] );
468 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
470 * @param string $name
471 * @param string $format
474 function tableName( $name, $format = 'quoted' ) {
475 // table names starting with sqlite_ are reserved
476 if ( strpos( $name, 'sqlite_' ) === 0 ) {
480 return str_replace( '"', '', parent
::tableName( $name, $format ) );
484 * This must be called after nextSequenceVal
488 function insertId() {
489 // PDO::lastInsertId yields a string :(
490 return intval( $this->getBindingHandle()->lastInsertId() );
494 * @param IResultWrapper|array $res
497 function dataSeek( $res, $row ) {
498 if ( $res instanceof ResultWrapper
) {
505 for ( $i = 0; $i < $row; $i++
) {
514 function lastError() {
515 if ( !is_object( $this->conn
) ) {
516 return "Cannot return last error, no db connection";
518 $e = $this->conn
->errorInfo();
526 function lastErrno() {
527 if ( !is_object( $this->conn
) ) {
528 return "Cannot return last error, no db connection";
530 $info = $this->conn
->errorInfo();
539 protected function fetchAffectedRowCount() {
540 return $this->lastAffectedRowCount
;
543 function tableExists( $table, $fname = __METHOD__
) {
544 $tableRaw = $this->tableName( $table, 'raw' );
545 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
546 return true; // already known to exist
549 $encTable = $this->addQuotes( $tableRaw );
551 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
553 return $res->numRows() ?
true : false;
557 * Returns information about an index
558 * Returns false if the index does not exist
559 * - if errors are explicitly ignored, returns NULL on failure
561 * @param string $table
562 * @param string $index
563 * @param string $fname
564 * @return array|false
566 function indexInfo( $table, $index, $fname = __METHOD__
) {
567 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
568 $res = $this->query( $sql, $fname );
569 if ( !$res ||
$res->numRows() == 0 ) {
573 foreach ( $res as $row ) {
574 $info[] = $row->name
;
581 * @param string $table
582 * @param string $index
583 * @param string $fname
586 function indexUnique( $table, $index, $fname = __METHOD__
) {
587 $row = $this->selectRow( 'sqlite_master', '*',
590 'name' => $this->indexName( $index ),
592 if ( !$row ||
!isset( $row->sql
) ) {
596 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
597 $indexPos = strpos( $row->sql
, 'INDEX' );
598 if ( $indexPos === false ) {
601 $firstPart = substr( $row->sql
, 0, $indexPos );
602 $options = explode( ' ', $firstPart );
604 return in_array( 'UNIQUE', $options );
608 * Filter the options used in SELECT statements
610 * @param array $options
613 function makeSelectOptions( $options ) {
614 foreach ( $options as $k => $v ) {
615 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
620 return parent
::makeSelectOptions( $options );
624 * @param array $options
627 protected function makeUpdateOptionsArray( $options ) {
628 $options = parent
::makeUpdateOptionsArray( $options );
629 $options = self
::fixIgnore( $options );
635 * @param array $options
638 static function fixIgnore( $options ) {
639 # SQLite uses OR IGNORE not just IGNORE
640 foreach ( $options as $k => $v ) {
641 if ( $v == 'IGNORE' ) {
642 $options[$k] = 'OR IGNORE';
650 * @param array $options
653 function makeInsertOptions( $options ) {
654 $options = self
::fixIgnore( $options );
656 return parent
::makeInsertOptions( $options );
660 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
661 * @param string $table
663 * @param string $fname
664 * @param array $options
667 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
668 if ( !count( $a ) ) {
672 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
673 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
674 $affectedRowCount = 0;
676 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
677 foreach ( $a as $v ) {
678 parent
::insert( $table, $v, "$fname/multi-row", $options );
679 $affectedRowCount +
= $this->affectedRows();
681 $this->endAtomic( $fname );
682 } catch ( Exception
$e ) {
683 $this->cancelAtomic( $fname );
686 $this->affectedRowCount
= $affectedRowCount;
688 parent
::insert( $table, $a, "$fname/single-row", $options );
695 * @param string $table
696 * @param array $uniqueIndexes Unused
697 * @param string|array $rows
698 * @param string $fname
700 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
701 if ( !count( $rows ) ) {
705 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
706 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
707 $affectedRowCount = 0;
709 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
710 foreach ( $rows as $v ) {
711 $this->nativeReplace( $table, $v, "$fname/multi-row" );
712 $affectedRowCount +
= $this->affectedRows();
714 $this->endAtomic( $fname );
715 } catch ( Exception
$e ) {
716 $this->cancelAtomic( $fname );
719 $this->affectedRowCount
= $affectedRowCount;
721 $this->nativeReplace( $table, $rows, "$fname/single-row" );
726 * Returns the size of a text field, or -1 for "unlimited"
727 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
729 * @param string $table
730 * @param string $field
733 function textFieldSize( $table, $field ) {
740 function unionSupportsOrderAndLimit() {
745 * @param string[] $sqls
746 * @param bool $all Whether to "UNION ALL" or not
749 function unionQueries( $sqls, $all ) {
750 $glue = $all ?
' UNION ALL ' : ' UNION ';
752 return implode( $glue, $sqls );
758 function wasDeadlock() {
759 return $this->lastErrno() == 5; // SQLITE_BUSY
765 function wasReadOnlyError() {
766 return $this->lastErrno() == 8; // SQLITE_READONLY;
769 public function wasConnectionError( $errno ) {
770 return $errno == 17; // SQLITE_SCHEMA;
773 protected function wasKnownStatementRollbackError() {
774 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
775 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
776 // https://sqlite.org/lang_createtable.html#uniqueconst
777 // https://sqlite.org/lang_conflict.html
781 public function serverIsReadOnly() {
782 return ( !$this->hasProcessMemoryPath() && !is_writable( $this->dbPath
) );
788 private function hasProcessMemoryPath() {
789 return ( strpos( $this->dbPath
, ':memory:' ) === 0 );
793 * @return string Wikitext of a link to the server software's web site
795 public function getSoftwareLink() {
796 return "[{{int:version-db-sqlite-url}} SQLite]";
800 * @return string Version information from the database
802 function getServerVersion() {
803 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
809 * Get information about a given field
810 * Returns false if the field does not exist.
812 * @param string $table
813 * @param string $field
814 * @return SQLiteField|bool False on failure
816 function fieldInfo( $table, $field ) {
817 $tableName = $this->tableName( $table );
818 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
819 $res = $this->query( $sql, __METHOD__
);
820 foreach ( $res as $row ) {
821 if ( $row->name
== $field ) {
822 return new SQLiteField( $row, $tableName );
829 protected function doBegin( $fname = '' ) {
830 if ( $this->trxMode
) {
831 $this->query( "BEGIN {$this->trxMode}", $fname );
833 $this->query( 'BEGIN', $fname );
841 function strencode( $s ) {
842 return substr( $this->addQuotes( $s ), 1, -1 );
849 function encodeBlob( $b ) {
850 return new Blob( $b );
854 * @param Blob|string $b
857 function decodeBlob( $b ) {
858 if ( $b instanceof Blob
) {
866 * @param string|int|null|bool|Blob $s
869 function addQuotes( $s ) {
870 if ( $s instanceof Blob
) {
871 return "x'" . bin2hex( $s->fetch() ) . "'";
872 } elseif ( is_bool( $s ) ) {
874 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
875 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
876 // This is a known limitation of SQLite's mprintf function which PDO
877 // should work around, but doesn't. I have reported this to php.net as bug #63419:
878 // https://bugs.php.net/bug.php?id=63419
879 // There was already a similar report for SQLite3::escapeString, bug #62361:
880 // https://bugs.php.net/bug.php?id=62361
881 // There is an additional bug regarding sorting this data after insert
882 // on older versions of sqlite shipped with ubuntu 12.04
883 // https://phabricator.wikimedia.org/T74367
884 $this->queryLogger
->debug(
886 ': Quoting value containing null byte. ' .
887 'For consistency all binary data should have been ' .
888 'first processed with self::encodeBlob()'
890 return "x'" . bin2hex( (string)$s ) . "'";
892 return $this->getBindingHandle()->quote( (string)$s );
896 public function buildSubstring( $input, $startPosition, $length = null ) {
897 $this->assertBuildSubstringParams( $startPosition, $length );
898 $params = [ $input, $startPosition ];
899 if ( $length !== null ) {
902 return 'SUBSTR(' . implode( ',', $params ) . ')';
906 * @param string $field Field or column to cast
910 public function buildStringCast( $field ) {
911 return 'CAST ( ' . $field . ' AS TEXT )';
915 * No-op version of deadlockLoop
919 public function deadlockLoop( /*...*/ ) {
920 $args = func_get_args();
921 $function = array_shift( $args );
923 return $function( ...$args );
930 protected function replaceVars( $s ) {
931 $s = parent
::replaceVars( $s );
932 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
933 // CREATE TABLE hacks to allow schema file sharing with MySQL
935 // binary/varbinary column type -> blob
936 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
937 // no such thing as unsigned
938 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
940 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
941 // floating point types -> REAL
943 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
948 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
949 // TEXT normalization
950 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
951 // BLOB normalization
952 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
954 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
956 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
958 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
959 // binary collation type -> nothing
960 $s = preg_replace( '/\bbinary\b/i', '', $s );
961 // auto_increment -> autoincrement
962 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
963 // No explicit options
964 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
965 // AUTOINCREMENT should immedidately follow PRIMARY KEY
966 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
967 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
968 // No truncated indexes
969 $s = preg_replace( '/\(\d+\)/', '', $s );
971 $s = preg_replace( '/\bfulltext\b/i', '', $s );
972 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
973 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
974 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
975 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
976 // INSERT IGNORE --> INSERT OR IGNORE
977 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
983 public function lock( $lockName, $method, $timeout = 5 ) {
984 // Give better error message for permission problems than just returning false
986 !is_dir( "{$this->dbDir}/locks" ) &&
987 ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) )
989 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
992 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
995 public function unlock( $lockName, $method ) {
996 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isGood();
1000 * Build a concatenation list to feed into a SQL query
1002 * @param string[] $stringList
1005 function buildConcat( $stringList ) {
1006 return '(' . implode( ') || (', $stringList ) . ')';
1009 public function buildGroupConcatField(
1010 $delim, $table, $field, $conds = '', $join_conds = []
1012 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1014 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1018 * @param string $oldName
1019 * @param string $newName
1020 * @param bool $temporary
1021 * @param string $fname
1022 * @return bool|IResultWrapper
1023 * @throws RuntimeException
1025 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1026 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1027 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1028 $obj = $this->fetchObject( $res );
1030 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1033 $sql = preg_replace(
1035 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1037 $this->addIdentifierQuotes( $newName ),
1042 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1043 $this->queryLogger
->debug(
1044 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1046 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1050 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1052 // Take over indexes
1053 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1054 foreach ( $indexList as $index ) {
1055 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1059 if ( $index->unique
) {
1060 $sql = 'CREATE UNIQUE INDEX';
1062 $sql = 'CREATE INDEX';
1064 // Try to come up with a new index name, given indexes have database scope in SQLite
1065 $indexName = $newName . '_' . $index->name
;
1066 $sql .= ' ' . $indexName . ' ON ' . $newName;
1068 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1070 foreach ( $indexInfo as $indexInfoRow ) {
1071 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1074 $sql .= '(' . implode( ',', $fields ) . ')';
1076 $this->query( $sql );
1083 * List all tables on the database
1085 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1086 * @param string $fname Calling function name
1090 function listTables( $prefix = null, $fname = __METHOD__
) {
1091 $result = $this->select(
1099 foreach ( $result as $table ) {
1100 $vars = get_object_vars( $table );
1101 $table = array_pop( $vars );
1103 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1104 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1105 $endArray[] = $table;
1114 * Override due to no CASCADE support
1116 * @param string $tableName
1117 * @param string $fName
1118 * @return bool|IResultWrapper
1119 * @throws DBReadOnlyError
1121 public function dropTable( $tableName, $fName = __METHOD__
) {
1122 if ( !$this->tableExists( $tableName, $fName ) ) {
1125 $sql = "DROP TABLE " . $this->tableName( $tableName );
1127 return $this->query( $sql, $fName );
1130 public function setTableAliases( array $aliases ) {
1131 parent
::setTableAliases( $aliases );
1132 foreach ( $this->tableAliases
as $params ) {
1133 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1136 $this->attachDatabase( $params['dbname'] );
1137 $this->alreadyAttached
[$params['dbname']] = true;
1141 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1142 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1143 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1144 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1147 public function databasesAreIndependent() {
1154 protected function getBindingHandle() {
1155 return parent
::getBindingHandle();
1160 * @deprecated since 1.29
1162 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );