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 /** @var FSLockManager (hopefully on the same server as the DB) */
47 function __construct( $p = null ) {
48 global $wgSharedDB, $wgSQLiteDataDir;
50 if ( !is_array( $p ) ) { // legacy calling pattern
51 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
52 $args = func_get_args();
54 'host' => isset( $args[0] ) ?
$args[0] : false,
55 'user' => isset( $args[1] ) ?
$args[1] : false,
56 'password' => isset( $args[2] ) ?
$args[2] : false,
57 'dbname' => isset( $args[3] ) ?
$args[3] : false,
58 'flags' => isset( $args[4] ) ?
$args[4] : 0,
59 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
60 'schema' => 'get from global',
61 'foreign' => isset( $args[6] ) ?
$args[6] : false
64 $this->mDBname
= $p['dbname'];
65 parent
::__construct( $p );
66 // parent doesn't open when $user is false, but we can work with $dbName
67 if ( $p['dbname'] && !$this->isOpen() ) {
68 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
70 $this->attachDatabase( $wgSharedDB );
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 # 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' );
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;
346 return is_array( $r ) ?
count( $r[0] ) : 0;
350 * @param ResultWrapper $res
354 function fieldName( $res, $n ) {
355 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
356 if ( is_array( $r ) ) {
357 $keys = array_keys( $r[0] );
366 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
368 * @param string $name
369 * @param string $format
372 function tableName( $name, $format = 'quoted' ) {
373 // table names starting with sqlite_ are reserved
374 if ( strpos( $name, 'sqlite_' ) === 0 ) {
378 return str_replace( '"', '', parent
::tableName( $name, $format ) );
382 * Index names have DB scope
384 * @param string $index
387 function indexName( $index ) {
392 * This must be called after nextSequenceVal
396 function insertId() {
397 // PDO::lastInsertId yields a string :(
398 return intval( $this->mConn
->lastInsertId() );
402 * @param ResultWrapper|array $res
405 function dataSeek( $res, $row ) {
406 if ( $res instanceof ResultWrapper
) {
413 for ( $i = 0; $i < $row; $i++
) {
422 function lastError() {
423 if ( !is_object( $this->mConn
) ) {
424 return "Cannot return last error, no db connection";
426 $e = $this->mConn
->errorInfo();
428 return isset( $e[2] ) ?
$e[2] : '';
434 function lastErrno() {
435 if ( !is_object( $this->mConn
) ) {
436 return "Cannot return last error, no db connection";
438 $info = $this->mConn
->errorInfo();
447 function affectedRows() {
448 return $this->mAffectedRows
;
452 * Returns information about an index
453 * Returns false if the index does not exist
454 * - if errors are explicitly ignored, returns NULL on failure
456 * @param string $table
457 * @param string $index
458 * @param string $fname
461 function indexInfo( $table, $index, $fname = __METHOD__
) {
462 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
463 $res = $this->query( $sql, $fname );
467 if ( $res->numRows() == 0 ) {
471 foreach ( $res as $row ) {
472 $info[] = $row->name
;
479 * @param string $table
480 * @param string $index
481 * @param string $fname
484 function indexUnique( $table, $index, $fname = __METHOD__
) {
485 $row = $this->selectRow( 'sqlite_master', '*',
488 'name' => $this->indexName( $index ),
490 if ( !$row ||
!isset( $row->sql
) ) {
494 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
495 $indexPos = strpos( $row->sql
, 'INDEX' );
496 if ( $indexPos === false ) {
499 $firstPart = substr( $row->sql
, 0, $indexPos );
500 $options = explode( ' ', $firstPart );
502 return in_array( 'UNIQUE', $options );
506 * Filter the options used in SELECT statements
508 * @param array $options
511 function makeSelectOptions( $options ) {
512 foreach ( $options as $k => $v ) {
513 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
518 return parent
::makeSelectOptions( $options );
522 * @param array $options
525 protected function makeUpdateOptions( $options ) {
526 $options = self
::fixIgnore( $options );
528 return parent
::makeUpdateOptions( $options );
532 * @param array $options
535 static function fixIgnore( $options ) {
536 # SQLite uses OR IGNORE not just IGNORE
537 foreach ( $options as $k => $v ) {
538 if ( $v == 'IGNORE' ) {
539 $options[$k] = 'OR IGNORE';
547 * @param array $options
550 function makeInsertOptions( $options ) {
551 $options = self
::fixIgnore( $options );
553 return parent
::makeInsertOptions( $options );
557 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
558 * @param string $table
560 * @param string $fname
561 * @param array $options
564 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
565 if ( !count( $a ) ) {
569 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
570 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
572 foreach ( $a as $v ) {
573 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
578 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
585 * @param string $table
586 * @param array $uniqueIndexes Unused
587 * @param string|array $rows
588 * @param string $fname
589 * @return bool|ResultWrapper
591 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
592 if ( !count( $rows ) ) {
596 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
597 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
599 foreach ( $rows as $v ) {
600 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
605 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
612 * Returns the size of a text field, or -1 for "unlimited"
613 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
615 * @param string $table
616 * @param string $field
619 function textFieldSize( $table, $field ) {
626 function unionSupportsOrderAndLimit() {
631 * @param string $sqls
632 * @param bool $all Whether to "UNION ALL" or not
635 function unionQueries( $sqls, $all ) {
636 $glue = $all ?
' UNION ALL ' : ' UNION ';
638 return implode( $glue, $sqls );
644 function wasDeadlock() {
645 return $this->lastErrno() == 5; // SQLITE_BUSY
651 function wasErrorReissuable() {
652 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
658 function wasReadOnlyError() {
659 return $this->lastErrno() == 8; // SQLITE_READONLY;
663 * @return string wikitext of a link to the server software's web site
665 public function getSoftwareLink() {
666 return "[{{int:version-db-sqlite-url}} SQLite]";
670 * @return string Version information from the database
672 function getServerVersion() {
673 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
679 * @return string User-friendly database information
681 public function getServerInfo() {
682 return wfMessage( self
::getFulltextSearchModule()
684 : 'sqlite-no-fts', $this->getServerVersion() )->text();
688 * Get information about a given field
689 * Returns false if the field does not exist.
691 * @param string $table
692 * @param string $field
693 * @return SQLiteField|bool False on failure
695 function fieldInfo( $table, $field ) {
696 $tableName = $this->tableName( $table );
697 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
698 $res = $this->query( $sql, __METHOD__
);
699 foreach ( $res as $row ) {
700 if ( $row->name
== $field ) {
701 return new SQLiteField( $row, $tableName );
708 protected function doBegin( $fname = '' ) {
709 if ( $this->mTrxLevel
== 1 ) {
710 $this->commit( __METHOD__
);
713 $this->mConn
->beginTransaction();
714 } catch ( PDOException
$e ) {
715 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
717 $this->mTrxLevel
= 1;
720 protected function doCommit( $fname = '' ) {
721 if ( $this->mTrxLevel
== 0 ) {
725 $this->mConn
->commit();
726 } catch ( PDOException
$e ) {
727 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
729 $this->mTrxLevel
= 0;
732 protected function doRollback( $fname = '' ) {
733 if ( $this->mTrxLevel
== 0 ) {
736 $this->mConn
->rollBack();
737 $this->mTrxLevel
= 0;
744 function strencode( $s ) {
745 return substr( $this->addQuotes( $s ), 1, -1 );
752 function encodeBlob( $b ) {
753 return new Blob( $b );
757 * @param $b Blob|string
760 function decodeBlob( $b ) {
761 if ( $b instanceof Blob
) {
769 * @param Blob|string $s
772 function addQuotes( $s ) {
773 if ( $s instanceof Blob
) {
774 return "x'" . bin2hex( $s->fetch() ) . "'";
775 } elseif ( is_bool( $s ) ) {
777 } elseif ( strpos( $s, "\0" ) !== false ) {
778 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
779 // This is a known limitation of SQLite's mprintf function which PDO should work around,
780 // but doesn't. I have reported this to php.net as bug #63419:
781 // https://bugs.php.net/bug.php?id=63419
782 // There was already a similar report for SQLite3::escapeString, bug #62361:
783 // https://bugs.php.net/bug.php?id=62361
784 return "x'" . bin2hex( $s ) . "'";
786 return $this->mConn
->quote( $s );
793 function buildLike() {
794 $params = func_get_args();
795 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
796 $params = $params[0];
799 return parent
::buildLike( $params ) . "ESCAPE '\' ";
805 public function getSearchEngine() {
806 return "SearchSqlite";
810 * No-op version of deadlockLoop
814 public function deadlockLoop( /*...*/ ) {
815 $args = func_get_args();
816 $function = array_shift( $args );
818 return call_user_func_array( $function, $args );
825 protected function replaceVars( $s ) {
826 $s = parent
::replaceVars( $s );
827 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
828 // CREATE TABLE hacks to allow schema file sharing with MySQL
830 // binary/varbinary column type -> blob
831 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
832 // no such thing as unsigned
833 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
835 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
836 // floating point types -> REAL
838 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
843 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
844 // TEXT normalization
845 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
846 // BLOB normalization
847 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
849 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
851 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
853 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
854 // binary collation type -> nothing
855 $s = preg_replace( '/\bbinary\b/i', '', $s );
856 // auto_increment -> autoincrement
857 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
858 // No explicit options
859 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
860 // AUTOINCREMENT should immedidately follow PRIMARY KEY
861 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
862 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
863 // No truncated indexes
864 $s = preg_replace( '/\(\d+\)/', '', $s );
866 $s = preg_replace( '/\bfulltext\b/i', '', $s );
867 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
868 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
869 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
875 public function lock( $lockName, $method, $timeout = 5 ) {
876 global $wgSQLiteDataDir;
878 if ( !is_dir( "$wgSQLiteDataDir/locks" ) ) { // create dir as needed
879 if ( !is_writable( $wgSQLiteDataDir ) ||
!mkdir( "$wgSQLiteDataDir/locks" ) ) {
880 throw new DBError( "Cannot create directory \"$wgSQLiteDataDir/locks\"." );
884 return $this->lockMgr
->lock( array( $lockName ), LockManager
::LOCK_EX
, $timeout )->isOK();
887 public function unlock( $lockName, $method ) {
888 return $this->lockMgr
->unlock( array( $lockName ), LockManager
::LOCK_EX
)->isOK();
892 * Build a concatenation list to feed into a SQL query
894 * @param string[] $stringList
897 function buildConcat( $stringList ) {
898 return '(' . implode( ') || (', $stringList ) . ')';
901 public function buildGroupConcatField(
902 $delim, $table, $field, $conds = '', $join_conds = array()
904 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
906 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
910 * @throws MWException
911 * @param string $oldName
912 * @param string $newName
913 * @param bool $temporary
914 * @param string $fname
915 * @return bool|ResultWrapper
917 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
918 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
919 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
920 $obj = $this->fetchObject( $res );
922 throw new MWException( "Couldn't retrieve structure for table $oldName" );
926 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
927 $this->addIdentifierQuotes( $newName ),
932 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
933 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
935 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
939 return $this->query( $sql, $fname );
943 * List all tables on the database
945 * @param string $prefix Only show tables with this prefix, e.g. mw_
946 * @param string $fname Calling function name
950 function listTables( $prefix = null, $fname = __METHOD__
) {
951 $result = $this->select(
959 foreach ( $result as $table ) {
960 $vars = get_object_vars( $table );
961 $table = array_pop( $vars );
963 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
964 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
965 $endArray[] = $table;
972 } // end DatabaseSqlite class
975 * This class allows simple acccess to a SQLite database independently from main database settings
978 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
979 public function __construct( $fileName, $flags = 0 ) {
980 $this->mFlags
= $flags;
981 $this->tablePrefix( null );
982 $this->openFile( $fileName );
989 class SQLiteField
implements Field
{
990 private $info, $tableName;
992 function __construct( $info, $tableName ) {
994 $this->tableName
= $tableName;
998 return $this->info
->name
;
1001 function tableName() {
1002 return $this->tableName
;
1005 function defaultValue() {
1006 if ( is_string( $this->info
->dflt_value
) ) {
1008 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
1009 return str_replace( "''", "'", $this->info
->dflt_value
);
1013 return $this->info
->dflt_value
;
1019 function isNullable() {
1020 return !$this->info
->notnull
;
1024 return $this->info
->type
;
1026 } // end SQLiteField