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( array $p ) {
48 global $wgSharedDB, $wgSQLiteDataDir;
50 $this->mDBname
= $p['dbname'];
51 parent
::__construct( $p );
52 // parent doesn't open when $user is false, but we can work with $dbName
53 if ( $p['dbname'] && !$this->isOpen() ) {
54 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
56 $this->attachDatabase( $wgSharedDB );
61 $this->lockMgr
= new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
72 * @todo Check if it should be true like parent class
76 function implicitGroupby() {
80 /** Open an SQLite database and return a resource handle to it
81 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
83 * @param string $server
86 * @param string $dbName
88 * @throws DBConnectionError
91 function open( $server, $user, $pass, $dbName ) {
92 global $wgSQLiteDataDir;
95 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
96 if ( !is_readable( $fileName ) ) {
98 throw new DBConnectionError( $this, "SQLite database not accessible" );
100 $this->openFile( $fileName );
106 * Opens a database file
108 * @param string $fileName
109 * @throws DBConnectionError
110 * @return PDO|bool SQL connection or false if failed
112 function openFile( $fileName ) {
115 $this->mDatabaseFile
= $fileName;
117 if ( $this->mFlags
& DBO_PERSISTENT
) {
118 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
119 array( PDO
::ATTR_PERSISTENT
=> true ) );
121 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
123 } catch ( PDOException
$e ) {
124 $err = $e->getMessage();
127 if ( !$this->mConn
) {
128 wfDebug( "DB connection error: $err\n" );
129 throw new DBConnectionError( $this, $err );
132 $this->mOpened
= !!$this->mConn
;
133 if ( $this->mOpened
) {
134 # Set error codes only, don't raise exceptions
135 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
136 # Enforce LIKE to be case sensitive, just like MySQL
137 $this->query( 'PRAGMA case_sensitive_like = 1' );
146 * Does not actually close the connection, just destroys the reference for GC to do its work
149 protected function closeConnection() {
156 * Generates a database file name. Explicitly public for installer.
157 * @param string $dir Directory where database resides
158 * @param string $dbName Database name
161 public static function generateFileName( $dir, $dbName ) {
162 return "$dir/$dbName.sqlite";
166 * Check if the searchindext table is FTS enabled.
167 * @return bool False if not enabled.
169 function checkForEnabledSearch() {
170 if ( self
::$fulltextEnabled === null ) {
171 self
::$fulltextEnabled = false;
172 $table = $this->tableName( 'searchindex' );
173 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
175 $row = $res->fetchRow();
176 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
180 return self
::$fulltextEnabled;
184 * Returns version of currently supported SQLite fulltext search module or false if none present.
187 static function getFulltextSearchModule() {
188 static $cachedResult = null;
189 if ( $cachedResult !== null ) {
190 return $cachedResult;
192 $cachedResult = false;
193 $table = 'dummy_search_test';
195 $db = new DatabaseSqliteStandalone( ':memory:' );
197 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
198 $cachedResult = 'FTS3';
202 return $cachedResult;
206 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
209 * @param string $name Database name to be used in queries like
210 * SELECT foo FROM dbname.table
211 * @param bool|string $file Database file name. If omitted, will be generated
212 * using $name and $wgSQLiteDataDir
213 * @param string $fname Calling function name
214 * @return ResultWrapper
216 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
217 global $wgSQLiteDataDir;
219 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
221 $file = $this->addQuotes( $file );
223 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
227 * @see DatabaseBase::isWriteQuery()
232 function isWriteQuery( $sql ) {
233 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
237 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
240 * @return bool|ResultWrapper
242 protected function doQuery( $sql ) {
243 $res = $this->mConn
->query( $sql );
244 if ( $res === false ) {
247 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
248 $this->mAffectedRows
= $r->rowCount();
249 $res = new ResultWrapper( $this, $r->fetchAll() );
256 * @param ResultWrapper|mixed $res
258 function freeResult( $res ) {
259 if ( $res instanceof ResultWrapper
) {
267 * @param ResultWrapper|array $res
268 * @return stdClass|bool
270 function fetchObject( $res ) {
271 if ( $res instanceof ResultWrapper
) {
277 $cur = current( $r );
278 if ( is_array( $cur ) ) {
281 foreach ( $cur as $k => $v ) {
282 if ( !is_numeric( $k ) ) {
294 * @param ResultWrapper|mixed $res
297 function fetchRow( $res ) {
298 if ( $res instanceof ResultWrapper
) {
303 $cur = current( $r );
304 if ( is_array( $cur ) ) {
314 * The PDO::Statement class implements the array interface so count() will work
316 * @param ResultWrapper|array $res
319 function numRows( $res ) {
320 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
326 * @param ResultWrapper $res
329 function numFields( $res ) {
330 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
331 if ( is_array( $r ) && count( $r ) > 0 ) {
332 // The size of the result array is twice the number of fields. (Bug: 65578)
333 return count( $r[0] ) / 2;
335 // If the result is empty return 0
341 * @param ResultWrapper $res
345 function fieldName( $res, $n ) {
346 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
347 if ( is_array( $r ) ) {
348 $keys = array_keys( $r[0] );
357 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
359 * @param string $name
360 * @param string $format
363 function tableName( $name, $format = 'quoted' ) {
364 // table names starting with sqlite_ are reserved
365 if ( strpos( $name, 'sqlite_' ) === 0 ) {
369 return str_replace( '"', '', parent
::tableName( $name, $format ) );
373 * Index names have DB scope
375 * @param string $index
378 function indexName( $index ) {
383 * This must be called after nextSequenceVal
387 function insertId() {
388 // PDO::lastInsertId yields a string :(
389 return intval( $this->mConn
->lastInsertId() );
393 * @param ResultWrapper|array $res
396 function dataSeek( $res, $row ) {
397 if ( $res instanceof ResultWrapper
) {
404 for ( $i = 0; $i < $row; $i++
) {
413 function lastError() {
414 if ( !is_object( $this->mConn
) ) {
415 return "Cannot return last error, no db connection";
417 $e = $this->mConn
->errorInfo();
419 return isset( $e[2] ) ?
$e[2] : '';
425 function lastErrno() {
426 if ( !is_object( $this->mConn
) ) {
427 return "Cannot return last error, no db connection";
429 $info = $this->mConn
->errorInfo();
438 function affectedRows() {
439 return $this->mAffectedRows
;
443 * Returns information about an index
444 * Returns false if the index does not exist
445 * - if errors are explicitly ignored, returns NULL on failure
447 * @param string $table
448 * @param string $index
449 * @param string $fname
452 function indexInfo( $table, $index, $fname = __METHOD__
) {
453 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
454 $res = $this->query( $sql, $fname );
458 if ( $res->numRows() == 0 ) {
462 foreach ( $res as $row ) {
463 $info[] = $row->name
;
470 * @param string $table
471 * @param string $index
472 * @param string $fname
475 function indexUnique( $table, $index, $fname = __METHOD__
) {
476 $row = $this->selectRow( 'sqlite_master', '*',
479 'name' => $this->indexName( $index ),
481 if ( !$row ||
!isset( $row->sql
) ) {
485 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
486 $indexPos = strpos( $row->sql
, 'INDEX' );
487 if ( $indexPos === false ) {
490 $firstPart = substr( $row->sql
, 0, $indexPos );
491 $options = explode( ' ', $firstPart );
493 return in_array( 'UNIQUE', $options );
497 * Filter the options used in SELECT statements
499 * @param array $options
502 function makeSelectOptions( $options ) {
503 foreach ( $options as $k => $v ) {
504 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
509 return parent
::makeSelectOptions( $options );
513 * @param array $options
516 protected function makeUpdateOptionsArray( $options ) {
517 $options = parent
::makeUpdateOptionsArray( $options );
518 $options = self
::fixIgnore( $options );
524 * @param array $options
527 static function fixIgnore( $options ) {
528 # SQLite uses OR IGNORE not just IGNORE
529 foreach ( $options as $k => $v ) {
530 if ( $v == 'IGNORE' ) {
531 $options[$k] = 'OR IGNORE';
539 * @param array $options
542 function makeInsertOptions( $options ) {
543 $options = self
::fixIgnore( $options );
545 return parent
::makeInsertOptions( $options );
549 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
550 * @param string $table
552 * @param string $fname
553 * @param array $options
556 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
557 if ( !count( $a ) ) {
561 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
562 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
564 foreach ( $a as $v ) {
565 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
570 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
577 * @param string $table
578 * @param array $uniqueIndexes Unused
579 * @param string|array $rows
580 * @param string $fname
581 * @return bool|ResultWrapper
583 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
584 if ( !count( $rows ) ) {
588 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
589 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
591 foreach ( $rows as $v ) {
592 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
597 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
604 * Returns the size of a text field, or -1 for "unlimited"
605 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
607 * @param string $table
608 * @param string $field
611 function textFieldSize( $table, $field ) {
618 function unionSupportsOrderAndLimit() {
623 * @param string $sqls
624 * @param bool $all Whether to "UNION ALL" or not
627 function unionQueries( $sqls, $all ) {
628 $glue = $all ?
' UNION ALL ' : ' UNION ';
630 return implode( $glue, $sqls );
636 function wasDeadlock() {
637 return $this->lastErrno() == 5; // SQLITE_BUSY
643 function wasErrorReissuable() {
644 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
650 function wasReadOnlyError() {
651 return $this->lastErrno() == 8; // SQLITE_READONLY;
655 * @return string Wikitext of a link to the server software's web site
657 public function getSoftwareLink() {
658 return "[{{int:version-db-sqlite-url}} SQLite]";
662 * @return string Version information from the database
664 function getServerVersion() {
665 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
671 * @return string User-friendly database information
673 public function getServerInfo() {
674 return wfMessage( self
::getFulltextSearchModule()
676 : 'sqlite-no-fts', $this->getServerVersion() )->text();
680 * Get information about a given field
681 * Returns false if the field does not exist.
683 * @param string $table
684 * @param string $field
685 * @return SQLiteField|bool False on failure
687 function fieldInfo( $table, $field ) {
688 $tableName = $this->tableName( $table );
689 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
690 $res = $this->query( $sql, __METHOD__
);
691 foreach ( $res as $row ) {
692 if ( $row->name
== $field ) {
693 return new SQLiteField( $row, $tableName );
704 function strencode( $s ) {
705 return substr( $this->addQuotes( $s ), 1, -1 );
712 function encodeBlob( $b ) {
713 return new Blob( $b );
717 * @param Blob|string $b
720 function decodeBlob( $b ) {
721 if ( $b instanceof Blob
) {
729 * @param Blob|string $s
732 function addQuotes( $s ) {
733 if ( $s instanceof Blob
) {
734 return "x'" . bin2hex( $s->fetch() ) . "'";
735 } elseif ( is_bool( $s ) ) {
737 } elseif ( strpos( $s, "\0" ) !== false ) {
738 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
739 // This is a known limitation of SQLite's mprintf function which PDO should work around,
740 // but doesn't. I have reported this to php.net as bug #63419:
741 // https://bugs.php.net/bug.php?id=63419
742 // There was already a similar report for SQLite3::escapeString, bug #62361:
743 // https://bugs.php.net/bug.php?id=62361
744 // There is an additional bug regarding sorting this data after insert
745 // on older versions of sqlite shipped with ubuntu 12.04
746 // https://bugzilla.wikimedia.org/show_bug.cgi?id=72367
747 wfDebugLog( __CLASS__
, __FUNCTION__
. ': Quoting value containing null byte. For consistency all binary data should have been first processed with self::encodeBlob()' );
748 return "x'" . bin2hex( $s ) . "'";
750 return $this->mConn
->quote( $s );
757 function buildLike() {
758 $params = func_get_args();
759 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
760 $params = $params[0];
763 return parent
::buildLike( $params ) . "ESCAPE '\' ";
769 public function getSearchEngine() {
770 return "SearchSqlite";
774 * No-op version of deadlockLoop
778 public function deadlockLoop( /*...*/ ) {
779 $args = func_get_args();
780 $function = array_shift( $args );
782 return call_user_func_array( $function, $args );
789 protected function replaceVars( $s ) {
790 $s = parent
::replaceVars( $s );
791 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
792 // CREATE TABLE hacks to allow schema file sharing with MySQL
794 // binary/varbinary column type -> blob
795 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
796 // no such thing as unsigned
797 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
799 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
800 // floating point types -> REAL
802 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
807 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
808 // TEXT normalization
809 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
810 // BLOB normalization
811 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
813 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
815 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
817 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
818 // binary collation type -> nothing
819 $s = preg_replace( '/\bbinary\b/i', '', $s );
820 // auto_increment -> autoincrement
821 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
822 // No explicit options
823 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
824 // AUTOINCREMENT should immedidately follow PRIMARY KEY
825 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
826 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
827 // No truncated indexes
828 $s = preg_replace( '/\(\d+\)/', '', $s );
830 $s = preg_replace( '/\bfulltext\b/i', '', $s );
831 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
832 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
833 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
834 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
835 // INSERT IGNORE --> INSERT OR IGNORE
836 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
842 public function lock( $lockName, $method, $timeout = 5 ) {
843 global $wgSQLiteDataDir;
845 if ( !is_dir( "$wgSQLiteDataDir/locks" ) ) { // create dir as needed
846 if ( !is_writable( $wgSQLiteDataDir ) ||
!mkdir( "$wgSQLiteDataDir/locks" ) ) {
847 throw new DBError( "Cannot create directory \"$wgSQLiteDataDir/locks\"." );
851 return $this->lockMgr
->lock( array( $lockName ), LockManager
::LOCK_EX
, $timeout )->isOK();
854 public function unlock( $lockName, $method ) {
855 return $this->lockMgr
->unlock( array( $lockName ), LockManager
::LOCK_EX
)->isOK();
859 * Build a concatenation list to feed into a SQL query
861 * @param string[] $stringList
864 function buildConcat( $stringList ) {
865 return '(' . implode( ') || (', $stringList ) . ')';
868 public function buildGroupConcatField(
869 $delim, $table, $field, $conds = '', $join_conds = array()
871 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
873 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
877 * @throws MWException
878 * @param string $oldName
879 * @param string $newName
880 * @param bool $temporary
881 * @param string $fname
882 * @return bool|ResultWrapper
884 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
885 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
886 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
887 $obj = $this->fetchObject( $res );
889 throw new MWException( "Couldn't retrieve structure for table $oldName" );
893 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
894 $this->addIdentifierQuotes( $newName ),
899 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
900 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
902 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
906 return $this->query( $sql, $fname );
910 * List all tables on the database
912 * @param string $prefix Only show tables with this prefix, e.g. mw_
913 * @param string $fname Calling function name
917 function listTables( $prefix = null, $fname = __METHOD__
) {
918 $result = $this->select(
926 foreach ( $result as $table ) {
927 $vars = get_object_vars( $table );
928 $table = array_pop( $vars );
930 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
931 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
932 $endArray[] = $table;
939 } // end DatabaseSqlite class
942 * This class allows simple acccess to a SQLite database independently from main database settings
945 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
946 public function __construct( $fileName, $flags = 0 ) {
947 global $wgSQLiteDataDir;
949 $this->mTrxAtomicLevels
= new SplStack
;
950 $this->lockMgr
= new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
952 $this->mFlags
= $flags;
953 $this->tablePrefix( null );
954 $this->openFile( $fileName );
961 class SQLiteField
implements Field
{
962 private $info, $tableName;
964 function __construct( $info, $tableName ) {
966 $this->tableName
= $tableName;
970 return $this->info
->name
;
973 function tableName() {
974 return $this->tableName
;
977 function defaultValue() {
978 if ( is_string( $this->info
->dflt_value
) ) {
980 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
981 return str_replace( "''", "'", $this->info
->dflt_value
);
985 return $this->info
->dflt_value
;
991 function isNullable() {
992 return !$this->info
->notnull
;
996 return $this->info
->type
;