3 * This script is the SQLite database abstraction layer
5 * See maintenance/sqlite/README for development notes and other specific information
13 class DatabaseSqlite
extends DatabaseBase
{
22 * Parameters $server, $user and $password are not used.
24 function __construct( $server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0 ) {
25 $this->mFailFunction
= $failFunction;
26 $this->mFlags
= $flags;
27 $this->mName
= $dbName;
28 $this->open( $server, $user, $password, $dbName );
36 * @todo: check if it should be true like parent class
38 function implicitGroupby() { return false; }
40 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
41 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
44 /** Open an SQLite database and return a resource handle to it
45 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
47 function open( $server, $user, $pass, $dbName ) {
48 global $wgSQLiteDataDir;
50 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
51 if ( !is_readable( $fileName ) ) {
52 throw new DBConnectionError( $this, "SQLite database not accessible" ); $this->mConn
= false;
54 $this->openFile( $fileName );
59 * Opens a database file
60 * @return SQL connection or false if failed
62 function openFile( $fileName ) {
63 $this->mDatabaseFile
= $fileName;
65 if ( $this->mFlags
& DBO_PERSISTENT
) {
66 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
67 array( PDO
::ATTR_PERSISTENT
=> true ) );
69 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
71 } catch ( PDOException
$e ) {
72 $err = $e->getMessage();
74 if ( $this->mConn
=== false ) {
75 wfDebug( "DB connection error: $err\n" );
76 if ( !$this->mFailFunction
) {
77 throw new DBConnectionError( $this, $err );
83 $this->mOpened
= $this->mConn
;
84 # set error codes only, don't raise exceptions
85 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
89 * Close an SQLite database
92 $this->mOpened
= false;
93 if ( is_object( $this->mConn
) ) {
94 if ( $this->trxLevel() ) $this->commit();
101 * Generates a database file name. Explicitly public for installer.
102 * @param $dir String: Directory where database resides
103 * @param $dbName String: Database name
106 public static function generateFileName( $dir, $dbName ) {
107 return "$dir/$dbName.sqlite";
111 * Returns version of currently supported SQLite fulltext search module or false if none present.
114 function getFulltextSearchModule() {
115 $table = 'dummy_search_test';
116 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
117 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
118 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
125 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
127 function doQuery( $sql ) {
128 $res = $this->mConn
->query( $sql );
129 if ( $res === false ) {
132 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
133 $this->mAffectedRows
= $r->rowCount();
134 $res = new ResultWrapper( $this, $r->fetchAll() );
139 function freeResult( $res ) {
140 if ( $res instanceof ResultWrapper
)
146 function fetchObject( $res ) {
147 if ( $res instanceof ResultWrapper
)
152 $cur = current( $r );
153 if ( is_array( $cur ) ) {
156 foreach ( $cur as $k => $v )
157 if ( !is_numeric( $k ) )
165 function fetchRow( $res ) {
166 if ( $res instanceof ResultWrapper
)
171 $cur = current( $r );
172 if ( is_array( $cur ) ) {
180 * The PDO::Statement class implements the array interface so count() will work
182 function numRows( $res ) {
183 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
187 function numFields( $res ) {
188 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
189 return is_array( $r ) ?
count( $r[0] ) : 0;
192 function fieldName( $res, $n ) {
193 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
194 if ( is_array( $r ) ) {
195 $keys = array_keys( $r[0] );
202 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
204 function tableName( $name ) {
205 return str_replace( '`', '', parent
::tableName( $name ) );
209 * Index names have DB scope
211 function indexName( $index ) {
216 * This must be called after nextSequenceVal
218 function insertId() {
219 return $this->mConn
->lastInsertId();
222 function dataSeek( $res, $row ) {
223 if ( $res instanceof ResultWrapper
)
229 for ( $i = 0; $i < $row; $i++
)
233 function lastError() {
234 if ( !is_object( $this->mConn
) )
235 return "Cannot return last error, no db connection";
236 $e = $this->mConn
->errorInfo();
237 return isset( $e[2] ) ?
$e[2] : '';
240 function lastErrno() {
241 if ( !is_object( $this->mConn
) ) {
242 return "Cannot return last error, no db connection";
244 $info = $this->mConn
->errorInfo();
249 function affectedRows() {
250 return $this->mAffectedRows
;
254 * Returns information about an index
255 * Returns false if the index does not exist
256 * - if errors are explicitly ignored, returns NULL on failure
258 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
259 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
260 $res = $this->query( $sql, $fname );
264 if ( $res->numRows() == 0 ) {
268 foreach ( $res as $row ) {
269 $info[] = $row->name
;
274 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
275 $row = $this->selectRow( 'sqlite_master', '*',
278 'name' => $this->indexName( $index ),
280 if ( !$row ||
!isset( $row->sql
) ) {
284 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
285 $indexPos = strpos( $row->sql
, 'INDEX' );
286 if ( $indexPos === false ) {
289 $firstPart = substr( $row->sql
, 0, $indexPos );
290 $options = explode( ' ', $firstPart );
291 return in_array( 'UNIQUE', $options );
295 * Filter the options used in SELECT statements
297 function makeSelectOptions( $options ) {
298 foreach ( $options as $k => $v )
299 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
301 return parent
::makeSelectOptions( $options );
305 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
307 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
308 if ( !count( $a ) ) return true;
309 if ( !is_array( $options ) ) $options = array( $options );
311 # SQLite uses OR IGNORE not just IGNORE
312 foreach ( $options as $k => $v )
313 if ( $v == 'IGNORE' )
314 $options[$k] = 'OR IGNORE';
316 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
317 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
319 foreach ( $a as $k => $v )
320 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
323 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
329 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
330 if ( !count( $rows ) ) return true;
332 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
333 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
335 foreach ( $rows as $k => $v )
336 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
339 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
346 * Returns the size of a text field, or -1 for "unlimited"
347 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
349 function textFieldSize( $table, $field ) {
353 function unionSupportsOrderAndLimit() {
357 function unionQueries( $sqls, $all ) {
358 $glue = $all ?
' UNION ALL ' : ' UNION ';
359 return implode( $glue, $sqls );
362 function wasDeadlock() {
363 return $this->lastErrno() == 5; // SQLITE_BUSY
366 function wasErrorReissuable() {
367 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
370 function wasReadOnlyError() {
371 return $this->lastErrno() == 8; // SQLITE_READONLY;
375 * @return string wikitext of a link to the server software's web site
377 function getSoftwareLink() {
378 return "[http://sqlite.org/ SQLite]";
382 * @return string Version information from the database
384 function getServerVersion() {
385 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
390 * Query whether a given column exists in the mediawiki schema
392 function fieldExists( $table, $field, $fname = '' ) {
393 $info = $this->fieldInfo( $table, $field );
398 * Get information about a given field
399 * Returns false if the field does not exist.
401 function fieldInfo( $table, $field ) {
402 $tableName = $this->tableName( $table );
403 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
404 $res = $this->query( $sql, __METHOD__
);
405 foreach ( $res as $row ) {
406 if ( $row->name
== $field ) {
407 return new SQLiteField( $row, $tableName );
413 function begin( $fname = '' ) {
414 if ( $this->mTrxLevel
== 1 ) $this->commit();
415 $this->mConn
->beginTransaction();
416 $this->mTrxLevel
= 1;
419 function commit( $fname = '' ) {
420 if ( $this->mTrxLevel
== 0 ) return;
421 $this->mConn
->commit();
422 $this->mTrxLevel
= 0;
425 function rollback( $fname = '' ) {
426 if ( $this->mTrxLevel
== 0 ) return;
427 $this->mConn
->rollBack();
428 $this->mTrxLevel
= 0;
431 function limitResultForUpdate( $sql, $num ) {
432 return $this->limitResult( $sql, $num );
435 function strencode( $s ) {
436 return substr( $this->addQuotes( $s ), 1, - 1 );
439 function encodeBlob( $b ) {
440 return new Blob( $b );
443 function decodeBlob( $b ) {
444 if ( $b instanceof Blob
) {
450 function addQuotes( $s ) {
451 if ( $s instanceof Blob
) {
452 return "x'" . bin2hex( $s->fetch() ) . "'";
454 return $this->mConn
->quote( $s );
458 function quote_ident( $s ) {
462 function buildLike() {
463 $params = func_get_args();
464 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
465 $params = $params[0];
467 return parent
::buildLike( $params ) . "ESCAPE '\' ";
471 * How lagged is this slave?
473 public function getLag() {
478 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
479 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
481 public function setup_database() {
484 # Process common MySQL/SQLite table definitions
485 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
486 if ( $err !== true ) {
487 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
491 # Use DatabasePostgres's code to populate interwiki from MySQL template
492 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
493 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
494 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
495 while ( !feof( $f ) ) {
496 $line = fgets( $f, 1024 );
498 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
499 $this->query( "$sql $matches[1],$matches[2])" );
503 public function getSearchEngine() {
504 return "SearchSqlite";
508 * No-op version of deadlockLoop
510 public function deadlockLoop( /*...*/ ) {
511 $args = func_get_args();
512 $function = array_shift( $args );
513 return call_user_func_array( $function, $args );
516 protected function replaceVars( $s ) {
517 $s = parent
::replaceVars( $s );
518 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
519 // CREATE TABLE hacks to allow schema file sharing with MySQL
521 // binary/varbinary column type -> blob
522 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
523 // no such thing as unsigned
524 $s = preg_replace( '/\bunsigned\b/i', '', $s );
525 // INT -> INTEGER for primary keys
526 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
528 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
529 // binary collation type -> nothing
530 $s = preg_replace( '/\bbinary\b/i', '', $s );
531 // auto_increment -> autoincrement
532 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
533 // No explicit options
534 $s = preg_replace( '/\)[^)]*$/', ')', $s );
535 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
536 // No truncated indexes
537 $s = preg_replace( '/\(\d+\)/', '', $s );
539 $s = preg_replace( '/\bfulltext\b/i', '', $s );
545 * Build a concatenation list to feed into a SQL query
547 function buildConcat( $stringList ) {
548 return '(' . implode( ') || (', $stringList ) . ')';
551 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
552 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
553 $sql = $this->fetchObject( $res )->sql
;
554 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
555 return $this->query( $sql, $fname );
558 } // end DatabaseSqlite class
561 * This class allows simple acccess to a SQLite database independently from main database settings
564 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
565 public function __construct( $fileName, $flags = 0 ) {
566 $this->mFlags
= $flags;
567 $this->openFile( $fileName );
575 private $info, $tableName;
576 function __construct( $info, $tableName ) {
578 $this->tableName
= $tableName;
582 return $this->info
->name
;
585 function tableName() {
586 return $this->tableName
;
589 function defaultValue() {
590 if ( is_string( $this->info
->dflt_value
) ) {
592 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
593 return str_replace( "''", "'", $this->info
->dflt_value
);
596 return $this->info
->dflt_value
;
599 function maxLength() {
603 function nullable() {
604 // SQLite dynamic types are always nullable
608 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
609 # Suggest removal from base class [TS]
612 return $this->info
->type
;