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
;
30 use InvalidArgumentException
;
37 class DatabaseSqlite
extends Database
{
38 /** @var bool Whether full text is enabled */
39 private static $fulltextEnabled = null;
41 /** @var string Directory */
43 /** @var string File name for SQLite database file */
45 /** @var string Transaction mode */
48 /** @var int The number of rows affected as an integer */
49 protected $lastAffectedRowCount;
51 protected $lastResultHandle;
56 /** @var FSLockManager (hopefully on the same server as the DB) */
59 /** @var array List of shared database already attached to this connection */
60 private $alreadyAttached = [];
63 * Additional params include:
64 * - dbDirectory : directory containing the DB and the lock file directory
65 * [defaults to $wgSQLiteDataDir]
66 * - dbFilePath : use this to force the path of the DB file
67 * - trxMode : one of (deferred, immediate, exclusive)
70 function __construct( array $p ) {
71 if ( isset( $p['dbFilePath'] ) ) {
72 $this->dbPath
= $p['dbFilePath'];
73 $lockDomain = md5( $this->dbPath
);
74 } elseif ( isset( $p['dbDirectory'] ) ) {
75 $this->dbDir
= $p['dbDirectory'];
76 $lockDomain = $p['dbname'];
78 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
81 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
82 if ( $this->trxMode
&&
83 !in_array( $this->trxMode
, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
85 $this->trxMode
= null;
86 $this->queryLogger
->warning( "Invalid SQLite transaction mode provided." );
89 $this->lockMgr
= new FSLockManager( [
90 'domain' => $lockDomain,
91 'lockDirectory' => "{$this->dbDir}/locks"
94 parent
::__construct( $p );
97 protected static function getAttributes() {
98 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
102 * @param string $filename
103 * @param array $p Options map; supports:
104 * - flags : (same as __construct counterpart)
105 * - trxMode : (same as __construct counterpart)
106 * - dbDirectory : (same as __construct counterpart)
107 * @return DatabaseSqlite
110 public static function newStandaloneInstance( $filename, array $p = [] ) {
111 $p['dbFilePath'] = $filename;
112 $p['schema'] = false;
113 $p['tablePrefix'] = '';
114 /** @var DatabaseSqlite $db */
115 $db = Database
::factory( 'sqlite', $p );
120 protected function doInitConnection() {
121 if ( $this->dbPath
!== null ) {
122 // Standalone .sqlite file mode.
123 $this->openFile( $this->dbPath
, $this->connectionParams
['dbname'] );
124 } elseif ( $this->dbDir
!== null ) {
125 // Stock wiki mode using standard file names per DB
126 if ( strlen( $this->connectionParams
['dbname'] ) ) {
128 $this->connectionParams
['host'],
129 $this->connectionParams
['user'],
130 $this->connectionParams
['password'],
131 $this->connectionParams
['dbname']
134 // Caller will manually call open() later?
135 $this->connLogger
->debug( __METHOD__
. ': no database opened.' );
138 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
150 * @todo Check if it should be true like parent class
154 function implicitGroupby() {
158 /** Open an SQLite database and return a resource handle to it
159 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
161 * @param string $server
162 * @param string $user Unused
163 * @param string $pass
164 * @param string $dbName
166 * @throws DBConnectionError
169 function open( $server, $user, $pass, $dbName ) {
171 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
172 if ( !is_readable( $fileName ) ) {
174 throw new DBConnectionError( $this, "SQLite database not accessible" );
176 $this->openFile( $fileName, $dbName );
178 return (bool)$this->conn
;
182 * Opens a database file
184 * @param string $fileName
185 * @param string $dbName
186 * @throws DBConnectionError
187 * @return PDO|bool SQL connection or false if failed
189 protected function openFile( $fileName, $dbName ) {
192 $this->dbPath
= $fileName;
194 if ( $this->flags
& self
::DBO_PERSISTENT
) {
195 $this->conn
= new PDO( "sqlite:$fileName", '', '',
196 [ PDO
::ATTR_PERSISTENT
=> true ] );
198 $this->conn
= new PDO( "sqlite:$fileName", '', '' );
200 } catch ( PDOException
$e ) {
201 $err = $e->getMessage();
204 if ( !$this->conn
) {
205 $this->queryLogger
->debug( "DB connection error: $err\n" );
206 throw new DBConnectionError( $this, $err );
209 $this->opened
= is_object( $this->conn
);
210 if ( $this->opened
) {
211 $this->dbName
= $dbName;
212 # Set error codes only, don't raise exceptions
213 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
214 # Enforce LIKE to be case sensitive, just like MySQL
215 $this->query( 'PRAGMA case_sensitive_like = 1' );
224 * @return string SQLite DB file path
227 public function getDbFilePath() {
228 return $this->dbPath
;
232 * Does not actually close the connection, just destroys the reference for GC to do its work
235 protected function closeConnection() {
242 * Generates a database file name. Explicitly public for installer.
243 * @param string $dir Directory where database resides
244 * @param string $dbName Database name
247 public static function generateFileName( $dir, $dbName ) {
248 return "$dir/$dbName.sqlite";
252 * Check if the searchindext table is FTS enabled.
253 * @return bool False if not enabled.
255 function checkForEnabledSearch() {
256 if ( self
::$fulltextEnabled === null ) {
257 self
::$fulltextEnabled = false;
258 $table = $this->tableName( 'searchindex' );
259 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
261 $row = $res->fetchRow();
262 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
266 return self
::$fulltextEnabled;
270 * Returns version of currently supported SQLite fulltext search module or false if none present.
273 static function getFulltextSearchModule() {
274 static $cachedResult = null;
275 if ( $cachedResult !== null ) {
276 return $cachedResult;
278 $cachedResult = false;
279 $table = 'dummy_search_test';
281 $db = self
::newStandaloneInstance( ':memory:' );
282 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
283 $cachedResult = 'FTS3';
287 return $cachedResult;
291 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
294 * @param string $name Database name to be used in queries like
295 * SELECT foo FROM dbname.table
296 * @param bool|string $file Database file name. If omitted, will be generated
297 * using $name and configured data directory
298 * @param string $fname Calling function name
299 * @return ResultWrapper
301 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
303 $file = self
::generateFileName( $this->dbDir
, $name );
305 $file = $this->addQuotes( $file );
307 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
310 function isWriteQuery( $sql ) {
311 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
314 protected function isTransactableQuery( $sql ) {
315 return parent
::isTransactableQuery( $sql ) && !in_array(
316 $this->getQueryVerb( $sql ),
317 [ 'ATTACH', 'PRAGMA' ],
323 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
326 * @return bool|ResultWrapper
328 protected function doQuery( $sql ) {
329 $res = $this->getBindingHandle()->query( $sql );
330 if ( $res === false ) {
334 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
335 $this->lastAffectedRowCount
= $r->rowCount();
336 $res = new ResultWrapper( $this, $r->fetchAll() );
342 * @param ResultWrapper|mixed $res
344 function freeResult( $res ) {
345 if ( $res instanceof ResultWrapper
) {
353 * @param ResultWrapper|array $res
354 * @return stdClass|bool
356 function fetchObject( $res ) {
357 if ( $res instanceof ResultWrapper
) {
363 $cur = current( $r );
364 if ( is_array( $cur ) ) {
367 foreach ( $cur as $k => $v ) {
368 if ( !is_numeric( $k ) ) {
380 * @param ResultWrapper|mixed $res
383 function fetchRow( $res ) {
384 if ( $res instanceof ResultWrapper
) {
389 $cur = current( $r );
390 if ( is_array( $cur ) ) {
400 * The PDO::Statement class implements the array interface so count() will work
402 * @param ResultWrapper|array $res
405 function numRows( $res ) {
406 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
412 * @param ResultWrapper $res
415 function numFields( $res ) {
416 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
417 if ( is_array( $r ) && count( $r ) > 0 ) {
418 // The size of the result array is twice the number of fields. (Bug: 65578)
419 return count( $r[0] ) / 2;
421 // If the result is empty return 0
427 * @param ResultWrapper $res
431 function fieldName( $res, $n ) {
432 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
433 if ( is_array( $r ) ) {
434 $keys = array_keys( $r[0] );
443 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
445 * @param string $name
446 * @param string $format
449 function tableName( $name, $format = 'quoted' ) {
450 // table names starting with sqlite_ are reserved
451 if ( strpos( $name, 'sqlite_' ) === 0 ) {
455 return str_replace( '"', '', parent
::tableName( $name, $format ) );
459 * This must be called after nextSequenceVal
463 function insertId() {
464 // PDO::lastInsertId yields a string :(
465 return intval( $this->getBindingHandle()->lastInsertId() );
469 * @param ResultWrapper|array $res
472 function dataSeek( $res, $row ) {
473 if ( $res instanceof ResultWrapper
) {
480 for ( $i = 0; $i < $row; $i++
) {
489 function lastError() {
490 if ( !is_object( $this->conn
) ) {
491 return "Cannot return last error, no db connection";
493 $e = $this->conn
->errorInfo();
501 function lastErrno() {
502 if ( !is_object( $this->conn
) ) {
503 return "Cannot return last error, no db connection";
505 $info = $this->conn
->errorInfo();
514 protected function fetchAffectedRowCount() {
515 return $this->lastAffectedRowCount
;
518 function tableExists( $table, $fname = __METHOD__
) {
519 $tableRaw = $this->tableName( $table, 'raw' );
520 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
521 return true; // already known to exist
524 $encTable = $this->addQuotes( $tableRaw );
526 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
528 return $res->numRows() ?
true : false;
532 * Returns information about an index
533 * Returns false if the index does not exist
534 * - if errors are explicitly ignored, returns NULL on failure
536 * @param string $table
537 * @param string $index
538 * @param string $fname
539 * @return array|false
541 function indexInfo( $table, $index, $fname = __METHOD__
) {
542 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
543 $res = $this->query( $sql, $fname );
544 if ( !$res ||
$res->numRows() == 0 ) {
548 foreach ( $res as $row ) {
549 $info[] = $row->name
;
556 * @param string $table
557 * @param string $index
558 * @param string $fname
561 function indexUnique( $table, $index, $fname = __METHOD__
) {
562 $row = $this->selectRow( 'sqlite_master', '*',
565 'name' => $this->indexName( $index ),
567 if ( !$row ||
!isset( $row->sql
) ) {
571 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
572 $indexPos = strpos( $row->sql
, 'INDEX' );
573 if ( $indexPos === false ) {
576 $firstPart = substr( $row->sql
, 0, $indexPos );
577 $options = explode( ' ', $firstPart );
579 return in_array( 'UNIQUE', $options );
583 * Filter the options used in SELECT statements
585 * @param array $options
588 function makeSelectOptions( $options ) {
589 foreach ( $options as $k => $v ) {
590 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
595 return parent
::makeSelectOptions( $options );
599 * @param array $options
602 protected function makeUpdateOptionsArray( $options ) {
603 $options = parent
::makeUpdateOptionsArray( $options );
604 $options = self
::fixIgnore( $options );
610 * @param array $options
613 static function fixIgnore( $options ) {
614 # SQLite uses OR IGNORE not just IGNORE
615 foreach ( $options as $k => $v ) {
616 if ( $v == 'IGNORE' ) {
617 $options[$k] = 'OR IGNORE';
625 * @param array $options
628 function makeInsertOptions( $options ) {
629 $options = self
::fixIgnore( $options );
631 return parent
::makeInsertOptions( $options );
635 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
636 * @param string $table
638 * @param string $fname
639 * @param array $options
642 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
643 if ( !count( $a ) ) {
647 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
648 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
650 foreach ( $a as $v ) {
651 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
656 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
663 * @param string $table
664 * @param array $uniqueIndexes Unused
665 * @param string|array $rows
666 * @param string $fname
667 * @return bool|ResultWrapper
669 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
670 if ( !count( $rows ) ) {
674 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
675 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
677 foreach ( $rows as $v ) {
678 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
683 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
690 * Returns the size of a text field, or -1 for "unlimited"
691 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
693 * @param string $table
694 * @param string $field
697 function textFieldSize( $table, $field ) {
704 function unionSupportsOrderAndLimit() {
709 * @param string[] $sqls
710 * @param bool $all Whether to "UNION ALL" or not
713 function unionQueries( $sqls, $all ) {
714 $glue = $all ?
' UNION ALL ' : ' UNION ';
716 return implode( $glue, $sqls );
722 function wasDeadlock() {
723 return $this->lastErrno() == 5; // SQLITE_BUSY
729 function wasReadOnlyError() {
730 return $this->lastErrno() == 8; // SQLITE_READONLY;
733 public function wasConnectionError( $errno ) {
734 return $errno == 17; // SQLITE_SCHEMA;
737 protected function wasKnownStatementRollbackError() {
738 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
739 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
740 // https://sqlite.org/lang_createtable.html#uniqueconst
741 // https://sqlite.org/lang_conflict.html
746 * @return string Wikitext of a link to the server software's web site
748 public function getSoftwareLink() {
749 return "[{{int:version-db-sqlite-url}} SQLite]";
753 * @return string Version information from the database
755 function getServerVersion() {
756 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
762 * Get information about a given field
763 * Returns false if the field does not exist.
765 * @param string $table
766 * @param string $field
767 * @return SQLiteField|bool False on failure
769 function fieldInfo( $table, $field ) {
770 $tableName = $this->tableName( $table );
771 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
772 $res = $this->query( $sql, __METHOD__
);
773 foreach ( $res as $row ) {
774 if ( $row->name
== $field ) {
775 return new SQLiteField( $row, $tableName );
782 protected function doBegin( $fname = '' ) {
783 if ( $this->trxMode
) {
784 $this->query( "BEGIN {$this->trxMode}", $fname );
786 $this->query( 'BEGIN', $fname );
795 function strencode( $s ) {
796 return substr( $this->addQuotes( $s ), 1, -1 );
803 function encodeBlob( $b ) {
804 return new Blob( $b );
808 * @param Blob|string $b
811 function decodeBlob( $b ) {
812 if ( $b instanceof Blob
) {
820 * @param string|int|null|bool|Blob $s
823 function addQuotes( $s ) {
824 if ( $s instanceof Blob
) {
825 return "x'" . bin2hex( $s->fetch() ) . "'";
826 } elseif ( is_bool( $s ) ) {
828 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
829 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
830 // This is a known limitation of SQLite's mprintf function which PDO
831 // should work around, but doesn't. I have reported this to php.net as bug #63419:
832 // https://bugs.php.net/bug.php?id=63419
833 // There was already a similar report for SQLite3::escapeString, bug #62361:
834 // https://bugs.php.net/bug.php?id=62361
835 // There is an additional bug regarding sorting this data after insert
836 // on older versions of sqlite shipped with ubuntu 12.04
837 // https://phabricator.wikimedia.org/T74367
838 $this->queryLogger
->debug(
840 ': Quoting value containing null byte. ' .
841 'For consistency all binary data should have been ' .
842 'first processed with self::encodeBlob()'
844 return "x'" . bin2hex( (string)$s ) . "'";
846 return $this->getBindingHandle()->quote( (string)$s );
850 public function buildSubstring( $input, $startPosition, $length = null ) {
851 $this->assertBuildSubstringParams( $startPosition, $length );
852 $params = [ $input, $startPosition ];
853 if ( $length !== null ) {
856 return 'SUBSTR(' . implode( ',', $params ) . ')';
860 * @param string $field Field or column to cast
864 public function buildStringCast( $field ) {
865 return 'CAST ( ' . $field . ' AS TEXT )';
869 * No-op version of deadlockLoop
873 public function deadlockLoop( /*...*/ ) {
874 $args = func_get_args();
875 $function = array_shift( $args );
877 return $function( ...$args );
884 protected function replaceVars( $s ) {
885 $s = parent
::replaceVars( $s );
886 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
887 // CREATE TABLE hacks to allow schema file sharing with MySQL
889 // binary/varbinary column type -> blob
890 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
891 // no such thing as unsigned
892 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
894 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
895 // floating point types -> REAL
897 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
902 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
903 // TEXT normalization
904 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
905 // BLOB normalization
906 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
908 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
910 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
912 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
913 // binary collation type -> nothing
914 $s = preg_replace( '/\bbinary\b/i', '', $s );
915 // auto_increment -> autoincrement
916 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
917 // No explicit options
918 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
919 // AUTOINCREMENT should immedidately follow PRIMARY KEY
920 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
921 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
922 // No truncated indexes
923 $s = preg_replace( '/\(\d+\)/', '', $s );
925 $s = preg_replace( '/\bfulltext\b/i', '', $s );
926 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
927 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
928 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
929 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
930 // INSERT IGNORE --> INSERT OR IGNORE
931 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
937 public function lock( $lockName, $method, $timeout = 5 ) {
938 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
939 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
940 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
944 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
947 public function unlock( $lockName, $method ) {
948 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
952 * Build a concatenation list to feed into a SQL query
954 * @param string[] $stringList
957 function buildConcat( $stringList ) {
958 return '(' . implode( ') || (', $stringList ) . ')';
961 public function buildGroupConcatField(
962 $delim, $table, $field, $conds = '', $join_conds = []
964 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
966 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
970 * @param string $oldName
971 * @param string $newName
972 * @param bool $temporary
973 * @param string $fname
974 * @return bool|ResultWrapper
975 * @throws RuntimeException
977 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
978 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
979 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
980 $obj = $this->fetchObject( $res );
982 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
986 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
987 $this->addIdentifierQuotes( $newName ),
992 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
993 $this->queryLogger
->debug(
994 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
996 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1000 $res = $this->query( $sql, $fname );
1002 // Take over indexes
1003 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1004 foreach ( $indexList as $index ) {
1005 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1009 if ( $index->unique
) {
1010 $sql = 'CREATE UNIQUE INDEX';
1012 $sql = 'CREATE INDEX';
1014 // Try to come up with a new index name, given indexes have database scope in SQLite
1015 $indexName = $newName . '_' . $index->name
;
1016 $sql .= ' ' . $indexName . ' ON ' . $newName;
1018 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1020 foreach ( $indexInfo as $indexInfoRow ) {
1021 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1024 $sql .= '(' . implode( ',', $fields ) . ')';
1026 $this->query( $sql );
1033 * List all tables on the database
1035 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1036 * @param string $fname Calling function name
1040 function listTables( $prefix = null, $fname = __METHOD__
) {
1041 $result = $this->select(
1049 foreach ( $result as $table ) {
1050 $vars = get_object_vars( $table );
1051 $table = array_pop( $vars );
1053 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1054 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1055 $endArray[] = $table;
1064 * Override due to no CASCADE support
1066 * @param string $tableName
1067 * @param string $fName
1068 * @return bool|ResultWrapper
1069 * @throws DBReadOnlyError
1071 public function dropTable( $tableName, $fName = __METHOD__
) {
1072 if ( !$this->tableExists( $tableName, $fName ) ) {
1075 $sql = "DROP TABLE " . $this->tableName( $tableName );
1077 return $this->query( $sql, $fName );
1080 public function setTableAliases( array $aliases ) {
1081 parent
::setTableAliases( $aliases );
1082 foreach ( $this->tableAliases
as $params ) {
1083 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1086 $this->attachDatabase( $params['dbname'] );
1087 $this->alreadyAttached
[$params['dbname']] = true;
1091 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1092 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1093 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1094 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1097 public function databasesAreIndependent() {
1104 public function __toString() {
1105 return is_object( $this->conn
)
1106 ?
'SQLite ' . (string)$this->conn
->getAttribute( PDO
::ATTR_SERVER_VERSION
)
1107 : '(not connected)';
1113 protected function getBindingHandle() {
1114 return parent
::getBindingHandle();
1119 * @deprecated since 1.29
1121 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );