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 global $wgSQLiteDataDir;
26 $this->mFailFunction
= $failFunction;
27 $this->mFlags
= $flags;
28 $this->mDatabaseFile
= self
::generateFileName( $wgSQLiteDataDir, $dbName );
29 if( !is_readable( $this->mDatabaseFile
) )
30 throw new DBConnectionError( $this, "SQLite database not accessible" );
31 $this->mName
= $dbName;
32 $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 ) {
50 $file = $this->mDatabaseFile
;
52 if ( $this->mFlags
& DBO_PERSISTENT
) {
53 $this->mConn
= new PDO( "sqlite:$file", $user, $pass,
54 array( PDO
::ATTR_PERSISTENT
=> true ) );
56 $this->mConn
= new PDO( "sqlite:$file", $user, $pass );
58 } catch ( PDOException
$e ) {
59 $err = $e->getMessage();
61 if ( $this->mConn
=== false ) {
62 wfDebug( "DB connection error: $err\n" );
63 if ( !$this->mFailFunction
) {
64 throw new DBConnectionError( $this, $err );
70 $this->mOpened
= $this->mConn
;
71 # set error codes only, don't raise exceptions
72 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
78 * Close an SQLite database
81 $this->mOpened
= false;
82 if ( is_object( $this->mConn
) ) {
83 if ( $this->trxLevel() ) $this->commit();
90 * Generates a database file name. Explicitly public for installer.
91 * @param $dir String: Directory where database resides
92 * @param $dbName String: Database name
95 public static function generateFileName( $dir, $dbName ) {
96 return "$dir/$dbName.sqlite";
100 * Returns version of currently supported SQLite fulltext search module or false if none present.
103 function getFulltextSearchModule() {
104 $table = 'dummy_search_test';
105 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
106 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
107 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
114 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
116 function doQuery( $sql ) {
117 $res = $this->mConn
->query( $sql );
118 if ( $res === false ) {
121 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
122 $this->mAffectedRows
= $r->rowCount();
123 $res = new ResultWrapper( $this, $r->fetchAll() );
128 function freeResult( $res ) {
129 if ( $res instanceof ResultWrapper
)
135 function fetchObject($res) {
136 if ($res instanceof ResultWrapper
)
141 $cur = current( $r );
142 if ( is_array( $cur ) ) {
145 foreach ( $cur as $k => $v )
146 if ( !is_numeric( $k ) )
154 function fetchRow($res) {
155 if ( $res instanceof ResultWrapper
)
161 if (is_array($cur)) {
169 * The PDO::Statement class implements the array interface so count() will work
171 function numRows( $res ) {
172 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
176 function numFields( $res ) {
177 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
178 return is_array( $r ) ?
count( $r[0] ) : 0;
181 function fieldName( $res, $n ) {
182 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
183 if ( is_array( $r ) ) {
184 $keys = array_keys( $r[0] );
191 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
193 function tableName( $name ) {
194 return str_replace( '`', '', parent
::tableName( $name ) );
198 * Index names have DB scope
200 function indexName( $index ) {
205 * This must be called after nextSequenceVal
207 function insertId() {
208 return $this->mConn
->lastInsertId();
211 function dataSeek( $res, $row ) {
212 if ( $res instanceof ResultWrapper
)
218 for ( $i = 0; $i < $row; $i++
)
222 function lastError() {
223 if ( !is_object( $this->mConn
) )
224 return "Cannot return last error, no db connection";
225 $e = $this->mConn
->errorInfo();
226 return isset( $e[2] ) ?
$e[2] : '';
229 function lastErrno() {
230 if ( !is_object( $this->mConn
) ) {
231 return "Cannot return last error, no db connection";
233 $info = $this->mConn
->errorInfo();
238 function affectedRows() {
239 return $this->mAffectedRows
;
243 * Returns information about an index
244 * Returns false if the index does not exist
245 * - if errors are explicitly ignored, returns NULL on failure
247 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
248 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
249 $res = $this->query( $sql, $fname );
253 if ( $res->numRows() == 0 ) {
257 foreach ( $res as $row ) {
258 $info[] = $row->name
;
263 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
264 $row = $this->selectRow( 'sqlite_master', '*',
267 'name' => $this->indexName( $index ),
269 if ( !$row ||
!isset( $row->sql
) ) {
273 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
274 $indexPos = strpos( $row->sql
, 'INDEX' );
275 if ( $indexPos === false ) {
278 $firstPart = substr( $row->sql
, 0, $indexPos );
279 $options = explode( ' ', $firstPart );
280 return in_array( 'UNIQUE', $options );
284 * Filter the options used in SELECT statements
286 function makeSelectOptions( $options ) {
287 foreach ( $options as $k => $v )
288 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
290 return parent
::makeSelectOptions( $options );
294 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
296 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
297 if ( !count( $a ) ) return true;
298 if ( !is_array( $options ) ) $options = array( $options );
300 # SQLite uses OR IGNORE not just IGNORE
301 foreach ( $options as $k => $v )
302 if ( $v == 'IGNORE' )
303 $options[$k] = 'OR IGNORE';
305 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
306 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
308 foreach ( $a as $k => $v )
309 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
312 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
319 * Returns the size of a text field, or -1 for "unlimited"
320 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
322 function textFieldSize( $table, $field ) {
326 function unionSupportsOrderAndLimit() {
330 function unionQueries( $sqls, $all ) {
331 $glue = $all ?
' UNION ALL ' : ' UNION ';
332 return implode( $glue, $sqls );
335 function wasDeadlock() {
336 return $this->lastErrno() == 5; // SQLITE_BUSY
339 function wasErrorReissuable() {
340 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
343 function wasReadOnlyError() {
344 return $this->lastErrno() == 8; // SQLITE_READONLY;
348 * @return string wikitext of a link to the server software's web site
350 function getSoftwareLink() {
351 return "[http://sqlite.org/ SQLite]";
355 * @return string Version information from the database
357 function getServerVersion() {
358 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
363 * Query whether a given column exists in the mediawiki schema
365 function fieldExists( $table, $field, $fname = '' ) {
366 $info = $this->fieldInfo( $table, $field );
371 * Get information about a given field
372 * Returns false if the field does not exist.
374 function fieldInfo( $table, $field ) {
375 $tableName = $this->tableName( $table );
376 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
377 $res = $this->query( $sql, __METHOD__
);
378 foreach ( $res as $row ) {
379 if ( $row->name
== $field ) {
380 return new SQLiteField( $row, $tableName );
386 function begin( $fname = '' ) {
387 if ( $this->mTrxLevel
== 1 ) $this->commit();
388 $this->mConn
->beginTransaction();
389 $this->mTrxLevel
= 1;
392 function commit( $fname = '' ) {
393 if ( $this->mTrxLevel
== 0 ) return;
394 $this->mConn
->commit();
395 $this->mTrxLevel
= 0;
398 function rollback( $fname = '' ) {
399 if ( $this->mTrxLevel
== 0 ) return;
400 $this->mConn
->rollBack();
401 $this->mTrxLevel
= 0;
404 function limitResultForUpdate( $sql, $num ) {
405 return $this->limitResult( $sql, $num );
408 function strencode( $s ) {
409 return substr( $this->addQuotes( $s ), 1, - 1 );
412 function encodeBlob( $b ) {
413 return new Blob( $b );
416 function decodeBlob( $b ) {
417 if ( $b instanceof Blob
) {
423 function addQuotes( $s ) {
424 if ( $s instanceof Blob
) {
425 return "x'" . bin2hex( $s->fetch() ) . "'";
427 return $this->mConn
->quote( $s );
431 function quote_ident( $s ) {
435 function buildLike() {
436 $params = func_get_args();
437 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
438 $params = $params[0];
440 return parent
::buildLike( $params ) . "ESCAPE '\' ";
444 * How lagged is this slave?
446 public function getLag() {
451 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
452 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
454 public function setup_database() {
457 # Process common MySQL/SQLite table definitions
458 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
459 if ( $err !== true ) {
460 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
464 # Use DatabasePostgres's code to populate interwiki from MySQL template
465 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
466 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
467 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
468 while ( !feof( $f ) ) {
469 $line = fgets( $f, 1024 );
471 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
472 $this->query( "$sql $matches[1],$matches[2])" );
476 public function getSearchEngine() {
477 return "SearchSqlite";
481 * No-op version of deadlockLoop
483 public function deadlockLoop( /*...*/ ) {
484 $args = func_get_args();
485 $function = array_shift( $args );
486 return call_user_func_array( $function, $args );
489 protected function replaceVars( $s ) {
490 $s = parent
::replaceVars( $s );
491 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
492 // CREATE TABLE hacks to allow schema file sharing with MySQL
494 // binary/varbinary column type -> blob
495 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
496 // no such thing as unsigned
497 $s = preg_replace( '/\bunsigned\b/i', '', $s );
498 // INT -> INTEGER for primary keys
499 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
501 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
502 // binary collation type -> nothing
503 $s = preg_replace( '/\bbinary\b/i', '', $s );
504 // auto_increment -> autoincrement
505 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
506 // No explicit options
507 $s = preg_replace( '/\)[^)]*$/', ')', $s );
508 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
509 // No truncated indexes
510 $s = preg_replace( '/\(\d+\)/', '', $s );
512 $s = preg_replace( '/\bfulltext\b/i', '', $s );
518 * Build a concatenation list to feed into a SQL query
520 function buildConcat( $stringList ) {
521 return '(' . implode( ') || (', $stringList ) . ')';
524 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
525 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
526 $sql = $this->fetchObject( $res )->sql
;
527 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
528 return $this->query( $sql, $fname );
531 } // end DatabaseSqlite class
537 private $info, $tableName;
538 function __construct( $info, $tableName ) {
540 $this->tableName
= $tableName;
544 return $this->info
->name
;
547 function tableName() {
548 return $this->tableName
;
551 function defaultValue() {
552 if ( is_string( $this->info
->dflt_value
) ) {
554 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
555 return str_replace( "''", "'", $this->info
->dflt_value
);
558 return $this->info
->dflt_value
;
561 function maxLength() {
565 function nullable() {
566 // SQLite dynamic types are always nullable
570 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
571 # Suggest removal from base class [TS]
574 return $this->info
->type
;