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" ); $this->mConn
= false;
54 $this->openFile( $fileName );
59 * Opens a database file
60 * @return SQL connection or false if failed
62 function openFile( $fileName ) {
63 $this->mDatabaseFile
= $fileName;
65 if ( $this->mFlags
& DBO_PERSISTENT
) {
66 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
67 array( PDO
::ATTR_PERSISTENT
=> true ) );
69 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
71 } catch ( PDOException
$e ) {
72 $err = $e->getMessage();
74 if ( $this->mConn
=== false ) {
75 wfDebug( "DB connection error: $err\n" );
76 if ( !$this->mFailFunction
) {
77 throw new DBConnectionError( $this, $err );
83 $this->mOpened
= !!$this->mConn
;
84 # set error codes only, don't raise exceptions
85 if ( $this->mOpened
) {
86 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
92 * Close an SQLite database
95 $this->mOpened
= false;
96 if ( is_object( $this->mConn
) ) {
97 if ( $this->trxLevel() ) $this->commit();
104 * Generates a database file name. Explicitly public for installer.
105 * @param $dir String: Directory where database resides
106 * @param $dbName String: Database name
109 public static function generateFileName( $dir, $dbName ) {
110 return "$dir/$dbName.sqlite";
114 * Returns version of currently supported SQLite fulltext search module or false if none present.
117 function getFulltextSearchModule() {
118 $table = 'dummy_search_test';
119 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
120 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
121 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
128 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
130 function doQuery( $sql ) {
131 $res = $this->mConn
->query( $sql );
132 if ( $res === false ) {
135 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
136 $this->mAffectedRows
= $r->rowCount();
137 $res = new ResultWrapper( $this, $r->fetchAll() );
142 function freeResult( $res ) {
143 if ( $res instanceof ResultWrapper
)
149 function fetchObject( $res ) {
150 if ( $res instanceof ResultWrapper
)
155 $cur = current( $r );
156 if ( is_array( $cur ) ) {
159 foreach ( $cur as $k => $v )
160 if ( !is_numeric( $k ) )
168 function fetchRow( $res ) {
169 if ( $res instanceof ResultWrapper
)
174 $cur = current( $r );
175 if ( is_array( $cur ) ) {
183 * The PDO::Statement class implements the array interface so count() will work
185 function numRows( $res ) {
186 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
190 function numFields( $res ) {
191 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
192 return is_array( $r ) ?
count( $r[0] ) : 0;
195 function fieldName( $res, $n ) {
196 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
197 if ( is_array( $r ) ) {
198 $keys = array_keys( $r[0] );
205 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
207 function tableName( $name ) {
208 return str_replace( '`', '', parent
::tableName( $name ) );
212 * Index names have DB scope
214 function indexName( $index ) {
219 * This must be called after nextSequenceVal
221 function insertId() {
222 return $this->mConn
->lastInsertId();
225 function dataSeek( $res, $row ) {
226 if ( $res instanceof ResultWrapper
)
232 for ( $i = 0; $i < $row; $i++
)
236 function lastError() {
237 if ( !is_object( $this->mConn
) )
238 return "Cannot return last error, no db connection";
239 $e = $this->mConn
->errorInfo();
240 return isset( $e[2] ) ?
$e[2] : '';
243 function lastErrno() {
244 if ( !is_object( $this->mConn
) ) {
245 return "Cannot return last error, no db connection";
247 $info = $this->mConn
->errorInfo();
252 function affectedRows() {
253 return $this->mAffectedRows
;
257 * Returns information about an index
258 * Returns false if the index does not exist
259 * - if errors are explicitly ignored, returns NULL on failure
261 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
262 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
263 $res = $this->query( $sql, $fname );
267 if ( $res->numRows() == 0 ) {
271 foreach ( $res as $row ) {
272 $info[] = $row->name
;
277 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
278 $row = $this->selectRow( 'sqlite_master', '*',
281 'name' => $this->indexName( $index ),
283 if ( !$row ||
!isset( $row->sql
) ) {
287 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
288 $indexPos = strpos( $row->sql
, 'INDEX' );
289 if ( $indexPos === false ) {
292 $firstPart = substr( $row->sql
, 0, $indexPos );
293 $options = explode( ' ', $firstPart );
294 return in_array( 'UNIQUE', $options );
298 * Filter the options used in SELECT statements
300 function makeSelectOptions( $options ) {
301 foreach ( $options as $k => $v )
302 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
304 return parent
::makeSelectOptions( $options );
308 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
310 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
311 if ( !count( $a ) ) return true;
312 if ( !is_array( $options ) ) $options = array( $options );
314 # SQLite uses OR IGNORE not just IGNORE
315 foreach ( $options as $k => $v )
316 if ( $v == 'IGNORE' )
317 $options[$k] = 'OR IGNORE';
319 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
320 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
322 foreach ( $a as $k => $v )
323 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
326 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
332 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
333 if ( !count( $rows ) ) return true;
335 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
336 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
338 foreach ( $rows as $k => $v )
339 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
342 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
349 * Returns the size of a text field, or -1 for "unlimited"
350 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
352 function textFieldSize( $table, $field ) {
356 function unionSupportsOrderAndLimit() {
360 function unionQueries( $sqls, $all ) {
361 $glue = $all ?
' UNION ALL ' : ' UNION ';
362 return implode( $glue, $sqls );
365 function wasDeadlock() {
366 return $this->lastErrno() == 5; // SQLITE_BUSY
369 function wasErrorReissuable() {
370 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
373 function wasReadOnlyError() {
374 return $this->lastErrno() == 8; // SQLITE_READONLY;
378 * @return string wikitext of a link to the server software's web site
380 function getSoftwareLink() {
381 return "[http://sqlite.org/ SQLite]";
385 * @return string Version information from the database
387 function getServerVersion() {
388 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
393 * Query whether a given column exists in the mediawiki schema
395 function fieldExists( $table, $field, $fname = '' ) {
396 $info = $this->fieldInfo( $table, $field );
401 * Get information about a given field
402 * Returns false if the field does not exist.
404 function fieldInfo( $table, $field ) {
405 $tableName = $this->tableName( $table );
406 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
407 $res = $this->query( $sql, __METHOD__
);
408 foreach ( $res as $row ) {
409 if ( $row->name
== $field ) {
410 return new SQLiteField( $row, $tableName );
416 function begin( $fname = '' ) {
417 if ( $this->mTrxLevel
== 1 ) $this->commit();
418 $this->mConn
->beginTransaction();
419 $this->mTrxLevel
= 1;
422 function commit( $fname = '' ) {
423 if ( $this->mTrxLevel
== 0 ) return;
424 $this->mConn
->commit();
425 $this->mTrxLevel
= 0;
428 function rollback( $fname = '' ) {
429 if ( $this->mTrxLevel
== 0 ) return;
430 $this->mConn
->rollBack();
431 $this->mTrxLevel
= 0;
434 function limitResultForUpdate( $sql, $num ) {
435 return $this->limitResult( $sql, $num );
438 function strencode( $s ) {
439 return substr( $this->addQuotes( $s ), 1, - 1 );
442 function encodeBlob( $b ) {
443 return new Blob( $b );
446 function decodeBlob( $b ) {
447 if ( $b instanceof Blob
) {
453 function addQuotes( $s ) {
454 if ( $s instanceof Blob
) {
455 return "x'" . bin2hex( $s->fetch() ) . "'";
457 return $this->mConn
->quote( $s );
461 function quote_ident( $s ) {
465 function buildLike() {
466 $params = func_get_args();
467 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
468 $params = $params[0];
470 return parent
::buildLike( $params ) . "ESCAPE '\' ";
474 * How lagged is this slave?
476 public function getLag() {
481 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
482 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
484 public function setup_database() {
487 # Process common MySQL/SQLite table definitions
488 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
489 if ( $err !== true ) {
490 echo " <b>FAILED</b></li>";
491 dieout( htmlspecialchars( $err ) );
495 # Use DatabasePostgres's code to populate interwiki from MySQL template
496 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
498 dieout( "Could not find the interwiki.sql file." );
501 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
502 while ( !feof( $f ) ) {
503 $line = fgets( $f, 1024 );
505 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
506 $this->query( "$sql $matches[1],$matches[2])" );
510 public function getSearchEngine() {
511 return "SearchSqlite";
515 * No-op version of deadlockLoop
517 public function deadlockLoop( /*...*/ ) {
518 $args = func_get_args();
519 $function = array_shift( $args );
520 return call_user_func_array( $function, $args );
523 protected function replaceVars( $s ) {
524 $s = parent
::replaceVars( $s );
525 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
526 // CREATE TABLE hacks to allow schema file sharing with MySQL
528 // binary/varbinary column type -> blob
529 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
530 // no such thing as unsigned
531 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
533 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\([\s\d]*\)|\b)/i', 'INTEGER', $s );
535 $s = preg_replace( '/\bvarchar\(\d+\)/i', 'TEXT', $s );
536 // TEXT normalization
537 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
538 // BLOB normalization
539 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
541 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
543 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
545 $s = preg_replace( '/enum\([^)]*\)/i', 'BLOB', $s );
546 // binary collation type -> nothing
547 $s = preg_replace( '/\bbinary\b/i', '', $s );
548 // auto_increment -> autoincrement
549 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
550 // No explicit options
551 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
552 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
553 // No truncated indexes
554 $s = preg_replace( '/\(\d+\)/', '', $s );
556 $s = preg_replace( '/\bfulltext\b/i', '', $s );
562 * Build a concatenation list to feed into a SQL query
564 function buildConcat( $stringList ) {
565 return '(' . implode( ') || (', $stringList ) . ')';
568 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
569 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
570 $obj = $this->fetchObject( $res );
572 throw new MWException( "Couldn't retrieve structure for table $oldName" );
575 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
576 return $this->query( $sql, $fname );
579 } // end DatabaseSqlite class
582 * This class allows simple acccess to a SQLite database independently from main database settings
585 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
586 public function __construct( $fileName, $flags = 0 ) {
587 $this->mFlags
= $flags;
588 $this->openFile( $fileName );
596 private $info, $tableName;
597 function __construct( $info, $tableName ) {
599 $this->tableName
= $tableName;
603 return $this->info
->name
;
606 function tableName() {
607 return $this->tableName
;
610 function defaultValue() {
611 if ( is_string( $this->info
->dflt_value
) ) {
613 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
614 return str_replace( "''", "'", $this->info
->dflt_value
);
617 return $this->info
->dflt_value
;
620 function maxLength() {
624 function nullable() {
625 // SQLite dynamic types are always nullable
629 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
630 # Suggest removal from base class [TS]
633 return $this->info
->type
;