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 DatabaseBase
{
29 private static $fulltextEnabled = null;
41 function __construct( $p = null ) {
44 if ( !is_array( $p ) ) { // legacy calling pattern
45 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
46 $args = func_get_args();
48 'host' => isset( $args[0] ) ?
$args[0] : false,
49 'user' => isset( $args[1] ) ?
$args[1] : false,
50 'password' => isset( $args[2] ) ?
$args[2] : false,
51 'dbname' => isset( $args[3] ) ?
$args[3] : false,
52 'flags' => isset( $args[4] ) ?
$args[4] : 0,
53 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
54 'foreign' => isset( $args[6] ) ?
$args[6] : false
57 $this->mName
= $p['dbname'];
58 parent
::__construct( $p );
59 // parent doesn't open when $user is false, but we can work with $dbName
60 if ( $p['dbname'] && !$this->isOpen() ) {
61 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
63 $this->attachDatabase( $wgSharedDB );
77 * @todo Check if it should be true like parent class
81 function implicitGroupby() {
85 /** Open an SQLite database and return a resource handle to it
86 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
88 * @param string $server
91 * @param string $dbName
93 * @throws DBConnectionError
96 function open( $server, $user, $pass, $dbName ) {
97 global $wgSQLiteDataDir;
100 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
101 if ( !is_readable( $fileName ) ) {
102 $this->mConn
= false;
103 throw new DBConnectionError( $this, "SQLite database not accessible" );
105 $this->openFile( $fileName );
111 * Opens a database file
113 * @param $fileName string
115 * @throws DBConnectionError
116 * @return PDO|bool SQL connection or false if failed
118 function openFile( $fileName ) {
119 $this->mDatabaseFile
= $fileName;
121 if ( $this->mFlags
& DBO_PERSISTENT
) {
122 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
123 array( PDO
::ATTR_PERSISTENT
=> true ) );
125 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
127 } catch ( PDOException
$e ) {
128 $err = $e->getMessage();
130 if ( !$this->mConn
) {
131 wfDebug( "DB connection error: $err\n" );
132 throw new DBConnectionError( $this, $err );
134 $this->mOpened
= !!$this->mConn
;
135 # set error codes only, don't raise exceptions
136 if ( $this->mOpened
) {
137 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
138 # Enforce LIKE to be case sensitive, just like MySQL
139 $this->query( 'PRAGMA case_sensitive_like = 1' );
146 * Does not actually close the connection, just destroys the reference for GC to do its work
149 protected function closeConnection() {
156 * Generates a database file name. Explicitly public for installer.
157 * @param string $dir Directory where database resides
158 * @param string $dbName Database name
161 public static function generateFileName( $dir, $dbName ) {
162 return "$dir/$dbName.sqlite";
166 * Check if the searchindext table is FTS enabled.
167 * @return bool False if not enabled.
169 function checkForEnabledSearch() {
170 if ( self
::$fulltextEnabled === null ) {
171 self
::$fulltextEnabled = false;
172 $table = $this->tableName( 'searchindex' );
173 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
175 $row = $res->fetchRow();
176 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
180 return self
::$fulltextEnabled;
184 * Returns version of currently supported SQLite fulltext search module or false if none present.
187 static function getFulltextSearchModule() {
188 static $cachedResult = null;
189 if ( $cachedResult !== null ) {
190 return $cachedResult;
192 $cachedResult = false;
193 $table = 'dummy_search_test';
195 $db = new DatabaseSqliteStandalone( ':memory:' );
197 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
198 $cachedResult = 'FTS3';
202 return $cachedResult;
206 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
209 * @param string $name database name to be used in queries like
210 * SELECT foo FROM dbname.table
211 * @param string $file database file name. If omitted, will be generated
212 * using $name and $wgSQLiteDataDir
213 * @param string $fname calling function name
215 * @return ResultWrapper
217 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
218 global $wgSQLiteDataDir;
220 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
222 $file = $this->addQuotes( $file );
224 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
228 * @see DatabaseBase::isWriteQuery()
234 function isWriteQuery( $sql ) {
235 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
239 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
243 * @return ResultWrapper
245 protected function doQuery( $sql ) {
246 $res = $this->mConn
->query( $sql );
247 if ( $res === false ) {
250 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
251 $this->mAffectedRows
= $r->rowCount();
252 $res = new ResultWrapper( $this, $r->fetchAll() );
259 * @param $res ResultWrapper
261 function freeResult( $res ) {
262 if ( $res instanceof ResultWrapper
) {
270 * @param $res ResultWrapper
271 * @return object|bool
273 function fetchObject( $res ) {
274 if ( $res instanceof ResultWrapper
) {
280 $cur = current( $r );
281 if ( is_array( $cur ) ) {
284 foreach ( $cur as $k => $v ) {
285 if ( !is_numeric( $k ) ) {
297 * @param $res ResultWrapper
300 function fetchRow( $res ) {
301 if ( $res instanceof ResultWrapper
) {
306 $cur = current( $r );
307 if ( is_array( $cur ) ) {
317 * The PDO::Statement class implements the array interface so count() will work
319 * @param $res ResultWrapper
323 function numRows( $res ) {
324 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
330 * @param $res ResultWrapper
333 function numFields( $res ) {
334 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
336 return is_array( $r ) ?
count( $r[0] ) : 0;
340 * @param $res ResultWrapper
344 function fieldName( $res, $n ) {
345 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
346 if ( is_array( $r ) ) {
347 $keys = array_keys( $r[0] );
356 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
359 * @param $format String
362 function tableName( $name, $format = 'quoted' ) {
363 // table names starting with sqlite_ are reserved
364 if ( strpos( $name, 'sqlite_' ) === 0 ) {
368 return str_replace( '"', '', parent
::tableName( $name, $format ) );
372 * Index names have DB scope
374 * @param $index string
378 function indexName( $index ) {
383 * This must be called after nextSequenceVal
387 function insertId() {
388 // PDO::lastInsertId yields a string :(
389 return intval( $this->mConn
->lastInsertId() );
393 * @param $res ResultWrapper
396 function dataSeek( $res, $row ) {
397 if ( $res instanceof ResultWrapper
) {
404 for ( $i = 0; $i < $row; $i++
) {
413 function lastError() {
414 if ( !is_object( $this->mConn
) ) {
415 return "Cannot return last error, no db connection";
417 $e = $this->mConn
->errorInfo();
419 return isset( $e[2] ) ?
$e[2] : '';
425 function lastErrno() {
426 if ( !is_object( $this->mConn
) ) {
427 return "Cannot return last error, no db connection";
429 $info = $this->mConn
->errorInfo();
438 function affectedRows() {
439 return $this->mAffectedRows
;
443 * Returns information about an index
444 * Returns false if the index does not exist
445 * - if errors are explicitly ignored, returns NULL on failure
449 function indexInfo( $table, $index, $fname = __METHOD__
) {
450 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
451 $res = $this->query( $sql, $fname );
455 if ( $res->numRows() == 0 ) {
459 foreach ( $res as $row ) {
460 $info[] = $row->name
;
469 * @param $fname string
472 function indexUnique( $table, $index, $fname = __METHOD__
) {
473 $row = $this->selectRow( 'sqlite_master', '*',
476 'name' => $this->indexName( $index ),
478 if ( !$row ||
!isset( $row->sql
) ) {
482 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
483 $indexPos = strpos( $row->sql
, 'INDEX' );
484 if ( $indexPos === false ) {
487 $firstPart = substr( $row->sql
, 0, $indexPos );
488 $options = explode( ' ', $firstPart );
490 return in_array( 'UNIQUE', $options );
494 * Filter the options used in SELECT statements
496 * @param $options array
500 function makeSelectOptions( $options ) {
501 foreach ( $options as $k => $v ) {
502 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
507 return parent
::makeSelectOptions( $options );
511 * @param $options array
514 function makeUpdateOptions( $options ) {
515 $options = self
::fixIgnore( $options );
517 return parent
::makeUpdateOptions( $options );
521 * @param $options array
524 static function fixIgnore( $options ) {
525 # SQLite uses OR IGNORE not just IGNORE
526 foreach ( $options as $k => $v ) {
527 if ( $v == 'IGNORE' ) {
528 $options[$k] = 'OR IGNORE';
536 * @param $options array
539 function makeInsertOptions( $options ) {
540 $options = self
::fixIgnore( $options );
542 return parent
::makeInsertOptions( $options );
546 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
549 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
550 if ( !count( $a ) ) {
554 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
555 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
557 foreach ( $a as $v ) {
558 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
563 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
571 * @param $uniqueIndexes
573 * @param $fname string
574 * @return bool|ResultWrapper
576 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
577 if ( !count( $rows ) ) {
581 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
582 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
584 foreach ( $rows as $v ) {
585 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
590 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
597 * Returns the size of a text field, or -1 for "unlimited"
598 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
602 function textFieldSize( $table, $field ) {
609 function unionSupportsOrderAndLimit() {
618 function unionQueries( $sqls, $all ) {
619 $glue = $all ?
' UNION ALL ' : ' UNION ';
621 return implode( $glue, $sqls );
627 function wasDeadlock() {
628 return $this->lastErrno() == 5; // SQLITE_BUSY
634 function wasErrorReissuable() {
635 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
641 function wasReadOnlyError() {
642 return $this->lastErrno() == 8; // SQLITE_READONLY;
646 * @return string wikitext of a link to the server software's web site
648 public function getSoftwareLink() {
649 return "[http://sqlite.org/ SQLite]";
653 * @return string Version information from the database
655 function getServerVersion() {
656 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
662 * @return string User-friendly database information
664 public function getServerInfo() {
665 return wfMessage( self
::getFulltextSearchModule()
667 : 'sqlite-no-fts', $this->getServerVersion() )->text();
671 * Get information about a given field
672 * Returns false if the field does not exist.
674 * @param $table string
675 * @param $field string
676 * @return SQLiteField|bool False on failure
678 function fieldInfo( $table, $field ) {
679 $tableName = $this->tableName( $table );
680 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
681 $res = $this->query( $sql, __METHOD__
);
682 foreach ( $res as $row ) {
683 if ( $row->name
== $field ) {
684 return new SQLiteField( $row, $tableName );
691 protected function doBegin( $fname = '' ) {
692 if ( $this->mTrxLevel
== 1 ) {
693 $this->commit( __METHOD__
);
696 $this->mConn
->beginTransaction();
697 } catch ( PDOException
$e ) {
698 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
700 $this->mTrxLevel
= 1;
703 protected function doCommit( $fname = '' ) {
704 if ( $this->mTrxLevel
== 0 ) {
708 $this->mConn
->commit();
709 } catch ( PDOException
$e ) {
710 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
712 $this->mTrxLevel
= 0;
715 protected function doRollback( $fname = '' ) {
716 if ( $this->mTrxLevel
== 0 ) {
719 $this->mConn
->rollBack();
720 $this->mTrxLevel
= 0;
727 function strencode( $s ) {
728 return substr( $this->addQuotes( $s ), 1, -1 );
735 function encodeBlob( $b ) {
736 return new Blob( $b );
740 * @param $b Blob|string
743 function decodeBlob( $b ) {
744 if ( $b instanceof Blob
) {
752 * @param $s Blob|string
755 function addQuotes( $s ) {
756 if ( $s instanceof Blob
) {
757 return "x'" . bin2hex( $s->fetch() ) . "'";
758 } elseif ( is_bool( $s ) ) {
760 } elseif ( strpos( $s, "\0" ) !== false ) {
761 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
762 // This is a known limitation of SQLite's mprintf function which PDO should work around,
763 // but doesn't. I have reported this to php.net as bug #63419:
764 // https://bugs.php.net/bug.php?id=63419
765 // There was already a similar report for SQLite3::escapeString, bug #62361:
766 // https://bugs.php.net/bug.php?id=62361
767 return "x'" . bin2hex( $s ) . "'";
769 return $this->mConn
->quote( $s );
776 function buildLike() {
777 $params = func_get_args();
778 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
779 $params = $params[0];
782 return parent
::buildLike( $params ) . "ESCAPE '\' ";
788 public function getSearchEngine() {
789 return "SearchSqlite";
793 * No-op version of deadlockLoop
796 public function deadlockLoop( /*...*/ ) {
797 $args = func_get_args();
798 $function = array_shift( $args );
800 return call_user_func_array( $function, $args );
807 protected function replaceVars( $s ) {
808 $s = parent
::replaceVars( $s );
809 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
810 // CREATE TABLE hacks to allow schema file sharing with MySQL
812 // binary/varbinary column type -> blob
813 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
814 // no such thing as unsigned
815 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
817 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
818 // floating point types -> REAL
820 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
825 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
826 // TEXT normalization
827 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
828 // BLOB normalization
829 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
831 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
833 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
835 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
836 // binary collation type -> nothing
837 $s = preg_replace( '/\bbinary\b/i', '', $s );
838 // auto_increment -> autoincrement
839 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
840 // No explicit options
841 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
842 // AUTOINCREMENT should immedidately follow PRIMARY KEY
843 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
844 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
845 // No truncated indexes
846 $s = preg_replace( '/\(\d+\)/', '', $s );
848 $s = preg_replace( '/\bfulltext\b/i', '', $s );
849 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
850 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
851 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
858 * Build a concatenation list to feed into a SQL query
860 * @param $stringList array
864 function buildConcat( $stringList ) {
865 return '(' . implode( ') || (', $stringList ) . ')';
868 public function buildGroupConcatField(
869 $delim, $table, $field, $conds = '', $join_conds = array()
871 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
873 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
877 * @throws MWException
880 * @param $temporary bool
881 * @param $fname string
882 * @return bool|ResultWrapper
884 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
885 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
886 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
887 $obj = $this->fetchObject( $res );
889 throw new MWException( "Couldn't retrieve structure for table $oldName" );
893 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
894 $this->addIdentifierQuotes( $newName ),
899 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
900 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
902 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
906 return $this->query( $sql, $fname );
910 * List all tables on the database
912 * @param string $prefix Only show tables with this prefix, e.g. mw_
913 * @param string $fname calling function name
917 function listTables( $prefix = null, $fname = __METHOD__
) {
918 $result = $this->select(
926 foreach ( $result as $table ) {
927 $vars = get_object_vars( $table );
928 $table = array_pop( $vars );
930 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
931 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
932 $endArray[] = $table;
939 } // end DatabaseSqlite class
942 * This class allows simple acccess to a SQLite database independently from main database settings
945 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
946 public function __construct( $fileName, $flags = 0 ) {
947 $this->mFlags
= $flags;
948 $this->tablePrefix( null );
949 $this->openFile( $fileName );
956 class SQLiteField
implements Field
{
957 private $info, $tableName;
959 function __construct( $info, $tableName ) {
961 $this->tableName
= $tableName;
965 return $this->info
->name
;
968 function tableName() {
969 return $this->tableName
;
972 function defaultValue() {
973 if ( is_string( $this->info
->dflt_value
) ) {
975 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
976 return str_replace( "''", "'", $this->info
->dflt_value
);
980 return $this->info
->dflt_value
;
986 function isNullable() {
987 return !$this->info
->notnull
;
991 return $this->info
->type
;