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
{
30 private static $fulltextEnabled = null;
44 * Parameters $server, $user and $password are not used.
45 * @param $server string
47 * @param $password string
48 * @param $dbName string
51 function __construct( $server = false, $user = false, $password = false, $dbName = false, $flags = 0 ) {
52 $this->mName
= $dbName;
53 parent
::__construct( $server, $user, $password, $dbName, $flags );
54 // parent doesn't open when $user is false, but we can work with $dbName
57 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
58 $this->attachDatabase( $wgSharedDB );
71 * @todo Check if it should be true like parent class
75 function implicitGroupby() {
79 /** Open an SQLite database and return a resource handle to it
80 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
82 * @param string $server
85 * @param string $dbName
87 * @throws DBConnectionError
90 function open( $server, $user, $pass, $dbName ) {
91 global $wgSQLiteDataDir;
93 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
94 if ( !is_readable( $fileName ) ) {
96 throw new DBConnectionError( $this, "SQLite database not accessible" );
98 $this->openFile( $fileName );
103 * Opens a database file
105 * @param $fileName string
107 * @throws DBConnectionError
108 * @return PDO|bool SQL connection or false if failed
110 function openFile( $fileName ) {
111 $this->mDatabaseFile
= $fileName;
113 if ( $this->mFlags
& DBO_PERSISTENT
) {
114 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
115 array( PDO
::ATTR_PERSISTENT
=> true ) );
117 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
119 } catch ( PDOException
$e ) {
120 $err = $e->getMessage();
122 if ( !$this->mConn
) {
123 wfDebug( "DB connection error: $err\n" );
124 throw new DBConnectionError( $this, $err );
126 $this->mOpened
= !!$this->mConn
;
127 # set error codes only, don't raise exceptions
128 if ( $this->mOpened
) {
129 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
130 # Enforce LIKE to be case sensitive, just like MySQL
131 $this->query( 'PRAGMA case_sensitive_like = 1' );
137 * Does not actually close the connection, just destroys the reference for GC to do its work
140 protected function closeConnection() {
146 * Generates a database file name. Explicitly public for installer.
147 * @param string $dir Directory where database resides
148 * @param string $dbName Database name
151 public static function generateFileName( $dir, $dbName ) {
152 return "$dir/$dbName.sqlite";
156 * Check if the searchindext table is FTS enabled.
157 * @return bool False if not enabled.
159 function checkForEnabledSearch() {
160 if ( self
::$fulltextEnabled === null ) {
161 self
::$fulltextEnabled = false;
162 $table = $this->tableName( 'searchindex' );
163 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
165 $row = $res->fetchRow();
166 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
169 return self
::$fulltextEnabled;
173 * Returns version of currently supported SQLite fulltext search module or false if none present.
176 static function getFulltextSearchModule() {
177 static $cachedResult = null;
178 if ( $cachedResult !== null ) {
179 return $cachedResult;
181 $cachedResult = false;
182 $table = 'dummy_search_test';
184 $db = new DatabaseSqliteStandalone( ':memory:' );
186 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
187 $cachedResult = 'FTS3';
190 return $cachedResult;
194 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
197 * @param string $name database name to be used in queries like SELECT foo FROM dbname.table
198 * @param string $file database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
199 * @param string $fname calling function name
201 * @return ResultWrapper
203 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
204 global $wgSQLiteDataDir;
206 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
208 $file = $this->addQuotes( $file );
209 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
213 * @see DatabaseBase::isWriteQuery()
219 function isWriteQuery( $sql ) {
220 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
224 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
228 * @return ResultWrapper
230 protected function doQuery( $sql ) {
231 $res = $this->mConn
->query( $sql );
232 if ( $res === false ) {
235 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
236 $this->mAffectedRows
= $r->rowCount();
237 $res = new ResultWrapper( $this, $r->fetchAll() );
243 * @param $res ResultWrapper
245 function freeResult( $res ) {
246 if ( $res instanceof ResultWrapper
) {
254 * @param $res ResultWrapper
255 * @return object|bool
257 function fetchObject( $res ) {
258 if ( $res instanceof ResultWrapper
) {
264 $cur = current( $r );
265 if ( is_array( $cur ) ) {
268 foreach ( $cur as $k => $v ) {
269 if ( !is_numeric( $k ) ) {
280 * @param $res ResultWrapper
283 function fetchRow( $res ) {
284 if ( $res instanceof ResultWrapper
) {
289 $cur = current( $r );
290 if ( is_array( $cur ) ) {
298 * The PDO::Statement class implements the array interface so count() will work
300 * @param $res ResultWrapper
304 function numRows( $res ) {
305 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
310 * @param $res ResultWrapper
313 function numFields( $res ) {
314 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
315 return is_array( $r ) ?
count( $r[0] ) : 0;
319 * @param $res ResultWrapper
323 function fieldName( $res, $n ) {
324 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
325 if ( is_array( $r ) ) {
326 $keys = array_keys( $r[0] );
333 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
336 * @param $format String
339 function tableName( $name, $format = 'quoted' ) {
340 // table names starting with sqlite_ are reserved
341 if ( strpos( $name, 'sqlite_' ) === 0 ) {
344 return str_replace( '"', '', parent
::tableName( $name, $format ) );
348 * Index names have DB scope
350 * @param $index string
354 function indexName( $index ) {
359 * This must be called after nextSequenceVal
363 function insertId() {
364 // PDO::lastInsertId yields a string :(
365 return intval( $this->mConn
->lastInsertId() );
369 * @param $res ResultWrapper
372 function dataSeek( $res, $row ) {
373 if ( $res instanceof ResultWrapper
) {
380 for ( $i = 0; $i < $row; $i++
) {
389 function lastError() {
390 if ( !is_object( $this->mConn
) ) {
391 return "Cannot return last error, no db connection";
393 $e = $this->mConn
->errorInfo();
394 return isset( $e[2] ) ?
$e[2] : '';
400 function lastErrno() {
401 if ( !is_object( $this->mConn
) ) {
402 return "Cannot return last error, no db connection";
404 $info = $this->mConn
->errorInfo();
412 function affectedRows() {
413 return $this->mAffectedRows
;
417 * Returns information about an index
418 * Returns false if the index does not exist
419 * - if errors are explicitly ignored, returns NULL on failure
423 function indexInfo( $table, $index, $fname = __METHOD__
) {
424 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
425 $res = $this->query( $sql, $fname );
429 if ( $res->numRows() == 0 ) {
433 foreach ( $res as $row ) {
434 $info[] = $row->name
;
442 * @param $fname string
445 function indexUnique( $table, $index, $fname = __METHOD__
) {
446 $row = $this->selectRow( 'sqlite_master', '*',
449 'name' => $this->indexName( $index ),
451 if ( !$row ||
!isset( $row->sql
) ) {
455 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
456 $indexPos = strpos( $row->sql
, 'INDEX' );
457 if ( $indexPos === false ) {
460 $firstPart = substr( $row->sql
, 0, $indexPos );
461 $options = explode( ' ', $firstPart );
462 return in_array( 'UNIQUE', $options );
466 * Filter the options used in SELECT statements
468 * @param $options array
472 function makeSelectOptions( $options ) {
473 foreach ( $options as $k => $v ) {
474 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
478 return parent
::makeSelectOptions( $options );
482 * @param $options array
485 function makeUpdateOptions( $options ) {
486 $options = self
::fixIgnore( $options );
487 return parent
::makeUpdateOptions( $options );
491 * @param $options array
494 static function fixIgnore( $options ) {
495 # SQLite uses OR IGNORE not just IGNORE
496 foreach ( $options as $k => $v ) {
497 if ( $v == 'IGNORE' ) {
498 $options[$k] = 'OR IGNORE';
505 * @param $options array
508 function makeInsertOptions( $options ) {
509 $options = self
::fixIgnore( $options );
510 return parent
::makeInsertOptions( $options );
514 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
517 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
518 if ( !count( $a ) ) {
522 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
523 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
525 foreach ( $a as $v ) {
526 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
531 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
539 * @param $uniqueIndexes
541 * @param $fname string
542 * @return bool|ResultWrapper
544 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
545 if ( !count( $rows ) ) {
549 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
550 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
552 foreach ( $rows as $v ) {
553 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
558 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
565 * Returns the size of a text field, or -1 for "unlimited"
566 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
570 function textFieldSize( $table, $field ) {
577 function unionSupportsOrderAndLimit() {
586 function unionQueries( $sqls, $all ) {
587 $glue = $all ?
' UNION ALL ' : ' UNION ';
588 return implode( $glue, $sqls );
594 function wasDeadlock() {
595 return $this->lastErrno() == 5; // SQLITE_BUSY
601 function wasErrorReissuable() {
602 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
608 function wasReadOnlyError() {
609 return $this->lastErrno() == 8; // SQLITE_READONLY;
613 * @return string wikitext of a link to the server software's web site
615 public function getSoftwareLink() {
616 return "[http://sqlite.org/ SQLite]";
620 * @return string Version information from the database
622 function getServerVersion() {
623 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
628 * @return string User-friendly database information
630 public function getServerInfo() {
631 return wfMessage( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() )->text();
635 * Get information about a given field
636 * Returns false if the field does not exist.
638 * @param $table string
639 * @param $field string
640 * @return SQLiteField|bool False on failure
642 function fieldInfo( $table, $field ) {
643 $tableName = $this->tableName( $table );
644 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
645 $res = $this->query( $sql, __METHOD__
);
646 foreach ( $res as $row ) {
647 if ( $row->name
== $field ) {
648 return new SQLiteField( $row, $tableName );
654 protected function doBegin( $fname = '' ) {
655 if ( $this->mTrxLevel
== 1 ) {
656 $this->commit( __METHOD__
);
658 $this->mConn
->beginTransaction();
659 $this->mTrxLevel
= 1;
662 protected function doCommit( $fname = '' ) {
663 if ( $this->mTrxLevel
== 0 ) {
666 $this->mConn
->commit();
667 $this->mTrxLevel
= 0;
670 protected function doRollback( $fname = '' ) {
671 if ( $this->mTrxLevel
== 0 ) {
674 $this->mConn
->rollBack();
675 $this->mTrxLevel
= 0;
682 function strencode( $s ) {
683 return substr( $this->addQuotes( $s ), 1, - 1 );
690 function encodeBlob( $b ) {
691 return new Blob( $b );
695 * @param $b Blob|string
698 function decodeBlob( $b ) {
699 if ( $b instanceof Blob
) {
706 * @param $s Blob|string
709 function addQuotes( $s ) {
710 if ( $s instanceof Blob
) {
711 return "x'" . bin2hex( $s->fetch() ) . "'";
712 } elseif ( strpos( $s, "\0" ) !== false ) {
713 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
714 // This is a known limitation of SQLite's mprintf function which PDO should work around,
715 // but doesn't. I have reported this to php.net as bug #63419:
716 // https://bugs.php.net/bug.php?id=63419
717 // There was already a similar report for SQLite3::escapeString, bug #62361:
718 // https://bugs.php.net/bug.php?id=62361
719 return "x'" . bin2hex( $s ) . "'";
721 return $this->mConn
->quote( $s );
728 function buildLike() {
729 $params = func_get_args();
730 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
731 $params = $params[0];
733 return parent
::buildLike( $params ) . "ESCAPE '\' ";
739 public function getSearchEngine() {
740 return "SearchSqlite";
744 * No-op version of deadlockLoop
747 public function deadlockLoop( /*...*/ ) {
748 $args = func_get_args();
749 $function = array_shift( $args );
750 return call_user_func_array( $function, $args );
757 protected function replaceVars( $s ) {
758 $s = parent
::replaceVars( $s );
759 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
760 // CREATE TABLE hacks to allow schema file sharing with MySQL
762 // binary/varbinary column type -> blob
763 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
764 // no such thing as unsigned
765 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
767 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
768 // floating point types -> REAL
769 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
771 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
772 // TEXT normalization
773 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
774 // BLOB normalization
775 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
777 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
779 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
781 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
782 // binary collation type -> nothing
783 $s = preg_replace( '/\bbinary\b/i', '', $s );
784 // auto_increment -> autoincrement
785 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
786 // No explicit options
787 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
788 // AUTOINCREMENT should immedidately follow PRIMARY KEY
789 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
790 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
791 // No truncated indexes
792 $s = preg_replace( '/\(\d+\)/', '', $s );
794 $s = preg_replace( '/\bfulltext\b/i', '', $s );
800 * Build a concatenation list to feed into a SQL query
802 * @param $stringList array
806 function buildConcat( $stringList ) {
807 return '(' . implode( ') || (', $stringList ) . ')';
811 * @throws MWException
814 * @param $temporary bool
815 * @param $fname string
816 * @return bool|ResultWrapper
818 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
819 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
820 $obj = $this->fetchObject( $res );
822 throw new MWException( "Couldn't retrieve structure for table $oldName" );
825 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
827 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
828 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
830 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
833 return $this->query( $sql, $fname );
837 * List all tables on the database
839 * @param string $prefix Only show tables with this prefix, e.g. mw_
840 * @param string $fname calling function name
844 function listTables( $prefix = null, $fname = __METHOD__
) {
845 $result = $this->select(
853 foreach ( $result as $table ) {
854 $vars = get_object_vars( $table );
855 $table = array_pop( $vars );
857 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
858 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
859 $endArray[] = $table;
868 } // end DatabaseSqlite class
871 * This class allows simple acccess to a SQLite database independently from main database settings
874 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
875 public function __construct( $fileName, $flags = 0 ) {
876 $this->mFlags
= $flags;
877 $this->tablePrefix( null );
878 $this->openFile( $fileName );
885 class SQLiteField
implements Field
{
886 private $info, $tableName;
887 function __construct( $info, $tableName ) {
889 $this->tableName
= $tableName;
893 return $this->info
->name
;
896 function tableName() {
897 return $this->tableName
;
900 function defaultValue() {
901 if ( is_string( $this->info
->dflt_value
) ) {
903 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
904 return str_replace( "''", "'", $this->info
->dflt_value
);
907 return $this->info
->dflt_value
;
913 function isNullable() {
914 return !$this->info
->notnull
;
918 return $this->info
->type
;