b963a2f7242856238f9dff6f96e6251ef2eabef8
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, $fileame = false ) {
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
)
164 $cur = current( $r );
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 generic 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 );
322 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
323 if ( !count( $rows ) ) return true;
325 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
326 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
328 foreach ( $rows as $k => $v )
329 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
332 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
339 * Returns the size of a text field, or -1 for "unlimited"
340 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
342 function textFieldSize( $table, $field ) {
346 function unionSupportsOrderAndLimit() {
350 function unionQueries( $sqls, $all ) {
351 $glue = $all ?
' UNION ALL ' : ' UNION ';
352 return implode( $glue, $sqls );
355 function wasDeadlock() {
356 return $this->lastErrno() == 5; // SQLITE_BUSY
359 function wasErrorReissuable() {
360 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
363 function wasReadOnlyError() {
364 return $this->lastErrno() == 8; // SQLITE_READONLY;
368 * @return string wikitext of a link to the server software's web site
370 function getSoftwareLink() {
371 return "[http://sqlite.org/ SQLite]";
375 * @return string Version information from the database
377 function getServerVersion() {
378 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
383 * Query whether a given column exists in the mediawiki schema
385 function fieldExists( $table, $field, $fname = '' ) {
386 $info = $this->fieldInfo( $table, $field );
391 * Get information about a given field
392 * Returns false if the field does not exist.
394 function fieldInfo( $table, $field ) {
395 $tableName = $this->tableName( $table );
396 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
397 $res = $this->query( $sql, __METHOD__
);
398 foreach ( $res as $row ) {
399 if ( $row->name
== $field ) {
400 return new SQLiteField( $row, $tableName );
406 function begin( $fname = '' ) {
407 if ( $this->mTrxLevel
== 1 ) $this->commit();
408 $this->mConn
->beginTransaction();
409 $this->mTrxLevel
= 1;
412 function commit( $fname = '' ) {
413 if ( $this->mTrxLevel
== 0 ) return;
414 $this->mConn
->commit();
415 $this->mTrxLevel
= 0;
418 function rollback( $fname = '' ) {
419 if ( $this->mTrxLevel
== 0 ) return;
420 $this->mConn
->rollBack();
421 $this->mTrxLevel
= 0;
424 function limitResultForUpdate( $sql, $num ) {
425 return $this->limitResult( $sql, $num );
428 function strencode( $s ) {
429 return substr( $this->addQuotes( $s ), 1, - 1 );
432 function encodeBlob( $b ) {
433 return new Blob( $b );
436 function decodeBlob( $b ) {
437 if ( $b instanceof Blob
) {
443 function addQuotes( $s ) {
444 if ( $s instanceof Blob
) {
445 return "x'" . bin2hex( $s->fetch() ) . "'";
447 return $this->mConn
->quote( $s );
451 function quote_ident( $s ) {
455 function buildLike() {
456 $params = func_get_args();
457 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
458 $params = $params[0];
460 return parent
::buildLike( $params ) . "ESCAPE '\' ";
464 * How lagged is this slave?
466 public function getLag() {
471 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
472 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
474 public function setup_database() {
477 # Process common MySQL/SQLite table definitions
478 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
479 if ( $err !== true ) {
480 $this->reportQueryError( $err, 0, $sql, __FUNCTION__
);
484 # Use DatabasePostgres's code to populate interwiki from MySQL template
485 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
486 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
487 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
488 while ( !feof( $f ) ) {
489 $line = fgets( $f, 1024 );
491 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
492 $this->query( "$sql $matches[1],$matches[2])" );
496 public function getSearchEngine() {
497 return "SearchSqlite";
501 * No-op version of deadlockLoop
503 public function deadlockLoop( /*...*/ ) {
504 $args = func_get_args();
505 $function = array_shift( $args );
506 return call_user_func_array( $function, $args );
509 protected function replaceVars( $s ) {
510 $s = parent
::replaceVars( $s );
511 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
512 // CREATE TABLE hacks to allow schema file sharing with MySQL
514 // binary/varbinary column type -> blob
515 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
516 // no such thing as unsigned
517 $s = preg_replace( '/\bunsigned\b/i', '', $s );
518 // INT -> INTEGER for primary keys
519 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
521 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
522 // binary collation type -> nothing
523 $s = preg_replace( '/\bbinary\b/i', '', $s );
524 // auto_increment -> autoincrement
525 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
526 // No explicit options
527 $s = preg_replace( '/\)[^)]*$/', ')', $s );
528 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
529 // No truncated indexes
530 $s = preg_replace( '/\(\d+\)/', '', $s );
532 $s = preg_replace( '/\bfulltext\b/i', '', $s );
538 * Build a concatenation list to feed into a SQL query
540 function buildConcat( $stringList ) {
541 return '(' . implode( ') || (', $stringList ) . ')';
544 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
545 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
546 $sql = $this->fetchObject( $res )->sql
;
547 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
548 return $this->query( $sql, $fname );
551 } // end DatabaseSqlite class
557 private $info, $tableName;
558 function __construct( $info, $tableName ) {
560 $this->tableName
= $tableName;
564 return $this->info
->name
;
567 function tableName() {
568 return $this->tableName
;
571 function defaultValue() {
572 if ( is_string( $this->info
->dflt_value
) ) {
574 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
575 return str_replace( "''", "'", $this->info
->dflt_value
);
578 return $this->info
->dflt_value
;
581 function maxLength() {
585 function nullable() {
586 // SQLite dynamic types are always nullable
590 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
591 # Suggest removal from base class [TS]
594 return $this->info
->type
;