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->mFailFunction
= $failFunction;
29 $this->mFlags
= $flags;
30 $this->mName
= $dbName;
32 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
33 $this->attachDatabase( $wgSharedDB );
38 * Serialization handler, see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep
39 * for details. Instances of this class sometimes get serialized, e.g. with Title and its BacklinkCache
40 * Because attempts to serialize mConn end in "can't serialize PDO objects" exceptions, we simply disallow
41 * to serialize anything in this class.
52 * @todo: check if it should be true like parent class
54 function implicitGroupby() { return false; }
56 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
57 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
60 /** Open an SQLite database and return a resource handle to it
61 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
63 function open( $server, $user, $pass, $dbName ) {
64 global $wgSQLiteDataDir;
66 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
67 if ( !is_readable( $fileName ) ) {
69 throw new DBConnectionError( $this, "SQLite database not accessible" );
71 $this->openFile( $fileName );
76 * Opens a database file
77 * @return SQL connection or false if failed
79 function openFile( $fileName ) {
80 $this->mDatabaseFile
= $fileName;
82 if ( $this->mFlags
& DBO_PERSISTENT
) {
83 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
84 array( PDO
::ATTR_PERSISTENT
=> true ) );
86 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
88 } catch ( PDOException
$e ) {
89 $err = $e->getMessage();
91 if ( $this->mConn
=== false ) {
92 wfDebug( "DB connection error: $err\n" );
93 if ( !$this->mFailFunction
) {
94 throw new DBConnectionError( $this, $err );
100 $this->mOpened
= !!$this->mConn
;
101 # set error codes only, don't raise exceptions
102 if ( $this->mOpened
) {
103 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
109 * Close an SQLite database
112 $this->mOpened
= false;
113 if ( is_object( $this->mConn
) ) {
114 if ( $this->trxLevel() ) $this->commit();
121 * Generates a database file name. Explicitly public for installer.
122 * @param $dir String: Directory where database resides
123 * @param $dbName String: Database name
126 public static function generateFileName( $dir, $dbName ) {
127 return "$dir/$dbName.sqlite";
131 * Check if the searchindext table is FTS enabled.
132 * @returns false if not enabled.
134 function checkForEnabledSearch() {
135 if ( self
::$fulltextEnabled === null ) {
136 self
::$fulltextEnabled = false;
137 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = 'searchindex'", __METHOD__
);
139 $row = $res->fetchRow();
140 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
143 return self
::$fulltextEnabled;
147 * Returns version of currently supported SQLite fulltext search module or false if none present.
150 function getFulltextSearchModule() {
151 $table = 'dummy_search_test';
152 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
154 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
155 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
162 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
164 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
165 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
166 * @param $fname String: calling function name
168 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
169 global $wgSQLiteDataDir;
171 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
173 $file = $this->addQuotes( $file );
174 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
178 * @see DatabaseBase::isWriteQuery()
180 function isWriteQuery( $sql ) {
181 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
185 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
187 function doQuery( $sql ) {
188 $res = $this->mConn
->query( $sql );
189 if ( $res === false ) {
192 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
193 $this->mAffectedRows
= $r->rowCount();
194 $res = new ResultWrapper( $this, $r->fetchAll() );
199 function freeResult( $res ) {
200 if ( $res instanceof ResultWrapper
) {
207 function fetchObject( $res ) {
208 if ( $res instanceof ResultWrapper
) {
214 $cur = current( $r );
215 if ( is_array( $cur ) ) {
218 foreach ( $cur as $k => $v ) {
219 if ( !is_numeric( $k ) ) {
229 function fetchRow( $res ) {
230 if ( $res instanceof ResultWrapper
) {
235 $cur = current( $r );
236 if ( is_array( $cur ) ) {
244 * The PDO::Statement class implements the array interface so count() will work
246 function numRows( $res ) {
247 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
251 function numFields( $res ) {
252 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
253 return is_array( $r ) ?
count( $r[0] ) : 0;
256 function fieldName( $res, $n ) {
257 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
258 if ( is_array( $r ) ) {
259 $keys = array_keys( $r[0] );
266 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
268 function tableName( $name ) {
269 // table names starting with sqlite_ are reserved
270 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
271 return str_replace( '`', '', parent
::tableName( $name ) );
275 * Index names have DB scope
277 function indexName( $index ) {
282 * This must be called after nextSequenceVal
284 function insertId() {
285 return $this->mConn
->lastInsertId();
288 function dataSeek( $res, $row ) {
289 if ( $res instanceof ResultWrapper
) {
296 for ( $i = 0; $i < $row; $i++
) {
302 function lastError() {
303 if ( !is_object( $this->mConn
) ) {
304 return "Cannot return last error, no db connection";
306 $e = $this->mConn
->errorInfo();
307 return isset( $e[2] ) ?
$e[2] : '';
310 function lastErrno() {
311 if ( !is_object( $this->mConn
) ) {
312 return "Cannot return last error, no db connection";
314 $info = $this->mConn
->errorInfo();
319 function affectedRows() {
320 return $this->mAffectedRows
;
324 * Returns information about an index
325 * Returns false if the index does not exist
326 * - if errors are explicitly ignored, returns NULL on failure
328 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
329 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
330 $res = $this->query( $sql, $fname );
334 if ( $res->numRows() == 0 ) {
338 foreach ( $res as $row ) {
339 $info[] = $row->name
;
344 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
345 $row = $this->selectRow( 'sqlite_master', '*',
348 'name' => $this->indexName( $index ),
350 if ( !$row ||
!isset( $row->sql
) ) {
354 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
355 $indexPos = strpos( $row->sql
, 'INDEX' );
356 if ( $indexPos === false ) {
359 $firstPart = substr( $row->sql
, 0, $indexPos );
360 $options = explode( ' ', $firstPart );
361 return in_array( 'UNIQUE', $options );
365 * Filter the options used in SELECT statements
367 function makeSelectOptions( $options ) {
368 foreach ( $options as $k => $v ) {
369 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
373 return parent
::makeSelectOptions( $options );
377 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
379 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
380 if ( !count( $a ) ) {
383 if ( !is_array( $options ) ) {
384 $options = array( $options );
387 # SQLite uses OR IGNORE not just IGNORE
388 foreach ( $options as $k => $v ) {
389 if ( $v == 'IGNORE' ) {
390 $options[$k] = 'OR IGNORE';
394 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
395 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
397 foreach ( $a as $k => $v ) {
398 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
403 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
409 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
410 if ( !count( $rows ) ) return true;
412 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
413 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
415 foreach ( $rows as $k => $v ) {
416 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
421 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
428 * Returns the size of a text field, or -1 for "unlimited"
429 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
431 function textFieldSize( $table, $field ) {
435 function unionSupportsOrderAndLimit() {
439 function unionQueries( $sqls, $all ) {
440 $glue = $all ?
' UNION ALL ' : ' UNION ';
441 return implode( $glue, $sqls );
444 function wasDeadlock() {
445 return $this->lastErrno() == 5; // SQLITE_BUSY
448 function wasErrorReissuable() {
449 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
452 function wasReadOnlyError() {
453 return $this->lastErrno() == 8; // SQLITE_READONLY;
457 * @return string wikitext of a link to the server software's web site
459 public static function getSoftwareLink() {
460 return "[http://sqlite.org/ SQLite]";
464 * @return string Version information from the database
466 function getServerVersion() {
467 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
472 * Get information about a given field
473 * Returns false if the field does not exist.
475 function fieldInfo( $table, $field ) {
476 $tableName = $this->tableName( $table );
477 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
478 $res = $this->query( $sql, __METHOD__
);
479 foreach ( $res as $row ) {
480 if ( $row->name
== $field ) {
481 return new SQLiteField( $row, $tableName );
487 function begin( $fname = '' ) {
488 if ( $this->mTrxLevel
== 1 ) $this->commit();
489 $this->mConn
->beginTransaction();
490 $this->mTrxLevel
= 1;
493 function commit( $fname = '' ) {
494 if ( $this->mTrxLevel
== 0 ) return;
495 $this->mConn
->commit();
496 $this->mTrxLevel
= 0;
499 function rollback( $fname = '' ) {
500 if ( $this->mTrxLevel
== 0 ) return;
501 $this->mConn
->rollBack();
502 $this->mTrxLevel
= 0;
505 function limitResultForUpdate( $sql, $num ) {
506 return $this->limitResult( $sql, $num );
509 function strencode( $s ) {
510 return substr( $this->addQuotes( $s ), 1, - 1 );
513 function encodeBlob( $b ) {
514 return new Blob( $b );
517 function decodeBlob( $b ) {
518 if ( $b instanceof Blob
) {
524 function addQuotes( $s ) {
525 if ( $s instanceof Blob
) {
526 return "x'" . bin2hex( $s->fetch() ) . "'";
528 return $this->mConn
->quote( $s );
532 function quote_ident( $s ) {
536 function buildLike() {
537 $params = func_get_args();
538 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
539 $params = $params[0];
541 return parent
::buildLike( $params ) . "ESCAPE '\' ";
545 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
546 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
548 public function setup_database() {
551 # Process common MySQL/SQLite table definitions
552 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
553 if ( $err !== true ) {
554 echo " <b>FAILED</b></li>";
555 dieout( htmlspecialchars( $err ) );
559 # Use DatabasePostgres's code to populate interwiki from MySQL template
560 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
562 dieout( "Could not find the interwiki.sql file." );
565 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local,iw_api,iw_wikiid) VALUES ";
566 while ( !feof( $f ) ) {
567 $line = fgets( $f, 1024 );
569 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
570 $this->query( "$sql $matches[1],$matches[2],'','')" );
574 public function getSearchEngine() {
575 return "SearchSqlite";
579 * No-op version of deadlockLoop
581 public function deadlockLoop( /*...*/ ) {
582 $args = func_get_args();
583 $function = array_shift( $args );
584 return call_user_func_array( $function, $args );
587 protected function replaceVars( $s ) {
588 $s = parent
::replaceVars( $s );
589 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
590 // CREATE TABLE hacks to allow schema file sharing with MySQL
592 // binary/varbinary column type -> blob
593 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
594 // no such thing as unsigned
595 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
597 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\([\s\d]*\)|\b)/i', 'INTEGER', $s );
599 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
600 // TEXT normalization
601 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
602 // BLOB normalization
603 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
605 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
607 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
609 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
610 // binary collation type -> nothing
611 $s = preg_replace( '/\bbinary\b/i', '', $s );
612 // auto_increment -> autoincrement
613 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
614 // No explicit options
615 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
616 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
617 // No truncated indexes
618 $s = preg_replace( '/\(\d+\)/', '', $s );
620 $s = preg_replace( '/\bfulltext\b/i', '', $s );
626 * Build a concatenation list to feed into a SQL query
628 function buildConcat( $stringList ) {
629 return '(' . implode( ') || (', $stringList ) . ')';
632 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
633 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
634 $obj = $this->fetchObject( $res );
636 throw new MWException( "Couldn't retrieve structure for table $oldName" );
639 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
640 return $this->query( $sql, $fname );
643 } // end DatabaseSqlite class
646 * This class allows simple acccess to a SQLite database independently from main database settings
649 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
650 public function __construct( $fileName, $flags = 0 ) {
651 $this->mFlags
= $flags;
652 $this->tablePrefix( null );
653 $this->openFile( $fileName );
661 private $info, $tableName;
662 function __construct( $info, $tableName ) {
664 $this->tableName
= $tableName;
668 return $this->info
->name
;
671 function tableName() {
672 return $this->tableName
;
675 function defaultValue() {
676 if ( is_string( $this->info
->dflt_value
) ) {
678 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
679 return str_replace( "''", "'", $this->info
->dflt_value
);
682 return $this->info
->dflt_value
;
685 function maxLength() {
689 function nullable() {
690 // SQLite dynamic types are always nullable
694 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
695 # Suggest removal from base class [TS]
698 return $this->info
->type
;