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
{
30 private static $fulltextEnabled = null;
42 function __construct( $p = null ) {
45 if ( !is_array( $p ) ) { // legacy calling pattern
46 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
47 $args = func_get_args();
49 'host' => isset( $args[0] ) ?
$args[0] : false,
50 'user' => isset( $args[1] ) ?
$args[1] : false,
51 'password' => isset( $args[2] ) ?
$args[2] : false,
52 'dbname' => isset( $args[3] ) ?
$args[3] : false,
53 'flags' => isset( $args[4] ) ?
$args[4] : 0,
54 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
55 'foreign' => isset( $args[6] ) ?
$args[6] : false
58 $this->mName
= $p['dbname'];
59 parent
::__construct( $p );
60 // parent doesn't open when $user is false, but we can work with $dbName
61 if ( $p['dbname'] && !$this->isOpen() ) {
62 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
64 $this->attachDatabase( $wgSharedDB );
78 * @todo Check if it should be true like parent class
82 function implicitGroupby() {
86 /** Open an SQLite database and return a resource handle to it
87 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
89 * @param string $server
92 * @param string $dbName
94 * @throws DBConnectionError
97 function open( $server, $user, $pass, $dbName ) {
98 global $wgSQLiteDataDir;
101 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
102 if ( !is_readable( $fileName ) ) {
103 $this->mConn
= false;
104 throw new DBConnectionError( $this, "SQLite database not accessible" );
106 $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' );
145 * Does not actually close the connection, just destroys the reference for GC to do its work
148 protected function closeConnection() {
154 * Generates a database file name. Explicitly public for installer.
155 * @param string $dir Directory where database resides
156 * @param string $dbName Database name
159 public static function generateFileName( $dir, $dbName ) {
160 return "$dir/$dbName.sqlite";
164 * Check if the searchindext table is FTS enabled.
165 * @return bool False if not enabled.
167 function checkForEnabledSearch() {
168 if ( self
::$fulltextEnabled === null ) {
169 self
::$fulltextEnabled = false;
170 $table = $this->tableName( 'searchindex' );
171 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
173 $row = $res->fetchRow();
174 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
177 return self
::$fulltextEnabled;
181 * Returns version of currently supported SQLite fulltext search module or false if none present.
184 static function getFulltextSearchModule() {
185 static $cachedResult = null;
186 if ( $cachedResult !== null ) {
187 return $cachedResult;
189 $cachedResult = false;
190 $table = 'dummy_search_test';
192 $db = new DatabaseSqliteStandalone( ':memory:' );
194 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
195 $cachedResult = 'FTS3';
198 return $cachedResult;
202 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
205 * @param string $name database name to be used in queries like SELECT foo FROM dbname.table
206 * @param string $file database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
207 * @param string $fname calling function name
209 * @return ResultWrapper
211 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
212 global $wgSQLiteDataDir;
214 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
216 $file = $this->addQuotes( $file );
217 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
221 * @see DatabaseBase::isWriteQuery()
227 function isWriteQuery( $sql ) {
228 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
232 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
236 * @return ResultWrapper
238 protected function doQuery( $sql ) {
239 $res = $this->mConn
->query( $sql );
240 if ( $res === false ) {
243 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
244 $this->mAffectedRows
= $r->rowCount();
245 $res = new ResultWrapper( $this, $r->fetchAll() );
251 * @param $res ResultWrapper
253 function freeResult( $res ) {
254 if ( $res instanceof ResultWrapper
) {
262 * @param $res ResultWrapper
263 * @return object|bool
265 function fetchObject( $res ) {
266 if ( $res instanceof ResultWrapper
) {
272 $cur = current( $r );
273 if ( is_array( $cur ) ) {
276 foreach ( $cur as $k => $v ) {
277 if ( !is_numeric( $k ) ) {
288 * @param $res ResultWrapper
291 function fetchRow( $res ) {
292 if ( $res instanceof ResultWrapper
) {
297 $cur = current( $r );
298 if ( is_array( $cur ) ) {
306 * The PDO::Statement class implements the array interface so count() will work
308 * @param $res ResultWrapper
312 function numRows( $res ) {
313 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
318 * @param $res ResultWrapper
321 function numFields( $res ) {
322 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
323 return is_array( $r ) ?
count( $r[0] ) : 0;
327 * @param $res ResultWrapper
331 function fieldName( $res, $n ) {
332 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
333 if ( is_array( $r ) ) {
334 $keys = array_keys( $r[0] );
341 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
344 * @param $format String
347 function tableName( $name, $format = 'quoted' ) {
348 // table names starting with sqlite_ are reserved
349 if ( strpos( $name, 'sqlite_' ) === 0 ) {
352 return str_replace( '"', '', parent
::tableName( $name, $format ) );
356 * Index names have DB scope
358 * @param $index string
362 function indexName( $index ) {
367 * This must be called after nextSequenceVal
371 function insertId() {
372 // PDO::lastInsertId yields a string :(
373 return intval( $this->mConn
->lastInsertId() );
377 * @param $res ResultWrapper
380 function dataSeek( $res, $row ) {
381 if ( $res instanceof ResultWrapper
) {
388 for ( $i = 0; $i < $row; $i++
) {
397 function lastError() {
398 if ( !is_object( $this->mConn
) ) {
399 return "Cannot return last error, no db connection";
401 $e = $this->mConn
->errorInfo();
402 return isset( $e[2] ) ?
$e[2] : '';
408 function lastErrno() {
409 if ( !is_object( $this->mConn
) ) {
410 return "Cannot return last error, no db connection";
412 $info = $this->mConn
->errorInfo();
420 function affectedRows() {
421 return $this->mAffectedRows
;
425 * Returns information about an index
426 * Returns false if the index does not exist
427 * - if errors are explicitly ignored, returns NULL on failure
431 function indexInfo( $table, $index, $fname = __METHOD__
) {
432 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
433 $res = $this->query( $sql, $fname );
437 if ( $res->numRows() == 0 ) {
441 foreach ( $res as $row ) {
442 $info[] = $row->name
;
450 * @param $fname string
453 function indexUnique( $table, $index, $fname = __METHOD__
) {
454 $row = $this->selectRow( 'sqlite_master', '*',
457 'name' => $this->indexName( $index ),
459 if ( !$row ||
!isset( $row->sql
) ) {
463 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
464 $indexPos = strpos( $row->sql
, 'INDEX' );
465 if ( $indexPos === false ) {
468 $firstPart = substr( $row->sql
, 0, $indexPos );
469 $options = explode( ' ', $firstPart );
470 return in_array( 'UNIQUE', $options );
474 * Filter the options used in SELECT statements
476 * @param $options array
480 function makeSelectOptions( $options ) {
481 foreach ( $options as $k => $v ) {
482 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
486 return parent
::makeSelectOptions( $options );
490 * @param $options array
493 function makeUpdateOptions( $options ) {
494 $options = self
::fixIgnore( $options );
495 return parent
::makeUpdateOptions( $options );
499 * @param $options array
502 static function fixIgnore( $options ) {
503 # SQLite uses OR IGNORE not just IGNORE
504 foreach ( $options as $k => $v ) {
505 if ( $v == 'IGNORE' ) {
506 $options[$k] = 'OR IGNORE';
513 * @param $options array
516 function makeInsertOptions( $options ) {
517 $options = self
::fixIgnore( $options );
518 return parent
::makeInsertOptions( $options );
522 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
525 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
526 if ( !count( $a ) ) {
530 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
531 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
533 foreach ( $a as $v ) {
534 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
539 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
547 * @param $uniqueIndexes
549 * @param $fname string
550 * @return bool|ResultWrapper
552 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
553 if ( !count( $rows ) ) {
557 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
558 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
560 foreach ( $rows as $v ) {
561 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
566 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
573 * Returns the size of a text field, or -1 for "unlimited"
574 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
578 function textFieldSize( $table, $field ) {
585 function unionSupportsOrderAndLimit() {
594 function unionQueries( $sqls, $all ) {
595 $glue = $all ?
' UNION ALL ' : ' UNION ';
596 return implode( $glue, $sqls );
602 function wasDeadlock() {
603 return $this->lastErrno() == 5; // SQLITE_BUSY
609 function wasErrorReissuable() {
610 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
616 function wasReadOnlyError() {
617 return $this->lastErrno() == 8; // SQLITE_READONLY;
621 * @return string wikitext of a link to the server software's web site
623 public function getSoftwareLink() {
624 return "[http://sqlite.org/ SQLite]";
628 * @return string Version information from the database
630 function getServerVersion() {
631 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
636 * @return string User-friendly database information
638 public function getServerInfo() {
639 return wfMessage( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() )->text();
643 * Get information about a given field
644 * Returns false if the field does not exist.
646 * @param $table string
647 * @param $field string
648 * @return SQLiteField|bool False on failure
650 function fieldInfo( $table, $field ) {
651 $tableName = $this->tableName( $table );
652 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
653 $res = $this->query( $sql, __METHOD__
);
654 foreach ( $res as $row ) {
655 if ( $row->name
== $field ) {
656 return new SQLiteField( $row, $tableName );
662 protected function doBegin( $fname = '' ) {
663 if ( $this->mTrxLevel
== 1 ) {
664 $this->commit( __METHOD__
);
667 $this->mConn
->beginTransaction();
668 } catch ( PDOException
$e ) {
669 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
671 $this->mTrxLevel
= 1;
674 protected function doCommit( $fname = '' ) {
675 if ( $this->mTrxLevel
== 0 ) {
679 $this->mConn
->commit();
680 } catch ( PDOException
$e ) {
681 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
683 $this->mTrxLevel
= 0;
686 protected function doRollback( $fname = '' ) {
687 if ( $this->mTrxLevel
== 0 ) {
690 $this->mConn
->rollBack();
691 $this->mTrxLevel
= 0;
698 function strencode( $s ) {
699 return substr( $this->addQuotes( $s ), 1, - 1 );
706 function encodeBlob( $b ) {
707 return new Blob( $b );
711 * @param $b Blob|string
714 function decodeBlob( $b ) {
715 if ( $b instanceof Blob
) {
722 * @param $s Blob|string
725 function addQuotes( $s ) {
726 if ( $s instanceof Blob
) {
727 return "x'" . bin2hex( $s->fetch() ) . "'";
728 } elseif ( is_bool( $s ) ) {
730 } elseif ( strpos( $s, "\0" ) !== false ) {
731 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
732 // This is a known limitation of SQLite's mprintf function which PDO should work around,
733 // but doesn't. I have reported this to php.net as bug #63419:
734 // https://bugs.php.net/bug.php?id=63419
735 // There was already a similar report for SQLite3::escapeString, bug #62361:
736 // https://bugs.php.net/bug.php?id=62361
737 return "x'" . bin2hex( $s ) . "'";
739 return $this->mConn
->quote( $s );
746 function buildLike() {
747 $params = func_get_args();
748 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
749 $params = $params[0];
751 return parent
::buildLike( $params ) . "ESCAPE '\' ";
757 public function getSearchEngine() {
758 return "SearchSqlite";
762 * No-op version of deadlockLoop
765 public function deadlockLoop( /*...*/ ) {
766 $args = func_get_args();
767 $function = array_shift( $args );
768 return call_user_func_array( $function, $args );
775 protected function replaceVars( $s ) {
776 $s = parent
::replaceVars( $s );
777 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
778 // CREATE TABLE hacks to allow schema file sharing with MySQL
780 // binary/varbinary column type -> blob
781 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
782 // no such thing as unsigned
783 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
785 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
786 // floating point types -> REAL
787 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
789 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
790 // TEXT normalization
791 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
792 // BLOB normalization
793 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
795 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
797 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
799 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
800 // binary collation type -> nothing
801 $s = preg_replace( '/\bbinary\b/i', '', $s );
802 // auto_increment -> autoincrement
803 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
804 // No explicit options
805 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
806 // AUTOINCREMENT should immedidately follow PRIMARY KEY
807 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
808 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
809 // No truncated indexes
810 $s = preg_replace( '/\(\d+\)/', '', $s );
812 $s = preg_replace( '/\bfulltext\b/i', '', $s );
813 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
814 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
815 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
821 * Build a concatenation list to feed into a SQL query
823 * @param $stringList array
827 function buildConcat( $stringList ) {
828 return '(' . implode( ') || (', $stringList ) . ')';
832 * @throws MWException
835 * @param $temporary bool
836 * @param $fname string
837 * @return bool|ResultWrapper
839 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
840 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
841 $obj = $this->fetchObject( $res );
843 throw new MWException( "Couldn't retrieve structure for table $oldName" );
846 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
848 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
849 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
851 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
854 return $this->query( $sql, $fname );
858 * List all tables on the database
860 * @param string $prefix Only show tables with this prefix, e.g. mw_
861 * @param string $fname calling function name
865 function listTables( $prefix = null, $fname = __METHOD__
) {
866 $result = $this->select(
874 foreach ( $result as $table ) {
875 $vars = get_object_vars( $table );
876 $table = array_pop( $vars );
878 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
879 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
880 $endArray[] = $table;
889 } // end DatabaseSqlite class
892 * This class allows simple acccess to a SQLite database independently from main database settings
895 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
896 public function __construct( $fileName, $flags = 0 ) {
897 $this->mFlags
= $flags;
898 $this->tablePrefix( null );
899 $this->openFile( $fileName );
906 class SQLiteField
implements Field
{
907 private $info, $tableName;
908 function __construct( $info, $tableName ) {
910 $this->tableName
= $tableName;
914 return $this->info
->name
;
917 function tableName() {
918 return $this->tableName
;
921 function defaultValue() {
922 if ( is_string( $this->info
->dflt_value
) ) {
924 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
925 return str_replace( "''", "'", $this->info
->dflt_value
);
928 return $this->info
->dflt_value
;
934 function isNullable() {
935 return !$this->info
->notnull
;
939 return $this->info
->type
;