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
);
135 * Does not actually close the connection, just destroys the reference for GC to do its work
138 protected function closeConnection() {
144 * Generates a database file name. Explicitly public for installer.
145 * @param $dir String: Directory where database resides
146 * @param $dbName String: Database name
149 public static function generateFileName( $dir, $dbName ) {
150 return "$dir/$dbName.sqlite";
154 * Check if the searchindext table is FTS enabled.
155 * @return bool False if not enabled.
157 function checkForEnabledSearch() {
158 if ( self
::$fulltextEnabled === null ) {
159 self
::$fulltextEnabled = false;
160 $table = $this->tableName( 'searchindex' );
161 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
163 $row = $res->fetchRow();
164 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
167 return self
::$fulltextEnabled;
171 * Returns version of currently supported SQLite fulltext search module or false if none present.
174 static function getFulltextSearchModule() {
175 static $cachedResult = null;
176 if ( $cachedResult !== null ) {
177 return $cachedResult;
179 $cachedResult = false;
180 $table = 'dummy_search_test';
182 $db = new DatabaseSqliteStandalone( ':memory:' );
184 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
185 $cachedResult = 'FTS3';
188 return $cachedResult;
192 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
195 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
196 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
197 * @param $fname String: calling function name
199 * @return ResultWrapper
201 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
202 global $wgSQLiteDataDir;
204 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
206 $file = $this->addQuotes( $file );
207 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
211 * @see DatabaseBase::isWriteQuery()
217 function isWriteQuery( $sql ) {
218 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
222 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
226 * @return ResultWrapper
228 protected function doQuery( $sql ) {
229 $res = $this->mConn
->query( $sql );
230 if ( $res === false ) {
233 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
234 $this->mAffectedRows
= $r->rowCount();
235 $res = new ResultWrapper( $this, $r->fetchAll() );
241 * @param $res ResultWrapper
243 function freeResult( $res ) {
244 if ( $res instanceof ResultWrapper
) {
252 * @param $res ResultWrapper
255 function fetchObject( $res ) {
256 if ( $res instanceof ResultWrapper
) {
262 $cur = current( $r );
263 if ( is_array( $cur ) ) {
266 foreach ( $cur as $k => $v ) {
267 if ( !is_numeric( $k ) ) {
278 * @param $res ResultWrapper
281 function fetchRow( $res ) {
282 if ( $res instanceof ResultWrapper
) {
287 $cur = current( $r );
288 if ( is_array( $cur ) ) {
296 * The PDO::Statement class implements the array interface so count() will work
298 * @param $res ResultWrapper
302 function numRows( $res ) {
303 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
308 * @param $res ResultWrapper
311 function numFields( $res ) {
312 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
313 return is_array( $r ) ?
count( $r[0] ) : 0;
317 * @param $res ResultWrapper
321 function fieldName( $res, $n ) {
322 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
323 if ( is_array( $r ) ) {
324 $keys = array_keys( $r[0] );
331 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
334 * @param $format String
337 function tableName( $name, $format = 'quoted' ) {
338 // table names starting with sqlite_ are reserved
339 if ( strpos( $name, 'sqlite_' ) === 0 ) {
342 return str_replace( '"', '', parent
::tableName( $name, $format ) );
346 * Index names have DB scope
348 * @param $index string
352 function indexName( $index ) {
357 * This must be called after nextSequenceVal
361 function insertId() {
362 // PDO::lastInsertId yields a string :(
363 return intval( $this->mConn
->lastInsertId() );
367 * @param $res ResultWrapper
370 function dataSeek( $res, $row ) {
371 if ( $res instanceof ResultWrapper
) {
378 for ( $i = 0; $i < $row; $i++
) {
387 function lastError() {
388 if ( !is_object( $this->mConn
) ) {
389 return "Cannot return last error, no db connection";
391 $e = $this->mConn
->errorInfo();
392 return isset( $e[2] ) ?
$e[2] : '';
398 function lastErrno() {
399 if ( !is_object( $this->mConn
) ) {
400 return "Cannot return last error, no db connection";
402 $info = $this->mConn
->errorInfo();
410 function affectedRows() {
411 return $this->mAffectedRows
;
415 * Returns information about an index
416 * Returns false if the index does not exist
417 * - if errors are explicitly ignored, returns NULL on failure
421 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
422 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
423 $res = $this->query( $sql, $fname );
427 if ( $res->numRows() == 0 ) {
431 foreach ( $res as $row ) {
432 $info[] = $row->name
;
440 * @param $fname string
443 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
444 $row = $this->selectRow( 'sqlite_master', '*',
447 'name' => $this->indexName( $index ),
449 if ( !$row ||
!isset( $row->sql
) ) {
453 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
454 $indexPos = strpos( $row->sql
, 'INDEX' );
455 if ( $indexPos === false ) {
458 $firstPart = substr( $row->sql
, 0, $indexPos );
459 $options = explode( ' ', $firstPart );
460 return in_array( 'UNIQUE', $options );
464 * Filter the options used in SELECT statements
466 * @param $options array
470 function makeSelectOptions( $options ) {
471 foreach ( $options as $k => $v ) {
472 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
476 return parent
::makeSelectOptions( $options );
480 * @param $options array
483 function makeUpdateOptions( $options ) {
484 $options = self
::fixIgnore( $options );
485 return parent
::makeUpdateOptions( $options );
489 * @param $options array
492 static function fixIgnore( $options ) {
493 # SQLite uses OR IGNORE not just IGNORE
494 foreach ( $options as $k => $v ) {
495 if ( $v == 'IGNORE' ) {
496 $options[$k] = 'OR IGNORE';
503 * @param $options array
506 function makeInsertOptions( $options ) {
507 $options = self
::fixIgnore( $options );
508 return parent
::makeInsertOptions( $options );
512 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
515 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
516 if ( !count( $a ) ) {
520 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
521 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
523 foreach ( $a as $v ) {
524 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
529 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
537 * @param $uniqueIndexes
539 * @param $fname string
540 * @return bool|ResultWrapper
542 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
543 if ( !count( $rows ) ) return true;
545 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
546 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
548 foreach ( $rows as $v ) {
549 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
554 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
561 * Returns the size of a text field, or -1 for "unlimited"
562 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
566 function textFieldSize( $table, $field ) {
573 function unionSupportsOrderAndLimit() {
582 function unionQueries( $sqls, $all ) {
583 $glue = $all ?
' UNION ALL ' : ' UNION ';
584 return implode( $glue, $sqls );
590 function wasDeadlock() {
591 return $this->lastErrno() == 5; // SQLITE_BUSY
597 function wasErrorReissuable() {
598 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
604 function wasReadOnlyError() {
605 return $this->lastErrno() == 8; // SQLITE_READONLY;
609 * @return string wikitext of a link to the server software's web site
611 public static function getSoftwareLink() {
612 return "[http://sqlite.org/ SQLite]";
616 * @return string Version information from the database
618 function getServerVersion() {
619 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
624 * @return string User-friendly database information
626 public function getServerInfo() {
627 return wfMessage( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() )->text();
631 * Get information about a given field
632 * Returns false if the field does not exist.
634 * @param $table string
635 * @param $field string
636 * @return SQLiteField|bool False on failure
638 function fieldInfo( $table, $field ) {
639 $tableName = $this->tableName( $table );
640 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
641 $res = $this->query( $sql, __METHOD__
);
642 foreach ( $res as $row ) {
643 if ( $row->name
== $field ) {
644 return new SQLiteField( $row, $tableName );
650 protected function doBegin( $fname = '' ) {
651 if ( $this->mTrxLevel
== 1 ) {
652 $this->commit( __METHOD__
);
654 $this->mConn
->beginTransaction();
655 $this->mTrxLevel
= 1;
658 protected function doCommit( $fname = '' ) {
659 if ( $this->mTrxLevel
== 0 ) {
662 $this->mConn
->commit();
663 $this->mTrxLevel
= 0;
666 protected function doRollback( $fname = '' ) {
667 if ( $this->mTrxLevel
== 0 ) {
670 $this->mConn
->rollBack();
671 $this->mTrxLevel
= 0;
678 function strencode( $s ) {
679 return substr( $this->addQuotes( $s ), 1, - 1 );
686 function encodeBlob( $b ) {
687 return new Blob( $b );
691 * @param $b Blob|string
694 function decodeBlob( $b ) {
695 if ( $b instanceof Blob
) {
702 * @param $s Blob|string
705 function addQuotes( $s ) {
706 if ( $s instanceof Blob
) {
707 return "x'" . bin2hex( $s->fetch() ) . "'";
708 } else if ( strpos( $s, "\0" ) !== false ) {
709 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
710 // This is a known limitation of SQLite's mprintf function which PDO should work around,
711 // but doesn't. I have reported this to php.net as bug #63419:
712 // https://bugs.php.net/bug.php?id=63419
713 // There was already a similar report for SQLite3::escapeString, bug #62361:
714 // https://bugs.php.net/bug.php?id=62361
715 return "x'" . bin2hex( $s ) . "'";
717 return $this->mConn
->quote( $s );
724 function buildLike() {
725 $params = func_get_args();
726 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
727 $params = $params[0];
729 return parent
::buildLike( $params ) . "ESCAPE '\' ";
735 public function getSearchEngine() {
736 return "SearchSqlite";
740 * No-op version of deadlockLoop
743 public function deadlockLoop( /*...*/ ) {
744 $args = func_get_args();
745 $function = array_shift( $args );
746 return call_user_func_array( $function, $args );
753 protected function replaceVars( $s ) {
754 $s = parent
::replaceVars( $s );
755 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
756 // CREATE TABLE hacks to allow schema file sharing with MySQL
758 // binary/varbinary column type -> blob
759 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
760 // no such thing as unsigned
761 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
763 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
764 // floating point types -> REAL
765 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
767 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
768 // TEXT normalization
769 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
770 // BLOB normalization
771 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
773 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
775 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
777 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
778 // binary collation type -> nothing
779 $s = preg_replace( '/\bbinary\b/i', '', $s );
780 // auto_increment -> autoincrement
781 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
782 // No explicit options
783 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
784 // AUTOINCREMENT should immedidately follow PRIMARY KEY
785 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
786 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
787 // No truncated indexes
788 $s = preg_replace( '/\(\d+\)/', '', $s );
790 $s = preg_replace( '/\bfulltext\b/i', '', $s );
796 * Build a concatenation list to feed into a SQL query
798 * @param $stringList array
802 function buildConcat( $stringList ) {
803 return '(' . implode( ') || (', $stringList ) . ')';
807 * @throws MWException
810 * @param $temporary bool
811 * @param $fname string
812 * @return bool|ResultWrapper
814 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
815 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
816 $obj = $this->fetchObject( $res );
818 throw new MWException( "Couldn't retrieve structure for table $oldName" );
821 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
823 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
824 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
826 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
829 return $this->query( $sql, $fname );
834 * List all tables on the database
836 * @param $prefix string Only show tables with this prefix, e.g. mw_
837 * @param $fname String: calling function name
841 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
842 $result = $this->select(
850 foreach( $result as $table ) {
851 $vars = get_object_vars($table);
852 $table = array_pop( $vars );
854 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
855 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
856 $endArray[] = $table;
865 } // end DatabaseSqlite class
868 * This class allows simple acccess to a SQLite database independently from main database settings
871 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
872 public function __construct( $fileName, $flags = 0 ) {
873 $this->mFlags
= $flags;
874 $this->tablePrefix( null );
875 $this->openFile( $fileName );
882 class SQLiteField
implements Field
{
883 private $info, $tableName;
884 function __construct( $info, $tableName ) {
886 $this->tableName
= $tableName;
890 return $this->info
->name
;
893 function tableName() {
894 return $this->tableName
;
897 function defaultValue() {
898 if ( is_string( $this->info
->dflt_value
) ) {
900 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
901 return str_replace( "''", "'", $this->info
->dflt_value
);
904 return $this->info
->dflt_value
;
910 function isNullable() {
911 return !$this->info
->notnull
;
915 return $this->info
->type
;