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
{
23 function __construct( $server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0 ) {
24 global $wgSQLiteDataDir;
25 $this->mFailFunction
= $failFunction;
26 $this->mFlags
= $flags;
27 $this->mDatabaseFile
= self
::generateFileName( $wgSQLiteDataDir, $dbName );
28 if( !is_readable( $this->mDatabaseFile
) )
29 throw new DBConnectionError( $this, "SQLite database not accessible" );
30 $this->mName
= $dbName;
31 $this->open( $server, $user, $password, $dbName );
35 * @todo: check if it should be true like parent class
37 function implicitGroupby() { return false; }
39 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
40 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
43 /** Open an SQLite database and return a resource handle to it
44 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
46 function open( $server, $user, $pass, $dbName ) {
49 $file = $this->mDatabaseFile
;
51 if ( $this->mFlags
& DBO_PERSISTENT
) {
52 $this->mConn
= new PDO( "sqlite:$file", $user, $pass,
53 array( PDO
::ATTR_PERSISTENT
=> true ) );
55 $this->mConn
= new PDO( "sqlite:$file", $user, $pass );
57 } catch ( PDOException
$e ) {
58 $err = $e->getMessage();
60 if ( $this->mConn
=== false ) {
61 wfDebug( "DB connection error: $err\n" );
62 if ( !$this->mFailFunction
) {
63 throw new DBConnectionError( $this, $err );
69 $this->mOpened
= $this->mConn
;
70 # set error codes only, don't raise exceptions
71 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
77 * Close an SQLite database
80 $this->mOpened
= false;
81 if ( is_object( $this->mConn
) ) {
82 if ( $this->trxLevel() ) $this->immediateCommit();
89 * Generates a database file name. Explicitly public for installer.
90 * @param $dir String: Directory where database resides
91 * @param $dbName String: Database name
94 public static function generateFileName( $dir, $dbName ) {
95 return "$dir/$dbName.sqlite";
99 * Returns version of currently supported SQLite fulltext search module or false if none present.
102 function getFulltextSearchModule() {
103 $table = 'dummy_search_test';
104 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
105 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
106 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
113 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
115 function doQuery( $sql ) {
116 $res = $this->mConn
->query( $sql );
117 if ( $res === false ) {
120 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
121 $this->mAffectedRows
= $r->rowCount();
122 $res = new ResultWrapper( $this, $r->fetchAll() );
127 function freeResult( $res ) {
128 if ( $res instanceof ResultWrapper
)
134 function fetchObject($res) {
135 if ($res instanceof ResultWrapper
)
140 $cur = current( $r );
141 if ( is_array( $cur ) ) {
144 foreach ( $cur as $k => $v )
145 if ( !is_numeric( $k ) )
153 function fetchRow($res) {
154 if ( $res instanceof ResultWrapper
)
160 if (is_array($cur)) {
168 * The PDO::Statement class implements the array interface so count() will work
170 function numRows( $res ) {
171 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
175 function numFields( $res ) {
176 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
177 return is_array( $r ) ?
count( $r[0] ) : 0;
180 function fieldName( $res, $n ) {
181 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
182 if ( is_array( $r ) ) {
183 $keys = array_keys( $r[0] );
190 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
192 function tableName( $name ) {
193 return str_replace( '`', '', parent
::tableName( $name ) );
197 * Index names have DB scope
199 function indexName( $index ) {
204 * This must be called after nextSequenceVal
206 function insertId() {
207 return $this->mConn
->lastInsertId();
210 function dataSeek( $res, $row ) {
211 if ( $res instanceof ResultWrapper
)
217 for ( $i = 0; $i < $row; $i++
)
221 function lastError() {
222 if ( !is_object( $this->mConn
) )
223 return "Cannot return last error, no db connection";
224 $e = $this->mConn
->errorInfo();
225 return isset( $e[2] ) ?
$e[2] : '';
228 function lastErrno() {
229 if ( !is_object( $this->mConn
) ) {
230 return "Cannot return last error, no db connection";
232 $info = $this->mConn
->errorInfo();
237 function affectedRows() {
238 return $this->mAffectedRows
;
242 * Returns information about an index
243 * Returns false if the index does not exist
244 * - if errors are explicitly ignored, returns NULL on failure
246 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
247 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
248 $res = $this->query( $sql, $fname );
252 if ( $res->numRows() == 0 ) {
256 foreach ( $res as $row ) {
257 $info[] = $row->name
;
262 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
263 $row = $this->selectRow( 'sqlite_master', '*',
266 'name' => $this->indexName( $index ),
268 if ( !$row ||
!isset( $row->sql
) ) {
272 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
273 $indexPos = strpos( $row->sql
, 'INDEX' );
274 if ( $indexPos === false ) {
277 $firstPart = substr( $row->sql
, 0, $indexPos );
278 $options = explode( ' ', $firstPart );
279 return in_array( 'UNIQUE', $options );
283 * Filter the options used in SELECT statements
285 function makeSelectOptions( $options ) {
286 foreach ( $options as $k => $v )
287 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
289 return parent
::makeSelectOptions( $options );
293 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
295 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
296 if ( !count( $a ) ) return true;
297 if ( !is_array( $options ) ) $options = array( $options );
299 # SQLite uses OR IGNORE not just IGNORE
300 foreach ( $options as $k => $v )
301 if ( $v == 'IGNORE' )
302 $options[$k] = 'OR IGNORE';
304 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
305 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
307 foreach ( $a as $k => $v )
308 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
311 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
318 * Returns the size of a text field, or -1 for "unlimited"
319 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
321 function textFieldSize( $table, $field ) {
325 function unionSupportsOrderAndLimit() {
329 function unionQueries( $sqls, $all ) {
330 $glue = $all ?
' UNION ALL ' : ' UNION ';
331 return implode( $glue, $sqls );
334 function wasDeadlock() {
335 return $this->lastErrno() == 5; // SQLITE_BUSY
338 function wasErrorReissuable() {
339 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
342 function wasReadOnlyError() {
343 return $this->lastErrno() == 8; // SQLITE_READONLY;
347 * @return string wikitext of a link to the server software's web site
349 function getSoftwareLink() {
350 return "[http://sqlite.org/ SQLite]";
354 * @return string Version information from the database
356 function getServerVersion() {
357 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
362 * Query whether a given column exists in the mediawiki schema
364 function fieldExists( $table, $field, $fname = '' ) {
365 $info = $this->fieldInfo( $table, $field );
370 * Get information about a given field
371 * Returns false if the field does not exist.
373 function fieldInfo( $table, $field ) {
374 $tableName = $this->tableName( $table );
375 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
376 $res = $this->query( $sql, __METHOD__
);
377 foreach ( $res as $row ) {
378 if ( $row->name
== $field ) {
379 return new SQLiteField( $row, $tableName );
385 function begin( $fname = '' ) {
386 if ( $this->mTrxLevel
== 1 ) $this->commit();
387 $this->mConn
->beginTransaction();
388 $this->mTrxLevel
= 1;
391 function commit( $fname = '' ) {
392 if ( $this->mTrxLevel
== 0 ) return;
393 $this->mConn
->commit();
394 $this->mTrxLevel
= 0;
397 function rollback( $fname = '' ) {
398 if ( $this->mTrxLevel
== 0 ) return;
399 $this->mConn
->rollBack();
400 $this->mTrxLevel
= 0;
403 function limitResultForUpdate( $sql, $num ) {
404 return $this->limitResult( $sql, $num );
407 function strencode( $s ) {
408 return substr( $this->addQuotes( $s ), 1, - 1 );
411 function encodeBlob( $b ) {
412 return new Blob( $b );
415 function decodeBlob( $b ) {
416 if ( $b instanceof Blob
) {
422 function addQuotes( $s ) {
423 if ( $s instanceof Blob
) {
424 return "x'" . bin2hex( $s->fetch() ) . "'";
426 return $this->mConn
->quote( $s );
430 function quote_ident( $s ) {
434 function buildLike() {
435 $params = func_get_args();
436 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
437 $params = $params[0];
439 return parent
::buildLike( $params ) . "ESCAPE '\' ";
443 * How lagged is this slave?
445 public function getLag() {
450 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
451 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
453 public function setup_database() {
456 # Process common MySQL/SQLite table definitions
457 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
458 if ( $err !== true ) {
459 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
463 # Use DatabasePostgres's code to populate interwiki from MySQL template
464 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
465 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
466 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
467 while ( !feof( $f ) ) {
468 $line = fgets( $f, 1024 );
470 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
471 $this->query( "$sql $matches[1],$matches[2])" );
475 public function getSearchEngine() {
476 return "SearchSqlite";
480 * No-op version of deadlockLoop
482 public function deadlockLoop( /*...*/ ) {
483 $args = func_get_args();
484 $function = array_shift( $args );
485 return call_user_func_array( $function, $args );
488 protected function replaceVars( $s ) {
489 $s = parent
::replaceVars( $s );
490 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
491 // CREATE TABLE hacks to allow schema file sharing with MySQL
493 // binary/varbinary column type -> blob
494 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
495 // no such thing as unsigned
496 $s = preg_replace( '/\bunsigned\b/i', '', $s );
497 // INT -> INTEGER for primary keys
498 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
500 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
501 // binary collation type -> nothing
502 $s = preg_replace( '/\bbinary\b/i', '', $s );
503 // auto_increment -> autoincrement
504 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
505 // No explicit options
506 $s = preg_replace( '/\)[^)]*$/', ')', $s );
507 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
508 // No truncated indexes
509 $s = preg_replace( '/\(\d+\)/', '', $s );
511 $s = preg_replace( '/\bfulltext\b/i', '', $s );
517 * Build a concatenation list to feed into a SQL query
519 function buildConcat( $stringList ) {
520 return '(' . implode( ') || (', $stringList ) . ')';
523 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
524 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
525 $sql = $this->fetchObject( $res )->sql
;
526 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
527 return $this->query( $sql, $fname );
530 } // end DatabaseSqlite class
536 private $info, $tableName;
537 function __construct( $info, $tableName ) {
539 $this->tableName
= $tableName;
543 return $this->info
->name
;
546 function tableName() {
547 return $this->tableName
;
550 function defaultValue() {
551 if ( is_string( $this->info
->dflt_value
) ) {
553 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
554 return str_replace( "''", "'", $this->info
->dflt_value
);
557 return $this->info
->dflt_value
;
560 function maxLength() {
564 function nullable() {
565 // SQLite dynamic types are always nullable
569 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
570 # Suggest removal from base class [TS]
573 return $this->info
->type
;