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 );
40 * @todo: check if it should be true like parent class
42 function implicitGroupby() { return false; }
44 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
45 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
48 /** Open an SQLite database and return a resource handle to it
49 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
51 function open( $server, $user, $pass, $dbName ) {
54 $file = $this->mDatabaseFile
;
56 if ( $this->mFlags
& DBO_PERSISTENT
) {
57 $this->mConn
= new PDO( "sqlite:$file", $user, $pass,
58 array( PDO
::ATTR_PERSISTENT
=> true ) );
60 $this->mConn
= new PDO( "sqlite:$file", $user, $pass );
62 } catch ( PDOException
$e ) {
63 $err = $e->getMessage();
65 if ( $this->mConn
=== false ) {
66 wfDebug( "DB connection error: $err\n" );
67 if ( !$this->mFailFunction
) {
68 throw new DBConnectionError( $this, $err );
74 $this->mOpened
= $this->mConn
;
75 # set error codes only, don't raise exceptions
76 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
82 * Close an SQLite database
85 $this->mOpened
= false;
86 if ( is_object( $this->mConn
) ) {
87 if ( $this->trxLevel() ) $this->commit();
94 * Generates a database file name. Explicitly public for installer.
95 * @param $dir String: Directory where database resides
96 * @param $dbName String: Database name
99 public static function generateFileName( $dir, $dbName ) {
100 return "$dir/$dbName.sqlite";
104 * Returns version of currently supported SQLite fulltext search module or false if none present.
107 function getFulltextSearchModule() {
108 $table = 'dummy_search_test';
109 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
110 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
111 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
118 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
120 function doQuery( $sql ) {
121 $res = $this->mConn
->query( $sql );
122 if ( $res === false ) {
125 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
126 $this->mAffectedRows
= $r->rowCount();
127 $res = new ResultWrapper( $this, $r->fetchAll() );
132 function freeResult( $res ) {
133 if ( $res instanceof ResultWrapper
)
139 function fetchObject($res) {
140 if ($res instanceof ResultWrapper
)
145 $cur = current( $r );
146 if ( is_array( $cur ) ) {
149 foreach ( $cur as $k => $v )
150 if ( !is_numeric( $k ) )
158 function fetchRow($res) {
159 if ( $res instanceof ResultWrapper
)
165 if (is_array($cur)) {
173 * The PDO::Statement class implements the array interface so count() will work
175 function numRows( $res ) {
176 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
180 function numFields( $res ) {
181 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
182 return is_array( $r ) ?
count( $r[0] ) : 0;
185 function fieldName( $res, $n ) {
186 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
187 if ( is_array( $r ) ) {
188 $keys = array_keys( $r[0] );
195 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
197 function tableName( $name ) {
198 return str_replace( '`', '', parent
::tableName( $name ) );
202 * Index names have DB scope
204 function indexName( $index ) {
209 * This must be called after nextSequenceVal
211 function insertId() {
212 return $this->mConn
->lastInsertId();
215 function dataSeek( $res, $row ) {
216 if ( $res instanceof ResultWrapper
)
222 for ( $i = 0; $i < $row; $i++
)
226 function lastError() {
227 if ( !is_object( $this->mConn
) )
228 return "Cannot return last error, no db connection";
229 $e = $this->mConn
->errorInfo();
230 return isset( $e[2] ) ?
$e[2] : '';
233 function lastErrno() {
234 if ( !is_object( $this->mConn
) ) {
235 return "Cannot return last error, no db connection";
237 $info = $this->mConn
->errorInfo();
242 function affectedRows() {
243 return $this->mAffectedRows
;
247 * Returns information about an index
248 * Returns false if the index does not exist
249 * - if errors are explicitly ignored, returns NULL on failure
251 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
252 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
253 $res = $this->query( $sql, $fname );
257 if ( $res->numRows() == 0 ) {
261 foreach ( $res as $row ) {
262 $info[] = $row->name
;
267 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
268 $row = $this->selectRow( 'sqlite_master', '*',
271 'name' => $this->indexName( $index ),
273 if ( !$row ||
!isset( $row->sql
) ) {
277 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
278 $indexPos = strpos( $row->sql
, 'INDEX' );
279 if ( $indexPos === false ) {
282 $firstPart = substr( $row->sql
, 0, $indexPos );
283 $options = explode( ' ', $firstPart );
284 return in_array( 'UNIQUE', $options );
288 * Filter the options used in SELECT statements
290 function makeSelectOptions( $options ) {
291 foreach ( $options as $k => $v )
292 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
294 return parent
::makeSelectOptions( $options );
298 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
300 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
301 if ( !count( $a ) ) return true;
302 if ( !is_array( $options ) ) $options = array( $options );
304 # SQLite uses OR IGNORE not just IGNORE
305 foreach ( $options as $k => $v )
306 if ( $v == 'IGNORE' )
307 $options[$k] = 'OR IGNORE';
309 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
310 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
312 foreach ( $a as $k => $v )
313 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
316 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
323 * Returns the size of a text field, or -1 for "unlimited"
324 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
326 function textFieldSize( $table, $field ) {
330 function unionSupportsOrderAndLimit() {
334 function unionQueries( $sqls, $all ) {
335 $glue = $all ?
' UNION ALL ' : ' UNION ';
336 return implode( $glue, $sqls );
339 function wasDeadlock() {
340 return $this->lastErrno() == 5; // SQLITE_BUSY
343 function wasErrorReissuable() {
344 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
347 function wasReadOnlyError() {
348 return $this->lastErrno() == 8; // SQLITE_READONLY;
352 * @return string wikitext of a link to the server software's web site
354 function getSoftwareLink() {
355 return "[http://sqlite.org/ SQLite]";
359 * @return string Version information from the database
361 function getServerVersion() {
362 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
367 * Query whether a given column exists in the mediawiki schema
369 function fieldExists( $table, $field, $fname = '' ) {
370 $info = $this->fieldInfo( $table, $field );
375 * Get information about a given field
376 * Returns false if the field does not exist.
378 function fieldInfo( $table, $field ) {
379 $tableName = $this->tableName( $table );
380 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
381 $res = $this->query( $sql, __METHOD__
);
382 foreach ( $res as $row ) {
383 if ( $row->name
== $field ) {
384 return new SQLiteField( $row, $tableName );
390 function begin( $fname = '' ) {
391 if ( $this->mTrxLevel
== 1 ) $this->commit();
392 $this->mConn
->beginTransaction();
393 $this->mTrxLevel
= 1;
396 function commit( $fname = '' ) {
397 if ( $this->mTrxLevel
== 0 ) return;
398 $this->mConn
->commit();
399 $this->mTrxLevel
= 0;
402 function rollback( $fname = '' ) {
403 if ( $this->mTrxLevel
== 0 ) return;
404 $this->mConn
->rollBack();
405 $this->mTrxLevel
= 0;
408 function limitResultForUpdate( $sql, $num ) {
409 return $this->limitResult( $sql, $num );
412 function strencode( $s ) {
413 return substr( $this->addQuotes( $s ), 1, - 1 );
416 function encodeBlob( $b ) {
417 return new Blob( $b );
420 function decodeBlob( $b ) {
421 if ( $b instanceof Blob
) {
427 function addQuotes( $s ) {
428 if ( $s instanceof Blob
) {
429 return "x'" . bin2hex( $s->fetch() ) . "'";
431 return $this->mConn
->quote( $s );
435 function quote_ident( $s ) {
439 function buildLike() {
440 $params = func_get_args();
441 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
442 $params = $params[0];
444 return parent
::buildLike( $params ) . "ESCAPE '\' ";
448 * How lagged is this slave?
450 public function getLag() {
455 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
456 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
458 public function setup_database() {
461 # Process common MySQL/SQLite table definitions
462 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
463 if ( $err !== true ) {
464 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
468 # Use DatabasePostgres's code to populate interwiki from MySQL template
469 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
470 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
471 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
472 while ( !feof( $f ) ) {
473 $line = fgets( $f, 1024 );
475 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
476 $this->query( "$sql $matches[1],$matches[2])" );
480 public function getSearchEngine() {
481 return "SearchSqlite";
485 * No-op version of deadlockLoop
487 public function deadlockLoop( /*...*/ ) {
488 $args = func_get_args();
489 $function = array_shift( $args );
490 return call_user_func_array( $function, $args );
493 protected function replaceVars( $s ) {
494 $s = parent
::replaceVars( $s );
495 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
496 // CREATE TABLE hacks to allow schema file sharing with MySQL
498 // binary/varbinary column type -> blob
499 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
500 // no such thing as unsigned
501 $s = preg_replace( '/\bunsigned\b/i', '', $s );
502 // INT -> INTEGER for primary keys
503 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
505 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
506 // binary collation type -> nothing
507 $s = preg_replace( '/\bbinary\b/i', '', $s );
508 // auto_increment -> autoincrement
509 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
510 // No explicit options
511 $s = preg_replace( '/\)[^)]*$/', ')', $s );
512 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
513 // No truncated indexes
514 $s = preg_replace( '/\(\d+\)/', '', $s );
516 $s = preg_replace( '/\bfulltext\b/i', '', $s );
522 * Build a concatenation list to feed into a SQL query
524 function buildConcat( $stringList ) {
525 return '(' . implode( ') || (', $stringList ) . ')';
528 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
529 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
530 $sql = $this->fetchObject( $res )->sql
;
531 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
532 return $this->query( $sql, $fname );
535 } // end DatabaseSqlite class
541 private $info, $tableName;
542 function __construct( $info, $tableName ) {
544 $this->tableName
= $tableName;
548 return $this->info
->name
;
551 function tableName() {
552 return $this->tableName
;
555 function defaultValue() {
556 if ( is_string( $this->info
->dflt_value
) ) {
558 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
559 return str_replace( "''", "'", $this->info
->dflt_value
);
562 return $this->info
->dflt_value
;
565 function maxLength() {
569 function nullable() {
570 // SQLite dynamic types are always nullable
574 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
575 # Suggest removal from base class [TS]
578 return $this->info
->type
;