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 string Transaction mode */
38 /** @var int The number of rows affected as an integer */
39 protected $mAffectedRows;
42 protected $mLastResult;
47 /** @var FSLockManager (hopefully on the same server as the DB) */
51 * Additional params include:
52 * - trxMode : one of (deferred, immediate, exclusive)
55 function __construct( array $p ) {
56 global $wgSharedDB, $wgSQLiteDataDir;
58 $this->mDBname
= $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 );
69 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
70 if ( $this->trxMode
&& !in_array( $this->trxMode
, array( 'IMMEDIATE', 'EXCLUSIVE' ) ) ) {
71 $this->trxMode
= null;
72 wfWarn( "Invalid SQLite transaction mode provided." );
75 $this->lockMgr
= new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
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 if ( $this->mOpened
) {
148 # Set error codes only, don't raise exceptions
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' );
160 * Does not actually close the connection, just destroys the reference for GC to do its work
163 protected function closeConnection() {
170 * Generates a database file name. Explicitly public for installer.
171 * @param string $dir Directory where database resides
172 * @param string $dbName Database name
175 public static function generateFileName( $dir, $dbName ) {
176 return "$dir/$dbName.sqlite";
180 * Check if the searchindext table is FTS enabled.
181 * @return bool False if not enabled.
183 function checkForEnabledSearch() {
184 if ( self
::$fulltextEnabled === null ) {
185 self
::$fulltextEnabled = false;
186 $table = $this->tableName( 'searchindex' );
187 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
189 $row = $res->fetchRow();
190 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
194 return self
::$fulltextEnabled;
198 * Returns version of currently supported SQLite fulltext search module or false if none present.
201 static function getFulltextSearchModule() {
202 static $cachedResult = null;
203 if ( $cachedResult !== null ) {
204 return $cachedResult;
206 $cachedResult = false;
207 $table = 'dummy_search_test';
209 $db = new DatabaseSqliteStandalone( ':memory:' );
211 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
212 $cachedResult = 'FTS3';
216 return $cachedResult;
220 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
223 * @param string $name Database name to be used in queries like
224 * SELECT foo FROM dbname.table
225 * @param bool|string $file Database file name. If omitted, will be generated
226 * using $name and $wgSQLiteDataDir
227 * @param string $fname Calling function name
228 * @return ResultWrapper
230 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
231 global $wgSQLiteDataDir;
233 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
235 $file = $this->addQuotes( $file );
237 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
241 * @see DatabaseBase::isWriteQuery()
246 function isWriteQuery( $sql ) {
247 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
251 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
254 * @return bool|ResultWrapper
256 protected function doQuery( $sql ) {
257 $res = $this->mConn
->query( $sql );
258 if ( $res === false ) {
261 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
262 $this->mAffectedRows
= $r->rowCount();
263 $res = new ResultWrapper( $this, $r->fetchAll() );
270 * @param ResultWrapper|mixed $res
272 function freeResult( $res ) {
273 if ( $res instanceof ResultWrapper
) {
281 * @param ResultWrapper|array $res
282 * @return stdClass|bool
284 function fetchObject( $res ) {
285 if ( $res instanceof ResultWrapper
) {
291 $cur = current( $r );
292 if ( is_array( $cur ) ) {
295 foreach ( $cur as $k => $v ) {
296 if ( !is_numeric( $k ) ) {
308 * @param ResultWrapper|mixed $res
311 function fetchRow( $res ) {
312 if ( $res instanceof ResultWrapper
) {
317 $cur = current( $r );
318 if ( is_array( $cur ) ) {
328 * The PDO::Statement class implements the array interface so count() will work
330 * @param ResultWrapper|array $res
333 function numRows( $res ) {
334 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
340 * @param ResultWrapper $res
343 function numFields( $res ) {
344 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
345 if ( is_array( $r ) && count( $r ) > 0 ) {
346 // The size of the result array is twice the number of fields. (Bug: 65578)
347 return count( $r[0] ) / 2;
349 // If the result is empty return 0
355 * @param ResultWrapper $res
359 function fieldName( $res, $n ) {
360 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
361 if ( is_array( $r ) ) {
362 $keys = array_keys( $r[0] );
371 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
373 * @param string $name
374 * @param string $format
377 function tableName( $name, $format = 'quoted' ) {
378 // table names starting with sqlite_ are reserved
379 if ( strpos( $name, 'sqlite_' ) === 0 ) {
383 return str_replace( '"', '', parent
::tableName( $name, $format ) );
387 * Index names have DB scope
389 * @param string $index
392 function indexName( $index ) {
397 * This must be called after nextSequenceVal
401 function insertId() {
402 // PDO::lastInsertId yields a string :(
403 return intval( $this->mConn
->lastInsertId() );
407 * @param ResultWrapper|array $res
410 function dataSeek( $res, $row ) {
411 if ( $res instanceof ResultWrapper
) {
418 for ( $i = 0; $i < $row; $i++
) {
427 function lastError() {
428 if ( !is_object( $this->mConn
) ) {
429 return "Cannot return last error, no db connection";
431 $e = $this->mConn
->errorInfo();
433 return isset( $e[2] ) ?
$e[2] : '';
439 function lastErrno() {
440 if ( !is_object( $this->mConn
) ) {
441 return "Cannot return last error, no db connection";
443 $info = $this->mConn
->errorInfo();
452 function affectedRows() {
453 return $this->mAffectedRows
;
457 * Returns information about an index
458 * Returns false if the index does not exist
459 * - if errors are explicitly ignored, returns NULL on failure
461 * @param string $table
462 * @param string $index
463 * @param string $fname
466 function indexInfo( $table, $index, $fname = __METHOD__
) {
467 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
468 $res = $this->query( $sql, $fname );
472 if ( $res->numRows() == 0 ) {
476 foreach ( $res as $row ) {
477 $info[] = $row->name
;
484 * @param string $table
485 * @param string $index
486 * @param string $fname
489 function indexUnique( $table, $index, $fname = __METHOD__
) {
490 $row = $this->selectRow( 'sqlite_master', '*',
493 'name' => $this->indexName( $index ),
495 if ( !$row ||
!isset( $row->sql
) ) {
499 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
500 $indexPos = strpos( $row->sql
, 'INDEX' );
501 if ( $indexPos === false ) {
504 $firstPart = substr( $row->sql
, 0, $indexPos );
505 $options = explode( ' ', $firstPart );
507 return in_array( 'UNIQUE', $options );
511 * Filter the options used in SELECT statements
513 * @param array $options
516 function makeSelectOptions( $options ) {
517 foreach ( $options as $k => $v ) {
518 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
523 return parent
::makeSelectOptions( $options );
527 * @param array $options
530 protected function makeUpdateOptionsArray( $options ) {
531 $options = parent
::makeUpdateOptionsArray( $options );
532 $options = self
::fixIgnore( $options );
538 * @param array $options
541 static function fixIgnore( $options ) {
542 # SQLite uses OR IGNORE not just IGNORE
543 foreach ( $options as $k => $v ) {
544 if ( $v == 'IGNORE' ) {
545 $options[$k] = 'OR IGNORE';
553 * @param array $options
556 function makeInsertOptions( $options ) {
557 $options = self
::fixIgnore( $options );
559 return parent
::makeInsertOptions( $options );
563 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
564 * @param string $table
566 * @param string $fname
567 * @param array $options
570 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
571 if ( !count( $a ) ) {
575 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
576 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
578 foreach ( $a as $v ) {
579 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
584 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
591 * @param string $table
592 * @param array $uniqueIndexes Unused
593 * @param string|array $rows
594 * @param string $fname
595 * @return bool|ResultWrapper
597 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
598 if ( !count( $rows ) ) {
602 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
603 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
605 foreach ( $rows as $v ) {
606 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
611 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
618 * Returns the size of a text field, or -1 for "unlimited"
619 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
621 * @param string $table
622 * @param string $field
625 function textFieldSize( $table, $field ) {
632 function unionSupportsOrderAndLimit() {
637 * @param string $sqls
638 * @param bool $all Whether to "UNION ALL" or not
641 function unionQueries( $sqls, $all ) {
642 $glue = $all ?
' UNION ALL ' : ' UNION ';
644 return implode( $glue, $sqls );
650 function wasDeadlock() {
651 return $this->lastErrno() == 5; // SQLITE_BUSY
657 function wasErrorReissuable() {
658 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
664 function wasReadOnlyError() {
665 return $this->lastErrno() == 8; // SQLITE_READONLY;
669 * @return string Wikitext of a link to the server software's web site
671 public function getSoftwareLink() {
672 return "[{{int:version-db-sqlite-url}} SQLite]";
676 * @return string Version information from the database
678 function getServerVersion() {
679 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
685 * @return string User-friendly database information
687 public function getServerInfo() {
688 return wfMessage( self
::getFulltextSearchModule()
690 : 'sqlite-no-fts', $this->getServerVersion() )->text();
694 * Get information about a given field
695 * Returns false if the field does not exist.
697 * @param string $table
698 * @param string $field
699 * @return SQLiteField|bool False on failure
701 function fieldInfo( $table, $field ) {
702 $tableName = $this->tableName( $table );
703 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
704 $res = $this->query( $sql, __METHOD__
);
705 foreach ( $res as $row ) {
706 if ( $row->name
== $field ) {
707 return new SQLiteField( $row, $tableName );
714 protected function doBegin( $fname = '' ) {
715 if ( $this->trxMode
) {
716 $this->query( "BEGIN {$this->trxMode}", $fname );
718 $this->query( 'BEGIN', $fname );
720 $this->mTrxLevel
= 1;
727 function strencode( $s ) {
728 return substr( $this->addQuotes( $s ), 1, -1 );
735 function encodeBlob( $b ) {
736 return new Blob( $b );
740 * @param Blob|string $b
743 function decodeBlob( $b ) {
744 if ( $b instanceof Blob
) {
752 * @param Blob|string $s
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 // There is an additional bug regarding sorting this data after insert
768 // on older versions of sqlite shipped with ubuntu 12.04
769 // https://bugzilla.wikimedia.org/show_bug.cgi?id=72367
770 wfDebugLog( __CLASS__
, __FUNCTION__
. ': Quoting value containing null byte. For consistency all binary data should have been first processed with self::encodeBlob()' );
771 return "x'" . bin2hex( $s ) . "'";
773 return $this->mConn
->quote( $s );
780 function buildLike() {
781 $params = func_get_args();
782 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
783 $params = $params[0];
786 return parent
::buildLike( $params ) . "ESCAPE '\' ";
792 public function getSearchEngine() {
793 return "SearchSqlite";
797 * No-op version of deadlockLoop
801 public function deadlockLoop( /*...*/ ) {
802 $args = func_get_args();
803 $function = array_shift( $args );
805 return call_user_func_array( $function, $args );
812 protected function replaceVars( $s ) {
813 $s = parent
::replaceVars( $s );
814 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
815 // CREATE TABLE hacks to allow schema file sharing with MySQL
817 // binary/varbinary column type -> blob
818 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
819 // no such thing as unsigned
820 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
822 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
823 // floating point types -> REAL
825 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
830 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
831 // TEXT normalization
832 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
833 // BLOB normalization
834 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
836 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
838 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
840 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
841 // binary collation type -> nothing
842 $s = preg_replace( '/\bbinary\b/i', '', $s );
843 // auto_increment -> autoincrement
844 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
845 // No explicit options
846 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
847 // AUTOINCREMENT should immedidately follow PRIMARY KEY
848 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
849 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
850 // No truncated indexes
851 $s = preg_replace( '/\(\d+\)/', '', $s );
853 $s = preg_replace( '/\bfulltext\b/i', '', $s );
854 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
855 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
856 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
857 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
858 // INSERT IGNORE --> INSERT OR IGNORE
859 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
865 public function lock( $lockName, $method, $timeout = 5 ) {
866 global $wgSQLiteDataDir;
868 if ( !is_dir( "$wgSQLiteDataDir/locks" ) ) { // create dir as needed
869 if ( !is_writable( $wgSQLiteDataDir ) ||
!mkdir( "$wgSQLiteDataDir/locks" ) ) {
870 throw new DBError( "Cannot create directory \"$wgSQLiteDataDir/locks\"." );
874 return $this->lockMgr
->lock( array( $lockName ), LockManager
::LOCK_EX
, $timeout )->isOK();
877 public function unlock( $lockName, $method ) {
878 return $this->lockMgr
->unlock( array( $lockName ), LockManager
::LOCK_EX
)->isOK();
882 * Build a concatenation list to feed into a SQL query
884 * @param string[] $stringList
887 function buildConcat( $stringList ) {
888 return '(' . implode( ') || (', $stringList ) . ')';
891 public function buildGroupConcatField(
892 $delim, $table, $field, $conds = '', $join_conds = array()
894 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
896 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
900 * @throws MWException
901 * @param string $oldName
902 * @param string $newName
903 * @param bool $temporary
904 * @param string $fname
905 * @return bool|ResultWrapper
907 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
908 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
909 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
910 $obj = $this->fetchObject( $res );
912 throw new MWException( "Couldn't retrieve structure for table $oldName" );
916 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
917 $this->addIdentifierQuotes( $newName ),
922 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
923 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
925 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
929 return $this->query( $sql, $fname );
933 * List all tables on the database
935 * @param string $prefix Only show tables with this prefix, e.g. mw_
936 * @param string $fname Calling function name
940 function listTables( $prefix = null, $fname = __METHOD__
) {
941 $result = $this->select(
949 foreach ( $result as $table ) {
950 $vars = get_object_vars( $table );
951 $table = array_pop( $vars );
953 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
954 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
955 $endArray[] = $table;
962 } // end DatabaseSqlite class
965 * This class allows simple acccess to a SQLite database independently from main database settings
968 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
969 public function __construct( $fileName, $flags = 0 ) {
970 global $wgSQLiteDataDir;
972 $this->mTrxAtomicLevels
= new SplStack
;
973 $this->lockMgr
= new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
975 $this->mFlags
= $flags;
976 $this->tablePrefix( null );
977 $this->openFile( $fileName );
984 class SQLiteField
implements Field
{
985 private $info, $tableName;
987 function __construct( $info, $tableName ) {
989 $this->tableName
= $tableName;
993 return $this->info
->name
;
996 function tableName() {
997 return $this->tableName
;
1000 function defaultValue() {
1001 if ( is_string( $this->info
->dflt_value
) ) {
1003 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
1004 return str_replace( "''", "'", $this->info
->dflt_value
);
1008 return $this->info
->dflt_value
;
1014 function isNullable() {
1015 return !$this->info
->notnull
;
1019 return $this->info
->type
;
1021 } // end SQLiteField