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 ) ) {
68 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
)
206 function fetchObject( $res ) {
207 if ( $res instanceof ResultWrapper
)
212 $cur = current( $r );
213 if ( is_array( $cur ) ) {
216 foreach ( $cur as $k => $v )
217 if ( !is_numeric( $k ) )
225 function fetchRow( $res ) {
226 if ( $res instanceof ResultWrapper
)
231 $cur = current( $r );
232 if ( is_array( $cur ) ) {
240 * The PDO::Statement class implements the array interface so count() will work
242 function numRows( $res ) {
243 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
247 function numFields( $res ) {
248 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
249 return is_array( $r ) ?
count( $r[0] ) : 0;
252 function fieldName( $res, $n ) {
253 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
254 if ( is_array( $r ) ) {
255 $keys = array_keys( $r[0] );
262 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
264 function tableName( $name ) {
265 return str_replace( '`', '', parent
::tableName( $name ) );
269 * Index names have DB scope
271 function indexName( $index ) {
276 * This must be called after nextSequenceVal
278 function insertId() {
279 return $this->mConn
->lastInsertId();
282 function dataSeek( $res, $row ) {
283 if ( $res instanceof ResultWrapper
)
289 for ( $i = 0; $i < $row; $i++
)
293 function lastError() {
294 if ( !is_object( $this->mConn
) )
295 return "Cannot return last error, no db connection";
296 $e = $this->mConn
->errorInfo();
297 return isset( $e[2] ) ?
$e[2] : '';
300 function lastErrno() {
301 if ( !is_object( $this->mConn
) ) {
302 return "Cannot return last error, no db connection";
304 $info = $this->mConn
->errorInfo();
309 function affectedRows() {
310 return $this->mAffectedRows
;
314 * Returns information about an index
315 * Returns false if the index does not exist
316 * - if errors are explicitly ignored, returns NULL on failure
318 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
319 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
320 $res = $this->query( $sql, $fname );
324 if ( $res->numRows() == 0 ) {
328 foreach ( $res as $row ) {
329 $info[] = $row->name
;
334 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
335 $row = $this->selectRow( 'sqlite_master', '*',
338 'name' => $this->indexName( $index ),
340 if ( !$row ||
!isset( $row->sql
) ) {
344 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
345 $indexPos = strpos( $row->sql
, 'INDEX' );
346 if ( $indexPos === false ) {
349 $firstPart = substr( $row->sql
, 0, $indexPos );
350 $options = explode( ' ', $firstPart );
351 return in_array( 'UNIQUE', $options );
355 * Filter the options used in SELECT statements
357 function makeSelectOptions( $options ) {
358 foreach ( $options as $k => $v )
359 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
361 return parent
::makeSelectOptions( $options );
365 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
367 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
368 if ( !count( $a ) ) return true;
369 if ( !is_array( $options ) ) $options = array( $options );
371 # SQLite uses OR IGNORE not just IGNORE
372 foreach ( $options as $k => $v )
373 if ( $v == 'IGNORE' )
374 $options[$k] = 'OR IGNORE';
376 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
377 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
379 foreach ( $a as $k => $v )
380 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
383 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
389 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
390 if ( !count( $rows ) ) return true;
392 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
393 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
395 foreach ( $rows as $k => $v )
396 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
399 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
406 * Returns the size of a text field, or -1 for "unlimited"
407 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
409 function textFieldSize( $table, $field ) {
413 function unionSupportsOrderAndLimit() {
417 function unionQueries( $sqls, $all ) {
418 $glue = $all ?
' UNION ALL ' : ' UNION ';
419 return implode( $glue, $sqls );
422 function wasDeadlock() {
423 return $this->lastErrno() == 5; // SQLITE_BUSY
426 function wasErrorReissuable() {
427 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
430 function wasReadOnlyError() {
431 return $this->lastErrno() == 8; // SQLITE_READONLY;
435 * @return string wikitext of a link to the server software's web site
437 function getSoftwareLink() {
438 return "[http://sqlite.org/ SQLite]";
442 * @return string Version information from the database
444 function getServerVersion() {
445 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
450 * Get information about a given field
451 * Returns false if the field does not exist.
453 function fieldInfo( $table, $field ) {
454 $tableName = $this->tableName( $table );
455 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
456 $res = $this->query( $sql, __METHOD__
);
457 foreach ( $res as $row ) {
458 if ( $row->name
== $field ) {
459 return new SQLiteField( $row, $tableName );
465 function begin( $fname = '' ) {
466 if ( $this->mTrxLevel
== 1 ) $this->commit();
467 $this->mConn
->beginTransaction();
468 $this->mTrxLevel
= 1;
471 function commit( $fname = '' ) {
472 if ( $this->mTrxLevel
== 0 ) return;
473 $this->mConn
->commit();
474 $this->mTrxLevel
= 0;
477 function rollback( $fname = '' ) {
478 if ( $this->mTrxLevel
== 0 ) return;
479 $this->mConn
->rollBack();
480 $this->mTrxLevel
= 0;
483 function limitResultForUpdate( $sql, $num ) {
484 return $this->limitResult( $sql, $num );
487 function strencode( $s ) {
488 return substr( $this->addQuotes( $s ), 1, - 1 );
491 function encodeBlob( $b ) {
492 return new Blob( $b );
495 function decodeBlob( $b ) {
496 if ( $b instanceof Blob
) {
502 function addQuotes( $s ) {
503 if ( $s instanceof Blob
) {
504 return "x'" . bin2hex( $s->fetch() ) . "'";
506 return $this->mConn
->quote( $s );
510 function quote_ident( $s ) {
514 function buildLike() {
515 $params = func_get_args();
516 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
517 $params = $params[0];
519 return parent
::buildLike( $params ) . "ESCAPE '\' ";
523 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
524 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
526 public function setup_database() {
529 # Process common MySQL/SQLite table definitions
530 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
531 if ( $err !== true ) {
532 echo " <b>FAILED</b></li>";
533 dieout( htmlspecialchars( $err ) );
537 # Use DatabasePostgres's code to populate interwiki from MySQL template
538 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
540 dieout( "Could not find the interwiki.sql file." );
543 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
544 while ( !feof( $f ) ) {
545 $line = fgets( $f, 1024 );
547 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
548 $this->query( "$sql $matches[1],$matches[2])" );
552 public function getSearchEngine() {
553 return "SearchSqlite";
557 * No-op version of deadlockLoop
559 public function deadlockLoop( /*...*/ ) {
560 $args = func_get_args();
561 $function = array_shift( $args );
562 return call_user_func_array( $function, $args );
565 protected function replaceVars( $s ) {
566 $s = parent
::replaceVars( $s );
567 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
568 // CREATE TABLE hacks to allow schema file sharing with MySQL
570 // binary/varbinary column type -> blob
571 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
572 // no such thing as unsigned
573 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
575 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\([\s\d]*\)|\b)/i', 'INTEGER', $s );
577 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
578 // TEXT normalization
579 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
580 // BLOB normalization
581 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
583 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
585 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
587 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
588 // binary collation type -> nothing
589 $s = preg_replace( '/\bbinary\b/i', '', $s );
590 // auto_increment -> autoincrement
591 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
592 // No explicit options
593 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
594 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
595 // No truncated indexes
596 $s = preg_replace( '/\(\d+\)/', '', $s );
598 $s = preg_replace( '/\bfulltext\b/i', '', $s );
604 * Build a concatenation list to feed into a SQL query
606 function buildConcat( $stringList ) {
607 return '(' . implode( ') || (', $stringList ) . ')';
610 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
611 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
612 $obj = $this->fetchObject( $res );
614 throw new MWException( "Couldn't retrieve structure for table $oldName" );
617 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
618 return $this->query( $sql, $fname );
621 } // end DatabaseSqlite class
624 * This class allows simple acccess to a SQLite database independently from main database settings
627 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
628 public function __construct( $fileName, $flags = 0 ) {
629 $this->mFlags
= $flags;
630 $this->openFile( $fileName );
638 private $info, $tableName;
639 function __construct( $info, $tableName ) {
641 $this->tableName
= $tableName;
645 return $this->info
->name
;
648 function tableName() {
649 return $this->tableName
;
652 function defaultValue() {
653 if ( is_string( $this->info
->dflt_value
) ) {
655 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
656 return str_replace( "''", "'", $this->info
->dflt_value
);
659 return $this->info
->dflt_value
;
662 function maxLength() {
666 function nullable() {
667 // SQLite dynamic types are always nullable
671 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
672 # Suggest removal from base class [TS]
675 return $this->info
->type
;