06dfd845951b8d065fca3eb4c6bd80441ee3278d
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
55 if ( $dbName && !$this->isOpen() ) {
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;
94 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
95 if ( !is_readable( $fileName ) ) {
97 throw new DBConnectionError( $this, "SQLite database not accessible" );
99 $this->openFile( $fileName );
104 * Opens a database file
106 * @param $fileName string
108 * @throws DBConnectionError
109 * @return PDO|bool SQL connection or false if failed
111 function openFile( $fileName ) {
112 $this->mDatabaseFile
= $fileName;
114 if ( $this->mFlags
& DBO_PERSISTENT
) {
115 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
116 array( PDO
::ATTR_PERSISTENT
=> true ) );
118 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
120 } catch ( PDOException
$e ) {
121 $err = $e->getMessage();
123 if ( !$this->mConn
) {
124 wfDebug( "DB connection error: $err\n" );
125 throw new DBConnectionError( $this, $err );
127 $this->mOpened
= !!$this->mConn
;
128 # set error codes only, don't raise exceptions
129 if ( $this->mOpened
) {
130 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
131 # Enforce LIKE to be case sensitive, just like MySQL
132 $this->query( 'PRAGMA case_sensitive_like = 1' );
138 * Does not actually close the connection, just destroys the reference for GC to do its work
141 protected function closeConnection() {
147 * Generates a database file name. Explicitly public for installer.
148 * @param string $dir Directory where database resides
149 * @param string $dbName Database name
152 public static function generateFileName( $dir, $dbName ) {
153 return "$dir/$dbName.sqlite";
157 * Check if the searchindext table is FTS enabled.
158 * @return bool False if not enabled.
160 function checkForEnabledSearch() {
161 if ( self
::$fulltextEnabled === null ) {
162 self
::$fulltextEnabled = false;
163 $table = $this->tableName( 'searchindex' );
164 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
166 $row = $res->fetchRow();
167 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
170 return self
::$fulltextEnabled;
174 * Returns version of currently supported SQLite fulltext search module or false if none present.
177 static function getFulltextSearchModule() {
178 static $cachedResult = null;
179 if ( $cachedResult !== null ) {
180 return $cachedResult;
182 $cachedResult = false;
183 $table = 'dummy_search_test';
185 $db = new DatabaseSqliteStandalone( ':memory:' );
187 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
188 $cachedResult = 'FTS3';
191 return $cachedResult;
195 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
198 * @param string $name database name to be used in queries like SELECT foo FROM dbname.table
199 * @param string $file database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
200 * @param string $fname calling function name
202 * @return ResultWrapper
204 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
205 global $wgSQLiteDataDir;
207 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
209 $file = $this->addQuotes( $file );
210 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
214 * @see DatabaseBase::isWriteQuery()
220 function isWriteQuery( $sql ) {
221 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
225 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
229 * @return ResultWrapper
231 protected function doQuery( $sql ) {
232 $res = $this->mConn
->query( $sql );
233 if ( $res === false ) {
236 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
237 $this->mAffectedRows
= $r->rowCount();
238 $res = new ResultWrapper( $this, $r->fetchAll() );
244 * @param $res ResultWrapper
246 function freeResult( $res ) {
247 if ( $res instanceof ResultWrapper
) {
255 * @param $res ResultWrapper
256 * @return object|bool
258 function fetchObject( $res ) {
259 if ( $res instanceof ResultWrapper
) {
265 $cur = current( $r );
266 if ( is_array( $cur ) ) {
269 foreach ( $cur as $k => $v ) {
270 if ( !is_numeric( $k ) ) {
281 * @param $res ResultWrapper
284 function fetchRow( $res ) {
285 if ( $res instanceof ResultWrapper
) {
290 $cur = current( $r );
291 if ( is_array( $cur ) ) {
299 * The PDO::Statement class implements the array interface so count() will work
301 * @param $res ResultWrapper
305 function numRows( $res ) {
306 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
311 * @param $res ResultWrapper
314 function numFields( $res ) {
315 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
316 return is_array( $r ) ?
count( $r[0] ) : 0;
320 * @param $res ResultWrapper
324 function fieldName( $res, $n ) {
325 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
326 if ( is_array( $r ) ) {
327 $keys = array_keys( $r[0] );
334 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
337 * @param $format String
340 function tableName( $name, $format = 'quoted' ) {
341 // table names starting with sqlite_ are reserved
342 if ( strpos( $name, 'sqlite_' ) === 0 ) {
345 return str_replace( '"', '', parent
::tableName( $name, $format ) );
349 * Index names have DB scope
351 * @param $index string
355 function indexName( $index ) {
360 * This must be called after nextSequenceVal
364 function insertId() {
365 // PDO::lastInsertId yields a string :(
366 return intval( $this->mConn
->lastInsertId() );
370 * @param $res ResultWrapper
373 function dataSeek( $res, $row ) {
374 if ( $res instanceof ResultWrapper
) {
381 for ( $i = 0; $i < $row; $i++
) {
390 function lastError() {
391 if ( !is_object( $this->mConn
) ) {
392 return "Cannot return last error, no db connection";
394 $e = $this->mConn
->errorInfo();
395 return isset( $e[2] ) ?
$e[2] : '';
401 function lastErrno() {
402 if ( !is_object( $this->mConn
) ) {
403 return "Cannot return last error, no db connection";
405 $info = $this->mConn
->errorInfo();
413 function affectedRows() {
414 return $this->mAffectedRows
;
418 * Returns information about an index
419 * Returns false if the index does not exist
420 * - if errors are explicitly ignored, returns NULL on failure
424 function indexInfo( $table, $index, $fname = __METHOD__
) {
425 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
426 $res = $this->query( $sql, $fname );
430 if ( $res->numRows() == 0 ) {
434 foreach ( $res as $row ) {
435 $info[] = $row->name
;
443 * @param $fname string
446 function indexUnique( $table, $index, $fname = __METHOD__
) {
447 $row = $this->selectRow( 'sqlite_master', '*',
450 'name' => $this->indexName( $index ),
452 if ( !$row ||
!isset( $row->sql
) ) {
456 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
457 $indexPos = strpos( $row->sql
, 'INDEX' );
458 if ( $indexPos === false ) {
461 $firstPart = substr( $row->sql
, 0, $indexPos );
462 $options = explode( ' ', $firstPart );
463 return in_array( 'UNIQUE', $options );
467 * Filter the options used in SELECT statements
469 * @param $options array
473 function makeSelectOptions( $options ) {
474 foreach ( $options as $k => $v ) {
475 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
479 return parent
::makeSelectOptions( $options );
483 * @param $options array
486 function makeUpdateOptions( $options ) {
487 $options = self
::fixIgnore( $options );
488 return parent
::makeUpdateOptions( $options );
492 * @param $options array
495 static function fixIgnore( $options ) {
496 # SQLite uses OR IGNORE not just IGNORE
497 foreach ( $options as $k => $v ) {
498 if ( $v == 'IGNORE' ) {
499 $options[$k] = 'OR IGNORE';
506 * @param $options array
509 function makeInsertOptions( $options ) {
510 $options = self
::fixIgnore( $options );
511 return parent
::makeInsertOptions( $options );
515 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
518 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
519 if ( !count( $a ) ) {
523 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
524 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
526 foreach ( $a as $v ) {
527 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
532 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
540 * @param $uniqueIndexes
542 * @param $fname string
543 * @return bool|ResultWrapper
545 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
546 if ( !count( $rows ) ) {
550 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
551 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
553 foreach ( $rows as $v ) {
554 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
559 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
566 * Returns the size of a text field, or -1 for "unlimited"
567 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
571 function textFieldSize( $table, $field ) {
578 function unionSupportsOrderAndLimit() {
587 function unionQueries( $sqls, $all ) {
588 $glue = $all ?
' UNION ALL ' : ' UNION ';
589 return implode( $glue, $sqls );
595 function wasDeadlock() {
596 return $this->lastErrno() == 5; // SQLITE_BUSY
602 function wasErrorReissuable() {
603 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
609 function wasReadOnlyError() {
610 return $this->lastErrno() == 8; // SQLITE_READONLY;
614 * @return string wikitext of a link to the server software's web site
616 public function getSoftwareLink() {
617 return "[http://sqlite.org/ SQLite]";
621 * @return string Version information from the database
623 function getServerVersion() {
624 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
629 * @return string User-friendly database information
631 public function getServerInfo() {
632 return wfMessage( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() )->text();
636 * Get information about a given field
637 * Returns false if the field does not exist.
639 * @param $table string
640 * @param $field string
641 * @return SQLiteField|bool False on failure
643 function fieldInfo( $table, $field ) {
644 $tableName = $this->tableName( $table );
645 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
646 $res = $this->query( $sql, __METHOD__
);
647 foreach ( $res as $row ) {
648 if ( $row->name
== $field ) {
649 return new SQLiteField( $row, $tableName );
655 protected function doBegin( $fname = '' ) {
656 if ( $this->mTrxLevel
== 1 ) {
657 $this->commit( __METHOD__
);
660 $this->mConn
->beginTransaction();
661 } catch ( PDOException
$e ) {
662 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
664 $this->mTrxLevel
= 1;
667 protected function doCommit( $fname = '' ) {
668 if ( $this->mTrxLevel
== 0 ) {
672 $this->mConn
->commit();
673 } catch ( PDOException
$e ) {
674 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
676 $this->mTrxLevel
= 0;
679 protected function doRollback( $fname = '' ) {
680 if ( $this->mTrxLevel
== 0 ) {
683 $this->mConn
->rollBack();
684 $this->mTrxLevel
= 0;
691 function strencode( $s ) {
692 return substr( $this->addQuotes( $s ), 1, - 1 );
699 function encodeBlob( $b ) {
700 return new Blob( $b );
704 * @param $b Blob|string
707 function decodeBlob( $b ) {
708 if ( $b instanceof Blob
) {
715 * @param $s Blob|string
718 function addQuotes( $s ) {
719 if ( $s instanceof Blob
) {
720 return "x'" . bin2hex( $s->fetch() ) . "'";
721 } elseif ( is_bool( $s ) ) {
723 } elseif ( strpos( $s, "\0" ) !== false ) {
724 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
725 // This is a known limitation of SQLite's mprintf function which PDO should work around,
726 // but doesn't. I have reported this to php.net as bug #63419:
727 // https://bugs.php.net/bug.php?id=63419
728 // There was already a similar report for SQLite3::escapeString, bug #62361:
729 // https://bugs.php.net/bug.php?id=62361
730 return "x'" . bin2hex( $s ) . "'";
732 return $this->mConn
->quote( $s );
739 function buildLike() {
740 $params = func_get_args();
741 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
742 $params = $params[0];
744 return parent
::buildLike( $params ) . "ESCAPE '\' ";
750 public function getSearchEngine() {
751 return "SearchSqlite";
755 * No-op version of deadlockLoop
758 public function deadlockLoop( /*...*/ ) {
759 $args = func_get_args();
760 $function = array_shift( $args );
761 return call_user_func_array( $function, $args );
768 protected function replaceVars( $s ) {
769 $s = parent
::replaceVars( $s );
770 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
771 // CREATE TABLE hacks to allow schema file sharing with MySQL
773 // binary/varbinary column type -> blob
774 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
775 // no such thing as unsigned
776 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
778 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
779 // floating point types -> REAL
780 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
782 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
783 // TEXT normalization
784 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
785 // BLOB normalization
786 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
788 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
790 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
792 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
793 // binary collation type -> nothing
794 $s = preg_replace( '/\bbinary\b/i', '', $s );
795 // auto_increment -> autoincrement
796 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
797 // No explicit options
798 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
799 // AUTOINCREMENT should immedidately follow PRIMARY KEY
800 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
801 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
802 // No truncated indexes
803 $s = preg_replace( '/\(\d+\)/', '', $s );
805 $s = preg_replace( '/\bfulltext\b/i', '', $s );
806 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
807 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
808 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
814 * Build a concatenation list to feed into a SQL query
816 * @param $stringList array
820 function buildConcat( $stringList ) {
821 return '(' . implode( ') || (', $stringList ) . ')';
825 * @throws MWException
828 * @param $temporary bool
829 * @param $fname string
830 * @return bool|ResultWrapper
832 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
833 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
834 $obj = $this->fetchObject( $res );
836 throw new MWException( "Couldn't retrieve structure for table $oldName" );
839 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
841 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
842 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
844 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
847 return $this->query( $sql, $fname );
851 * List all tables on the database
853 * @param string $prefix Only show tables with this prefix, e.g. mw_
854 * @param string $fname calling function name
858 function listTables( $prefix = null, $fname = __METHOD__
) {
859 $result = $this->select(
867 foreach ( $result as $table ) {
868 $vars = get_object_vars( $table );
869 $table = array_pop( $vars );
871 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
872 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
873 $endArray[] = $table;
882 } // end DatabaseSqlite class
885 * This class allows simple acccess to a SQLite database independently from main database settings
888 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
889 public function __construct( $fileName, $flags = 0 ) {
890 $this->mFlags
= $flags;
891 $this->tablePrefix( null );
892 $this->openFile( $fileName );
899 class SQLiteField
implements Field
{
900 private $info, $tableName;
901 function __construct( $info, $tableName ) {
903 $this->tableName
= $tableName;
907 return $this->info
->name
;
910 function tableName() {
911 return $this->tableName
;
914 function defaultValue() {
915 if ( is_string( $this->info
->dflt_value
) ) {
917 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
918 return str_replace( "''", "'", $this->info
->dflt_value
);
921 return $this->info
->dflt_value
;
927 function isNullable() {
928 return !$this->info
->notnull
;
932 return $this->info
->type
;