3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 namespace Wikimedia\Rdbms
;
31 use InvalidArgumentException
;
38 class DatabaseSqlite
extends Database
{
39 /** @var bool Whether full text is enabled */
40 private static $fulltextEnabled = null;
42 /** @var string Directory */
44 /** @var string File name for SQLite database file */
46 /** @var string Transaction mode */
49 /** @var int The number of rows affected as an integer */
50 protected $lastAffectedRowCount;
52 protected $lastResultHandle;
57 /** @var FSLockManager (hopefully on the same server as the DB) */
60 /** @var array List of shared database already attached to this connection */
61 private $alreadyAttached = [];
64 * Additional params include:
65 * - dbDirectory : directory containing the DB and the lock file directory
66 * [defaults to $wgSQLiteDataDir]
67 * - dbFilePath : use this to force the path of the DB file
68 * - trxMode : one of (deferred, immediate, exclusive)
71 function __construct( array $p ) {
72 if ( isset( $p['dbFilePath'] ) ) {
73 $this->dbPath
= $p['dbFilePath'];
74 $lockDomain = md5( $this->dbPath
);
75 // Use "X" for things like X.sqlite and ":memory:" for RAM-only DBs
76 if ( !isset( $p['dbname'] ) ||
!strlen( $p['dbname'] ) ) {
77 $p['dbname'] = preg_replace( '/\.sqlite\d?$/', '', basename( $this->dbPath
) );
79 } elseif ( isset( $p['dbDirectory'] ) ) {
80 $this->dbDir
= $p['dbDirectory'];
81 $lockDomain = $p['dbname'];
83 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
86 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
87 if ( $this->trxMode
&&
88 !in_array( $this->trxMode
, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
90 $this->trxMode
= null;
91 $this->queryLogger
->warning( "Invalid SQLite transaction mode provided." );
94 $this->lockMgr
= new FSLockManager( [
95 'domain' => $lockDomain,
96 'lockDirectory' => "{$this->dbDir}/locks"
99 parent
::__construct( $p );
102 protected static function getAttributes() {
103 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
107 * @param string $filename
108 * @param array $p Options map; supports:
109 * - flags : (same as __construct counterpart)
110 * - trxMode : (same as __construct counterpart)
111 * - dbDirectory : (same as __construct counterpart)
112 * @return DatabaseSqlite
115 public static function newStandaloneInstance( $filename, array $p = [] ) {
116 $p['dbFilePath'] = $filename;
118 $p['tablePrefix'] = '';
119 /** @var DatabaseSqlite $db */
120 $db = Database
::factory( 'sqlite', $p );
125 protected function doInitConnection() {
126 if ( $this->dbPath
!== null ) {
127 // Standalone .sqlite file mode.
130 $this->connectionParams
['dbname'],
131 $this->connectionParams
['tablePrefix']
133 } elseif ( $this->dbDir
!== null ) {
134 // Stock wiki mode using standard file names per DB
135 if ( strlen( $this->connectionParams
['dbname'] ) ) {
137 $this->connectionParams
['host'],
138 $this->connectionParams
['user'],
139 $this->connectionParams
['password'],
140 $this->connectionParams
['dbname'],
141 $this->connectionParams
['schema'],
142 $this->connectionParams
['tablePrefix']
145 // Caller will manually call open() later?
146 $this->connLogger
->debug( __METHOD__
. ': no database opened.' );
149 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
161 * @todo Check if it should be true like parent class
165 function implicitGroupby() {
169 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
171 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
172 if ( !is_readable( $fileName ) ) {
174 throw new DBConnectionError( $this, "SQLite database not accessible" );
176 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
177 $this->openFile( $fileName, $dbName, $tablePrefix );
179 return (bool)$this->conn
;
183 * Opens a database file
185 * @param string $fileName
186 * @param string $dbName
187 * @param string $tablePrefix
188 * @throws DBConnectionError
189 * @return PDO|bool SQL connection or false if failed
191 protected function openFile( $fileName, $dbName, $tablePrefix ) {
194 $this->dbPath
= $fileName;
196 if ( $this->flags
& self
::DBO_PERSISTENT
) {
197 $this->conn
= new PDO( "sqlite:$fileName", '', '',
198 [ PDO
::ATTR_PERSISTENT
=> true ] );
200 $this->conn
= new PDO( "sqlite:$fileName", '', '' );
202 } catch ( PDOException
$e ) {
203 $err = $e->getMessage();
206 if ( !$this->conn
) {
207 $this->queryLogger
->debug( "DB connection error: $err\n" );
208 throw new DBConnectionError( $this, $err );
211 $this->opened
= is_object( $this->conn
);
212 if ( $this->opened
) {
213 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
214 # Set error codes only, don't raise exceptions
215 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
216 # Enforce LIKE to be case sensitive, just like MySQL
217 $this->query( 'PRAGMA case_sensitive_like = 1' );
226 * @return string SQLite DB file path
229 public function getDbFilePath() {
230 return $this->dbPath
;
234 * Does not actually close the connection, just destroys the reference for GC to do its work
237 protected function closeConnection() {
244 * Generates a database file name. Explicitly public for installer.
245 * @param string $dir Directory where database resides
246 * @param string $dbName Database name
249 public static function generateFileName( $dir, $dbName ) {
250 return "$dir/$dbName.sqlite";
254 * Check if the searchindext table is FTS enabled.
255 * @return bool False if not enabled.
257 function checkForEnabledSearch() {
258 if ( self
::$fulltextEnabled === null ) {
259 self
::$fulltextEnabled = false;
260 $table = $this->tableName( 'searchindex' );
261 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
263 $row = $res->fetchRow();
264 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
268 return self
::$fulltextEnabled;
272 * Returns version of currently supported SQLite fulltext search module or false if none present.
275 static function getFulltextSearchModule() {
276 static $cachedResult = null;
277 if ( $cachedResult !== null ) {
278 return $cachedResult;
280 $cachedResult = false;
281 $table = 'dummy_search_test';
283 $db = self
::newStandaloneInstance( ':memory:' );
284 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
285 $cachedResult = 'FTS3';
289 return $cachedResult;
293 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
296 * @param string $name Database name to be used in queries like
297 * SELECT foo FROM dbname.table
298 * @param bool|string $file Database file name. If omitted, will be generated
299 * using $name and configured data directory
300 * @param string $fname Calling function name
301 * @return ResultWrapper
303 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
305 $file = self
::generateFileName( $this->dbDir
, $name );
307 $file = $this->addQuotes( $file );
309 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
312 protected function isWriteQuery( $sql ) {
313 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
316 protected function isTransactableQuery( $sql ) {
317 return parent
::isTransactableQuery( $sql ) && !in_array(
318 $this->getQueryVerb( $sql ),
319 [ 'ATTACH', 'PRAGMA' ],
325 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
328 * @return bool|ResultWrapper
330 protected function doQuery( $sql ) {
331 $res = $this->getBindingHandle()->query( $sql );
332 if ( $res === false ) {
336 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
337 $this->lastAffectedRowCount
= $r->rowCount();
338 $res = new ResultWrapper( $this, $r->fetchAll() );
344 * @param ResultWrapper|mixed $res
346 function freeResult( $res ) {
347 if ( $res instanceof ResultWrapper
) {
355 * @param ResultWrapper|array $res
356 * @return stdClass|bool
358 function fetchObject( $res ) {
359 if ( $res instanceof ResultWrapper
) {
365 $cur = current( $r );
366 if ( is_array( $cur ) ) {
369 foreach ( $cur as $k => $v ) {
370 if ( !is_numeric( $k ) ) {
382 * @param ResultWrapper|mixed $res
385 function fetchRow( $res ) {
386 if ( $res instanceof ResultWrapper
) {
391 $cur = current( $r );
392 if ( is_array( $cur ) ) {
402 * The PDO::Statement class implements the array interface so count() will work
404 * @param ResultWrapper|array|false $res
407 function numRows( $res ) {
408 // false does not implement Countable
409 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
411 return is_array( $r ) ?
count( $r ) : 0;
415 * @param ResultWrapper $res
418 function numFields( $res ) {
419 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
420 if ( is_array( $r ) && count( $r ) > 0 ) {
421 // The size of the result array is twice the number of fields. (T67578)
422 return count( $r[0] ) / 2;
424 // If the result is empty return 0
430 * @param ResultWrapper $res
434 function fieldName( $res, $n ) {
435 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
436 if ( is_array( $r ) ) {
437 $keys = array_keys( $r[0] );
446 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
448 * @param string $name
449 * @param string $format
452 function tableName( $name, $format = 'quoted' ) {
453 // table names starting with sqlite_ are reserved
454 if ( strpos( $name, 'sqlite_' ) === 0 ) {
458 return str_replace( '"', '', parent
::tableName( $name, $format ) );
462 * This must be called after nextSequenceVal
466 function insertId() {
467 // PDO::lastInsertId yields a string :(
468 return intval( $this->getBindingHandle()->lastInsertId() );
472 * @param ResultWrapper|array $res
475 function dataSeek( $res, $row ) {
476 if ( $res instanceof ResultWrapper
) {
483 for ( $i = 0; $i < $row; $i++
) {
492 function lastError() {
493 if ( !is_object( $this->conn
) ) {
494 return "Cannot return last error, no db connection";
496 $e = $this->conn
->errorInfo();
504 function lastErrno() {
505 if ( !is_object( $this->conn
) ) {
506 return "Cannot return last error, no db connection";
508 $info = $this->conn
->errorInfo();
517 protected function fetchAffectedRowCount() {
518 return $this->lastAffectedRowCount
;
521 function tableExists( $table, $fname = __METHOD__
) {
522 $tableRaw = $this->tableName( $table, 'raw' );
523 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
524 return true; // already known to exist
527 $encTable = $this->addQuotes( $tableRaw );
529 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
531 return $res->numRows() ?
true : false;
535 * Returns information about an index
536 * Returns false if the index does not exist
537 * - if errors are explicitly ignored, returns NULL on failure
539 * @param string $table
540 * @param string $index
541 * @param string $fname
542 * @return array|false
544 function indexInfo( $table, $index, $fname = __METHOD__
) {
545 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
546 $res = $this->query( $sql, $fname );
547 if ( !$res ||
$res->numRows() == 0 ) {
551 foreach ( $res as $row ) {
552 $info[] = $row->name
;
559 * @param string $table
560 * @param string $index
561 * @param string $fname
564 function indexUnique( $table, $index, $fname = __METHOD__
) {
565 $row = $this->selectRow( 'sqlite_master', '*',
568 'name' => $this->indexName( $index ),
570 if ( !$row ||
!isset( $row->sql
) ) {
574 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
575 $indexPos = strpos( $row->sql
, 'INDEX' );
576 if ( $indexPos === false ) {
579 $firstPart = substr( $row->sql
, 0, $indexPos );
580 $options = explode( ' ', $firstPart );
582 return in_array( 'UNIQUE', $options );
586 * Filter the options used in SELECT statements
588 * @param array $options
591 function makeSelectOptions( $options ) {
592 foreach ( $options as $k => $v ) {
593 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
598 return parent
::makeSelectOptions( $options );
602 * @param array $options
605 protected function makeUpdateOptionsArray( $options ) {
606 $options = parent
::makeUpdateOptionsArray( $options );
607 $options = self
::fixIgnore( $options );
613 * @param array $options
616 static function fixIgnore( $options ) {
617 # SQLite uses OR IGNORE not just IGNORE
618 foreach ( $options as $k => $v ) {
619 if ( $v == 'IGNORE' ) {
620 $options[$k] = 'OR IGNORE';
628 * @param array $options
631 function makeInsertOptions( $options ) {
632 $options = self
::fixIgnore( $options );
634 return parent
::makeInsertOptions( $options );
638 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
639 * @param string $table
641 * @param string $fname
642 * @param array $options
645 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
646 if ( !count( $a ) ) {
650 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
651 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
652 $affectedRowCount = 0;
654 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
655 foreach ( $a as $v ) {
656 parent
::insert( $table, $v, "$fname/multi-row", $options );
657 $affectedRowCount +
= $this->affectedRows();
659 $this->endAtomic( $fname );
660 } catch ( Exception
$e ) {
661 $this->cancelAtomic( $fname );
664 $this->affectedRowCount
= $affectedRowCount;
666 parent
::insert( $table, $a, "$fname/single-row", $options );
673 * @param string $table
674 * @param array $uniqueIndexes Unused
675 * @param string|array $rows
676 * @param string $fname
678 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
679 if ( !count( $rows ) ) {
683 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
684 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
685 $affectedRowCount = 0;
687 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
688 foreach ( $rows as $v ) {
689 $this->nativeReplace( $table, $v, "$fname/multi-row" );
690 $affectedRowCount +
= $this->affectedRows();
692 $this->endAtomic( $fname );
693 } catch ( Exception
$e ) {
694 $this->cancelAtomic( $fname );
697 $this->affectedRowCount
= $affectedRowCount;
699 $this->nativeReplace( $table, $rows, "$fname/single-row" );
704 * Returns the size of a text field, or -1 for "unlimited"
705 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
707 * @param string $table
708 * @param string $field
711 function textFieldSize( $table, $field ) {
718 function unionSupportsOrderAndLimit() {
723 * @param string[] $sqls
724 * @param bool $all Whether to "UNION ALL" or not
727 function unionQueries( $sqls, $all ) {
728 $glue = $all ?
' UNION ALL ' : ' UNION ';
730 return implode( $glue, $sqls );
736 function wasDeadlock() {
737 return $this->lastErrno() == 5; // SQLITE_BUSY
743 function wasReadOnlyError() {
744 return $this->lastErrno() == 8; // SQLITE_READONLY;
747 public function wasConnectionError( $errno ) {
748 return $errno == 17; // SQLITE_SCHEMA;
751 protected function wasKnownStatementRollbackError() {
752 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
753 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
754 // https://sqlite.org/lang_createtable.html#uniqueconst
755 // https://sqlite.org/lang_conflict.html
760 * @return string Wikitext of a link to the server software's web site
762 public function getSoftwareLink() {
763 return "[{{int:version-db-sqlite-url}} SQLite]";
767 * @return string Version information from the database
769 function getServerVersion() {
770 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
776 * Get information about a given field
777 * Returns false if the field does not exist.
779 * @param string $table
780 * @param string $field
781 * @return SQLiteField|bool False on failure
783 function fieldInfo( $table, $field ) {
784 $tableName = $this->tableName( $table );
785 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
786 $res = $this->query( $sql, __METHOD__
);
787 foreach ( $res as $row ) {
788 if ( $row->name
== $field ) {
789 return new SQLiteField( $row, $tableName );
796 protected function doBegin( $fname = '' ) {
797 if ( $this->trxMode
) {
798 $this->query( "BEGIN {$this->trxMode}", $fname );
800 $this->query( 'BEGIN', $fname );
809 function strencode( $s ) {
810 return substr( $this->addQuotes( $s ), 1, -1 );
817 function encodeBlob( $b ) {
818 return new Blob( $b );
822 * @param Blob|string $b
825 function decodeBlob( $b ) {
826 if ( $b instanceof Blob
) {
834 * @param string|int|null|bool|Blob $s
837 function addQuotes( $s ) {
838 if ( $s instanceof Blob
) {
839 return "x'" . bin2hex( $s->fetch() ) . "'";
840 } elseif ( is_bool( $s ) ) {
842 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
843 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
844 // This is a known limitation of SQLite's mprintf function which PDO
845 // should work around, but doesn't. I have reported this to php.net as bug #63419:
846 // https://bugs.php.net/bug.php?id=63419
847 // There was already a similar report for SQLite3::escapeString, bug #62361:
848 // https://bugs.php.net/bug.php?id=62361
849 // There is an additional bug regarding sorting this data after insert
850 // on older versions of sqlite shipped with ubuntu 12.04
851 // https://phabricator.wikimedia.org/T74367
852 $this->queryLogger
->debug(
854 ': Quoting value containing null byte. ' .
855 'For consistency all binary data should have been ' .
856 'first processed with self::encodeBlob()'
858 return "x'" . bin2hex( (string)$s ) . "'";
860 return $this->getBindingHandle()->quote( (string)$s );
864 public function buildSubstring( $input, $startPosition, $length = null ) {
865 $this->assertBuildSubstringParams( $startPosition, $length );
866 $params = [ $input, $startPosition ];
867 if ( $length !== null ) {
870 return 'SUBSTR(' . implode( ',', $params ) . ')';
874 * @param string $field Field or column to cast
878 public function buildStringCast( $field ) {
879 return 'CAST ( ' . $field . ' AS TEXT )';
883 * No-op version of deadlockLoop
887 public function deadlockLoop( /*...*/ ) {
888 $args = func_get_args();
889 $function = array_shift( $args );
891 return $function( ...$args );
898 protected function replaceVars( $s ) {
899 $s = parent
::replaceVars( $s );
900 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
901 // CREATE TABLE hacks to allow schema file sharing with MySQL
903 // binary/varbinary column type -> blob
904 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
905 // no such thing as unsigned
906 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
908 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
909 // floating point types -> REAL
911 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
916 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
917 // TEXT normalization
918 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
919 // BLOB normalization
920 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
922 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
924 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
926 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
927 // binary collation type -> nothing
928 $s = preg_replace( '/\bbinary\b/i', '', $s );
929 // auto_increment -> autoincrement
930 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
931 // No explicit options
932 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
933 // AUTOINCREMENT should immedidately follow PRIMARY KEY
934 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
935 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
936 // No truncated indexes
937 $s = preg_replace( '/\(\d+\)/', '', $s );
939 $s = preg_replace( '/\bfulltext\b/i', '', $s );
940 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
941 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
942 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
943 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
944 // INSERT IGNORE --> INSERT OR IGNORE
945 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
951 public function lock( $lockName, $method, $timeout = 5 ) {
952 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
953 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
954 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
958 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
961 public function unlock( $lockName, $method ) {
962 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
966 * Build a concatenation list to feed into a SQL query
968 * @param string[] $stringList
971 function buildConcat( $stringList ) {
972 return '(' . implode( ') || (', $stringList ) . ')';
975 public function buildGroupConcatField(
976 $delim, $table, $field, $conds = '', $join_conds = []
978 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
980 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
984 * @param string $oldName
985 * @param string $newName
986 * @param bool $temporary
987 * @param string $fname
988 * @return bool|ResultWrapper
989 * @throws RuntimeException
991 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
992 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
993 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
994 $obj = $this->fetchObject( $res );
996 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1001 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1003 $this->addIdentifierQuotes( $newName ),
1008 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1009 $this->queryLogger
->debug(
1010 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1012 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1016 $res = $this->query( $sql, $fname );
1018 // Take over indexes
1019 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1020 foreach ( $indexList as $index ) {
1021 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1025 if ( $index->unique
) {
1026 $sql = 'CREATE UNIQUE INDEX';
1028 $sql = 'CREATE INDEX';
1030 // Try to come up with a new index name, given indexes have database scope in SQLite
1031 $indexName = $newName . '_' . $index->name
;
1032 $sql .= ' ' . $indexName . ' ON ' . $newName;
1034 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1036 foreach ( $indexInfo as $indexInfoRow ) {
1037 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1040 $sql .= '(' . implode( ',', $fields ) . ')';
1042 $this->query( $sql );
1049 * List all tables on the database
1051 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1052 * @param string $fname Calling function name
1056 function listTables( $prefix = null, $fname = __METHOD__
) {
1057 $result = $this->select(
1065 foreach ( $result as $table ) {
1066 $vars = get_object_vars( $table );
1067 $table = array_pop( $vars );
1069 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1070 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1071 $endArray[] = $table;
1080 * Override due to no CASCADE support
1082 * @param string $tableName
1083 * @param string $fName
1084 * @return bool|ResultWrapper
1085 * @throws DBReadOnlyError
1087 public function dropTable( $tableName, $fName = __METHOD__
) {
1088 if ( !$this->tableExists( $tableName, $fName ) ) {
1091 $sql = "DROP TABLE " . $this->tableName( $tableName );
1093 return $this->query( $sql, $fName );
1096 public function setTableAliases( array $aliases ) {
1097 parent
::setTableAliases( $aliases );
1098 foreach ( $this->tableAliases
as $params ) {
1099 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1102 $this->attachDatabase( $params['dbname'] );
1103 $this->alreadyAttached
[$params['dbname']] = true;
1107 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1108 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1109 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1110 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1113 public function databasesAreIndependent() {
1120 public function __toString() {
1121 return is_object( $this->conn
)
1122 ?
'SQLite ' . (string)$this->conn
->getAttribute( PDO
::ATTR_SERVER_VERSION
)
1123 : '(not connected)';
1129 protected function getBindingHandle() {
1130 return parent
::getBindingHandle();
1135 * @deprecated since 1.29
1137 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );