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
= "$wgSQLiteDataDir/$dbName.sqlite";
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 these should be true like parent class
37 function implicitGroupby() { return false; }
38 function implicitOrderby() { 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->immediateCommit();
90 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
92 function doQuery( $sql ) {
93 $res = $this->mConn
->query( $sql );
94 if ( $res === false ) {
97 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
98 $this->mAffectedRows
= $r->rowCount();
99 $res = new ResultWrapper( $this, $r->fetchAll() );
104 function freeResult( $res ) {
105 if ( $res instanceof ResultWrapper
)
111 function fetchObject($res) {
112 if ($res instanceof ResultWrapper
)
117 $cur = current( $r );
118 if ( is_array( $cur ) ) {
121 foreach ( $cur as $k => $v )
122 if ( !is_numeric( $k ) )
130 function fetchRow($res) {
131 if ( $res instanceof ResultWrapper
)
137 if (is_array($cur)) {
145 * The PDO::Statement class implements the array interface so count() will work
147 function numRows( $res ) {
148 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
152 function numFields( $res ) {
153 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
154 return is_array( $r ) ?
count( $r[0] ) : 0;
157 function fieldName( $res, $n ) {
158 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
159 if ( is_array( $r ) ) {
160 $keys = array_keys( $r[0] );
167 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
169 function tableName( $name ) {
170 return str_replace( '`', '', parent
::tableName( $name ) );
174 * Index names have DB scope
176 function indexName( $index ) {
181 * This must be called after nextSequenceVal
183 function insertId() {
184 return $this->mConn
->lastInsertId();
187 function dataSeek( $res, $row ) {
188 if ( $res instanceof ResultWrapper
)
194 for ( $i = 0; $i < $row; $i++
)
198 function lastError() {
199 if ( !is_object( $this->mConn
) )
200 return "Cannot return last error, no db connection";
201 $e = $this->mConn
->errorInfo();
202 return isset( $e[2] ) ?
$e[2] : '';
205 function lastErrno() {
206 if ( !is_object( $this->mConn
) ) {
207 return "Cannot return last error, no db connection";
209 $info = $this->mConn
->errorInfo();
214 function affectedRows() {
215 return $this->mAffectedRows
;
219 * Returns information about an index
220 * Returns false if the index does not exist
221 * - if errors are explicitly ignored, returns NULL on failure
223 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
224 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
225 $res = $this->query( $sql, $fname );
229 if ( $res->numRows() == 0 ) {
233 foreach ( $res as $row ) {
234 $info[] = $row->name
;
239 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
240 $row = $this->selectRow( 'sqlite_master', '*',
243 'name' => $this->indexName( $index ),
245 if ( !$row ||
!isset( $row->sql
) ) {
249 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
250 $indexPos = strpos( $row->sql
, 'INDEX' );
251 if ( $indexPos === false ) {
254 $firstPart = substr( $row->sql
, 0, $indexPos );
255 $options = explode( ' ', $firstPart );
256 return in_array( 'UNIQUE', $options );
260 * Filter the options used in SELECT statements
262 function makeSelectOptions( $options ) {
263 foreach ( $options as $k => $v )
264 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
266 return parent
::makeSelectOptions( $options );
270 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
272 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
273 if ( !count( $a ) ) return true;
274 if ( !is_array( $options ) ) $options = array( $options );
276 # SQLite uses OR IGNORE not just IGNORE
277 foreach ( $options as $k => $v )
278 if ( $v == 'IGNORE' )
279 $options[$k] = 'OR IGNORE';
281 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
282 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
284 foreach ( $a as $k => $v )
285 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
288 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
295 * Returns the size of a text field, or -1 for "unlimited"
296 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
298 function textFieldSize( $table, $field ) {
302 function wasDeadlock() {
303 return $this->lastErrno() == SQLITE_BUSY
;
306 function wasErrorReissuable() {
307 return $this->lastErrno() == SQLITE_SCHEMA
;
310 function wasReadOnlyError() {
311 return $this->lastErrno() == SQLITE_READONLY
;
315 * @return string wikitext of a link to the server software's web site
317 function getSoftwareLink() {
318 return "[http://sqlite.org/ SQLite]";
322 * @return string Version information from the database
324 function getServerVersion() {
325 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
330 * Query whether a given column exists in the mediawiki schema
332 function fieldExists( $table, $field, $fname = '' ) {
333 $info = $this->fieldInfo( $table, $field );
338 * Get information about a given field
339 * Returns false if the field does not exist.
341 function fieldInfo( $table, $field ) {
342 $tableName = $this->tableName( $table );
343 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
344 $res = $this->query( $sql, __METHOD__
);
345 foreach ( $res as $row ) {
346 if ( $row->name
== $field ) {
347 return new SQLiteField( $row, $tableName );
353 function begin( $fname = '' ) {
354 if ( $this->mTrxLevel
== 1 ) $this->commit();
355 $this->mConn
->beginTransaction();
356 $this->mTrxLevel
= 1;
359 function commit( $fname = '' ) {
360 if ( $this->mTrxLevel
== 0 ) return;
361 $this->mConn
->commit();
362 $this->mTrxLevel
= 0;
365 function rollback( $fname = '' ) {
366 if ( $this->mTrxLevel
== 0 ) return;
367 $this->mConn
->rollBack();
368 $this->mTrxLevel
= 0;
371 function limitResultForUpdate( $sql, $num ) {
372 return $this->limitResult( $sql, $num );
375 function strencode( $s ) {
376 return substr( $this->addQuotes( $s ), 1, - 1 );
379 function encodeBlob( $b ) {
380 return new Blob( $b );
383 function decodeBlob( $b ) {
384 if ( $b instanceof Blob
) {
390 function addQuotes( $s ) {
391 if ( $s instanceof Blob
) {
392 return "x'" . bin2hex( $s->fetch() ) . "'";
394 return $this->mConn
->quote( $s );
398 function quote_ident( $s ) {
403 * How lagged is this slave?
405 public function getLag() {
410 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
411 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
413 public function setup_database() {
414 global $IP, $wgSQLiteDataDir, $wgDBTableOptions;
415 $wgDBTableOptions = '';
417 # Process common MySQL/SQLite table definitions
418 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
419 if ( $err !== true ) {
420 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
424 # Use DatabasePostgres's code to populate interwiki from MySQL template
425 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
426 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
427 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
428 while ( !feof( $f ) ) {
429 $line = fgets( $f, 1024 );
431 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
432 $this->query( "$sql $matches[1],$matches[2])" );
436 public function getSearchEngine() {
437 return "SearchEngineDummy";
441 * No-op version of deadlockLoop
443 public function deadlockLoop( /*...*/ ) {
444 $args = func_get_args();
445 $function = array_shift( $args );
446 return call_user_func_array( $function, $args );
449 protected function replaceVars( $s ) {
450 $s = parent
::replaceVars( $s );
451 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
452 // CREATE TABLE hacks to allow schema file sharing with MySQL
454 // binary/varbinary column type -> blob
455 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
456 // no such thing as unsigned
457 $s = preg_replace( '/\bunsigned\b/i', '', $s );
458 // INT -> INTEGER for primary keys
459 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
461 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
462 // binary collation type -> nothing
463 $s = preg_replace( '/\bbinary\b/i', '', $s );
464 // auto_increment -> autoincrement
465 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
466 // No explicit options
467 $s = preg_replace( '/\)[^)]*$/', ')', $s );
468 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
469 // No truncated indexes
470 $s = preg_replace( '/\(\d+\)/', '', $s );
472 $s = preg_replace( '/\bfulltext\b/i', '', $s );
478 * Build a concatenation list to feed into a SQL query
480 function buildConcat( $stringList ) {
481 return '(' . implode( ') || (', $stringList ) . ')';
484 } // end DatabaseSqlite class
490 private $info, $tableName;
491 function __construct( $info, $tableName ) {
493 $this->tableName
= $tableName;
497 return $this->info
->name
;
500 function tableName() {
501 return $this->tableName
;
504 function defaultValue() {
505 if ( is_string( $this->info
->dflt_value
) ) {
507 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
508 return str_replace( "''", "'", $this->info
->dflt_value
);
511 return $this->info
->dflt_value
;
514 function maxLength() {
518 function nullable() {
519 // SQLite dynamic types are always nullable
523 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
524 # Suggest removal from base class [TS]
527 return $this->info
->type
;