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
28 class DatabaseSqlite
extends Database
{
29 /** @var bool Whether full text is enabled */
30 private static $fulltextEnabled = null;
32 /** @var string Directory */
34 /** @var string File name for SQLite database file */
36 /** @var string Transaction mode */
39 /** @var int The number of rows affected as an integer */
40 protected $mAffectedRows;
42 protected $mLastResult;
47 /** @var FSLockManager (hopefully on the same server as the DB) */
51 * Additional params include:
52 * - dbDirectory : directory containing the DB and the lock file directory
53 * [defaults to $wgSQLiteDataDir]
54 * - dbFilePath : use this to force the path of the DB file
55 * - trxMode : one of (deferred, immediate, exclusive)
58 function __construct( array $p ) {
59 if ( isset( $p['dbFilePath'] ) ) {
60 parent
::__construct( $p );
61 // Standalone .sqlite file mode.
62 // Super doesn't open when $user is false, but we can work with $dbName,
63 // which is derived from the file path in this case.
64 $this->openFile( $p['dbFilePath'] );
65 $lockDomain = md5( $p['dbFilePath'] );
66 } elseif ( !isset( $p['dbDirectory'] ) ) {
67 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
69 $this->dbDir
= $p['dbDirectory'];
70 $this->mDBname
= $p['dbname'];
71 $lockDomain = $this->mDBname
;
72 // Stock wiki mode using standard file names per DB.
73 parent
::__construct( $p );
74 // Super doesn't open when $user is false, but we can work with $dbName
75 if ( $p['dbname'] && !$this->isOpen() ) {
76 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
78 foreach ( $this->tableAliases
as $params ) {
79 if ( isset( $done[$params['dbname']] ) ) {
82 $this->attachDatabase( $params['dbname'] );
83 $done[$params['dbname']] = 1;
89 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
90 if ( $this->trxMode
&&
91 !in_array( $this->trxMode
, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
93 $this->trxMode
= null;
94 $this->queryLogger
->warning( "Invalid SQLite transaction mode provided." );
97 $this->lockMgr
= new FSLockManager( [
98 'domain' => $lockDomain,
99 'lockDirectory' => "{$this->dbDir}/locks"
104 * @param string $filename
105 * @param array $p Options map; supports:
106 * - flags : (same as __construct counterpart)
107 * - trxMode : (same as __construct counterpart)
108 * - dbDirectory : (same as __construct counterpart)
109 * @return DatabaseSqlite
112 public static function newStandaloneInstance( $filename, array $p = [] ) {
113 $p['dbFilePath'] = $filename;
114 $p['schema'] = false;
115 $p['tablePrefix'] = '';
117 return Database
::factory( 'sqlite', $p );
128 * @todo Check if it should be true like parent class
132 function implicitGroupby() {
136 /** Open an SQLite database and return a resource handle to it
137 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
139 * @param string $server
140 * @param string $user
141 * @param string $pass
142 * @param string $dbName
144 * @throws DBConnectionError
147 function open( $server, $user, $pass, $dbName ) {
149 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
150 if ( !is_readable( $fileName ) ) {
151 $this->mConn
= false;
152 throw new DBConnectionError( $this, "SQLite database not accessible" );
154 $this->openFile( $fileName );
156 return (bool)$this->mConn
;
160 * Opens a database file
162 * @param string $fileName
163 * @throws DBConnectionError
164 * @return PDO|bool SQL connection or false if failed
166 protected function openFile( $fileName ) {
169 $this->dbPath
= $fileName;
171 if ( $this->mFlags
& self
::DBO_PERSISTENT
) {
172 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
173 [ PDO
::ATTR_PERSISTENT
=> true ] );
175 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
177 } catch ( PDOException
$e ) {
178 $err = $e->getMessage();
181 if ( !$this->mConn
) {
182 $this->queryLogger
->debug( "DB connection error: $err\n" );
183 throw new DBConnectionError( $this, $err );
186 $this->mOpened
= !!$this->mConn
;
187 if ( $this->mOpened
) {
188 # Set error codes only, don't raise exceptions
189 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
190 # Enforce LIKE to be case sensitive, just like MySQL
191 $this->query( 'PRAGMA case_sensitive_like = 1' );
199 public function selectDB( $db ) {
200 return false; // doesn't make sense
204 * @return string SQLite DB file path
207 public function getDbFilePath() {
208 return $this->dbPath
;
212 * Does not actually close the connection, just destroys the reference for GC to do its work
215 protected function closeConnection() {
222 * Generates a database file name. Explicitly public for installer.
223 * @param string $dir Directory where database resides
224 * @param string $dbName Database name
227 public static function generateFileName( $dir, $dbName ) {
228 return "$dir/$dbName.sqlite";
232 * Check if the searchindext table is FTS enabled.
233 * @return bool False if not enabled.
235 function checkForEnabledSearch() {
236 if ( self
::$fulltextEnabled === null ) {
237 self
::$fulltextEnabled = false;
238 $table = $this->tableName( 'searchindex' );
239 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
241 $row = $res->fetchRow();
242 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
246 return self
::$fulltextEnabled;
250 * Returns version of currently supported SQLite fulltext search module or false if none present.
253 static function getFulltextSearchModule() {
254 static $cachedResult = null;
255 if ( $cachedResult !== null ) {
256 return $cachedResult;
258 $cachedResult = false;
259 $table = 'dummy_search_test';
261 $db = self
::newStandaloneInstance( ':memory:' );
262 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
263 $cachedResult = 'FTS3';
267 return $cachedResult;
271 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
274 * @param string $name Database name to be used in queries like
275 * SELECT foo FROM dbname.table
276 * @param bool|string $file Database file name. If omitted, will be generated
277 * using $name and configured data directory
278 * @param string $fname Calling function name
279 * @return ResultWrapper
281 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
283 $file = self
::generateFileName( $this->dbDir
, $name );
285 $file = $this->addQuotes( $file );
287 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
290 function isWriteQuery( $sql ) {
291 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
295 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
298 * @return bool|ResultWrapper
300 protected function doQuery( $sql ) {
301 $res = $this->mConn
->query( $sql );
302 if ( $res === false ) {
306 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
307 $this->mAffectedRows
= $r->rowCount();
308 $res = new ResultWrapper( $this, $r->fetchAll() );
314 * @param ResultWrapper|mixed $res
316 function freeResult( $res ) {
317 if ( $res instanceof ResultWrapper
) {
325 * @param ResultWrapper|array $res
326 * @return stdClass|bool
328 function fetchObject( $res ) {
329 if ( $res instanceof ResultWrapper
) {
335 $cur = current( $r );
336 if ( is_array( $cur ) ) {
339 foreach ( $cur as $k => $v ) {
340 if ( !is_numeric( $k ) ) {
352 * @param ResultWrapper|mixed $res
355 function fetchRow( $res ) {
356 if ( $res instanceof ResultWrapper
) {
361 $cur = current( $r );
362 if ( is_array( $cur ) ) {
372 * The PDO::Statement class implements the array interface so count() will work
374 * @param ResultWrapper|array $res
377 function numRows( $res ) {
378 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
384 * @param ResultWrapper $res
387 function numFields( $res ) {
388 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
389 if ( is_array( $r ) && count( $r ) > 0 ) {
390 // The size of the result array is twice the number of fields. (Bug: 65578)
391 return count( $r[0] ) / 2;
393 // If the result is empty return 0
399 * @param ResultWrapper $res
403 function fieldName( $res, $n ) {
404 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
405 if ( is_array( $r ) ) {
406 $keys = array_keys( $r[0] );
415 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
417 * @param string $name
418 * @param string $format
421 function tableName( $name, $format = 'quoted' ) {
422 // table names starting with sqlite_ are reserved
423 if ( strpos( $name, 'sqlite_' ) === 0 ) {
427 return str_replace( '"', '', parent
::tableName( $name, $format ) );
431 * This must be called after nextSequenceVal
435 function insertId() {
436 // PDO::lastInsertId yields a string :(
437 return intval( $this->mConn
->lastInsertId() );
441 * @param ResultWrapper|array $res
444 function dataSeek( $res, $row ) {
445 if ( $res instanceof ResultWrapper
) {
452 for ( $i = 0; $i < $row; $i++
) {
461 function lastError() {
462 if ( !is_object( $this->mConn
) ) {
463 return "Cannot return last error, no db connection";
465 $e = $this->mConn
->errorInfo();
467 return isset( $e[2] ) ?
$e[2] : '';
473 function lastErrno() {
474 if ( !is_object( $this->mConn
) ) {
475 return "Cannot return last error, no db connection";
477 $info = $this->mConn
->errorInfo();
486 function affectedRows() {
487 return $this->mAffectedRows
;
491 * Returns information about an index
492 * Returns false if the index does not exist
493 * - if errors are explicitly ignored, returns NULL on failure
495 * @param string $table
496 * @param string $index
497 * @param string $fname
498 * @return array|false
500 function indexInfo( $table, $index, $fname = __METHOD__
) {
501 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
502 $res = $this->query( $sql, $fname );
503 if ( !$res ||
$res->numRows() == 0 ) {
507 foreach ( $res as $row ) {
508 $info[] = $row->name
;
515 * @param string $table
516 * @param string $index
517 * @param string $fname
520 function indexUnique( $table, $index, $fname = __METHOD__
) {
521 $row = $this->selectRow( 'sqlite_master', '*',
524 'name' => $this->indexName( $index ),
526 if ( !$row ||
!isset( $row->sql
) ) {
530 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
531 $indexPos = strpos( $row->sql
, 'INDEX' );
532 if ( $indexPos === false ) {
535 $firstPart = substr( $row->sql
, 0, $indexPos );
536 $options = explode( ' ', $firstPart );
538 return in_array( 'UNIQUE', $options );
542 * Filter the options used in SELECT statements
544 * @param array $options
547 function makeSelectOptions( $options ) {
548 foreach ( $options as $k => $v ) {
549 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
554 return parent
::makeSelectOptions( $options );
558 * @param array $options
561 protected function makeUpdateOptionsArray( $options ) {
562 $options = parent
::makeUpdateOptionsArray( $options );
563 $options = self
::fixIgnore( $options );
569 * @param array $options
572 static function fixIgnore( $options ) {
573 # SQLite uses OR IGNORE not just IGNORE
574 foreach ( $options as $k => $v ) {
575 if ( $v == 'IGNORE' ) {
576 $options[$k] = 'OR IGNORE';
584 * @param array $options
587 function makeInsertOptions( $options ) {
588 $options = self
::fixIgnore( $options );
590 return parent
::makeInsertOptions( $options );
594 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
595 * @param string $table
597 * @param string $fname
598 * @param array $options
601 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
602 if ( !count( $a ) ) {
606 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
607 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
609 foreach ( $a as $v ) {
610 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
615 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
622 * @param string $table
623 * @param array $uniqueIndexes Unused
624 * @param string|array $rows
625 * @param string $fname
626 * @return bool|ResultWrapper
628 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
629 if ( !count( $rows ) ) {
633 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
634 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
636 foreach ( $rows as $v ) {
637 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
642 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
649 * Returns the size of a text field, or -1 for "unlimited"
650 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
652 * @param string $table
653 * @param string $field
656 function textFieldSize( $table, $field ) {
663 function unionSupportsOrderAndLimit() {
668 * @param string[] $sqls
669 * @param bool $all Whether to "UNION ALL" or not
672 function unionQueries( $sqls, $all ) {
673 $glue = $all ?
' UNION ALL ' : ' UNION ';
675 return implode( $glue, $sqls );
681 function wasDeadlock() {
682 return $this->lastErrno() == 5; // SQLITE_BUSY
688 function wasErrorReissuable() {
689 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
695 function wasReadOnlyError() {
696 return $this->lastErrno() == 8; // SQLITE_READONLY;
700 * @return string Wikitext of a link to the server software's web site
702 public function getSoftwareLink() {
703 return "[{{int:version-db-sqlite-url}} SQLite]";
707 * @return string Version information from the database
709 function getServerVersion() {
710 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
716 * Get information about a given field
717 * Returns false if the field does not exist.
719 * @param string $table
720 * @param string $field
721 * @return SQLiteField|bool False on failure
723 function fieldInfo( $table, $field ) {
724 $tableName = $this->tableName( $table );
725 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
726 $res = $this->query( $sql, __METHOD__
);
727 foreach ( $res as $row ) {
728 if ( $row->name
== $field ) {
729 return new SQLiteField( $row, $tableName );
736 protected function doBegin( $fname = '' ) {
737 if ( $this->trxMode
) {
738 $this->query( "BEGIN {$this->trxMode}", $fname );
740 $this->query( 'BEGIN', $fname );
742 $this->mTrxLevel
= 1;
749 function strencode( $s ) {
750 return substr( $this->addQuotes( $s ), 1, -1 );
757 function encodeBlob( $b ) {
758 return new Blob( $b );
762 * @param Blob|string $b
765 function decodeBlob( $b ) {
766 if ( $b instanceof Blob
) {
774 * @param string|int|null|bool|Blob $s
777 function addQuotes( $s ) {
778 if ( $s instanceof Blob
) {
779 return "x'" . bin2hex( $s->fetch() ) . "'";
780 } elseif ( is_bool( $s ) ) {
782 } elseif ( strpos( $s, "\0" ) !== false ) {
783 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
784 // This is a known limitation of SQLite's mprintf function which PDO
785 // should work around, but doesn't. I have reported this to php.net as bug #63419:
786 // https://bugs.php.net/bug.php?id=63419
787 // There was already a similar report for SQLite3::escapeString, bug #62361:
788 // https://bugs.php.net/bug.php?id=62361
789 // There is an additional bug regarding sorting this data after insert
790 // on older versions of sqlite shipped with ubuntu 12.04
791 // https://phabricator.wikimedia.org/T74367
792 $this->queryLogger
->debug(
794 ': Quoting value containing null byte. ' .
795 'For consistency all binary data should have been ' .
796 'first processed with self::encodeBlob()'
798 return "x'" . bin2hex( $s ) . "'";
800 return $this->mConn
->quote( $s );
807 function buildLike() {
808 $params = func_get_args();
809 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
810 $params = $params[0];
813 return parent
::buildLike( $params ) . "ESCAPE '\' ";
817 * @param string $field Field or column to cast
821 public function buildStringCast( $field ) {
822 return 'CAST ( ' . $field . ' AS TEXT )';
826 * No-op version of deadlockLoop
830 public function deadlockLoop( /*...*/ ) {
831 $args = func_get_args();
832 $function = array_shift( $args );
834 return call_user_func_array( $function, $args );
841 protected function replaceVars( $s ) {
842 $s = parent
::replaceVars( $s );
843 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
844 // CREATE TABLE hacks to allow schema file sharing with MySQL
846 // binary/varbinary column type -> blob
847 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
848 // no such thing as unsigned
849 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
851 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
852 // floating point types -> REAL
854 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
859 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
860 // TEXT normalization
861 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
862 // BLOB normalization
863 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
865 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
867 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
869 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
870 // binary collation type -> nothing
871 $s = preg_replace( '/\bbinary\b/i', '', $s );
872 // auto_increment -> autoincrement
873 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
874 // No explicit options
875 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
876 // AUTOINCREMENT should immedidately follow PRIMARY KEY
877 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
878 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
879 // No truncated indexes
880 $s = preg_replace( '/\(\d+\)/', '', $s );
882 $s = preg_replace( '/\bfulltext\b/i', '', $s );
883 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
884 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
885 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
886 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
887 // INSERT IGNORE --> INSERT OR IGNORE
888 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
894 public function lock( $lockName, $method, $timeout = 5 ) {
895 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
896 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
897 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
901 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
904 public function unlock( $lockName, $method ) {
905 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
909 * Build a concatenation list to feed into a SQL query
911 * @param string[] $stringList
914 function buildConcat( $stringList ) {
915 return '(' . implode( ') || (', $stringList ) . ')';
918 public function buildGroupConcatField(
919 $delim, $table, $field, $conds = '', $join_conds = []
921 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
923 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
927 * @param string $oldName
928 * @param string $newName
929 * @param bool $temporary
930 * @param string $fname
931 * @return bool|ResultWrapper
932 * @throws RuntimeException
934 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
935 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
936 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
937 $obj = $this->fetchObject( $res );
939 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
943 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
944 $this->addIdentifierQuotes( $newName ),
949 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
950 $this->queryLogger
->debug(
951 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
953 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
957 $res = $this->query( $sql, $fname );
960 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
961 foreach ( $indexList as $index ) {
962 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
966 if ( $index->unique
) {
967 $sql = 'CREATE UNIQUE INDEX';
969 $sql = 'CREATE INDEX';
971 // Try to come up with a new index name, given indexes have database scope in SQLite
972 $indexName = $newName . '_' . $index->name
;
973 $sql .= ' ' . $indexName . ' ON ' . $newName;
975 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
977 foreach ( $indexInfo as $indexInfoRow ) {
978 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
981 $sql .= '(' . implode( ',', $fields ) . ')';
983 $this->query( $sql );
990 * List all tables on the database
992 * @param string $prefix Only show tables with this prefix, e.g. mw_
993 * @param string $fname Calling function name
997 function listTables( $prefix = null, $fname = __METHOD__
) {
998 $result = $this->select(
1006 foreach ( $result as $table ) {
1007 $vars = get_object_vars( $table );
1008 $table = array_pop( $vars );
1010 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1011 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1012 $endArray[] = $table;
1021 * Override due to no CASCADE support
1023 * @param string $tableName
1024 * @param string $fName
1025 * @return bool|ResultWrapper
1026 * @throws DBReadOnlyError
1028 public function dropTable( $tableName, $fName = __METHOD__
) {
1029 if ( !$this->tableExists( $tableName, $fName ) ) {
1032 $sql = "DROP TABLE " . $this->tableName( $tableName );
1034 return $this->query( $sql, $fName );
1037 protected function requiresDatabaseUser() {
1038 return false; // just a file
1044 public function __toString() {
1045 return 'SQLite ' . (string)$this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);