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;
24 * Parameters $server, $user and $password are not used.
26 function __construct( $server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0 ) {
28 $this->mFlags
= $flags;
29 $this->mName
= $dbName;
31 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
32 $this->attachDatabase( $wgSharedDB );
41 * @todo: check if it should be true like parent class
43 function implicitGroupby() { return false; }
45 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
46 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
49 /** Open an SQLite database and return a resource handle to it
50 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
52 function open( $server, $user, $pass, $dbName ) {
53 global $wgSQLiteDataDir;
55 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
56 if ( !is_readable( $fileName ) ) {
58 throw new DBConnectionError( $this, "SQLite database not accessible" );
60 $this->openFile( $fileName );
65 * Opens a database file
66 * @return SQL connection or false if failed
68 function openFile( $fileName ) {
69 $this->mDatabaseFile
= $fileName;
71 if ( $this->mFlags
& DBO_PERSISTENT
) {
72 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
73 array( PDO
::ATTR_PERSISTENT
=> true ) );
75 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
77 } catch ( PDOException
$e ) {
78 $err = $e->getMessage();
80 if ( !$this->mConn
) {
81 wfDebug( "DB connection error: $err\n" );
82 throw new DBConnectionError( $this, $err );
84 $this->mOpened
= !!$this->mConn
;
85 # set error codes only, don't raise exceptions
86 if ( $this->mOpened
) {
87 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
93 * Close an SQLite database
96 $this->mOpened
= false;
97 if ( is_object( $this->mConn
) ) {
98 if ( $this->trxLevel() ) $this->commit();
105 * Generates a database file name. Explicitly public for installer.
106 * @param $dir String: Directory where database resides
107 * @param $dbName String: Database name
110 public static function generateFileName( $dir, $dbName ) {
111 return "$dir/$dbName.sqlite";
115 * Check if the searchindext table is FTS enabled.
116 * @returns false if not enabled.
118 function checkForEnabledSearch() {
119 if ( self
::$fulltextEnabled === null ) {
120 self
::$fulltextEnabled = false;
121 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = 'searchindex'", __METHOD__
);
123 $row = $res->fetchRow();
124 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
127 return self
::$fulltextEnabled;
131 * Returns version of currently supported SQLite fulltext search module or false if none present.
134 function getFulltextSearchModule() {
135 static $cachedResult = null;
136 if ( $cachedResult !== null ) {
137 return $cachedResult;
139 $cachedResult = false;
140 $table = 'dummy_search_test';
141 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
143 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
144 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
145 $cachedResult = 'FTS3';
147 return $cachedResult;
151 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
153 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
154 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
155 * @param $fname String: calling function name
157 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
158 global $wgSQLiteDataDir;
160 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
162 $file = $this->addQuotes( $file );
163 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
167 * @see DatabaseBase::isWriteQuery()
169 function isWriteQuery( $sql ) {
170 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
174 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
176 function doQuery( $sql ) {
177 $res = $this->mConn
->query( $sql );
178 if ( $res === false ) {
181 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
182 $this->mAffectedRows
= $r->rowCount();
183 $res = new ResultWrapper( $this, $r->fetchAll() );
188 function freeResult( $res ) {
189 if ( $res instanceof ResultWrapper
) {
196 function fetchObject( $res ) {
197 if ( $res instanceof ResultWrapper
) {
203 $cur = current( $r );
204 if ( is_array( $cur ) ) {
207 foreach ( $cur as $k => $v ) {
208 if ( !is_numeric( $k ) ) {
218 function fetchRow( $res ) {
219 if ( $res instanceof ResultWrapper
) {
224 $cur = current( $r );
225 if ( is_array( $cur ) ) {
233 * The PDO::Statement class implements the array interface so count() will work
235 function numRows( $res ) {
236 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
240 function numFields( $res ) {
241 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
242 return is_array( $r ) ?
count( $r[0] ) : 0;
245 function fieldName( $res, $n ) {
246 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
247 if ( is_array( $r ) ) {
248 $keys = array_keys( $r[0] );
255 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
257 function tableName( $name ) {
258 // table names starting with sqlite_ are reserved
259 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
260 return str_replace( '`', '', parent
::tableName( $name ) );
264 * Index names have DB scope
266 function indexName( $index ) {
271 * This must be called after nextSequenceVal
273 function insertId() {
274 return $this->mConn
->lastInsertId();
277 function dataSeek( $res, $row ) {
278 if ( $res instanceof ResultWrapper
) {
285 for ( $i = 0; $i < $row; $i++
) {
291 function lastError() {
292 if ( !is_object( $this->mConn
) ) {
293 return "Cannot return last error, no db connection";
295 $e = $this->mConn
->errorInfo();
296 return isset( $e[2] ) ?
$e[2] : '';
299 function lastErrno() {
300 if ( !is_object( $this->mConn
) ) {
301 return "Cannot return last error, no db connection";
303 $info = $this->mConn
->errorInfo();
308 function affectedRows() {
309 return $this->mAffectedRows
;
313 * Returns information about an index
314 * Returns false if the index does not exist
315 * - if errors are explicitly ignored, returns NULL on failure
317 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
318 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
319 $res = $this->query( $sql, $fname );
323 if ( $res->numRows() == 0 ) {
327 foreach ( $res as $row ) {
328 $info[] = $row->name
;
333 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
334 $row = $this->selectRow( 'sqlite_master', '*',
337 'name' => $this->indexName( $index ),
339 if ( !$row ||
!isset( $row->sql
) ) {
343 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
344 $indexPos = strpos( $row->sql
, 'INDEX' );
345 if ( $indexPos === false ) {
348 $firstPart = substr( $row->sql
, 0, $indexPos );
349 $options = explode( ' ', $firstPart );
350 return in_array( 'UNIQUE', $options );
354 * Filter the options used in SELECT statements
356 function makeSelectOptions( $options ) {
357 foreach ( $options as $k => $v ) {
358 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
362 return parent
::makeSelectOptions( $options );
366 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
368 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
369 if ( !count( $a ) ) {
372 if ( !is_array( $options ) ) {
373 $options = array( $options );
376 # SQLite uses OR IGNORE not just IGNORE
377 foreach ( $options as $k => $v ) {
378 if ( $v == 'IGNORE' ) {
379 $options[$k] = 'OR IGNORE';
383 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
384 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
386 foreach ( $a as $v ) {
387 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
392 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
398 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
399 if ( !count( $rows ) ) return true;
401 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
402 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
404 foreach ( $rows as $v ) {
405 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
410 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
417 * Returns the size of a text field, or -1 for "unlimited"
418 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
420 function textFieldSize( $table, $field ) {
424 function unionSupportsOrderAndLimit() {
428 function unionQueries( $sqls, $all ) {
429 $glue = $all ?
' UNION ALL ' : ' UNION ';
430 return implode( $glue, $sqls );
433 function wasDeadlock() {
434 return $this->lastErrno() == 5; // SQLITE_BUSY
437 function wasErrorReissuable() {
438 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
441 function wasReadOnlyError() {
442 return $this->lastErrno() == 8; // SQLITE_READONLY;
446 * @return string wikitext of a link to the server software's web site
448 public static function getSoftwareLink() {
449 return "[http://sqlite.org/ SQLite]";
453 * @return string Version information from the database
455 function getServerVersion() {
456 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
461 * @return string User-friendly database information
463 public function getServerInfo() {
464 return wfMsg( $this->getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
468 * Get information about a given field
469 * Returns false if the field does not exist.
471 function fieldInfo( $table, $field ) {
472 $tableName = $this->tableName( $table );
473 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
474 $res = $this->query( $sql, __METHOD__
);
475 foreach ( $res as $row ) {
476 if ( $row->name
== $field ) {
477 return new SQLiteField( $row, $tableName );
483 function begin( $fname = '' ) {
484 if ( $this->mTrxLevel
== 1 ) $this->commit();
485 $this->mConn
->beginTransaction();
486 $this->mTrxLevel
= 1;
489 function commit( $fname = '' ) {
490 if ( $this->mTrxLevel
== 0 ) return;
491 $this->mConn
->commit();
492 $this->mTrxLevel
= 0;
495 function rollback( $fname = '' ) {
496 if ( $this->mTrxLevel
== 0 ) return;
497 $this->mConn
->rollBack();
498 $this->mTrxLevel
= 0;
501 function limitResultForUpdate( $sql, $num ) {
502 return $this->limitResult( $sql, $num );
505 function strencode( $s ) {
506 return substr( $this->addQuotes( $s ), 1, - 1 );
509 function encodeBlob( $b ) {
510 return new Blob( $b );
513 function decodeBlob( $b ) {
514 if ( $b instanceof Blob
) {
520 function addQuotes( $s ) {
521 if ( $s instanceof Blob
) {
522 return "x'" . bin2hex( $s->fetch() ) . "'";
524 return $this->mConn
->quote( $s );
528 function quote_ident( $s ) {
532 function buildLike() {
533 $params = func_get_args();
534 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
535 $params = $params[0];
537 return parent
::buildLike( $params ) . "ESCAPE '\' ";
541 * Called by the installer script
542 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using DatabaseBase::sourceFile()
544 public function setup_database() {
547 # Process common MySQL/SQLite table definitions
548 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
549 if ( $err !== true ) {
550 echo " <b>FAILED</b></li>";
551 dieout( htmlspecialchars( $err ) );
555 # Use DatabasePostgres's code to populate interwiki from MySQL template
556 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
558 dieout( "Could not find the interwiki.sql file." );
561 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local,iw_api,iw_wikiid) VALUES ";
562 while ( !feof( $f ) ) {
563 $line = fgets( $f, 1024 );
565 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
566 $this->query( "$sql $matches[1],$matches[2],'','')" );
570 public function getSearchEngine() {
571 return "SearchSqlite";
575 * No-op version of deadlockLoop
577 public function deadlockLoop( /*...*/ ) {
578 $args = func_get_args();
579 $function = array_shift( $args );
580 return call_user_func_array( $function, $args );
583 protected function replaceVars( $s ) {
584 $s = parent
::replaceVars( $s );
585 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
586 // CREATE TABLE hacks to allow schema file sharing with MySQL
588 // binary/varbinary column type -> blob
589 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
590 // no such thing as unsigned
591 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
593 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
594 // floating point types -> REAL
595 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
597 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
598 // TEXT normalization
599 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
600 // BLOB normalization
601 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
603 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
605 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
607 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
608 // binary collation type -> nothing
609 $s = preg_replace( '/\bbinary\b/i', '', $s );
610 // auto_increment -> autoincrement
611 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
612 // No explicit options
613 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
614 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
615 // No truncated indexes
616 $s = preg_replace( '/\(\d+\)/', '', $s );
618 $s = preg_replace( '/\bfulltext\b/i', '', $s );
624 * Build a concatenation list to feed into a SQL query
626 function buildConcat( $stringList ) {
627 return '(' . implode( ') || (', $stringList ) . ')';
630 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
631 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
632 $obj = $this->fetchObject( $res );
634 throw new MWException( "Couldn't retrieve structure for table $oldName" );
637 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
638 return $this->query( $sql, $fname );
641 } // end DatabaseSqlite class
644 * This class allows simple acccess to a SQLite database independently from main database settings
647 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
648 public function __construct( $fileName, $flags = 0 ) {
649 $this->mFlags
= $flags;
650 $this->tablePrefix( null );
651 $this->openFile( $fileName );
659 private $info, $tableName;
660 function __construct( $info, $tableName ) {
662 $this->tableName
= $tableName;
666 return $this->info
->name
;
669 function tableName() {
670 return $this->tableName
;
673 function defaultValue() {
674 if ( is_string( $this->info
->dflt_value
) ) {
676 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
677 return str_replace( "''", "'", $this->info
->dflt_value
);
680 return $this->info
->dflt_value
;
683 function maxLength() {
687 function nullable() {
688 // SQLite dynamic types are always nullable
692 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
693 # Suggest removal from base class [TS]
696 return $this->info
->type
;