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|bool 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 * Does not actually close the connection, just destroys the reference for GC to do its work
121 protected function closeConnection() {
127 * Generates a database file name. Explicitly public for installer.
128 * @param $dir String: Directory where database resides
129 * @param $dbName String: Database name
132 public static function generateFileName( $dir, $dbName ) {
133 return "$dir/$dbName.sqlite";
137 * Check if the searchindext table is FTS enabled.
138 * @return bool False if not enabled.
140 function checkForEnabledSearch() {
141 if ( self
::$fulltextEnabled === null ) {
142 self
::$fulltextEnabled = false;
143 $table = $this->tableName( 'searchindex' );
144 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
146 $row = $res->fetchRow();
147 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
150 return self
::$fulltextEnabled;
154 * Returns version of currently supported SQLite fulltext search module or false if none present.
157 static function getFulltextSearchModule() {
158 static $cachedResult = null;
159 if ( $cachedResult !== null ) {
160 return $cachedResult;
162 $cachedResult = false;
163 $table = 'dummy_search_test';
165 $db = new DatabaseSqliteStandalone( ':memory:' );
167 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
168 $cachedResult = 'FTS3';
171 return $cachedResult;
175 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
178 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
179 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
180 * @param $fname String: calling function name
182 * @return ResultWrapper
184 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
185 global $wgSQLiteDataDir;
187 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
189 $file = $this->addQuotes( $file );
190 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
194 * @see DatabaseBase::isWriteQuery()
200 function isWriteQuery( $sql ) {
201 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
205 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
209 * @return ResultWrapper
211 protected function doQuery( $sql ) {
212 $res = $this->mConn
->query( $sql );
213 if ( $res === false ) {
216 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
217 $this->mAffectedRows
= $r->rowCount();
218 $res = new ResultWrapper( $this, $r->fetchAll() );
224 * @param $res ResultWrapper
226 function freeResult( $res ) {
227 if ( $res instanceof ResultWrapper
) {
235 * @param $res ResultWrapper
238 function fetchObject( $res ) {
239 if ( $res instanceof ResultWrapper
) {
245 $cur = current( $r );
246 if ( is_array( $cur ) ) {
249 foreach ( $cur as $k => $v ) {
250 if ( !is_numeric( $k ) ) {
261 * @param $res ResultWrapper
264 function fetchRow( $res ) {
265 if ( $res instanceof ResultWrapper
) {
270 $cur = current( $r );
271 if ( is_array( $cur ) ) {
279 * The PDO::Statement class implements the array interface so count() will work
281 * @param $res ResultWrapper
285 function numRows( $res ) {
286 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
291 * @param $res ResultWrapper
294 function numFields( $res ) {
295 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
296 return is_array( $r ) ?
count( $r[0] ) : 0;
300 * @param $res ResultWrapper
304 function fieldName( $res, $n ) {
305 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
306 if ( is_array( $r ) ) {
307 $keys = array_keys( $r[0] );
314 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
317 * @param $format String
320 function tableName( $name, $format = 'quoted' ) {
321 // table names starting with sqlite_ are reserved
322 if ( strpos( $name, 'sqlite_' ) === 0 ) {
325 return str_replace( '"', '', parent
::tableName( $name, $format ) );
329 * Index names have DB scope
331 * @param $index string
335 function indexName( $index ) {
340 * This must be called after nextSequenceVal
344 function insertId() {
345 return $this->mConn
->lastInsertId();
349 * @param $res ResultWrapper
352 function dataSeek( $res, $row ) {
353 if ( $res instanceof ResultWrapper
) {
360 for ( $i = 0; $i < $row; $i++
) {
369 function lastError() {
370 if ( !is_object( $this->mConn
) ) {
371 return "Cannot return last error, no db connection";
373 $e = $this->mConn
->errorInfo();
374 return isset( $e[2] ) ?
$e[2] : '';
380 function lastErrno() {
381 if ( !is_object( $this->mConn
) ) {
382 return "Cannot return last error, no db connection";
384 $info = $this->mConn
->errorInfo();
392 function affectedRows() {
393 return $this->mAffectedRows
;
397 * Returns information about an index
398 * Returns false if the index does not exist
399 * - if errors are explicitly ignored, returns NULL on failure
403 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
404 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
405 $res = $this->query( $sql, $fname );
409 if ( $res->numRows() == 0 ) {
413 foreach ( $res as $row ) {
414 $info[] = $row->name
;
422 * @param $fname string
425 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
426 $row = $this->selectRow( 'sqlite_master', '*',
429 'name' => $this->indexName( $index ),
431 if ( !$row ||
!isset( $row->sql
) ) {
435 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
436 $indexPos = strpos( $row->sql
, 'INDEX' );
437 if ( $indexPos === false ) {
440 $firstPart = substr( $row->sql
, 0, $indexPos );
441 $options = explode( ' ', $firstPart );
442 return in_array( 'UNIQUE', $options );
446 * Filter the options used in SELECT statements
448 * @param $options array
452 function makeSelectOptions( $options ) {
453 foreach ( $options as $k => $v ) {
454 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
458 return parent
::makeSelectOptions( $options );
462 * @param $options array
465 function makeUpdateOptions( $options ) {
466 $options = self
::fixIgnore( $options );
467 return parent
::makeUpdateOptions( $options );
471 * @param $options array
474 static function fixIgnore( $options ) {
475 # SQLite uses OR IGNORE not just IGNORE
476 foreach ( $options as $k => $v ) {
477 if ( $v == 'IGNORE' ) {
478 $options[$k] = 'OR IGNORE';
485 * @param $options array
488 function makeInsertOptions( $options ) {
489 $options = self
::fixIgnore( $options );
490 return parent
::makeInsertOptions( $options );
494 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
497 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
498 if ( !count( $a ) ) {
502 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
503 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
505 foreach ( $a as $v ) {
506 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
511 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
519 * @param $uniqueIndexes
521 * @param $fname string
522 * @return bool|ResultWrapper
524 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
525 if ( !count( $rows ) ) return true;
527 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
528 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
530 foreach ( $rows as $v ) {
531 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
536 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
543 * Returns the size of a text field, or -1 for "unlimited"
544 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
548 function textFieldSize( $table, $field ) {
555 function unionSupportsOrderAndLimit() {
564 function unionQueries( $sqls, $all ) {
565 $glue = $all ?
' UNION ALL ' : ' UNION ';
566 return implode( $glue, $sqls );
572 function wasDeadlock() {
573 return $this->lastErrno() == 5; // SQLITE_BUSY
579 function wasErrorReissuable() {
580 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
586 function wasReadOnlyError() {
587 return $this->lastErrno() == 8; // SQLITE_READONLY;
591 * @return string wikitext of a link to the server software's web site
593 public static function getSoftwareLink() {
594 return "[http://sqlite.org/ SQLite]";
598 * @return string Version information from the database
600 function getServerVersion() {
601 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
606 * @return string User-friendly database information
608 public function getServerInfo() {
609 return wfMsg( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
613 * Get information about a given field
614 * Returns false if the field does not exist.
616 * @param $table string
617 * @param $field string
618 * @return SQLiteField|bool False on failure
620 function fieldInfo( $table, $field ) {
621 $tableName = $this->tableName( $table );
622 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
623 $res = $this->query( $sql, __METHOD__
);
624 foreach ( $res as $row ) {
625 if ( $row->name
== $field ) {
626 return new SQLiteField( $row, $tableName );
632 function begin( $fname = '' ) {
633 if ( $this->mTrxLevel
== 1 ) {
634 $this->commit( __METHOD__
);
636 $this->mConn
->beginTransaction();
637 $this->mTrxLevel
= 1;
640 function commit( $fname = '' ) {
641 if ( $this->mTrxLevel
== 0 ) {
644 $this->mConn
->commit();
645 $this->mTrxLevel
= 0;
648 function rollback( $fname = '' ) {
649 if ( $this->mTrxLevel
== 0 ) {
652 $this->mConn
->rollBack();
653 $this->mTrxLevel
= 0;
661 function limitResultForUpdate( $sql, $num ) {
662 return $this->limitResult( $sql, $num );
669 function strencode( $s ) {
670 return substr( $this->addQuotes( $s ), 1, - 1 );
677 function encodeBlob( $b ) {
678 return new Blob( $b );
682 * @param $b Blob|string
685 function decodeBlob( $b ) {
686 if ( $b instanceof Blob
) {
693 * @param $s Blob|string
696 function addQuotes( $s ) {
697 if ( $s instanceof Blob
) {
698 return "x'" . bin2hex( $s->fetch() ) . "'";
700 return $this->mConn
->quote( $s );
707 function buildLike() {
708 $params = func_get_args();
709 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
710 $params = $params[0];
712 return parent
::buildLike( $params ) . "ESCAPE '\' ";
718 public function getSearchEngine() {
719 return "SearchSqlite";
723 * No-op version of deadlockLoop
726 public function deadlockLoop( /*...*/ ) {
727 $args = func_get_args();
728 $function = array_shift( $args );
729 return call_user_func_array( $function, $args );
736 protected function replaceVars( $s ) {
737 $s = parent
::replaceVars( $s );
738 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
739 // CREATE TABLE hacks to allow schema file sharing with MySQL
741 // binary/varbinary column type -> blob
742 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
743 // no such thing as unsigned
744 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
746 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
747 // floating point types -> REAL
748 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
750 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
751 // TEXT normalization
752 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
753 // BLOB normalization
754 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
756 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
758 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
760 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
761 // binary collation type -> nothing
762 $s = preg_replace( '/\bbinary\b/i', '', $s );
763 // auto_increment -> autoincrement
764 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
765 // No explicit options
766 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
767 // AUTOINCREMENT should immedidately follow PRIMARY KEY
768 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
769 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
770 // No truncated indexes
771 $s = preg_replace( '/\(\d+\)/', '', $s );
773 $s = preg_replace( '/\bfulltext\b/i', '', $s );
779 * Build a concatenation list to feed into a SQL query
781 * @param $stringList array
785 function buildConcat( $stringList ) {
786 return '(' . implode( ') || (', $stringList ) . ')';
790 * @throws MWException
793 * @param $temporary bool
794 * @param $fname string
795 * @return bool|ResultWrapper
797 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
798 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
799 $obj = $this->fetchObject( $res );
801 throw new MWException( "Couldn't retrieve structure for table $oldName" );
804 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
806 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
807 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
809 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
812 return $this->query( $sql, $fname );
817 * List all tables on the database
819 * @param $prefix string Only show tables with this prefix, e.g. mw_
820 * @param $fname String: calling function name
824 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
825 $result = $this->select(
833 foreach( $result as $table ) {
834 $vars = get_object_vars($table);
835 $table = array_pop( $vars );
837 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
838 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
839 $endArray[] = $table;
848 } // end DatabaseSqlite class
851 * This class allows simple acccess to a SQLite database independently from main database settings
854 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
855 public function __construct( $fileName, $flags = 0 ) {
856 $this->mFlags
= $flags;
857 $this->tablePrefix( null );
858 $this->openFile( $fileName );
865 class SQLiteField
implements Field
{
866 private $info, $tableName;
867 function __construct( $info, $tableName ) {
869 $this->tableName
= $tableName;
873 return $this->info
->name
;
876 function tableName() {
877 return $this->tableName
;
880 function defaultValue() {
881 if ( is_string( $this->info
->dflt_value
) ) {
883 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
884 return str_replace( "''", "'", $this->info
->dflt_value
);
887 return $this->info
->dflt_value
;
893 function isNullable() {
894 return !$this->info
->notnull
;
898 return $this->info
->type
;