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;
43 * @todo Seems to serve no purpose. Remove?
50 function __construct( $p = null ) {
53 if ( !is_array( $p ) ) { // legacy calling pattern
54 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
55 $args = func_get_args();
57 'host' => isset( $args[0] ) ?
$args[0] : false,
58 'user' => isset( $args[1] ) ?
$args[1] : false,
59 'password' => isset( $args[2] ) ?
$args[2] : false,
60 'dbname' => isset( $args[3] ) ?
$args[3] : false,
61 'flags' => isset( $args[4] ) ?
$args[4] : 0,
62 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
63 'foreign' => isset( $args[6] ) ?
$args[6] : false
66 $this->mName
= $p['dbname'];
67 parent
::__construct( $p );
68 // parent doesn't open when $user is false, but we can work with $dbName
69 if ( $p['dbname'] && !$this->isOpen() ) {
70 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
72 $this->attachDatabase( $wgSharedDB );
86 * @todo Check if it should be true like parent class
90 function implicitGroupby() {
94 /** Open an SQLite database and return a resource handle to it
95 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
97 * @param string $server
100 * @param string $dbName
102 * @throws DBConnectionError
105 function open( $server, $user, $pass, $dbName ) {
106 global $wgSQLiteDataDir;
109 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
110 if ( !is_readable( $fileName ) ) {
111 $this->mConn
= false;
112 throw new DBConnectionError( $this, "SQLite database not accessible" );
114 $this->openFile( $fileName );
120 * Opens a database file
122 * @param string $fileName
123 * @throws DBConnectionError
124 * @return PDO|bool SQL connection or false if failed
126 function openFile( $fileName ) {
129 $this->mDatabaseFile
= $fileName;
131 if ( $this->mFlags
& DBO_PERSISTENT
) {
132 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
133 array( PDO
::ATTR_PERSISTENT
=> true ) );
135 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
137 } catch ( PDOException
$e ) {
138 $err = $e->getMessage();
141 if ( !$this->mConn
) {
142 wfDebug( "DB connection error: $err\n" );
143 throw new DBConnectionError( $this, $err );
146 $this->mOpened
= !!$this->mConn
;
147 # set error codes only, don't raise exceptions
148 if ( $this->mOpened
) {
149 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
150 # Enforce LIKE to be case sensitive, just like MySQL
151 $this->query( 'PRAGMA case_sensitive_like = 1' );
158 * Does not actually close the connection, just destroys the reference for GC to do its work
161 protected function closeConnection() {
168 * Generates a database file name. Explicitly public for installer.
169 * @param string $dir Directory where database resides
170 * @param string $dbName Database name
173 public static function generateFileName( $dir, $dbName ) {
174 return "$dir/$dbName.sqlite";
178 * Check if the searchindext table is FTS enabled.
179 * @return bool False if not enabled.
181 function checkForEnabledSearch() {
182 if ( self
::$fulltextEnabled === null ) {
183 self
::$fulltextEnabled = false;
184 $table = $this->tableName( 'searchindex' );
185 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
187 $row = $res->fetchRow();
188 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
192 return self
::$fulltextEnabled;
196 * Returns version of currently supported SQLite fulltext search module or false if none present.
199 static function getFulltextSearchModule() {
200 static $cachedResult = null;
201 if ( $cachedResult !== null ) {
202 return $cachedResult;
204 $cachedResult = false;
205 $table = 'dummy_search_test';
207 $db = new DatabaseSqliteStandalone( ':memory:' );
209 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
210 $cachedResult = 'FTS3';
214 return $cachedResult;
218 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
221 * @param string $name Database name to be used in queries like
222 * SELECT foo FROM dbname.table
223 * @param bool|string $file Database file name. If omitted, will be generated
224 * using $name and $wgSQLiteDataDir
225 * @param string $fname Calling function name
226 * @return ResultWrapper
228 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
229 global $wgSQLiteDataDir;
231 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
233 $file = $this->addQuotes( $file );
235 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
239 * @see DatabaseBase::isWriteQuery()
244 function isWriteQuery( $sql ) {
245 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
249 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
252 * @return bool|ResultWrapper
254 protected function doQuery( $sql ) {
255 $res = $this->mConn
->query( $sql );
256 if ( $res === false ) {
259 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
260 $this->mAffectedRows
= $r->rowCount();
261 $res = new ResultWrapper( $this, $r->fetchAll() );
268 * @param ResultWrapper|mixed $res
270 function freeResult( $res ) {
271 if ( $res instanceof ResultWrapper
) {
279 * @param ResultWrapper|array $res
280 * @return stdClass|bool
282 function fetchObject( $res ) {
283 if ( $res instanceof ResultWrapper
) {
289 $cur = current( $r );
290 if ( is_array( $cur ) ) {
293 foreach ( $cur as $k => $v ) {
294 if ( !is_numeric( $k ) ) {
306 * @param ResultWrapper|mixed $res
309 function fetchRow( $res ) {
310 if ( $res instanceof ResultWrapper
) {
315 $cur = current( $r );
316 if ( is_array( $cur ) ) {
326 * The PDO::Statement class implements the array interface so count() will work
328 * @param ResultWrapper|array $res
331 function numRows( $res ) {
332 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
338 * @param ResultWrapper $res
341 function numFields( $res ) {
342 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
344 return is_array( $r ) ?
count( $r[0] ) : 0;
348 * @param ResultWrapper $res
352 function fieldName( $res, $n ) {
353 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
354 if ( is_array( $r ) ) {
355 $keys = array_keys( $r[0] );
364 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
366 * @param string $name
367 * @param string $format
370 function tableName( $name, $format = 'quoted' ) {
371 // table names starting with sqlite_ are reserved
372 if ( strpos( $name, 'sqlite_' ) === 0 ) {
376 return str_replace( '"', '', parent
::tableName( $name, $format ) );
380 * Index names have DB scope
382 * @param string $index
385 function indexName( $index ) {
390 * This must be called after nextSequenceVal
394 function insertId() {
395 // PDO::lastInsertId yields a string :(
396 return intval( $this->mConn
->lastInsertId() );
400 * @param ResultWrapper|array $res
403 function dataSeek( $res, $row ) {
404 if ( $res instanceof ResultWrapper
) {
411 for ( $i = 0; $i < $row; $i++
) {
420 function lastError() {
421 if ( !is_object( $this->mConn
) ) {
422 return "Cannot return last error, no db connection";
424 $e = $this->mConn
->errorInfo();
426 return isset( $e[2] ) ?
$e[2] : '';
432 function lastErrno() {
433 if ( !is_object( $this->mConn
) ) {
434 return "Cannot return last error, no db connection";
436 $info = $this->mConn
->errorInfo();
445 function affectedRows() {
446 return $this->mAffectedRows
;
450 * Returns information about an index
451 * Returns false if the index does not exist
452 * - if errors are explicitly ignored, returns NULL on failure
454 * @param string $table
455 * @param string $index
456 * @param string $fname
459 function indexInfo( $table, $index, $fname = __METHOD__
) {
460 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
461 $res = $this->query( $sql, $fname );
465 if ( $res->numRows() == 0 ) {
469 foreach ( $res as $row ) {
470 $info[] = $row->name
;
477 * @param string $table
478 * @param string $index
479 * @param string $fname
482 function indexUnique( $table, $index, $fname = __METHOD__
) {
483 $row = $this->selectRow( 'sqlite_master', '*',
486 'name' => $this->indexName( $index ),
488 if ( !$row ||
!isset( $row->sql
) ) {
492 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
493 $indexPos = strpos( $row->sql
, 'INDEX' );
494 if ( $indexPos === false ) {
497 $firstPart = substr( $row->sql
, 0, $indexPos );
498 $options = explode( ' ', $firstPart );
500 return in_array( 'UNIQUE', $options );
504 * Filter the options used in SELECT statements
506 * @param array $options
509 function makeSelectOptions( $options ) {
510 foreach ( $options as $k => $v ) {
511 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
516 return parent
::makeSelectOptions( $options );
520 * @param array $options
523 protected function makeUpdateOptions( $options ) {
524 $options = self
::fixIgnore( $options );
526 return parent
::makeUpdateOptions( $options );
530 * @param array $options
533 static function fixIgnore( $options ) {
534 # SQLite uses OR IGNORE not just IGNORE
535 foreach ( $options as $k => $v ) {
536 if ( $v == 'IGNORE' ) {
537 $options[$k] = 'OR IGNORE';
545 * @param array $options
548 function makeInsertOptions( $options ) {
549 $options = self
::fixIgnore( $options );
551 return parent
::makeInsertOptions( $options );
555 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
556 * @param string $table
558 * @param string $fname
559 * @param array $options
562 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
563 if ( !count( $a ) ) {
567 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
568 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
570 foreach ( $a as $v ) {
571 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
576 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
583 * @param string $table
584 * @param array $uniqueIndexes Unused
585 * @param string|array $rows
586 * @param string $fname
587 * @return bool|ResultWrapper
589 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
590 if ( !count( $rows ) ) {
594 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
595 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
597 foreach ( $rows as $v ) {
598 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
603 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
610 * Returns the size of a text field, or -1 for "unlimited"
611 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
613 * @param string $table
614 * @param string $field
617 function textFieldSize( $table, $field ) {
624 function unionSupportsOrderAndLimit() {
629 * @param string $sqls
630 * @param bool $all Whether to "UNION ALL" or not
633 function unionQueries( $sqls, $all ) {
634 $glue = $all ?
' UNION ALL ' : ' UNION ';
636 return implode( $glue, $sqls );
642 function wasDeadlock() {
643 return $this->lastErrno() == 5; // SQLITE_BUSY
649 function wasErrorReissuable() {
650 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
656 function wasReadOnlyError() {
657 return $this->lastErrno() == 8; // SQLITE_READONLY;
661 * @return string wikitext of a link to the server software's web site
663 public function getSoftwareLink() {
664 return "[http://sqlite.org/ SQLite]";
668 * @return string Version information from the database
670 function getServerVersion() {
671 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
677 * @return string User-friendly database information
679 public function getServerInfo() {
680 return wfMessage( self
::getFulltextSearchModule()
682 : 'sqlite-no-fts', $this->getServerVersion() )->text();
686 * Get information about a given field
687 * Returns false if the field does not exist.
689 * @param string $table
690 * @param string $field
691 * @return SQLiteField|bool False on failure
693 function fieldInfo( $table, $field ) {
694 $tableName = $this->tableName( $table );
695 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
696 $res = $this->query( $sql, __METHOD__
);
697 foreach ( $res as $row ) {
698 if ( $row->name
== $field ) {
699 return new SQLiteField( $row, $tableName );
706 protected function doBegin( $fname = '' ) {
707 if ( $this->mTrxLevel
== 1 ) {
708 $this->commit( __METHOD__
);
711 $this->mConn
->beginTransaction();
712 } catch ( PDOException
$e ) {
713 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
715 $this->mTrxLevel
= 1;
718 protected function doCommit( $fname = '' ) {
719 if ( $this->mTrxLevel
== 0 ) {
723 $this->mConn
->commit();
724 } catch ( PDOException
$e ) {
725 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
727 $this->mTrxLevel
= 0;
730 protected function doRollback( $fname = '' ) {
731 if ( $this->mTrxLevel
== 0 ) {
734 $this->mConn
->rollBack();
735 $this->mTrxLevel
= 0;
742 function strencode( $s ) {
743 return substr( $this->addQuotes( $s ), 1, -1 );
750 function encodeBlob( $b ) {
751 return new Blob( $b );
755 * @param $b Blob|string
758 function decodeBlob( $b ) {
759 if ( $b instanceof Blob
) {
767 * @param Blob|string $s
770 function addQuotes( $s ) {
771 if ( $s instanceof Blob
) {
772 return "x'" . bin2hex( $s->fetch() ) . "'";
773 } elseif ( is_bool( $s ) ) {
775 } elseif ( strpos( $s, "\0" ) !== false ) {
776 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
777 // This is a known limitation of SQLite's mprintf function which PDO should work around,
778 // but doesn't. I have reported this to php.net as bug #63419:
779 // https://bugs.php.net/bug.php?id=63419
780 // There was already a similar report for SQLite3::escapeString, bug #62361:
781 // https://bugs.php.net/bug.php?id=62361
782 return "x'" . bin2hex( $s ) . "'";
784 return $this->mConn
->quote( $s );
791 function buildLike() {
792 $params = func_get_args();
793 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
794 $params = $params[0];
797 return parent
::buildLike( $params ) . "ESCAPE '\' ";
803 public function getSearchEngine() {
804 return "SearchSqlite";
808 * No-op version of deadlockLoop
812 public function deadlockLoop( /*...*/ ) {
813 $args = func_get_args();
814 $function = array_shift( $args );
816 return call_user_func_array( $function, $args );
823 protected function replaceVars( $s ) {
824 $s = parent
::replaceVars( $s );
825 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
826 // CREATE TABLE hacks to allow schema file sharing with MySQL
828 // binary/varbinary column type -> blob
829 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
830 // no such thing as unsigned
831 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
833 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
834 // floating point types -> REAL
836 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
841 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
842 // TEXT normalization
843 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
844 // BLOB normalization
845 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
847 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
849 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
851 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
852 // binary collation type -> nothing
853 $s = preg_replace( '/\bbinary\b/i', '', $s );
854 // auto_increment -> autoincrement
855 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
856 // No explicit options
857 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
858 // AUTOINCREMENT should immedidately follow PRIMARY KEY
859 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
860 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
861 // No truncated indexes
862 $s = preg_replace( '/\(\d+\)/', '', $s );
864 $s = preg_replace( '/\bfulltext\b/i', '', $s );
865 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
866 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
867 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
874 * Build a concatenation list to feed into a SQL query
876 * @param string[] $stringList
879 function buildConcat( $stringList ) {
880 return '(' . implode( ') || (', $stringList ) . ')';
883 public function buildGroupConcatField(
884 $delim, $table, $field, $conds = '', $join_conds = array()
886 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
888 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
892 * @throws MWException
893 * @param string $oldName
894 * @param string $newName
895 * @param bool $temporary
896 * @param string $fname
897 * @return bool|ResultWrapper
899 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
900 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
901 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
902 $obj = $this->fetchObject( $res );
904 throw new MWException( "Couldn't retrieve structure for table $oldName" );
908 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
909 $this->addIdentifierQuotes( $newName ),
914 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
915 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
917 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
921 return $this->query( $sql, $fname );
925 * List all tables on the database
927 * @param string $prefix Only show tables with this prefix, e.g. mw_
928 * @param string $fname Calling function name
932 function listTables( $prefix = null, $fname = __METHOD__
) {
933 $result = $this->select(
941 foreach ( $result as $table ) {
942 $vars = get_object_vars( $table );
943 $table = array_pop( $vars );
945 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
946 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
947 $endArray[] = $table;
954 } // end DatabaseSqlite class
957 * This class allows simple acccess to a SQLite database independently from main database settings
960 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
961 public function __construct( $fileName, $flags = 0 ) {
962 $this->mFlags
= $flags;
963 $this->tablePrefix( null );
964 $this->openFile( $fileName );
971 class SQLiteField
implements Field
{
972 private $info, $tableName;
974 function __construct( $info, $tableName ) {
976 $this->tableName
= $tableName;
980 return $this->info
->name
;
983 function tableName() {
984 return $this->tableName
;
987 function defaultValue() {
988 if ( is_string( $this->info
->dflt_value
) ) {
990 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
991 return str_replace( "''", "'", $this->info
->dflt_value
);
995 return $this->info
->dflt_value
;
1001 function isNullable() {
1002 return !$this->info
->notnull
;
1006 return $this->info
->type
;
1008 } // end SQLiteField