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 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 * 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 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
102 function doQuery( $sql ) {
103 $res = $this->mConn
->query( $sql );
104 if ( $res === false ) {
107 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
108 $this->mAffectedRows
= $r->rowCount();
109 $res = new ResultWrapper( $this, $r->fetchAll() );
114 function freeResult( $res ) {
115 if ( $res instanceof ResultWrapper
)
121 function fetchObject($res) {
122 if ($res instanceof ResultWrapper
)
127 $cur = current( $r );
128 if ( is_array( $cur ) ) {
131 foreach ( $cur as $k => $v )
132 if ( !is_numeric( $k ) )
140 function fetchRow($res) {
141 if ( $res instanceof ResultWrapper
)
147 if (is_array($cur)) {
155 * The PDO::Statement class implements the array interface so count() will work
157 function numRows( $res ) {
158 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
162 function numFields( $res ) {
163 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
164 return is_array( $r ) ?
count( $r[0] ) : 0;
167 function fieldName( $res, $n ) {
168 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
169 if ( is_array( $r ) ) {
170 $keys = array_keys( $r[0] );
177 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
179 function tableName( $name ) {
180 return str_replace( '`', '', parent
::tableName( $name ) );
184 * Index names have DB scope
186 function indexName( $index ) {
191 * This must be called after nextSequenceVal
193 function insertId() {
194 return $this->mConn
->lastInsertId();
197 function dataSeek( $res, $row ) {
198 if ( $res instanceof ResultWrapper
)
204 for ( $i = 0; $i < $row; $i++
)
208 function lastError() {
209 if ( !is_object( $this->mConn
) )
210 return "Cannot return last error, no db connection";
211 $e = $this->mConn
->errorInfo();
212 return isset( $e[2] ) ?
$e[2] : '';
215 function lastErrno() {
216 if ( !is_object( $this->mConn
) ) {
217 return "Cannot return last error, no db connection";
219 $info = $this->mConn
->errorInfo();
224 function affectedRows() {
225 return $this->mAffectedRows
;
229 * Returns information about an index
230 * Returns false if the index does not exist
231 * - if errors are explicitly ignored, returns NULL on failure
233 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
234 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
235 $res = $this->query( $sql, $fname );
239 if ( $res->numRows() == 0 ) {
243 foreach ( $res as $row ) {
244 $info[] = $row->name
;
249 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
250 $row = $this->selectRow( 'sqlite_master', '*',
253 'name' => $this->indexName( $index ),
255 if ( !$row ||
!isset( $row->sql
) ) {
259 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
260 $indexPos = strpos( $row->sql
, 'INDEX' );
261 if ( $indexPos === false ) {
264 $firstPart = substr( $row->sql
, 0, $indexPos );
265 $options = explode( ' ', $firstPart );
266 return in_array( 'UNIQUE', $options );
270 * Filter the options used in SELECT statements
272 function makeSelectOptions( $options ) {
273 foreach ( $options as $k => $v )
274 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
276 return parent
::makeSelectOptions( $options );
280 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
282 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
283 if ( !count( $a ) ) return true;
284 if ( !is_array( $options ) ) $options = array( $options );
286 # SQLite uses OR IGNORE not just IGNORE
287 foreach ( $options as $k => $v )
288 if ( $v == 'IGNORE' )
289 $options[$k] = 'OR IGNORE';
291 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
292 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
294 foreach ( $a as $k => $v )
295 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
298 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
305 * Returns the size of a text field, or -1 for "unlimited"
306 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
308 function textFieldSize( $table, $field ) {
312 function unionSupportsOrderAndLimit() {
316 function unionQueries( $sqls, $all ) {
317 $glue = $all ?
' UNION ALL ' : ' UNION ';
318 return implode( $glue, $sqls );
321 function wasDeadlock() {
322 return $this->lastErrno() == SQLITE_BUSY
;
325 function wasErrorReissuable() {
326 return $this->lastErrno() == SQLITE_SCHEMA
;
329 function wasReadOnlyError() {
330 return $this->lastErrno() == SQLITE_READONLY
;
334 * @return string wikitext of a link to the server software's web site
336 function getSoftwareLink() {
337 return "[http://sqlite.org/ SQLite]";
341 * @return string Version information from the database
343 function getServerVersion() {
344 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
349 * Query whether a given column exists in the mediawiki schema
351 function fieldExists( $table, $field, $fname = '' ) {
352 $info = $this->fieldInfo( $table, $field );
357 * Get information about a given field
358 * Returns false if the field does not exist.
360 function fieldInfo( $table, $field ) {
361 $tableName = $this->tableName( $table );
362 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
363 $res = $this->query( $sql, __METHOD__
);
364 foreach ( $res as $row ) {
365 if ( $row->name
== $field ) {
366 return new SQLiteField( $row, $tableName );
372 function begin( $fname = '' ) {
373 if ( $this->mTrxLevel
== 1 ) $this->commit();
374 $this->mConn
->beginTransaction();
375 $this->mTrxLevel
= 1;
378 function commit( $fname = '' ) {
379 if ( $this->mTrxLevel
== 0 ) return;
380 $this->mConn
->commit();
381 $this->mTrxLevel
= 0;
384 function rollback( $fname = '' ) {
385 if ( $this->mTrxLevel
== 0 ) return;
386 $this->mConn
->rollBack();
387 $this->mTrxLevel
= 0;
390 function limitResultForUpdate( $sql, $num ) {
391 return $this->limitResult( $sql, $num );
394 function strencode( $s ) {
395 return substr( $this->addQuotes( $s ), 1, - 1 );
398 function encodeBlob( $b ) {
399 return new Blob( $b );
402 function decodeBlob( $b ) {
403 if ( $b instanceof Blob
) {
409 function addQuotes( $s ) {
410 if ( $s instanceof Blob
) {
411 return "x'" . bin2hex( $s->fetch() ) . "'";
413 return $this->mConn
->quote( $s );
417 function quote_ident( $s ) {
421 function buildLike() {
422 $params = func_get_args();
423 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
424 $params = $params[0];
426 return parent
::buildLike( $params ) . "ESCAPE '\' ";
430 * How lagged is this slave?
432 public function getLag() {
437 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
438 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
440 public function setup_database() {
443 # Process common MySQL/SQLite table definitions
444 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
445 if ( $err !== true ) {
446 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
450 # Use DatabasePostgres's code to populate interwiki from MySQL template
451 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
452 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
453 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
454 while ( !feof( $f ) ) {
455 $line = fgets( $f, 1024 );
457 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
458 $this->query( "$sql $matches[1],$matches[2])" );
462 public function getSearchEngine() {
463 return "SearchEngineDummy";
467 * No-op version of deadlockLoop
469 public function deadlockLoop( /*...*/ ) {
470 $args = func_get_args();
471 $function = array_shift( $args );
472 return call_user_func_array( $function, $args );
475 protected function replaceVars( $s ) {
476 $s = parent
::replaceVars( $s );
477 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
478 // CREATE TABLE hacks to allow schema file sharing with MySQL
480 // binary/varbinary column type -> blob
481 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
482 // no such thing as unsigned
483 $s = preg_replace( '/\bunsigned\b/i', '', $s );
484 // INT -> INTEGER for primary keys
485 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
487 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
488 // binary collation type -> nothing
489 $s = preg_replace( '/\bbinary\b/i', '', $s );
490 // auto_increment -> autoincrement
491 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
492 // No explicit options
493 $s = preg_replace( '/\)[^)]*$/', ')', $s );
494 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
495 // No truncated indexes
496 $s = preg_replace( '/\(\d+\)/', '', $s );
498 $s = preg_replace( '/\bfulltext\b/i', '', $s );
504 * Build a concatenation list to feed into a SQL query
506 function buildConcat( $stringList ) {
507 return '(' . implode( ') || (', $stringList ) . ')';
510 } // end DatabaseSqlite class
516 private $info, $tableName;
517 function __construct( $info, $tableName ) {
519 $this->tableName
= $tableName;
523 return $this->info
->name
;
526 function tableName() {
527 return $this->tableName
;
530 function defaultValue() {
531 if ( is_string( $this->info
->dflt_value
) ) {
533 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
534 return str_replace( "''", "'", $this->info
->dflt_value
);
537 return $this->info
->dflt_value
;
540 function maxLength() {
544 function nullable() {
545 // SQLite dynamic types are always nullable
549 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
550 # Suggest removal from base class [TS]
553 return $this->info
->type
;