3bdcd65671a5760a157add57ca29484b83fa30a3
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 $mAffectedRows;
51 protected $mLastResult;
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->mDBname
= $p['dbname'];
83 $lockDomain = $this->mDBname
;
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"
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;
117 $p['schema'] = false;
118 $p['tablePrefix'] = '';
119 /** @var DatabaseSqlite $db */
120 $db = Database
::factory( 'sqlite', $p );
133 * @todo Check if it should be true like parent class
137 function implicitGroupby() {
141 /** Open an SQLite database and return a resource handle to it
142 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
144 * @param string $server
145 * @param string $user
146 * @param string $pass
147 * @param string $dbName
149 * @throws DBConnectionError
152 function open( $server, $user, $pass, $dbName ) {
154 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
155 if ( !is_readable( $fileName ) ) {
156 $this->mConn
= false;
157 throw new DBConnectionError( $this, "SQLite database not accessible" );
159 $this->openFile( $fileName );
161 return (bool)$this->mConn
;
165 * Opens a database file
167 * @param string $fileName
168 * @throws DBConnectionError
169 * @return PDO|bool SQL connection or false if failed
171 protected function openFile( $fileName ) {
174 $this->dbPath
= $fileName;
176 if ( $this->mFlags
& self
::DBO_PERSISTENT
) {
177 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
178 [ PDO
::ATTR_PERSISTENT
=> true ] );
180 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
182 } catch ( PDOException
$e ) {
183 $err = $e->getMessage();
186 if ( !$this->mConn
) {
187 $this->queryLogger
->debug( "DB connection error: $err\n" );
188 throw new DBConnectionError( $this, $err );
191 $this->mOpened
= !!$this->mConn
;
192 if ( $this->mOpened
) {
193 # Set error codes only, don't raise exceptions
194 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
195 # Enforce LIKE to be case sensitive, just like MySQL
196 $this->query( 'PRAGMA case_sensitive_like = 1' );
204 public function selectDB( $db ) {
205 return false; // doesn't make sense
209 * @return string SQLite DB file path
212 public function getDbFilePath() {
213 return $this->dbPath
;
217 * Does not actually close the connection, just destroys the reference for GC to do its work
220 protected function closeConnection() {
227 * Generates a database file name. Explicitly public for installer.
228 * @param string $dir Directory where database resides
229 * @param string $dbName Database name
232 public static function generateFileName( $dir, $dbName ) {
233 return "$dir/$dbName.sqlite";
237 * Check if the searchindext table is FTS enabled.
238 * @return bool False if not enabled.
240 function checkForEnabledSearch() {
241 if ( self
::$fulltextEnabled === null ) {
242 self
::$fulltextEnabled = false;
243 $table = $this->tableName( 'searchindex' );
244 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
246 $row = $res->fetchRow();
247 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
251 return self
::$fulltextEnabled;
255 * Returns version of currently supported SQLite fulltext search module or false if none present.
258 static function getFulltextSearchModule() {
259 static $cachedResult = null;
260 if ( $cachedResult !== null ) {
261 return $cachedResult;
263 $cachedResult = false;
264 $table = 'dummy_search_test';
266 $db = self
::newStandaloneInstance( ':memory:' );
267 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
268 $cachedResult = 'FTS3';
272 return $cachedResult;
276 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
279 * @param string $name Database name to be used in queries like
280 * SELECT foo FROM dbname.table
281 * @param bool|string $file Database file name. If omitted, will be generated
282 * using $name and configured data directory
283 * @param string $fname Calling function name
284 * @return ResultWrapper
286 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
288 $file = self
::generateFileName( $this->dbDir
, $name );
290 $file = $this->addQuotes( $file );
292 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
295 function isWriteQuery( $sql ) {
296 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
299 protected function isTransactableQuery( $sql ) {
300 return parent
::isTransactableQuery( $sql ) && !in_array(
301 $this->getQueryVerb( $sql ),
302 [ 'ATTACH', 'PRAGMA' ],
308 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
311 * @return bool|ResultWrapper
313 protected function doQuery( $sql ) {
314 $res = $this->mConn
->query( $sql );
315 if ( $res === false ) {
319 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
320 $this->mAffectedRows
= $r->rowCount();
321 $res = new ResultWrapper( $this, $r->fetchAll() );
327 * @param ResultWrapper|mixed $res
329 function freeResult( $res ) {
330 if ( $res instanceof ResultWrapper
) {
338 * @param ResultWrapper|array $res
339 * @return stdClass|bool
341 function fetchObject( $res ) {
342 if ( $res instanceof ResultWrapper
) {
348 $cur = current( $r );
349 if ( is_array( $cur ) ) {
352 foreach ( $cur as $k => $v ) {
353 if ( !is_numeric( $k ) ) {
365 * @param ResultWrapper|mixed $res
368 function fetchRow( $res ) {
369 if ( $res instanceof ResultWrapper
) {
374 $cur = current( $r );
375 if ( is_array( $cur ) ) {
385 * The PDO::Statement class implements the array interface so count() will work
387 * @param ResultWrapper|array $res
390 function numRows( $res ) {
391 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
397 * @param ResultWrapper $res
400 function numFields( $res ) {
401 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
402 if ( is_array( $r ) && count( $r ) > 0 ) {
403 // The size of the result array is twice the number of fields. (Bug: 65578)
404 return count( $r[0] ) / 2;
406 // If the result is empty return 0
412 * @param ResultWrapper $res
416 function fieldName( $res, $n ) {
417 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
418 if ( is_array( $r ) ) {
419 $keys = array_keys( $r[0] );
428 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
430 * @param string $name
431 * @param string $format
434 function tableName( $name, $format = 'quoted' ) {
435 // table names starting with sqlite_ are reserved
436 if ( strpos( $name, 'sqlite_' ) === 0 ) {
440 return str_replace( '"', '', parent
::tableName( $name, $format ) );
444 * This must be called after nextSequenceVal
448 function insertId() {
449 // PDO::lastInsertId yields a string :(
450 return intval( $this->mConn
->lastInsertId() );
454 * @param ResultWrapper|array $res
457 function dataSeek( $res, $row ) {
458 if ( $res instanceof ResultWrapper
) {
465 for ( $i = 0; $i < $row; $i++
) {
474 function lastError() {
475 if ( !is_object( $this->mConn
) ) {
476 return "Cannot return last error, no db connection";
478 $e = $this->mConn
->errorInfo();
480 return isset( $e[2] ) ?
$e[2] : '';
486 function lastErrno() {
487 if ( !is_object( $this->mConn
) ) {
488 return "Cannot return last error, no db connection";
490 $info = $this->mConn
->errorInfo();
499 function affectedRows() {
500 return $this->mAffectedRows
;
504 * Returns information about an index
505 * Returns false if the index does not exist
506 * - if errors are explicitly ignored, returns NULL on failure
508 * @param string $table
509 * @param string $index
510 * @param string $fname
511 * @return array|false
513 function indexInfo( $table, $index, $fname = __METHOD__
) {
514 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
515 $res = $this->query( $sql, $fname );
516 if ( !$res ||
$res->numRows() == 0 ) {
520 foreach ( $res as $row ) {
521 $info[] = $row->name
;
528 * @param string $table
529 * @param string $index
530 * @param string $fname
533 function indexUnique( $table, $index, $fname = __METHOD__
) {
534 $row = $this->selectRow( 'sqlite_master', '*',
537 'name' => $this->indexName( $index ),
539 if ( !$row ||
!isset( $row->sql
) ) {
543 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
544 $indexPos = strpos( $row->sql
, 'INDEX' );
545 if ( $indexPos === false ) {
548 $firstPart = substr( $row->sql
, 0, $indexPos );
549 $options = explode( ' ', $firstPart );
551 return in_array( 'UNIQUE', $options );
555 * Filter the options used in SELECT statements
557 * @param array $options
560 function makeSelectOptions( $options ) {
561 foreach ( $options as $k => $v ) {
562 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
567 return parent
::makeSelectOptions( $options );
571 * @param array $options
574 protected function makeUpdateOptionsArray( $options ) {
575 $options = parent
::makeUpdateOptionsArray( $options );
576 $options = self
::fixIgnore( $options );
582 * @param array $options
585 static function fixIgnore( $options ) {
586 # SQLite uses OR IGNORE not just IGNORE
587 foreach ( $options as $k => $v ) {
588 if ( $v == 'IGNORE' ) {
589 $options[$k] = 'OR IGNORE';
597 * @param array $options
600 function makeInsertOptions( $options ) {
601 $options = self
::fixIgnore( $options );
603 return parent
::makeInsertOptions( $options );
607 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
608 * @param string $table
610 * @param string $fname
611 * @param array $options
614 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
615 if ( !count( $a ) ) {
619 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
620 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
622 foreach ( $a as $v ) {
623 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
628 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
635 * @param string $table
636 * @param array $uniqueIndexes Unused
637 * @param string|array $rows
638 * @param string $fname
639 * @return bool|ResultWrapper
641 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
642 if ( !count( $rows ) ) {
646 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
647 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
649 foreach ( $rows as $v ) {
650 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
655 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
662 * Returns the size of a text field, or -1 for "unlimited"
663 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
665 * @param string $table
666 * @param string $field
669 function textFieldSize( $table, $field ) {
676 function unionSupportsOrderAndLimit() {
681 * @param string[] $sqls
682 * @param bool $all Whether to "UNION ALL" or not
685 function unionQueries( $sqls, $all ) {
686 $glue = $all ?
' UNION ALL ' : ' UNION ';
688 return implode( $glue, $sqls );
694 function wasDeadlock() {
695 return $this->lastErrno() == 5; // SQLITE_BUSY
701 function wasErrorReissuable() {
702 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
708 function wasReadOnlyError() {
709 return $this->lastErrno() == 8; // SQLITE_READONLY;
713 * @return string Wikitext of a link to the server software's web site
715 public function getSoftwareLink() {
716 return "[{{int:version-db-sqlite-url}} SQLite]";
720 * @return string Version information from the database
722 function getServerVersion() {
723 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
729 * Get information about a given field
730 * Returns false if the field does not exist.
732 * @param string $table
733 * @param string $field
734 * @return SQLiteField|bool False on failure
736 function fieldInfo( $table, $field ) {
737 $tableName = $this->tableName( $table );
738 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
739 $res = $this->query( $sql, __METHOD__
);
740 foreach ( $res as $row ) {
741 if ( $row->name
== $field ) {
742 return new SQLiteField( $row, $tableName );
749 protected function doBegin( $fname = '' ) {
750 if ( $this->trxMode
) {
751 $this->query( "BEGIN {$this->trxMode}", $fname );
753 $this->query( 'BEGIN', $fname );
755 $this->mTrxLevel
= 1;
762 function strencode( $s ) {
763 return substr( $this->addQuotes( $s ), 1, -1 );
770 function encodeBlob( $b ) {
771 return new Blob( $b );
775 * @param Blob|string $b
778 function decodeBlob( $b ) {
779 if ( $b instanceof Blob
) {
787 * @param string|int|null|bool|Blob $s
790 function addQuotes( $s ) {
791 if ( $s instanceof Blob
) {
792 return "x'" . bin2hex( $s->fetch() ) . "'";
793 } elseif ( is_bool( $s ) ) {
795 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
796 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
797 // This is a known limitation of SQLite's mprintf function which PDO
798 // should work around, but doesn't. I have reported this to php.net as bug #63419:
799 // https://bugs.php.net/bug.php?id=63419
800 // There was already a similar report for SQLite3::escapeString, bug #62361:
801 // https://bugs.php.net/bug.php?id=62361
802 // There is an additional bug regarding sorting this data after insert
803 // on older versions of sqlite shipped with ubuntu 12.04
804 // https://phabricator.wikimedia.org/T74367
805 $this->queryLogger
->debug(
807 ': Quoting value containing null byte. ' .
808 'For consistency all binary data should have been ' .
809 'first processed with self::encodeBlob()'
811 return "x'" . bin2hex( (string)$s ) . "'";
813 return $this->mConn
->quote( (string)$s );
818 * @param string $field Field or column to cast
822 public function buildStringCast( $field ) {
823 return 'CAST ( ' . $field . ' AS TEXT )';
827 * No-op version of deadlockLoop
831 public function deadlockLoop( /*...*/ ) {
832 $args = func_get_args();
833 $function = array_shift( $args );
835 return call_user_func_array( $function, $args );
842 protected function replaceVars( $s ) {
843 $s = parent
::replaceVars( $s );
844 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
845 // CREATE TABLE hacks to allow schema file sharing with MySQL
847 // binary/varbinary column type -> blob
848 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
849 // no such thing as unsigned
850 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
852 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
853 // floating point types -> REAL
855 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
860 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
861 // TEXT normalization
862 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
863 // BLOB normalization
864 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
866 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
868 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
870 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
871 // binary collation type -> nothing
872 $s = preg_replace( '/\bbinary\b/i', '', $s );
873 // auto_increment -> autoincrement
874 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
875 // No explicit options
876 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
877 // AUTOINCREMENT should immedidately follow PRIMARY KEY
878 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
879 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
880 // No truncated indexes
881 $s = preg_replace( '/\(\d+\)/', '', $s );
883 $s = preg_replace( '/\bfulltext\b/i', '', $s );
884 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
885 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
886 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
887 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
888 // INSERT IGNORE --> INSERT OR IGNORE
889 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
895 public function lock( $lockName, $method, $timeout = 5 ) {
896 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
897 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
898 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
902 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
905 public function unlock( $lockName, $method ) {
906 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
910 * Build a concatenation list to feed into a SQL query
912 * @param string[] $stringList
915 function buildConcat( $stringList ) {
916 return '(' . implode( ') || (', $stringList ) . ')';
919 public function buildGroupConcatField(
920 $delim, $table, $field, $conds = '', $join_conds = []
922 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
924 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
928 * @param string $oldName
929 * @param string $newName
930 * @param bool $temporary
931 * @param string $fname
932 * @return bool|ResultWrapper
933 * @throws RuntimeException
935 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
936 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
937 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
938 $obj = $this->fetchObject( $res );
940 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
944 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
945 $this->addIdentifierQuotes( $newName ),
950 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
951 $this->queryLogger
->debug(
952 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
954 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
958 $res = $this->query( $sql, $fname );
961 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
962 foreach ( $indexList as $index ) {
963 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
967 if ( $index->unique
) {
968 $sql = 'CREATE UNIQUE INDEX';
970 $sql = 'CREATE INDEX';
972 // Try to come up with a new index name, given indexes have database scope in SQLite
973 $indexName = $newName . '_' . $index->name
;
974 $sql .= ' ' . $indexName . ' ON ' . $newName;
976 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
978 foreach ( $indexInfo as $indexInfoRow ) {
979 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
982 $sql .= '(' . implode( ',', $fields ) . ')';
984 $this->query( $sql );
991 * List all tables on the database
993 * @param string $prefix Only show tables with this prefix, e.g. mw_
994 * @param string $fname Calling function name
998 function listTables( $prefix = null, $fname = __METHOD__
) {
999 $result = $this->select(
1007 foreach ( $result as $table ) {
1008 $vars = get_object_vars( $table );
1009 $table = array_pop( $vars );
1011 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1012 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1013 $endArray[] = $table;
1022 * Override due to no CASCADE support
1024 * @param string $tableName
1025 * @param string $fName
1026 * @return bool|ResultWrapper
1027 * @throws DBReadOnlyError
1029 public function dropTable( $tableName, $fName = __METHOD__
) {
1030 if ( !$this->tableExists( $tableName, $fName ) ) {
1033 $sql = "DROP TABLE " . $this->tableName( $tableName );
1035 return $this->query( $sql, $fName );
1038 public function setTableAliases( array $aliases ) {
1039 parent
::setTableAliases( $aliases );
1040 foreach ( $this->tableAliases
as $params ) {
1041 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1044 $this->attachDatabase( $params['dbname'] );
1045 $this->alreadyAttached
[$params['dbname']] = true;
1049 protected function requiresDatabaseUser() {
1050 return false; // just a file
1056 public function __toString() {
1057 return 'SQLite ' . (string)$this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
1061 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );