3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
13 class DatabaseSqlite
extends DatabaseBase
{
15 private static $fulltextEnabled = null;
29 * Parameters $server, $user and $password are not used.
30 * @param $server string
32 * @param $password string
33 * @param $dbName string
36 function __construct( $server = false, $user = false, $password = false, $dbName = false, $flags = 0 ) {
37 $this->mName
= $dbName;
38 parent
::__construct( $server, $user, $password, $dbName, $flags );
39 // parent doesn't open when $user is false, but we can work with $dbName
42 if( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
43 $this->attachDatabase( $wgSharedDB );
56 * @todo: check if it should be true like parent class
60 function implicitGroupby() {
64 /** Open an SQLite database and return a resource handle to it
65 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
74 function open( $server, $user, $pass, $dbName ) {
75 global $wgSQLiteDataDir;
77 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
78 if ( !is_readable( $fileName ) ) {
80 throw new DBConnectionError( $this, "SQLite database not accessible" );
82 $this->openFile( $fileName );
87 * Opens a database file
89 * @param $fileName string
91 * @return PDO|false SQL connection or false if failed
93 function openFile( $fileName ) {
94 $this->mDatabaseFile
= $fileName;
96 if ( $this->mFlags
& DBO_PERSISTENT
) {
97 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
98 array( PDO
::ATTR_PERSISTENT
=> true ) );
100 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
102 } catch ( PDOException
$e ) {
103 $err = $e->getMessage();
105 if ( !$this->mConn
) {
106 wfDebug( "DB connection error: $err\n" );
107 throw new DBConnectionError( $this, $err );
109 $this->mOpened
= !!$this->mConn
;
110 # set error codes only, don't raise exceptions
111 if ( $this->mOpened
) {
112 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
118 * Close an SQLite database
123 $this->mOpened
= false;
124 if ( is_object( $this->mConn
) ) {
125 if ( $this->trxLevel() ) $this->commit();
132 * Generates a database file name. Explicitly public for installer.
133 * @param $dir String: Directory where database resides
134 * @param $dbName String: Database name
137 public static function generateFileName( $dir, $dbName ) {
138 return "$dir/$dbName.sqlite";
142 * Check if the searchindext table is FTS enabled.
143 * @return false if not enabled.
145 function checkForEnabledSearch() {
146 if ( self
::$fulltextEnabled === null ) {
147 self
::$fulltextEnabled = false;
148 $table = $this->tableName( 'searchindex' );
149 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
151 $row = $res->fetchRow();
152 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
155 return self
::$fulltextEnabled;
159 * Returns version of currently supported SQLite fulltext search module or false if none present.
162 static function getFulltextSearchModule() {
163 static $cachedResult = null;
164 if ( $cachedResult !== null ) {
165 return $cachedResult;
167 $cachedResult = false;
168 $table = 'dummy_search_test';
170 $db = new DatabaseSqliteStandalone( ':memory:' );
172 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
173 $cachedResult = 'FTS3';
176 return $cachedResult;
180 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
183 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
184 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
185 * @param $fname String: calling function name
187 * @return ResultWrapper
189 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
190 global $wgSQLiteDataDir;
192 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
194 $file = $this->addQuotes( $file );
195 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
199 * @see DatabaseBase::isWriteQuery()
205 function isWriteQuery( $sql ) {
206 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
210 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
214 * @return ResultWrapper
216 protected function doQuery( $sql ) {
217 $res = $this->mConn
->query( $sql );
218 if ( $res === false ) {
221 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
222 $this->mAffectedRows
= $r->rowCount();
223 $res = new ResultWrapper( $this, $r->fetchAll() );
229 * @param $res ResultWrapper
231 function freeResult( $res ) {
232 if ( $res instanceof ResultWrapper
) {
240 * @param $res ResultWrapper
243 function fetchObject( $res ) {
244 if ( $res instanceof ResultWrapper
) {
250 $cur = current( $r );
251 if ( is_array( $cur ) ) {
254 foreach ( $cur as $k => $v ) {
255 if ( !is_numeric( $k ) ) {
266 * @param $res ResultWrapper
269 function fetchRow( $res ) {
270 if ( $res instanceof ResultWrapper
) {
275 $cur = current( $r );
276 if ( is_array( $cur ) ) {
284 * The PDO::Statement class implements the array interface so count() will work
286 * @param $res ResultWrapper
290 function numRows( $res ) {
291 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
296 * @param $res ResultWrapper
299 function numFields( $res ) {
300 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
301 return is_array( $r ) ?
count( $r[0] ) : 0;
305 * @param $res ResultWrapper
309 function fieldName( $res, $n ) {
310 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
311 if ( is_array( $r ) ) {
312 $keys = array_keys( $r[0] );
319 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
322 * @param $format String
325 function tableName( $name, $format = 'quoted' ) {
326 // table names starting with sqlite_ are reserved
327 if ( strpos( $name, 'sqlite_' ) === 0 ) {
330 return str_replace( '"', '', parent
::tableName( $name, $format ) );
334 * Index names have DB scope
336 * @param $index string
340 function indexName( $index ) {
345 * This must be called after nextSequenceVal
349 function insertId() {
350 return $this->mConn
->lastInsertId();
354 * @param $res ResultWrapper
357 function dataSeek( $res, $row ) {
358 if ( $res instanceof ResultWrapper
) {
365 for ( $i = 0; $i < $row; $i++
) {
374 function lastError() {
375 if ( !is_object( $this->mConn
) ) {
376 return "Cannot return last error, no db connection";
378 $e = $this->mConn
->errorInfo();
379 return isset( $e[2] ) ?
$e[2] : '';
385 function lastErrno() {
386 if ( !is_object( $this->mConn
) ) {
387 return "Cannot return last error, no db connection";
389 $info = $this->mConn
->errorInfo();
397 function affectedRows() {
398 return $this->mAffectedRows
;
402 * Returns information about an index
403 * Returns false if the index does not exist
404 * - if errors are explicitly ignored, returns NULL on failure
408 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
409 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
410 $res = $this->query( $sql, $fname );
414 if ( $res->numRows() == 0 ) {
418 foreach ( $res as $row ) {
419 $info[] = $row->name
;
427 * @param $fname string
430 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
431 $row = $this->selectRow( 'sqlite_master', '*',
434 'name' => $this->indexName( $index ),
436 if ( !$row ||
!isset( $row->sql
) ) {
440 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
441 $indexPos = strpos( $row->sql
, 'INDEX' );
442 if ( $indexPos === false ) {
445 $firstPart = substr( $row->sql
, 0, $indexPos );
446 $options = explode( ' ', $firstPart );
447 return in_array( 'UNIQUE', $options );
451 * Filter the options used in SELECT statements
453 * @param $options array
457 function makeSelectOptions( $options ) {
458 foreach ( $options as $k => $v ) {
459 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
463 return parent
::makeSelectOptions( $options );
467 * @param $options array
470 function makeUpdateOptions( $options ) {
471 $options = self
::fixIgnore( $options );
472 return parent
::makeUpdateOptions( $options );
476 * @param $options array
479 static function fixIgnore( $options ) {
480 # SQLite uses OR IGNORE not just IGNORE
481 foreach ( $options as $k => $v ) {
482 if ( $v == 'IGNORE' ) {
483 $options[$k] = 'OR IGNORE';
490 * @param $options array
493 function makeInsertOptions( $options ) {
494 $options = self
::fixIgnore( $options );
495 return parent
::makeInsertOptions( $options );
499 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
501 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
502 if ( !count( $a ) ) {
506 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
507 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
509 foreach ( $a as $v ) {
510 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
515 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
523 * @param $uniqueIndexes
525 * @param $fname string
526 * @return bool|ResultWrapper
528 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
529 if ( !count( $rows ) ) return true;
531 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
532 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
534 foreach ( $rows as $v ) {
535 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
540 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
547 * Returns the size of a text field, or -1 for "unlimited"
548 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
552 function textFieldSize( $table, $field ) {
559 function unionSupportsOrderAndLimit() {
568 function unionQueries( $sqls, $all ) {
569 $glue = $all ?
' UNION ALL ' : ' UNION ';
570 return implode( $glue, $sqls );
576 function wasDeadlock() {
577 return $this->lastErrno() == 5; // SQLITE_BUSY
583 function wasErrorReissuable() {
584 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
590 function wasReadOnlyError() {
591 return $this->lastErrno() == 8; // SQLITE_READONLY;
595 * @return string wikitext of a link to the server software's web site
597 public static function getSoftwareLink() {
598 return "[http://sqlite.org/ SQLite]";
602 * @return string Version information from the database
604 function getServerVersion() {
605 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
610 * @return string User-friendly database information
612 public function getServerInfo() {
613 return wfMsg( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
617 * Get information about a given field
618 * Returns false if the field does not exist.
620 * @return SQLiteField|false
622 function fieldInfo( $table, $field ) {
623 $tableName = $this->tableName( $table );
624 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
625 $res = $this->query( $sql, __METHOD__
);
626 foreach ( $res as $row ) {
627 if ( $row->name
== $field ) {
628 return new SQLiteField( $row, $tableName );
634 function begin( $fname = '' ) {
635 if ( $this->mTrxLevel
== 1 ) {
638 $this->mConn
->beginTransaction();
639 $this->mTrxLevel
= 1;
642 function commit( $fname = '' ) {
643 if ( $this->mTrxLevel
== 0 ) {
646 $this->mConn
->commit();
647 $this->mTrxLevel
= 0;
650 function rollback( $fname = '' ) {
651 if ( $this->mTrxLevel
== 0 ) {
654 $this->mConn
->rollBack();
655 $this->mTrxLevel
= 0;
663 function limitResultForUpdate( $sql, $num ) {
664 return $this->limitResult( $sql, $num );
671 function strencode( $s ) {
672 return substr( $this->addQuotes( $s ), 1, - 1 );
679 function encodeBlob( $b ) {
680 return new Blob( $b );
684 * @param $b Blob|string
687 function decodeBlob( $b ) {
688 if ( $b instanceof Blob
) {
695 * @param $s Blob|string
698 function addQuotes( $s ) {
699 if ( $s instanceof Blob
) {
700 return "x'" . bin2hex( $s->fetch() ) . "'";
702 return $this->mConn
->quote( $s );
709 function buildLike() {
710 $params = func_get_args();
711 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
712 $params = $params[0];
714 return parent
::buildLike( $params ) . "ESCAPE '\' ";
720 public function getSearchEngine() {
721 return "SearchSqlite";
725 * No-op version of deadlockLoop
727 public function deadlockLoop( /*...*/ ) {
728 $args = func_get_args();
729 $function = array_shift( $args );
730 return call_user_func_array( $function, $args );
737 protected function replaceVars( $s ) {
738 $s = parent
::replaceVars( $s );
739 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
740 // CREATE TABLE hacks to allow schema file sharing with MySQL
742 // binary/varbinary column type -> blob
743 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
744 // no such thing as unsigned
745 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
747 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
748 // floating point types -> REAL
749 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
751 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
752 // TEXT normalization
753 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
754 // BLOB normalization
755 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
757 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
759 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
761 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
762 // binary collation type -> nothing
763 $s = preg_replace( '/\bbinary\b/i', '', $s );
764 // auto_increment -> autoincrement
765 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
766 // No explicit options
767 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
768 // AUTOINCREMENT should immedidately follow PRIMARY KEY
769 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
770 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
771 // No truncated indexes
772 $s = preg_replace( '/\(\d+\)/', '', $s );
774 $s = preg_replace( '/\bfulltext\b/i', '', $s );
780 * Build a concatenation list to feed into a SQL query
782 * @param $stringList array
786 function buildConcat( $stringList ) {
787 return '(' . implode( ') || (', $stringList ) . ')';
791 * @throws MWException
794 * @param $temporary bool
795 * @param $fname string
796 * @return bool|ResultWrapper
798 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
799 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
800 $obj = $this->fetchObject( $res );
802 throw new MWException( "Couldn't retrieve structure for table $oldName" );
805 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
807 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
808 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
810 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
813 return $this->query( $sql, $fname );
818 * List all tables on the database
820 * @param $prefix Only show tables with this prefix, e.g. mw_
821 * @param $fname String: calling function name
825 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
826 $result = $this->select(
834 foreach( $result as $table ) {
835 $vars = get_object_vars($table);
836 $table = array_pop( $vars );
838 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
839 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
840 $endArray[] = $table;
849 } // end DatabaseSqlite class
852 * This class allows simple acccess to a SQLite database independently from main database settings
855 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
856 public function __construct( $fileName, $flags = 0 ) {
857 $this->mFlags
= $flags;
858 $this->tablePrefix( null );
859 $this->openFile( $fileName );
866 class SQLiteField
implements Field
{
867 private $info, $tableName;
868 function __construct( $info, $tableName ) {
870 $this->tableName
= $tableName;
874 return $this->info
->name
;
877 function tableName() {
878 return $this->tableName
;
881 function defaultValue() {
882 if ( is_string( $this->info
->dflt_value
) ) {
884 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
885 return str_replace( "''", "'", $this->info
->dflt_value
);
888 return $this->info
->dflt_value
;
894 function isNullable() {
895 return !$this->info
->notnull
;
899 return $this->info
->type
;