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 ) {
171 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
172 if ( !is_readable( $fileName ) ) {
174 throw new DBConnectionError( $this, "SQLite database not accessible" );
176 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
177 $this->openFile( $fileName, $dbName, $tablePrefix );
179 return (bool)$this->conn
;
183 * Opens a database file
185 * @param string $fileName
186 * @param string $dbName
187 * @param string $tablePrefix
188 * @throws DBConnectionError
189 * @return PDO|bool SQL connection or false if failed
191 protected function openFile( $fileName, $dbName, $tablePrefix ) {
194 $this->dbPath
= $fileName;
196 if ( $this->flags
& self
::DBO_PERSISTENT
) {
197 $this->conn
= new PDO( "sqlite:$fileName", '', '',
198 [ PDO
::ATTR_PERSISTENT
=> true ] );
200 $this->conn
= new PDO( "sqlite:$fileName", '', '' );
202 } catch ( PDOException
$e ) {
203 $err = $e->getMessage();
206 if ( !$this->conn
) {
207 $this->queryLogger
->debug( "DB connection error: $err\n" );
208 throw new DBConnectionError( $this, $err );
211 $this->opened
= is_object( $this->conn
);
212 if ( $this->opened
) {
213 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
214 # Set error codes only, don't raise exceptions
215 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
216 # Enforce LIKE to be case sensitive, just like MySQL
217 $this->query( 'PRAGMA case_sensitive_like = 1' );
219 $sync = $this->connectionVariables
['synchronous'] ??
null;
220 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
221 $this->query( "PRAGMA synchronous = $sync" );
231 * @return string SQLite DB file path
234 public function getDbFilePath() {
235 return $this->dbPath
;
239 * Does not actually close the connection, just destroys the reference for GC to do its work
242 protected function closeConnection() {
249 * Generates a database file name. Explicitly public for installer.
250 * @param string $dir Directory where database resides
251 * @param string $dbName Database name
254 public static function generateFileName( $dir, $dbName ) {
255 return "$dir/$dbName.sqlite";
259 * Check if the searchindext table is FTS enabled.
260 * @return bool False if not enabled.
262 public function checkForEnabledSearch() {
263 if ( self
::$fulltextEnabled === null ) {
264 self
::$fulltextEnabled = false;
265 $table = $this->tableName( 'searchindex' );
266 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
268 $row = $res->fetchRow();
269 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
273 return self
::$fulltextEnabled;
277 * Returns version of currently supported SQLite fulltext search module or false if none present.
280 static function getFulltextSearchModule() {
281 static $cachedResult = null;
282 if ( $cachedResult !== null ) {
283 return $cachedResult;
285 $cachedResult = false;
286 $table = 'dummy_search_test';
288 $db = self
::newStandaloneInstance( ':memory:' );
289 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
290 $cachedResult = 'FTS3';
294 return $cachedResult;
298 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
301 * @param string $name Database name to be used in queries like
302 * SELECT foo FROM dbname.table
303 * @param bool|string $file Database file name. If omitted, will be generated
304 * using $name and configured data directory
305 * @param string $fname Calling function name
306 * @return IResultWrapper
308 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
310 $file = self
::generateFileName( $this->dbDir
, $name );
312 $file = $this->addQuotes( $file );
314 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
317 protected function isWriteQuery( $sql ) {
318 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
321 protected function isTransactableQuery( $sql ) {
322 return parent
::isTransactableQuery( $sql ) && !in_array(
323 $this->getQueryVerb( $sql ),
324 [ 'ATTACH', 'PRAGMA' ],
330 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
333 * @return bool|IResultWrapper
335 protected function doQuery( $sql ) {
336 $res = $this->getBindingHandle()->query( $sql );
337 if ( $res === false ) {
341 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
342 $this->lastAffectedRowCount
= $r->rowCount();
343 $res = new ResultWrapper( $this, $r->fetchAll() );
349 * @param IResultWrapper|mixed $res
351 function freeResult( $res ) {
352 if ( $res instanceof ResultWrapper
) {
360 * @param IResultWrapper|array $res
361 * @return stdClass|bool
363 function fetchObject( $res ) {
364 if ( $res instanceof ResultWrapper
) {
370 $cur = current( $r );
371 if ( is_array( $cur ) ) {
374 foreach ( $cur as $k => $v ) {
375 if ( !is_numeric( $k ) ) {
387 * @param IResultWrapper|mixed $res
390 function fetchRow( $res ) {
391 if ( $res instanceof ResultWrapper
) {
396 $cur = current( $r );
397 if ( is_array( $cur ) ) {
407 * The PDO::Statement class implements the array interface so count() will work
409 * @param IResultWrapper|array|false $res
412 function numRows( $res ) {
413 // false does not implement Countable
414 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
416 return is_array( $r ) ?
count( $r ) : 0;
420 * @param IResultWrapper $res
423 function numFields( $res ) {
424 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
425 if ( is_array( $r ) && count( $r ) > 0 ) {
426 // The size of the result array is twice the number of fields. (T67578)
427 return count( $r[0] ) / 2;
429 // If the result is empty return 0
435 * @param IResultWrapper $res
439 function fieldName( $res, $n ) {
440 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
441 if ( is_array( $r ) ) {
442 $keys = array_keys( $r[0] );
451 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
453 * @param string $name
454 * @param string $format
457 function tableName( $name, $format = 'quoted' ) {
458 // table names starting with sqlite_ are reserved
459 if ( strpos( $name, 'sqlite_' ) === 0 ) {
463 return str_replace( '"', '', parent
::tableName( $name, $format ) );
467 * This must be called after nextSequenceVal
471 function insertId() {
472 // PDO::lastInsertId yields a string :(
473 return intval( $this->getBindingHandle()->lastInsertId() );
477 * @param IResultWrapper|array $res
480 function dataSeek( $res, $row ) {
481 if ( $res instanceof ResultWrapper
) {
488 for ( $i = 0; $i < $row; $i++
) {
497 function lastError() {
498 if ( !is_object( $this->conn
) ) {
499 return "Cannot return last error, no db connection";
501 $e = $this->conn
->errorInfo();
509 function lastErrno() {
510 if ( !is_object( $this->conn
) ) {
511 return "Cannot return last error, no db connection";
513 $info = $this->conn
->errorInfo();
522 protected function fetchAffectedRowCount() {
523 return $this->lastAffectedRowCount
;
526 function tableExists( $table, $fname = __METHOD__
) {
527 $tableRaw = $this->tableName( $table, 'raw' );
528 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
529 return true; // already known to exist
532 $encTable = $this->addQuotes( $tableRaw );
534 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
536 return $res->numRows() ?
true : false;
540 * Returns information about an index
541 * Returns false if the index does not exist
542 * - if errors are explicitly ignored, returns NULL on failure
544 * @param string $table
545 * @param string $index
546 * @param string $fname
547 * @return array|false
549 function indexInfo( $table, $index, $fname = __METHOD__
) {
550 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
551 $res = $this->query( $sql, $fname );
552 if ( !$res ||
$res->numRows() == 0 ) {
556 foreach ( $res as $row ) {
557 $info[] = $row->name
;
564 * @param string $table
565 * @param string $index
566 * @param string $fname
569 function indexUnique( $table, $index, $fname = __METHOD__
) {
570 $row = $this->selectRow( 'sqlite_master', '*',
573 'name' => $this->indexName( $index ),
575 if ( !$row ||
!isset( $row->sql
) ) {
579 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
580 $indexPos = strpos( $row->sql
, 'INDEX' );
581 if ( $indexPos === false ) {
584 $firstPart = substr( $row->sql
, 0, $indexPos );
585 $options = explode( ' ', $firstPart );
587 return in_array( 'UNIQUE', $options );
591 * Filter the options used in SELECT statements
593 * @param array $options
596 function makeSelectOptions( $options ) {
597 foreach ( $options as $k => $v ) {
598 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
603 return parent
::makeSelectOptions( $options );
607 * @param array $options
610 protected function makeUpdateOptionsArray( $options ) {
611 $options = parent
::makeUpdateOptionsArray( $options );
612 $options = self
::fixIgnore( $options );
618 * @param array $options
621 static function fixIgnore( $options ) {
622 # SQLite uses OR IGNORE not just IGNORE
623 foreach ( $options as $k => $v ) {
624 if ( $v == 'IGNORE' ) {
625 $options[$k] = 'OR IGNORE';
633 * @param array $options
636 function makeInsertOptions( $options ) {
637 $options = self
::fixIgnore( $options );
639 return parent
::makeInsertOptions( $options );
643 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
644 * @param string $table
646 * @param string $fname
647 * @param array $options
650 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
651 if ( !count( $a ) ) {
655 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
656 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
657 $affectedRowCount = 0;
659 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
660 foreach ( $a as $v ) {
661 parent
::insert( $table, $v, "$fname/multi-row", $options );
662 $affectedRowCount +
= $this->affectedRows();
664 $this->endAtomic( $fname );
665 } catch ( Exception
$e ) {
666 $this->cancelAtomic( $fname );
669 $this->affectedRowCount
= $affectedRowCount;
671 parent
::insert( $table, $a, "$fname/single-row", $options );
678 * @param string $table
679 * @param array $uniqueIndexes Unused
680 * @param string|array $rows
681 * @param string $fname
683 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
684 if ( !count( $rows ) ) {
688 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
689 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
690 $affectedRowCount = 0;
692 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
693 foreach ( $rows as $v ) {
694 $this->nativeReplace( $table, $v, "$fname/multi-row" );
695 $affectedRowCount +
= $this->affectedRows();
697 $this->endAtomic( $fname );
698 } catch ( Exception
$e ) {
699 $this->cancelAtomic( $fname );
702 $this->affectedRowCount
= $affectedRowCount;
704 $this->nativeReplace( $table, $rows, "$fname/single-row" );
709 * Returns the size of a text field, or -1 for "unlimited"
710 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
712 * @param string $table
713 * @param string $field
716 function textFieldSize( $table, $field ) {
723 function unionSupportsOrderAndLimit() {
728 * @param string[] $sqls
729 * @param bool $all Whether to "UNION ALL" or not
732 function unionQueries( $sqls, $all ) {
733 $glue = $all ?
' UNION ALL ' : ' UNION ';
735 return implode( $glue, $sqls );
741 function wasDeadlock() {
742 return $this->lastErrno() == 5; // SQLITE_BUSY
748 function wasReadOnlyError() {
749 return $this->lastErrno() == 8; // SQLITE_READONLY;
752 public function wasConnectionError( $errno ) {
753 return $errno == 17; // SQLITE_SCHEMA;
756 protected function wasKnownStatementRollbackError() {
757 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
758 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
759 // https://sqlite.org/lang_createtable.html#uniqueconst
760 // https://sqlite.org/lang_conflict.html
765 * @return string Wikitext of a link to the server software's web site
767 public function getSoftwareLink() {
768 return "[{{int:version-db-sqlite-url}} SQLite]";
772 * @return string Version information from the database
774 function getServerVersion() {
775 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
781 * Get information about a given field
782 * Returns false if the field does not exist.
784 * @param string $table
785 * @param string $field
786 * @return SQLiteField|bool False on failure
788 function fieldInfo( $table, $field ) {
789 $tableName = $this->tableName( $table );
790 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
791 $res = $this->query( $sql, __METHOD__
);
792 foreach ( $res as $row ) {
793 if ( $row->name
== $field ) {
794 return new SQLiteField( $row, $tableName );
801 protected function doBegin( $fname = '' ) {
802 if ( $this->trxMode
) {
803 $this->query( "BEGIN {$this->trxMode}", $fname );
805 $this->query( 'BEGIN', $fname );
814 function strencode( $s ) {
815 return substr( $this->addQuotes( $s ), 1, -1 );
822 function encodeBlob( $b ) {
823 return new Blob( $b );
827 * @param Blob|string $b
830 function decodeBlob( $b ) {
831 if ( $b instanceof Blob
) {
839 * @param string|int|null|bool|Blob $s
842 function addQuotes( $s ) {
843 if ( $s instanceof Blob
) {
844 return "x'" . bin2hex( $s->fetch() ) . "'";
845 } elseif ( is_bool( $s ) ) {
847 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
848 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
849 // This is a known limitation of SQLite's mprintf function which PDO
850 // should work around, but doesn't. I have reported this to php.net as bug #63419:
851 // https://bugs.php.net/bug.php?id=63419
852 // There was already a similar report for SQLite3::escapeString, bug #62361:
853 // https://bugs.php.net/bug.php?id=62361
854 // There is an additional bug regarding sorting this data after insert
855 // on older versions of sqlite shipped with ubuntu 12.04
856 // https://phabricator.wikimedia.org/T74367
857 $this->queryLogger
->debug(
859 ': Quoting value containing null byte. ' .
860 'For consistency all binary data should have been ' .
861 'first processed with self::encodeBlob()'
863 return "x'" . bin2hex( (string)$s ) . "'";
865 return $this->getBindingHandle()->quote( (string)$s );
869 public function buildSubstring( $input, $startPosition, $length = null ) {
870 $this->assertBuildSubstringParams( $startPosition, $length );
871 $params = [ $input, $startPosition ];
872 if ( $length !== null ) {
875 return 'SUBSTR(' . implode( ',', $params ) . ')';
879 * @param string $field Field or column to cast
883 public function buildStringCast( $field ) {
884 return 'CAST ( ' . $field . ' AS TEXT )';
888 * No-op version of deadlockLoop
892 public function deadlockLoop( /*...*/ ) {
893 $args = func_get_args();
894 $function = array_shift( $args );
896 return $function( ...$args );
903 protected function replaceVars( $s ) {
904 $s = parent
::replaceVars( $s );
905 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
906 // CREATE TABLE hacks to allow schema file sharing with MySQL
908 // binary/varbinary column type -> blob
909 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
910 // no such thing as unsigned
911 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
913 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
914 // floating point types -> REAL
916 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
921 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
922 // TEXT normalization
923 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
924 // BLOB normalization
925 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
927 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
929 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
931 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
932 // binary collation type -> nothing
933 $s = preg_replace( '/\bbinary\b/i', '', $s );
934 // auto_increment -> autoincrement
935 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
936 // No explicit options
937 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
938 // AUTOINCREMENT should immedidately follow PRIMARY KEY
939 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
940 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
941 // No truncated indexes
942 $s = preg_replace( '/\(\d+\)/', '', $s );
944 $s = preg_replace( '/\bfulltext\b/i', '', $s );
945 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
946 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
947 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
948 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
949 // INSERT IGNORE --> INSERT OR IGNORE
950 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
956 public function lock( $lockName, $method, $timeout = 5 ) {
957 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
958 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
959 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
963 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
966 public function unlock( $lockName, $method ) {
967 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
971 * Build a concatenation list to feed into a SQL query
973 * @param string[] $stringList
976 function buildConcat( $stringList ) {
977 return '(' . implode( ') || (', $stringList ) . ')';
980 public function buildGroupConcatField(
981 $delim, $table, $field, $conds = '', $join_conds = []
983 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
985 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
989 * @param string $oldName
990 * @param string $newName
991 * @param bool $temporary
992 * @param string $fname
993 * @return bool|IResultWrapper
994 * @throws RuntimeException
996 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
997 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
998 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
999 $obj = $this->fetchObject( $res );
1001 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1004 $sql = preg_replace(
1006 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1008 $this->addIdentifierQuotes( $newName ),
1013 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1014 $this->queryLogger
->debug(
1015 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1017 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1021 $res = $this->query( $sql, $fname, self
::QUERY_PSEUDO_PERMANENT
);
1023 // Take over indexes
1024 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1025 foreach ( $indexList as $index ) {
1026 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1030 if ( $index->unique
) {
1031 $sql = 'CREATE UNIQUE INDEX';
1033 $sql = 'CREATE INDEX';
1035 // Try to come up with a new index name, given indexes have database scope in SQLite
1036 $indexName = $newName . '_' . $index->name
;
1037 $sql .= ' ' . $indexName . ' ON ' . $newName;
1039 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1041 foreach ( $indexInfo as $indexInfoRow ) {
1042 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1045 $sql .= '(' . implode( ',', $fields ) . ')';
1047 $this->query( $sql );
1054 * List all tables on the database
1056 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1057 * @param string $fname Calling function name
1061 function listTables( $prefix = null, $fname = __METHOD__
) {
1062 $result = $this->select(
1070 foreach ( $result as $table ) {
1071 $vars = get_object_vars( $table );
1072 $table = array_pop( $vars );
1074 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1075 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1076 $endArray[] = $table;
1085 * Override due to no CASCADE support
1087 * @param string $tableName
1088 * @param string $fName
1089 * @return bool|IResultWrapper
1090 * @throws DBReadOnlyError
1092 public function dropTable( $tableName, $fName = __METHOD__
) {
1093 if ( !$this->tableExists( $tableName, $fName ) ) {
1096 $sql = "DROP TABLE " . $this->tableName( $tableName );
1098 return $this->query( $sql, $fName );
1101 public function setTableAliases( array $aliases ) {
1102 parent
::setTableAliases( $aliases );
1103 foreach ( $this->tableAliases
as $params ) {
1104 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1107 $this->attachDatabase( $params['dbname'] );
1108 $this->alreadyAttached
[$params['dbname']] = true;
1112 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1113 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1114 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1115 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1118 public function databasesAreIndependent() {
1125 protected function getBindingHandle() {
1126 return parent
::getBindingHandle();
1131 * @deprecated since 1.29
1133 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );