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 $this->mFailFunction
= $failFunction;
26 $this->mFlags
= $flags;
27 $this->mName
= $dbName;
28 $this->open( $server, $user, $password, $dbName );
36 * @todo: check if it should be true like parent class
38 function implicitGroupby() { 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 ) {
48 global $wgSQLiteDataDir;
50 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
51 if ( !is_readable( $fileName ) ) {
52 throw new DBConnectionError( $this, "SQLite database not accessible" );
55 $this->openFile( $fileName );
60 * Opens a database file
61 * @return SQL connection or false if failed
63 function openFile( $fileName ) {
64 $this->mDatabaseFile
= $fileName;
66 if ( $this->mFlags
& DBO_PERSISTENT
) {
67 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
68 array( PDO
::ATTR_PERSISTENT
=> true ) );
70 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
72 } catch ( PDOException
$e ) {
73 $err = $e->getMessage();
75 if ( $this->mConn
=== false ) {
76 wfDebug( "DB connection error: $err\n" );
77 if ( !$this->mFailFunction
) {
78 throw new DBConnectionError( $this, $err );
84 $this->mOpened
= !!$this->mConn
;
85 # set error codes only, don't raise exceptions
86 if ( $this->mOpened
) {
87 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
93 * Close an SQLite database
96 $this->mOpened
= false;
97 if ( is_object( $this->mConn
) ) {
98 if ( $this->trxLevel() ) $this->commit();
105 * Generates a database file name. Explicitly public for installer.
106 * @param $dir String: Directory where database resides
107 * @param $dbName String: Database name
110 public static function generateFileName( $dir, $dbName ) {
111 return "$dir/$dbName.sqlite";
115 * Returns version of currently supported SQLite fulltext search module or false if none present.
118 function getFulltextSearchModule() {
119 $table = 'dummy_search_test';
120 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
121 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
122 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
129 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
131 function doQuery( $sql ) {
132 $res = $this->mConn
->query( $sql );
133 if ( $res === false ) {
136 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
137 $this->mAffectedRows
= $r->rowCount();
138 $res = new ResultWrapper( $this, $r->fetchAll() );
143 function freeResult( $res ) {
144 if ( $res instanceof ResultWrapper
)
150 function fetchObject( $res ) {
151 if ( $res instanceof ResultWrapper
)
156 $cur = current( $r );
157 if ( is_array( $cur ) ) {
160 foreach ( $cur as $k => $v )
161 if ( !is_numeric( $k ) )
169 function fetchRow( $res ) {
170 if ( $res instanceof ResultWrapper
)
175 $cur = current( $r );
176 if ( is_array( $cur ) ) {
184 * The PDO::Statement class implements the array interface so count() will work
186 function numRows( $res ) {
187 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
191 function numFields( $res ) {
192 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
193 return is_array( $r ) ?
count( $r[0] ) : 0;
196 function fieldName( $res, $n ) {
197 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
198 if ( is_array( $r ) ) {
199 $keys = array_keys( $r[0] );
206 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
208 function tableName( $name ) {
209 return str_replace( '`', '', parent
::tableName( $name ) );
213 * Index names have DB scope
215 function indexName( $index ) {
220 * This must be called after nextSequenceVal
222 function insertId() {
223 return $this->mConn
->lastInsertId();
226 function dataSeek( $res, $row ) {
227 if ( $res instanceof ResultWrapper
)
233 for ( $i = 0; $i < $row; $i++
)
237 function lastError() {
238 if ( !is_object( $this->mConn
) )
239 return "Cannot return last error, no db connection";
240 $e = $this->mConn
->errorInfo();
241 return isset( $e[2] ) ?
$e[2] : '';
244 function lastErrno() {
245 if ( !is_object( $this->mConn
) ) {
246 return "Cannot return last error, no db connection";
248 $info = $this->mConn
->errorInfo();
253 function affectedRows() {
254 return $this->mAffectedRows
;
258 * Returns information about an index
259 * Returns false if the index does not exist
260 * - if errors are explicitly ignored, returns NULL on failure
262 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
263 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
264 $res = $this->query( $sql, $fname );
268 if ( $res->numRows() == 0 ) {
272 foreach ( $res as $row ) {
273 $info[] = $row->name
;
278 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
279 $row = $this->selectRow( 'sqlite_master', '*',
282 'name' => $this->indexName( $index ),
284 if ( !$row ||
!isset( $row->sql
) ) {
288 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
289 $indexPos = strpos( $row->sql
, 'INDEX' );
290 if ( $indexPos === false ) {
293 $firstPart = substr( $row->sql
, 0, $indexPos );
294 $options = explode( ' ', $firstPart );
295 return in_array( 'UNIQUE', $options );
299 * Filter the options used in SELECT statements
301 function makeSelectOptions( $options ) {
302 foreach ( $options as $k => $v )
303 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
305 return parent
::makeSelectOptions( $options );
309 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
311 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
312 if ( !count( $a ) ) return true;
313 if ( !is_array( $options ) ) $options = array( $options );
315 # SQLite uses OR IGNORE not just IGNORE
316 foreach ( $options as $k => $v )
317 if ( $v == 'IGNORE' )
318 $options[$k] = 'OR IGNORE';
320 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
321 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
323 foreach ( $a as $k => $v )
324 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
327 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
333 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
334 if ( !count( $rows ) ) return true;
336 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
337 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
339 foreach ( $rows as $k => $v )
340 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
343 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
350 * Returns the size of a text field, or -1 for "unlimited"
351 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
353 function textFieldSize( $table, $field ) {
357 function unionSupportsOrderAndLimit() {
361 function unionQueries( $sqls, $all ) {
362 $glue = $all ?
' UNION ALL ' : ' UNION ';
363 return implode( $glue, $sqls );
366 function wasDeadlock() {
367 return $this->lastErrno() == 5; // SQLITE_BUSY
370 function wasErrorReissuable() {
371 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
374 function wasReadOnlyError() {
375 return $this->lastErrno() == 8; // SQLITE_READONLY;
379 * @return string wikitext of a link to the server software's web site
381 function getSoftwareLink() {
382 return "[http://sqlite.org/ SQLite]";
386 * @return string Version information from the database
388 function getServerVersion() {
389 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
394 * Query whether a given column exists in the mediawiki schema
396 function fieldExists( $table, $field, $fname = '' ) {
397 $info = $this->fieldInfo( $table, $field );
402 * Get information about a given field
403 * Returns false if the field does not exist.
405 function fieldInfo( $table, $field ) {
406 $tableName = $this->tableName( $table );
407 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
408 $res = $this->query( $sql, __METHOD__
);
409 foreach ( $res as $row ) {
410 if ( $row->name
== $field ) {
411 return new SQLiteField( $row, $tableName );
417 function begin( $fname = '' ) {
418 if ( $this->mTrxLevel
== 1 ) $this->commit();
419 $this->mConn
->beginTransaction();
420 $this->mTrxLevel
= 1;
423 function commit( $fname = '' ) {
424 if ( $this->mTrxLevel
== 0 ) return;
425 $this->mConn
->commit();
426 $this->mTrxLevel
= 0;
429 function rollback( $fname = '' ) {
430 if ( $this->mTrxLevel
== 0 ) return;
431 $this->mConn
->rollBack();
432 $this->mTrxLevel
= 0;
435 function limitResultForUpdate( $sql, $num ) {
436 return $this->limitResult( $sql, $num );
439 function strencode( $s ) {
440 return substr( $this->addQuotes( $s ), 1, - 1 );
443 function encodeBlob( $b ) {
444 return new Blob( $b );
447 function decodeBlob( $b ) {
448 if ( $b instanceof Blob
) {
454 function addQuotes( $s ) {
455 if ( $s instanceof Blob
) {
456 return "x'" . bin2hex( $s->fetch() ) . "'";
458 return $this->mConn
->quote( $s );
462 function quote_ident( $s ) {
466 function buildLike() {
467 $params = func_get_args();
468 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
469 $params = $params[0];
471 return parent
::buildLike( $params ) . "ESCAPE '\' ";
475 * How lagged is this slave?
477 public function getLag() {
482 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
483 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
485 public function setup_database() {
488 # Process common MySQL/SQLite table definitions
489 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
490 if ( $err !== true ) {
491 echo " <b>FAILED</b></li>";
492 dieout( htmlspecialchars( $err ) );
496 # Use DatabasePostgres's code to populate interwiki from MySQL template
497 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
499 dieout( "Could not find the interwiki.sql file." );
502 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
503 while ( !feof( $f ) ) {
504 $line = fgets( $f, 1024 );
506 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
507 $this->query( "$sql $matches[1],$matches[2])" );
511 public function getSearchEngine() {
512 return "SearchSqlite";
516 * No-op version of deadlockLoop
518 public function deadlockLoop( /*...*/ ) {
519 $args = func_get_args();
520 $function = array_shift( $args );
521 return call_user_func_array( $function, $args );
524 protected function replaceVars( $s ) {
525 $s = parent
::replaceVars( $s );
526 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
527 // CREATE TABLE hacks to allow schema file sharing with MySQL
529 // binary/varbinary column type -> blob
530 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
531 // no such thing as unsigned
532 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
534 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\([\s\d]*\)|\b)/i', 'INTEGER', $s );
536 $s = preg_replace( '/\bvarchar\(\d+\)/i', 'TEXT', $s );
537 // TEXT normalization
538 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
539 // BLOB normalization
540 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
542 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
544 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
546 $s = preg_replace( '/enum\([^)]*\)/i', 'BLOB', $s );
547 // binary collation type -> nothing
548 $s = preg_replace( '/\bbinary\b/i', '', $s );
549 // auto_increment -> autoincrement
550 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
551 // No explicit options
552 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
553 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
554 // No truncated indexes
555 $s = preg_replace( '/\(\d+\)/', '', $s );
557 $s = preg_replace( '/\bfulltext\b/i', '', $s );
563 * Build a concatenation list to feed into a SQL query
565 function buildConcat( $stringList ) {
566 return '(' . implode( ') || (', $stringList ) . ')';
569 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
570 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
571 $obj = $this->fetchObject( $res );
573 throw new MWException( "Couldn't retrieve structure for table $oldName" );
576 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
577 return $this->query( $sql, $fname );
580 } // end DatabaseSqlite class
583 * This class allows simple acccess to a SQLite database independently from main database settings
586 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
587 public function __construct( $fileName, $flags = 0 ) {
588 $this->mFlags
= $flags;
589 $this->openFile( $fileName );
597 private $info, $tableName;
598 function __construct( $info, $tableName ) {
600 $this->tableName
= $tableName;
604 return $this->info
->name
;
607 function tableName() {
608 return $this->tableName
;
611 function defaultValue() {
612 if ( is_string( $this->info
->dflt_value
) ) {
614 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
615 return str_replace( "''", "'", $this->info
->dflt_value
);
618 return $this->info
->dflt_value
;
621 function maxLength() {
625 function nullable() {
626 // SQLite dynamic types are always nullable
630 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
631 # Suggest removal from base class [TS]
634 return $this->info
->type
;