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 parent
::__construct( $p );
73 // Standalone .sqlite file mode.
74 // Super doesn't open when $user is false, but we can work with $dbName,
75 // which is derived from the file path in this case.
76 $this->openFile( $p['dbFilePath'] );
77 $lockDomain = md5( $p['dbFilePath'] );
78 } elseif ( !isset( $p['dbDirectory'] ) ) {
79 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
81 $this->dbDir
= $p['dbDirectory'];
82 $this->dbName
= $p['dbname'];
83 $lockDomain = $this->dbName
;
84 // Stock wiki mode using standard file names per DB.
85 parent
::__construct( $p );
86 // Super doesn't open when $user is false, but we can work with $dbName
87 if ( $p['dbname'] && !$this->isOpen() ) {
88 $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] );
92 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
93 if ( $this->trxMode
&&
94 !in_array( $this->trxMode
, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
96 $this->trxMode
= null;
97 $this->queryLogger
->warning( "Invalid SQLite transaction mode provided." );
100 $this->lockMgr
= new FSLockManager( [
101 'domain' => $lockDomain,
102 'lockDirectory' => "{$this->dbDir}/locks"
106 protected static function getAttributes() {
107 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
111 * @param string $filename
112 * @param array $p Options map; supports:
113 * - flags : (same as __construct counterpart)
114 * - trxMode : (same as __construct counterpart)
115 * - dbDirectory : (same as __construct counterpart)
116 * @return DatabaseSqlite
119 public static function newStandaloneInstance( $filename, array $p = [] ) {
120 $p['dbFilePath'] = $filename;
121 $p['schema'] = false;
122 $p['tablePrefix'] = '';
123 /** @var DatabaseSqlite $db */
124 $db = Database
::factory( 'sqlite', $p );
137 * @todo Check if it should be true like parent class
141 function implicitGroupby() {
145 /** Open an SQLite database and return a resource handle to it
146 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
148 * @param string $server
149 * @param string $user
150 * @param string $pass
151 * @param string $dbName
153 * @throws DBConnectionError
156 function open( $server, $user, $pass, $dbName ) {
158 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
159 if ( !is_readable( $fileName ) ) {
161 throw new DBConnectionError( $this, "SQLite database not accessible" );
163 $this->openFile( $fileName );
165 return (bool)$this->conn
;
169 * Opens a database file
171 * @param string $fileName
172 * @throws DBConnectionError
173 * @return PDO|bool SQL connection or false if failed
175 protected function openFile( $fileName ) {
178 $this->dbPath
= $fileName;
180 if ( $this->flags
& self
::DBO_PERSISTENT
) {
181 $this->conn
= new PDO( "sqlite:$fileName", '', '',
182 [ PDO
::ATTR_PERSISTENT
=> true ] );
184 $this->conn
= new PDO( "sqlite:$fileName", '', '' );
186 } catch ( PDOException
$e ) {
187 $err = $e->getMessage();
190 if ( !$this->conn
) {
191 $this->queryLogger
->debug( "DB connection error: $err\n" );
192 throw new DBConnectionError( $this, $err );
195 $this->opened
= !!$this->conn
;
196 if ( $this->opened
) {
197 # Set error codes only, don't raise exceptions
198 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
199 # Enforce LIKE to be case sensitive, just like MySQL
200 $this->query( 'PRAGMA case_sensitive_like = 1' );
208 public function selectDB( $db ) {
209 return false; // doesn't make sense
213 * @return string SQLite DB file path
216 public function getDbFilePath() {
217 return $this->dbPath
;
221 * Does not actually close the connection, just destroys the reference for GC to do its work
224 protected function closeConnection() {
231 * Generates a database file name. Explicitly public for installer.
232 * @param string $dir Directory where database resides
233 * @param string $dbName Database name
236 public static function generateFileName( $dir, $dbName ) {
237 return "$dir/$dbName.sqlite";
241 * Check if the searchindext table is FTS enabled.
242 * @return bool False if not enabled.
244 function checkForEnabledSearch() {
245 if ( self
::$fulltextEnabled === null ) {
246 self
::$fulltextEnabled = false;
247 $table = $this->tableName( 'searchindex' );
248 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
250 $row = $res->fetchRow();
251 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
255 return self
::$fulltextEnabled;
259 * Returns version of currently supported SQLite fulltext search module or false if none present.
262 static function getFulltextSearchModule() {
263 static $cachedResult = null;
264 if ( $cachedResult !== null ) {
265 return $cachedResult;
267 $cachedResult = false;
268 $table = 'dummy_search_test';
270 $db = self
::newStandaloneInstance( ':memory:' );
271 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
272 $cachedResult = 'FTS3';
276 return $cachedResult;
280 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
283 * @param string $name Database name to be used in queries like
284 * SELECT foo FROM dbname.table
285 * @param bool|string $file Database file name. If omitted, will be generated
286 * using $name and configured data directory
287 * @param string $fname Calling function name
288 * @return ResultWrapper
290 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
292 $file = self
::generateFileName( $this->dbDir
, $name );
294 $file = $this->addQuotes( $file );
296 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
299 function isWriteQuery( $sql ) {
300 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
303 protected function isTransactableQuery( $sql ) {
304 return parent
::isTransactableQuery( $sql ) && !in_array(
305 $this->getQueryVerb( $sql ),
306 [ 'ATTACH', 'PRAGMA' ],
312 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
315 * @return bool|ResultWrapper
317 protected function doQuery( $sql ) {
318 $res = $this->conn
->query( $sql );
319 if ( $res === false ) {
323 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
324 $this->lastAffectedRowCount
= $r->rowCount();
325 $res = new ResultWrapper( $this, $r->fetchAll() );
331 * @param ResultWrapper|mixed $res
333 function freeResult( $res ) {
334 if ( $res instanceof ResultWrapper
) {
342 * @param ResultWrapper|array $res
343 * @return stdClass|bool
345 function fetchObject( $res ) {
346 if ( $res instanceof ResultWrapper
) {
352 $cur = current( $r );
353 if ( is_array( $cur ) ) {
356 foreach ( $cur as $k => $v ) {
357 if ( !is_numeric( $k ) ) {
369 * @param ResultWrapper|mixed $res
372 function fetchRow( $res ) {
373 if ( $res instanceof ResultWrapper
) {
378 $cur = current( $r );
379 if ( is_array( $cur ) ) {
389 * The PDO::Statement class implements the array interface so count() will work
391 * @param ResultWrapper|array $res
394 function numRows( $res ) {
395 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
401 * @param ResultWrapper $res
404 function numFields( $res ) {
405 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
406 if ( is_array( $r ) && count( $r ) > 0 ) {
407 // The size of the result array is twice the number of fields. (Bug: 65578)
408 return count( $r[0] ) / 2;
410 // If the result is empty return 0
416 * @param ResultWrapper $res
420 function fieldName( $res, $n ) {
421 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
422 if ( is_array( $r ) ) {
423 $keys = array_keys( $r[0] );
432 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
434 * @param string $name
435 * @param string $format
438 function tableName( $name, $format = 'quoted' ) {
439 // table names starting with sqlite_ are reserved
440 if ( strpos( $name, 'sqlite_' ) === 0 ) {
444 return str_replace( '"', '', parent
::tableName( $name, $format ) );
448 * This must be called after nextSequenceVal
452 function insertId() {
453 // PDO::lastInsertId yields a string :(
454 return intval( $this->conn
->lastInsertId() );
458 * @param ResultWrapper|array $res
461 function dataSeek( $res, $row ) {
462 if ( $res instanceof ResultWrapper
) {
469 for ( $i = 0; $i < $row; $i++
) {
478 function lastError() {
479 if ( !is_object( $this->conn
) ) {
480 return "Cannot return last error, no db connection";
482 $e = $this->conn
->errorInfo();
484 return isset( $e[2] ) ?
$e[2] : '';
490 function lastErrno() {
491 if ( !is_object( $this->conn
) ) {
492 return "Cannot return last error, no db connection";
494 $info = $this->conn
->errorInfo();
503 protected function fetchAffectedRowCount() {
504 return $this->lastAffectedRowCount
;
508 * Returns information about an index
509 * Returns false if the index does not exist
510 * - if errors are explicitly ignored, returns NULL on failure
512 * @param string $table
513 * @param string $index
514 * @param string $fname
515 * @return array|false
517 function indexInfo( $table, $index, $fname = __METHOD__
) {
518 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
519 $res = $this->query( $sql, $fname );
520 if ( !$res ||
$res->numRows() == 0 ) {
524 foreach ( $res as $row ) {
525 $info[] = $row->name
;
532 * @param string $table
533 * @param string $index
534 * @param string $fname
537 function indexUnique( $table, $index, $fname = __METHOD__
) {
538 $row = $this->selectRow( 'sqlite_master', '*',
541 'name' => $this->indexName( $index ),
543 if ( !$row ||
!isset( $row->sql
) ) {
547 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
548 $indexPos = strpos( $row->sql
, 'INDEX' );
549 if ( $indexPos === false ) {
552 $firstPart = substr( $row->sql
, 0, $indexPos );
553 $options = explode( ' ', $firstPart );
555 return in_array( 'UNIQUE', $options );
559 * Filter the options used in SELECT statements
561 * @param array $options
564 function makeSelectOptions( $options ) {
565 foreach ( $options as $k => $v ) {
566 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
571 return parent
::makeSelectOptions( $options );
575 * @param array $options
578 protected function makeUpdateOptionsArray( $options ) {
579 $options = parent
::makeUpdateOptionsArray( $options );
580 $options = self
::fixIgnore( $options );
586 * @param array $options
589 static function fixIgnore( $options ) {
590 # SQLite uses OR IGNORE not just IGNORE
591 foreach ( $options as $k => $v ) {
592 if ( $v == 'IGNORE' ) {
593 $options[$k] = 'OR IGNORE';
601 * @param array $options
604 function makeInsertOptions( $options ) {
605 $options = self
::fixIgnore( $options );
607 return parent
::makeInsertOptions( $options );
611 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
612 * @param string $table
614 * @param string $fname
615 * @param array $options
618 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
619 if ( !count( $a ) ) {
623 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
624 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
626 foreach ( $a as $v ) {
627 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
632 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
639 * @param string $table
640 * @param array $uniqueIndexes Unused
641 * @param string|array $rows
642 * @param string $fname
643 * @return bool|ResultWrapper
645 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
646 if ( !count( $rows ) ) {
650 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
651 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
653 foreach ( $rows as $v ) {
654 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
659 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
666 * Returns the size of a text field, or -1 for "unlimited"
667 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
669 * @param string $table
670 * @param string $field
673 function textFieldSize( $table, $field ) {
680 function unionSupportsOrderAndLimit() {
685 * @param string[] $sqls
686 * @param bool $all Whether to "UNION ALL" or not
689 function unionQueries( $sqls, $all ) {
690 $glue = $all ?
' UNION ALL ' : ' UNION ';
692 return implode( $glue, $sqls );
698 function wasDeadlock() {
699 return $this->lastErrno() == 5; // SQLITE_BUSY
705 function wasErrorReissuable() {
706 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
712 function wasReadOnlyError() {
713 return $this->lastErrno() == 8; // SQLITE_READONLY;
717 * @return string Wikitext of a link to the server software's web site
719 public function getSoftwareLink() {
720 return "[{{int:version-db-sqlite-url}} SQLite]";
724 * @return string Version information from the database
726 function getServerVersion() {
727 $ver = $this->conn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
733 * Get information about a given field
734 * Returns false if the field does not exist.
736 * @param string $table
737 * @param string $field
738 * @return SQLiteField|bool False on failure
740 function fieldInfo( $table, $field ) {
741 $tableName = $this->tableName( $table );
742 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
743 $res = $this->query( $sql, __METHOD__
);
744 foreach ( $res as $row ) {
745 if ( $row->name
== $field ) {
746 return new SQLiteField( $row, $tableName );
753 protected function doBegin( $fname = '' ) {
754 if ( $this->trxMode
) {
755 $this->query( "BEGIN {$this->trxMode}", $fname );
757 $this->query( 'BEGIN', $fname );
766 function strencode( $s ) {
767 return substr( $this->addQuotes( $s ), 1, -1 );
774 function encodeBlob( $b ) {
775 return new Blob( $b );
779 * @param Blob|string $b
782 function decodeBlob( $b ) {
783 if ( $b instanceof Blob
) {
791 * @param string|int|null|bool|Blob $s
794 function addQuotes( $s ) {
795 if ( $s instanceof Blob
) {
796 return "x'" . bin2hex( $s->fetch() ) . "'";
797 } elseif ( is_bool( $s ) ) {
799 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
800 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
801 // This is a known limitation of SQLite's mprintf function which PDO
802 // should work around, but doesn't. I have reported this to php.net as bug #63419:
803 // https://bugs.php.net/bug.php?id=63419
804 // There was already a similar report for SQLite3::escapeString, bug #62361:
805 // https://bugs.php.net/bug.php?id=62361
806 // There is an additional bug regarding sorting this data after insert
807 // on older versions of sqlite shipped with ubuntu 12.04
808 // https://phabricator.wikimedia.org/T74367
809 $this->queryLogger
->debug(
811 ': Quoting value containing null byte. ' .
812 'For consistency all binary data should have been ' .
813 'first processed with self::encodeBlob()'
815 return "x'" . bin2hex( (string)$s ) . "'";
817 return $this->conn
->quote( (string)$s );
821 public function buildSubstring( $input, $startPosition, $length = null ) {
822 $this->assertBuildSubstringParams( $startPosition, $length );
823 $params = [ $input, $startPosition ];
824 if ( $length !== null ) {
827 return 'SUBSTR(' . implode( ',', $params ) . ')';
831 * @param string $field Field or column to cast
835 public function buildStringCast( $field ) {
836 return 'CAST ( ' . $field . ' AS TEXT )';
840 * No-op version of deadlockLoop
844 public function deadlockLoop( /*...*/ ) {
845 $args = func_get_args();
846 $function = array_shift( $args );
848 return call_user_func_array( $function, $args );
855 protected function replaceVars( $s ) {
856 $s = parent
::replaceVars( $s );
857 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
858 // CREATE TABLE hacks to allow schema file sharing with MySQL
860 // binary/varbinary column type -> blob
861 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
862 // no such thing as unsigned
863 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
865 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
866 // floating point types -> REAL
868 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
873 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
874 // TEXT normalization
875 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
876 // BLOB normalization
877 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
879 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
881 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
883 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
884 // binary collation type -> nothing
885 $s = preg_replace( '/\bbinary\b/i', '', $s );
886 // auto_increment -> autoincrement
887 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
888 // No explicit options
889 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
890 // AUTOINCREMENT should immedidately follow PRIMARY KEY
891 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
892 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
893 // No truncated indexes
894 $s = preg_replace( '/\(\d+\)/', '', $s );
896 $s = preg_replace( '/\bfulltext\b/i', '', $s );
897 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
898 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
899 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
900 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
901 // INSERT IGNORE --> INSERT OR IGNORE
902 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
908 public function lock( $lockName, $method, $timeout = 5 ) {
909 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
910 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
911 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
915 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
918 public function unlock( $lockName, $method ) {
919 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
923 * Build a concatenation list to feed into a SQL query
925 * @param string[] $stringList
928 function buildConcat( $stringList ) {
929 return '(' . implode( ') || (', $stringList ) . ')';
932 public function buildGroupConcatField(
933 $delim, $table, $field, $conds = '', $join_conds = []
935 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
937 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
941 * @param string $oldName
942 * @param string $newName
943 * @param bool $temporary
944 * @param string $fname
945 * @return bool|ResultWrapper
946 * @throws RuntimeException
948 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
949 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
950 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
951 $obj = $this->fetchObject( $res );
953 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
957 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
958 $this->addIdentifierQuotes( $newName ),
963 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
964 $this->queryLogger
->debug(
965 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
967 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
971 $res = $this->query( $sql, $fname );
974 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
975 foreach ( $indexList as $index ) {
976 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
980 if ( $index->unique
) {
981 $sql = 'CREATE UNIQUE INDEX';
983 $sql = 'CREATE INDEX';
985 // Try to come up with a new index name, given indexes have database scope in SQLite
986 $indexName = $newName . '_' . $index->name
;
987 $sql .= ' ' . $indexName . ' ON ' . $newName;
989 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
991 foreach ( $indexInfo as $indexInfoRow ) {
992 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
995 $sql .= '(' . implode( ',', $fields ) . ')';
997 $this->query( $sql );
1004 * List all tables on the database
1006 * @param string $prefix Only show tables with this prefix, e.g. mw_
1007 * @param string $fname Calling function name
1011 function listTables( $prefix = null, $fname = __METHOD__
) {
1012 $result = $this->select(
1020 foreach ( $result as $table ) {
1021 $vars = get_object_vars( $table );
1022 $table = array_pop( $vars );
1024 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1025 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1026 $endArray[] = $table;
1035 * Override due to no CASCADE support
1037 * @param string $tableName
1038 * @param string $fName
1039 * @return bool|ResultWrapper
1040 * @throws DBReadOnlyError
1042 public function dropTable( $tableName, $fName = __METHOD__
) {
1043 if ( !$this->tableExists( $tableName, $fName ) ) {
1046 $sql = "DROP TABLE " . $this->tableName( $tableName );
1048 return $this->query( $sql, $fName );
1051 public function setTableAliases( array $aliases ) {
1052 parent
::setTableAliases( $aliases );
1053 foreach ( $this->tableAliases
as $params ) {
1054 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1057 $this->attachDatabase( $params['dbname'] );
1058 $this->alreadyAttached
[$params['dbname']] = true;
1062 protected function requiresDatabaseUser() {
1063 return false; // just a file
1069 public function __toString() {
1070 return 'SQLite ' . (string)$this->conn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
1074 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );