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 Directory */
35 /** @var string File name for SQLite database file */
38 /** @var string Transaction mode */
41 /** @var int The number of rows affected as an integer */
42 protected $mAffectedRows;
45 protected $mLastResult;
50 /** @var FSLockManager (hopefully on the same server as the DB) */
54 * Additional params include:
55 * - dbDirectory : directory containing the DB and the lock file directory
56 * [defaults to $wgSQLiteDataDir]
57 * - dbFilePath : use this to force the path of the DB file
58 * - trxMode : one of (deferred, immediate, exclusive)
61 function __construct( array $p ) {
62 global $wgSharedDB, $wgSQLiteDataDir;
64 $this->dbDir
= isset( $p['dbDirectory'] ) ?
$p['dbDirectory'] : $wgSQLiteDataDir;
66 if ( isset( $p['dbFilePath'] ) ) {
67 $this->mFlags
= isset( $p['flags'] ) ?
$p['flags'] : 0;
68 // Standalone .sqlite file mode
69 $this->openFile( $p['dbFilePath'] );
70 // @FIXME: clean up base constructor so this can call super instead
71 $this->mTrxAtomicLevels
= new SplStack
;
73 $this->mDBname
= $p['dbname'];
74 // Stock wiki mode using standard file names per DB
75 parent
::__construct( $p );
76 // parent doesn't open when $user is false, but we can work with $dbName
77 if ( $p['dbname'] && !$this->isOpen() ) {
78 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
80 $this->attachDatabase( $wgSharedDB );
86 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
87 if ( $this->trxMode
&&
88 !in_array( $this->trxMode
, array( 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ) )
90 $this->trxMode
= null;
91 wfWarn( "Invalid SQLite transaction mode provided." );
94 $this->lockMgr
= new FSLockManager( array( 'lockDirectory' => "{$this->dbDir}/locks" ) );
98 * @param string $filename
99 * @param array $p Options map; supports:
100 * - flags : (same as __construct counterpart)
101 * - trxMode : (same as __construct counterpart)
102 * - dbDirectory : (same as __construct counterpart)
103 * @return DatabaseSqlite
106 public static function newStandaloneInstance( $filename, array $p = array() ) {
107 $p['dbFilePath'] = $filename;
109 return new self( $p );
120 * @todo Check if it should be true like parent class
124 function implicitGroupby() {
128 /** Open an SQLite database and return a resource handle to it
129 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
131 * @param string $server
132 * @param string $user
133 * @param string $pass
134 * @param string $dbName
136 * @throws DBConnectionError
139 function open( $server, $user, $pass, $dbName ) {
141 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
142 if ( !is_readable( $fileName ) ) {
143 $this->mConn
= false;
144 throw new DBConnectionError( $this, "SQLite database not accessible" );
146 $this->openFile( $fileName );
152 * Opens a database file
154 * @param string $fileName
155 * @throws DBConnectionError
156 * @return PDO|bool SQL connection or false if failed
158 protected function openFile( $fileName ) {
161 $this->dbPath
= $fileName;
163 if ( $this->mFlags
& DBO_PERSISTENT
) {
164 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
165 array( PDO
::ATTR_PERSISTENT
=> true ) );
167 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
169 } catch ( PDOException
$e ) {
170 $err = $e->getMessage();
173 if ( !$this->mConn
) {
174 wfDebug( "DB connection error: $err\n" );
175 throw new DBConnectionError( $this, $err );
178 $this->mOpened
= !!$this->mConn
;
179 if ( $this->mOpened
) {
180 # Set error codes only, don't raise exceptions
181 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
182 # Enforce LIKE to be case sensitive, just like MySQL
183 $this->query( 'PRAGMA case_sensitive_like = 1' );
192 * @return string SQLite DB file path
195 public function getDbFilePath() {
196 return $this->dbPath
;
200 * Does not actually close the connection, just destroys the reference for GC to do its work
203 protected function closeConnection() {
210 * Generates a database file name. Explicitly public for installer.
211 * @param string $dir Directory where database resides
212 * @param string $dbName Database name
215 public static function generateFileName( $dir, $dbName ) {
216 return "$dir/$dbName.sqlite";
220 * Check if the searchindext table is FTS enabled.
221 * @return bool False if not enabled.
223 function checkForEnabledSearch() {
224 if ( self
::$fulltextEnabled === null ) {
225 self
::$fulltextEnabled = false;
226 $table = $this->tableName( 'searchindex' );
227 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
229 $row = $res->fetchRow();
230 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
234 return self
::$fulltextEnabled;
238 * Returns version of currently supported SQLite fulltext search module or false if none present.
241 static function getFulltextSearchModule() {
242 static $cachedResult = null;
243 if ( $cachedResult !== null ) {
244 return $cachedResult;
246 $cachedResult = false;
247 $table = 'dummy_search_test';
249 $db = self
::newStandaloneInstance( ':memory:' );
250 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
251 $cachedResult = 'FTS3';
255 return $cachedResult;
259 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
262 * @param string $name Database name to be used in queries like
263 * SELECT foo FROM dbname.table
264 * @param bool|string $file Database file name. If omitted, will be generated
265 * using $name and configured data directory
266 * @param string $fname Calling function name
267 * @return ResultWrapper
269 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
271 $file = self
::generateFileName( $this->dbDir
, $name );
273 $file = $this->addQuotes( $file );
275 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
279 * @see DatabaseBase::isWriteQuery()
284 function isWriteQuery( $sql ) {
285 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
289 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
292 * @return bool|ResultWrapper
294 protected function doQuery( $sql ) {
295 $res = $this->mConn
->query( $sql );
296 if ( $res === false ) {
299 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
300 $this->mAffectedRows
= $r->rowCount();
301 $res = new ResultWrapper( $this, $r->fetchAll() );
308 * @param ResultWrapper|mixed $res
310 function freeResult( $res ) {
311 if ( $res instanceof ResultWrapper
) {
319 * @param ResultWrapper|array $res
320 * @return stdClass|bool
322 function fetchObject( $res ) {
323 if ( $res instanceof ResultWrapper
) {
329 $cur = current( $r );
330 if ( is_array( $cur ) ) {
333 foreach ( $cur as $k => $v ) {
334 if ( !is_numeric( $k ) ) {
346 * @param ResultWrapper|mixed $res
349 function fetchRow( $res ) {
350 if ( $res instanceof ResultWrapper
) {
355 $cur = current( $r );
356 if ( is_array( $cur ) ) {
366 * The PDO::Statement class implements the array interface so count() will work
368 * @param ResultWrapper|array $res
371 function numRows( $res ) {
372 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
378 * @param ResultWrapper $res
381 function numFields( $res ) {
382 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
383 if ( is_array( $r ) && count( $r ) > 0 ) {
384 // The size of the result array is twice the number of fields. (Bug: 65578)
385 return count( $r[0] ) / 2;
387 // If the result is empty return 0
393 * @param ResultWrapper $res
397 function fieldName( $res, $n ) {
398 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
399 if ( is_array( $r ) ) {
400 $keys = array_keys( $r[0] );
409 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
411 * @param string $name
412 * @param string $format
415 function tableName( $name, $format = 'quoted' ) {
416 // table names starting with sqlite_ are reserved
417 if ( strpos( $name, 'sqlite_' ) === 0 ) {
421 return str_replace( '"', '', parent
::tableName( $name, $format ) );
425 * Index names have DB scope
427 * @param string $index
430 function indexName( $index ) {
435 * This must be called after nextSequenceVal
439 function insertId() {
440 // PDO::lastInsertId yields a string :(
441 return intval( $this->mConn
->lastInsertId() );
445 * @param ResultWrapper|array $res
448 function dataSeek( $res, $row ) {
449 if ( $res instanceof ResultWrapper
) {
456 for ( $i = 0; $i < $row; $i++
) {
465 function lastError() {
466 if ( !is_object( $this->mConn
) ) {
467 return "Cannot return last error, no db connection";
469 $e = $this->mConn
->errorInfo();
471 return isset( $e[2] ) ?
$e[2] : '';
477 function lastErrno() {
478 if ( !is_object( $this->mConn
) ) {
479 return "Cannot return last error, no db connection";
481 $info = $this->mConn
->errorInfo();
490 function affectedRows() {
491 return $this->mAffectedRows
;
495 * Returns information about an index
496 * Returns false if the index does not exist
497 * - if errors are explicitly ignored, returns NULL on failure
499 * @param string $table
500 * @param string $index
501 * @param string $fname
504 function indexInfo( $table, $index, $fname = __METHOD__
) {
505 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
506 $res = $this->query( $sql, $fname );
510 if ( $res->numRows() == 0 ) {
514 foreach ( $res as $row ) {
515 $info[] = $row->name
;
522 * @param string $table
523 * @param string $index
524 * @param string $fname
527 function indexUnique( $table, $index, $fname = __METHOD__
) {
528 $row = $this->selectRow( 'sqlite_master', '*',
531 'name' => $this->indexName( $index ),
533 if ( !$row ||
!isset( $row->sql
) ) {
537 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
538 $indexPos = strpos( $row->sql
, 'INDEX' );
539 if ( $indexPos === false ) {
542 $firstPart = substr( $row->sql
, 0, $indexPos );
543 $options = explode( ' ', $firstPart );
545 return in_array( 'UNIQUE', $options );
549 * Filter the options used in SELECT statements
551 * @param array $options
554 function makeSelectOptions( $options ) {
555 foreach ( $options as $k => $v ) {
556 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
561 return parent
::makeSelectOptions( $options );
565 * @param array $options
568 protected function makeUpdateOptionsArray( $options ) {
569 $options = parent
::makeUpdateOptionsArray( $options );
570 $options = self
::fixIgnore( $options );
576 * @param array $options
579 static function fixIgnore( $options ) {
580 # SQLite uses OR IGNORE not just IGNORE
581 foreach ( $options as $k => $v ) {
582 if ( $v == 'IGNORE' ) {
583 $options[$k] = 'OR IGNORE';
591 * @param array $options
594 function makeInsertOptions( $options ) {
595 $options = self
::fixIgnore( $options );
597 return parent
::makeInsertOptions( $options );
601 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
602 * @param string $table
604 * @param string $fname
605 * @param array $options
608 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
609 if ( !count( $a ) ) {
613 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
614 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
616 foreach ( $a as $v ) {
617 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
622 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
629 * @param string $table
630 * @param array $uniqueIndexes Unused
631 * @param string|array $rows
632 * @param string $fname
633 * @return bool|ResultWrapper
635 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
636 if ( !count( $rows ) ) {
640 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
641 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
643 foreach ( $rows as $v ) {
644 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
649 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
656 * Returns the size of a text field, or -1 for "unlimited"
657 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
659 * @param string $table
660 * @param string $field
663 function textFieldSize( $table, $field ) {
670 function unionSupportsOrderAndLimit() {
675 * @param string $sqls
676 * @param bool $all Whether to "UNION ALL" or not
679 function unionQueries( $sqls, $all ) {
680 $glue = $all ?
' UNION ALL ' : ' UNION ';
682 return implode( $glue, $sqls );
688 function wasDeadlock() {
689 return $this->lastErrno() == 5; // SQLITE_BUSY
695 function wasErrorReissuable() {
696 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
702 function wasReadOnlyError() {
703 return $this->lastErrno() == 8; // SQLITE_READONLY;
707 * @return string Wikitext of a link to the server software's web site
709 public function getSoftwareLink() {
710 return "[{{int:version-db-sqlite-url}} SQLite]";
714 * @return string Version information from the database
716 function getServerVersion() {
717 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
723 * @return string User-friendly database information
725 public function getServerInfo() {
726 return wfMessage( self
::getFulltextSearchModule()
728 : 'sqlite-no-fts', $this->getServerVersion() )->text();
732 * Get information about a given field
733 * Returns false if the field does not exist.
735 * @param string $table
736 * @param string $field
737 * @return SQLiteField|bool False on failure
739 function fieldInfo( $table, $field ) {
740 $tableName = $this->tableName( $table );
741 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
742 $res = $this->query( $sql, __METHOD__
);
743 foreach ( $res as $row ) {
744 if ( $row->name
== $field ) {
745 return new SQLiteField( $row, $tableName );
752 protected function doBegin( $fname = '' ) {
753 if ( $this->trxMode
) {
754 $this->query( "BEGIN {$this->trxMode}", $fname );
756 $this->query( 'BEGIN', $fname );
758 $this->mTrxLevel
= 1;
765 function strencode( $s ) {
766 return substr( $this->addQuotes( $s ), 1, -1 );
773 function encodeBlob( $b ) {
774 return new Blob( $b );
778 * @param Blob|string $b
781 function decodeBlob( $b ) {
782 if ( $b instanceof Blob
) {
790 * @param Blob|string $s
793 function addQuotes( $s ) {
794 if ( $s instanceof Blob
) {
795 return "x'" . bin2hex( $s->fetch() ) . "'";
796 } elseif ( is_bool( $s ) ) {
798 } elseif ( strpos( $s, "\0" ) !== false ) {
799 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
800 // This is a known limitation of SQLite's mprintf function which PDO should work around,
801 // but doesn't. I have reported this to php.net as bug #63419:
802 // https://bugs.php.net/bug.php?id=63419
803 // There was already a similar report for SQLite3::escapeString, bug #62361:
804 // https://bugs.php.net/bug.php?id=62361
805 // There is an additional bug regarding sorting this data after insert
806 // on older versions of sqlite shipped with ubuntu 12.04
807 // https://bugzilla.wikimedia.org/show_bug.cgi?id=72367
808 wfDebugLog( __CLASS__
, __FUNCTION__
. ': Quoting value containing null byte. For consistency all binary data should have been first processed with self::encodeBlob()' );
809 return "x'" . bin2hex( $s ) . "'";
811 return $this->mConn
->quote( $s );
818 function buildLike() {
819 $params = func_get_args();
820 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
821 $params = $params[0];
824 return parent
::buildLike( $params ) . "ESCAPE '\' ";
830 public function getSearchEngine() {
831 return "SearchSqlite";
835 * No-op version of deadlockLoop
839 public function deadlockLoop( /*...*/ ) {
840 $args = func_get_args();
841 $function = array_shift( $args );
843 return call_user_func_array( $function, $args );
850 protected function replaceVars( $s ) {
851 $s = parent
::replaceVars( $s );
852 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
853 // CREATE TABLE hacks to allow schema file sharing with MySQL
855 // binary/varbinary column type -> blob
856 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
857 // no such thing as unsigned
858 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
860 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
861 // floating point types -> REAL
863 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
868 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
869 // TEXT normalization
870 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
871 // BLOB normalization
872 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
874 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
876 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
878 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
879 // binary collation type -> nothing
880 $s = preg_replace( '/\bbinary\b/i', '', $s );
881 // auto_increment -> autoincrement
882 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
883 // No explicit options
884 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
885 // AUTOINCREMENT should immedidately follow PRIMARY KEY
886 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
887 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
888 // No truncated indexes
889 $s = preg_replace( '/\(\d+\)/', '', $s );
891 $s = preg_replace( '/\bfulltext\b/i', '', $s );
892 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
893 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
894 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
895 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
896 // INSERT IGNORE --> INSERT OR IGNORE
897 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
903 public function lock( $lockName, $method, $timeout = 5 ) {
904 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
905 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
906 throw new DBError( "Cannot create directory \"{$this->dbDir}/locks\"." );
910 return $this->lockMgr
->lock( array( $lockName ), LockManager
::LOCK_EX
, $timeout )->isOK();
913 public function unlock( $lockName, $method ) {
914 return $this->lockMgr
->unlock( array( $lockName ), LockManager
::LOCK_EX
)->isOK();
918 * Build a concatenation list to feed into a SQL query
920 * @param string[] $stringList
923 function buildConcat( $stringList ) {
924 return '(' . implode( ') || (', $stringList ) . ')';
927 public function buildGroupConcatField(
928 $delim, $table, $field, $conds = '', $join_conds = array()
930 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
932 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
936 * @throws MWException
937 * @param string $oldName
938 * @param string $newName
939 * @param bool $temporary
940 * @param string $fname
941 * @return bool|ResultWrapper
943 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
944 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
945 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
946 $obj = $this->fetchObject( $res );
948 throw new MWException( "Couldn't retrieve structure for table $oldName" );
952 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
953 $this->addIdentifierQuotes( $newName ),
958 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
959 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
961 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
965 return $this->query( $sql, $fname );
969 * List all tables on the database
971 * @param string $prefix Only show tables with this prefix, e.g. mw_
972 * @param string $fname Calling function name
976 function listTables( $prefix = null, $fname = __METHOD__
) {
977 $result = $this->select(
985 foreach ( $result as $table ) {
986 $vars = get_object_vars( $table );
987 $table = array_pop( $vars );
989 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
990 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
991 $endArray[] = $table;
998 } // end DatabaseSqlite class
1003 class SQLiteField
implements Field
{
1004 private $info, $tableName;
1006 function __construct( $info, $tableName ) {
1007 $this->info
= $info;
1008 $this->tableName
= $tableName;
1012 return $this->info
->name
;
1015 function tableName() {
1016 return $this->tableName
;
1019 function defaultValue() {
1020 if ( is_string( $this->info
->dflt_value
) ) {
1022 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
1023 return str_replace( "''", "'", $this->info
->dflt_value
);
1027 return $this->info
->dflt_value
;
1033 function isNullable() {
1034 return !$this->info
->notnull
;
1038 return $this->info
->type
;
1040 } // end SQLiteField