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 unionSupportsOrderAndLimit() {
306 function unionQueries( $sqls, $all ) {
307 $glue = $all ?
' UNION ALL ' : ' UNION ';
308 return implode( $glue, $sqls );
311 function wasDeadlock() {
312 return $this->lastErrno() == SQLITE_BUSY
;
315 function wasErrorReissuable() {
316 return $this->lastErrno() == SQLITE_SCHEMA
;
319 function wasReadOnlyError() {
320 return $this->lastErrno() == SQLITE_READONLY
;
324 * @return string wikitext of a link to the server software's web site
326 function getSoftwareLink() {
327 return "[http://sqlite.org/ SQLite]";
331 * @return string Version information from the database
333 function getServerVersion() {
334 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
339 * Query whether a given column exists in the mediawiki schema
341 function fieldExists( $table, $field, $fname = '' ) {
342 $info = $this->fieldInfo( $table, $field );
347 * Get information about a given field
348 * Returns false if the field does not exist.
350 function fieldInfo( $table, $field ) {
351 $tableName = $this->tableName( $table );
352 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
353 $res = $this->query( $sql, __METHOD__
);
354 foreach ( $res as $row ) {
355 if ( $row->name
== $field ) {
356 return new SQLiteField( $row, $tableName );
362 function begin( $fname = '' ) {
363 if ( $this->mTrxLevel
== 1 ) $this->commit();
364 $this->mConn
->beginTransaction();
365 $this->mTrxLevel
= 1;
368 function commit( $fname = '' ) {
369 if ( $this->mTrxLevel
== 0 ) return;
370 $this->mConn
->commit();
371 $this->mTrxLevel
= 0;
374 function rollback( $fname = '' ) {
375 if ( $this->mTrxLevel
== 0 ) return;
376 $this->mConn
->rollBack();
377 $this->mTrxLevel
= 0;
380 function limitResultForUpdate( $sql, $num ) {
381 return $this->limitResult( $sql, $num );
384 function strencode( $s ) {
385 return substr( $this->addQuotes( $s ), 1, - 1 );
388 function encodeBlob( $b ) {
389 return new Blob( $b );
392 function decodeBlob( $b ) {
393 if ( $b instanceof Blob
) {
399 function addQuotes( $s ) {
400 if ( $s instanceof Blob
) {
401 return "x'" . bin2hex( $s->fetch() ) . "'";
403 return $this->mConn
->quote( $s );
407 function quote_ident( $s ) {
412 * How lagged is this slave?
414 public function getLag() {
419 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
420 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
422 public function setup_database() {
423 global $IP, $wgSQLiteDataDir, $wgDBTableOptions;
424 $wgDBTableOptions = '';
426 # Process common MySQL/SQLite table definitions
427 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
428 if ( $err !== true ) {
429 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
433 # Use DatabasePostgres's code to populate interwiki from MySQL template
434 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
435 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
436 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
437 while ( !feof( $f ) ) {
438 $line = fgets( $f, 1024 );
440 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
441 $this->query( "$sql $matches[1],$matches[2])" );
445 public function getSearchEngine() {
446 return "SearchEngineDummy";
450 * No-op version of deadlockLoop
452 public function deadlockLoop( /*...*/ ) {
453 $args = func_get_args();
454 $function = array_shift( $args );
455 return call_user_func_array( $function, $args );
458 protected function replaceVars( $s ) {
459 $s = parent
::replaceVars( $s );
460 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
461 // CREATE TABLE hacks to allow schema file sharing with MySQL
463 // binary/varbinary column type -> blob
464 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
465 // no such thing as unsigned
466 $s = preg_replace( '/\bunsigned\b/i', '', $s );
467 // INT -> INTEGER for primary keys
468 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
470 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
471 // binary collation type -> nothing
472 $s = preg_replace( '/\bbinary\b/i', '', $s );
473 // auto_increment -> autoincrement
474 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
475 // No explicit options
476 $s = preg_replace( '/\)[^)]*$/', ')', $s );
477 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
478 // No truncated indexes
479 $s = preg_replace( '/\(\d+\)/', '', $s );
481 $s = preg_replace( '/\bfulltext\b/i', '', $s );
487 * Build a concatenation list to feed into a SQL query
489 function buildConcat( $stringList ) {
490 return '(' . implode( ') || (', $stringList ) . ')';
493 } // end DatabaseSqlite class
499 private $info, $tableName;
500 function __construct( $info, $tableName ) {
502 $this->tableName
= $tableName;
506 return $this->info
->name
;
509 function tableName() {
510 return $this->tableName
;
513 function defaultValue() {
514 if ( is_string( $this->info
->dflt_value
) ) {
516 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
517 return str_replace( "''", "'", $this->info
->dflt_value
);
520 return $this->info
->dflt_value
;
523 function maxLength() {
527 function nullable() {
528 // SQLite dynamic types are always nullable
532 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
533 # Suggest removal from base class [TS]
536 return $this->info
->type
;