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 /** @var bool Whether full text is enabled */
30 private static $fulltextEnabled = null;
32 /** @var string File name for SQLite database file */
33 public $mDatabaseFile;
35 /** @var int The number of rows affected as an integer */
36 protected $mAffectedRows;
39 protected $mLastResult;
44 function __construct( $p = null ) {
47 if ( !is_array( $p ) ) { // legacy calling pattern
48 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
49 $args = func_get_args();
51 'host' => isset( $args[0] ) ?
$args[0] : false,
52 'user' => isset( $args[1] ) ?
$args[1] : false,
53 'password' => isset( $args[2] ) ?
$args[2] : false,
54 'dbname' => isset( $args[3] ) ?
$args[3] : false,
55 'flags' => isset( $args[4] ) ?
$args[4] : 0,
56 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
57 'foreign' => isset( $args[6] ) ?
$args[6] : false
60 $this->mDBname
= $p['dbname'];
61 parent
::__construct( $p );
62 // parent doesn't open when $user is false, but we can work with $dbName
63 if ( $p['dbname'] && !$this->isOpen() ) {
64 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
66 $this->attachDatabase( $wgSharedDB );
80 * @todo Check if it should be true like parent class
84 function implicitGroupby() {
88 /** Open an SQLite database and return a resource handle to it
89 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
91 * @param string $server
94 * @param string $dbName
96 * @throws DBConnectionError
99 function open( $server, $user, $pass, $dbName ) {
100 global $wgSQLiteDataDir;
103 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
104 if ( !is_readable( $fileName ) ) {
105 $this->mConn
= false;
106 throw new DBConnectionError( $this, "SQLite database not accessible" );
108 $this->openFile( $fileName );
114 * Opens a database file
116 * @param string $fileName
117 * @throws DBConnectionError
118 * @return PDO|bool SQL connection or false if failed
120 function openFile( $fileName ) {
123 $this->mDatabaseFile
= $fileName;
125 if ( $this->mFlags
& DBO_PERSISTENT
) {
126 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
127 array( PDO
::ATTR_PERSISTENT
=> true ) );
129 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
131 } catch ( PDOException
$e ) {
132 $err = $e->getMessage();
135 if ( !$this->mConn
) {
136 wfDebug( "DB connection error: $err\n" );
137 throw new DBConnectionError( $this, $err );
140 $this->mOpened
= !!$this->mConn
;
141 # set error codes only, don't raise exceptions
142 if ( $this->mOpened
) {
143 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
144 # Enforce LIKE to be case sensitive, just like MySQL
145 $this->query( 'PRAGMA case_sensitive_like = 1' );
154 * Does not actually close the connection, just destroys the reference for GC to do its work
157 protected function closeConnection() {
164 * Generates a database file name. Explicitly public for installer.
165 * @param string $dir Directory where database resides
166 * @param string $dbName Database name
169 public static function generateFileName( $dir, $dbName ) {
170 return "$dir/$dbName.sqlite";
174 * Check if the searchindext table is FTS enabled.
175 * @return bool False if not enabled.
177 function checkForEnabledSearch() {
178 if ( self
::$fulltextEnabled === null ) {
179 self
::$fulltextEnabled = false;
180 $table = $this->tableName( 'searchindex' );
181 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
183 $row = $res->fetchRow();
184 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
188 return self
::$fulltextEnabled;
192 * Returns version of currently supported SQLite fulltext search module or false if none present.
195 static function getFulltextSearchModule() {
196 static $cachedResult = null;
197 if ( $cachedResult !== null ) {
198 return $cachedResult;
200 $cachedResult = false;
201 $table = 'dummy_search_test';
203 $db = new DatabaseSqliteStandalone( ':memory:' );
205 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
206 $cachedResult = 'FTS3';
210 return $cachedResult;
214 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
217 * @param string $name Database name to be used in queries like
218 * SELECT foo FROM dbname.table
219 * @param bool|string $file Database file name. If omitted, will be generated
220 * using $name and $wgSQLiteDataDir
221 * @param string $fname Calling function name
222 * @return ResultWrapper
224 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
225 global $wgSQLiteDataDir;
227 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
229 $file = $this->addQuotes( $file );
231 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
235 * @see DatabaseBase::isWriteQuery()
240 function isWriteQuery( $sql ) {
241 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
245 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
248 * @return bool|ResultWrapper
250 protected function doQuery( $sql ) {
251 $res = $this->mConn
->query( $sql );
252 if ( $res === false ) {
255 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
256 $this->mAffectedRows
= $r->rowCount();
257 $res = new ResultWrapper( $this, $r->fetchAll() );
264 * @param ResultWrapper|mixed $res
266 function freeResult( $res ) {
267 if ( $res instanceof ResultWrapper
) {
275 * @param ResultWrapper|array $res
276 * @return stdClass|bool
278 function fetchObject( $res ) {
279 if ( $res instanceof ResultWrapper
) {
285 $cur = current( $r );
286 if ( is_array( $cur ) ) {
289 foreach ( $cur as $k => $v ) {
290 if ( !is_numeric( $k ) ) {
302 * @param ResultWrapper|mixed $res
305 function fetchRow( $res ) {
306 if ( $res instanceof ResultWrapper
) {
311 $cur = current( $r );
312 if ( is_array( $cur ) ) {
322 * The PDO::Statement class implements the array interface so count() will work
324 * @param ResultWrapper|array $res
327 function numRows( $res ) {
328 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
334 * @param ResultWrapper $res
337 function numFields( $res ) {
338 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
340 return is_array( $r ) ?
count( $r[0] ) : 0;
344 * @param ResultWrapper $res
348 function fieldName( $res, $n ) {
349 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
350 if ( is_array( $r ) ) {
351 $keys = array_keys( $r[0] );
360 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
362 * @param string $name
363 * @param string $format
366 function tableName( $name, $format = 'quoted' ) {
367 // table names starting with sqlite_ are reserved
368 if ( strpos( $name, 'sqlite_' ) === 0 ) {
372 return str_replace( '"', '', parent
::tableName( $name, $format ) );
376 * Index names have DB scope
378 * @param string $index
381 function indexName( $index ) {
386 * This must be called after nextSequenceVal
390 function insertId() {
391 // PDO::lastInsertId yields a string :(
392 return intval( $this->mConn
->lastInsertId() );
396 * @param ResultWrapper|array $res
399 function dataSeek( $res, $row ) {
400 if ( $res instanceof ResultWrapper
) {
407 for ( $i = 0; $i < $row; $i++
) {
416 function lastError() {
417 if ( !is_object( $this->mConn
) ) {
418 return "Cannot return last error, no db connection";
420 $e = $this->mConn
->errorInfo();
422 return isset( $e[2] ) ?
$e[2] : '';
428 function lastErrno() {
429 if ( !is_object( $this->mConn
) ) {
430 return "Cannot return last error, no db connection";
432 $info = $this->mConn
->errorInfo();
441 function affectedRows() {
442 return $this->mAffectedRows
;
446 * Returns information about an index
447 * Returns false if the index does not exist
448 * - if errors are explicitly ignored, returns NULL on failure
450 * @param string $table
451 * @param string $index
452 * @param string $fname
455 function indexInfo( $table, $index, $fname = __METHOD__
) {
456 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
457 $res = $this->query( $sql, $fname );
461 if ( $res->numRows() == 0 ) {
465 foreach ( $res as $row ) {
466 $info[] = $row->name
;
473 * @param string $table
474 * @param string $index
475 * @param string $fname
478 function indexUnique( $table, $index, $fname = __METHOD__
) {
479 $row = $this->selectRow( 'sqlite_master', '*',
482 'name' => $this->indexName( $index ),
484 if ( !$row ||
!isset( $row->sql
) ) {
488 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
489 $indexPos = strpos( $row->sql
, 'INDEX' );
490 if ( $indexPos === false ) {
493 $firstPart = substr( $row->sql
, 0, $indexPos );
494 $options = explode( ' ', $firstPart );
496 return in_array( 'UNIQUE', $options );
500 * Filter the options used in SELECT statements
502 * @param array $options
505 function makeSelectOptions( $options ) {
506 foreach ( $options as $k => $v ) {
507 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
512 return parent
::makeSelectOptions( $options );
516 * @param array $options
519 protected function makeUpdateOptions( $options ) {
520 $options = self
::fixIgnore( $options );
522 return parent
::makeUpdateOptions( $options );
526 * @param array $options
529 static function fixIgnore( $options ) {
530 # SQLite uses OR IGNORE not just IGNORE
531 foreach ( $options as $k => $v ) {
532 if ( $v == 'IGNORE' ) {
533 $options[$k] = 'OR IGNORE';
541 * @param array $options
544 function makeInsertOptions( $options ) {
545 $options = self
::fixIgnore( $options );
547 return parent
::makeInsertOptions( $options );
551 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
552 * @param string $table
554 * @param string $fname
555 * @param array $options
558 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
559 if ( !count( $a ) ) {
563 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
564 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
566 foreach ( $a as $v ) {
567 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
572 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
579 * @param string $table
580 * @param array $uniqueIndexes Unused
581 * @param string|array $rows
582 * @param string $fname
583 * @return bool|ResultWrapper
585 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
586 if ( !count( $rows ) ) {
590 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
591 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
593 foreach ( $rows as $v ) {
594 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
599 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
606 * Returns the size of a text field, or -1 for "unlimited"
607 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
609 * @param string $table
610 * @param string $field
613 function textFieldSize( $table, $field ) {
620 function unionSupportsOrderAndLimit() {
625 * @param string $sqls
626 * @param bool $all Whether to "UNION ALL" or not
629 function unionQueries( $sqls, $all ) {
630 $glue = $all ?
' UNION ALL ' : ' UNION ';
632 return implode( $glue, $sqls );
638 function wasDeadlock() {
639 return $this->lastErrno() == 5; // SQLITE_BUSY
645 function wasErrorReissuable() {
646 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
652 function wasReadOnlyError() {
653 return $this->lastErrno() == 8; // SQLITE_READONLY;
657 * @return string wikitext of a link to the server software's web site
659 public function getSoftwareLink() {
660 return "[{{int:version-db-sqlite-url}} SQLite]";
664 * @return string Version information from the database
666 function getServerVersion() {
667 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
673 * @return string User-friendly database information
675 public function getServerInfo() {
676 return wfMessage( self
::getFulltextSearchModule()
678 : 'sqlite-no-fts', $this->getServerVersion() )->text();
682 * Get information about a given field
683 * Returns false if the field does not exist.
685 * @param string $table
686 * @param string $field
687 * @return SQLiteField|bool False on failure
689 function fieldInfo( $table, $field ) {
690 $tableName = $this->tableName( $table );
691 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
692 $res = $this->query( $sql, __METHOD__
);
693 foreach ( $res as $row ) {
694 if ( $row->name
== $field ) {
695 return new SQLiteField( $row, $tableName );
702 protected function doBegin( $fname = '' ) {
703 if ( $this->mTrxLevel
== 1 ) {
704 $this->commit( __METHOD__
);
707 $this->mConn
->beginTransaction();
708 } catch ( PDOException
$e ) {
709 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
711 $this->mTrxLevel
= 1;
714 protected function doCommit( $fname = '' ) {
715 if ( $this->mTrxLevel
== 0 ) {
719 $this->mConn
->commit();
720 } catch ( PDOException
$e ) {
721 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
723 $this->mTrxLevel
= 0;
726 protected function doRollback( $fname = '' ) {
727 if ( $this->mTrxLevel
== 0 ) {
730 $this->mConn
->rollBack();
731 $this->mTrxLevel
= 0;
738 function strencode( $s ) {
739 return substr( $this->addQuotes( $s ), 1, -1 );
746 function encodeBlob( $b ) {
747 return new Blob( $b );
751 * @param $b Blob|string
754 function decodeBlob( $b ) {
755 if ( $b instanceof Blob
) {
763 * @param Blob|string $s
766 function addQuotes( $s ) {
767 if ( $s instanceof Blob
) {
768 return "x'" . bin2hex( $s->fetch() ) . "'";
769 } elseif ( is_bool( $s ) ) {
771 } elseif ( strpos( $s, "\0" ) !== false ) {
772 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
773 // This is a known limitation of SQLite's mprintf function which PDO should work around,
774 // but doesn't. I have reported this to php.net as bug #63419:
775 // https://bugs.php.net/bug.php?id=63419
776 // There was already a similar report for SQLite3::escapeString, bug #62361:
777 // https://bugs.php.net/bug.php?id=62361
778 return "x'" . bin2hex( $s ) . "'";
780 return $this->mConn
->quote( $s );
787 function buildLike() {
788 $params = func_get_args();
789 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
790 $params = $params[0];
793 return parent
::buildLike( $params ) . "ESCAPE '\' ";
799 public function getSearchEngine() {
800 return "SearchSqlite";
804 * No-op version of deadlockLoop
808 public function deadlockLoop( /*...*/ ) {
809 $args = func_get_args();
810 $function = array_shift( $args );
812 return call_user_func_array( $function, $args );
819 protected function replaceVars( $s ) {
820 $s = parent
::replaceVars( $s );
821 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
822 // CREATE TABLE hacks to allow schema file sharing with MySQL
824 // binary/varbinary column type -> blob
825 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
826 // no such thing as unsigned
827 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
829 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
830 // floating point types -> REAL
832 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
837 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
838 // TEXT normalization
839 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
840 // BLOB normalization
841 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
843 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
845 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
847 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
848 // binary collation type -> nothing
849 $s = preg_replace( '/\bbinary\b/i', '', $s );
850 // auto_increment -> autoincrement
851 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
852 // No explicit options
853 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
854 // AUTOINCREMENT should immedidately follow PRIMARY KEY
855 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
856 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
857 // No truncated indexes
858 $s = preg_replace( '/\(\d+\)/', '', $s );
860 $s = preg_replace( '/\bfulltext\b/i', '', $s );
861 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
862 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
863 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
870 * Build a concatenation list to feed into a SQL query
872 * @param string[] $stringList
875 function buildConcat( $stringList ) {
876 return '(' . implode( ') || (', $stringList ) . ')';
879 public function buildGroupConcatField(
880 $delim, $table, $field, $conds = '', $join_conds = array()
882 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
884 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
888 * @throws MWException
889 * @param string $oldName
890 * @param string $newName
891 * @param bool $temporary
892 * @param string $fname
893 * @return bool|ResultWrapper
895 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
896 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
897 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
898 $obj = $this->fetchObject( $res );
900 throw new MWException( "Couldn't retrieve structure for table $oldName" );
904 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
905 $this->addIdentifierQuotes( $newName ),
910 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
911 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
913 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
917 return $this->query( $sql, $fname );
921 * List all tables on the database
923 * @param string $prefix Only show tables with this prefix, e.g. mw_
924 * @param string $fname Calling function name
928 function listTables( $prefix = null, $fname = __METHOD__
) {
929 $result = $this->select(
937 foreach ( $result as $table ) {
938 $vars = get_object_vars( $table );
939 $table = array_pop( $vars );
941 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
942 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
943 $endArray[] = $table;
950 } // end DatabaseSqlite class
953 * This class allows simple acccess to a SQLite database independently from main database settings
956 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
957 public function __construct( $fileName, $flags = 0 ) {
958 $this->mFlags
= $flags;
959 $this->tablePrefix( null );
960 $this->openFile( $fileName );
967 class SQLiteField
implements Field
{
968 private $info, $tableName;
970 function __construct( $info, $tableName ) {
972 $this->tableName
= $tableName;
976 return $this->info
->name
;
979 function tableName() {
980 return $this->tableName
;
983 function defaultValue() {
984 if ( is_string( $this->info
->dflt_value
) ) {
986 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
987 return str_replace( "''", "'", $this->info
->dflt_value
);
991 return $this->info
->dflt_value
;
997 function isNullable() {
998 return !$this->info
->notnull
;
1002 return $this->info
->type
;
1004 } // end SQLiteField