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
{
15 private static $fulltextEnabled = null;
24 * Parameters $server, $user and $password are not used.
26 function __construct( $server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0 ) {
27 $this->mFailFunction
= $failFunction;
28 $this->mFlags
= $flags;
29 $this->mName
= $dbName;
30 $this->open( $server, $user, $password, $dbName );
38 * @todo: check if it should be true like parent class
40 function implicitGroupby() { return false; }
42 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
43 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
46 /** Open an SQLite database and return a resource handle to it
47 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
49 function open( $server, $user, $pass, $dbName ) {
50 global $wgSQLiteDataDir;
52 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
53 if ( !is_readable( $fileName ) ) {
54 throw new DBConnectionError( $this, "SQLite database not accessible" );
57 $this->openFile( $fileName );
62 * Opens a database file
63 * @return SQL connection or false if failed
65 function openFile( $fileName ) {
66 $this->mDatabaseFile
= $fileName;
68 if ( $this->mFlags
& DBO_PERSISTENT
) {
69 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
70 array( PDO
::ATTR_PERSISTENT
=> true ) );
72 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
74 } catch ( PDOException
$e ) {
75 $err = $e->getMessage();
77 if ( $this->mConn
=== false ) {
78 wfDebug( "DB connection error: $err\n" );
79 if ( !$this->mFailFunction
) {
80 throw new DBConnectionError( $this, $err );
86 $this->mOpened
= !!$this->mConn
;
87 # set error codes only, don't raise exceptions
88 if ( $this->mOpened
) {
89 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
95 * Close an SQLite database
98 $this->mOpened
= false;
99 if ( is_object( $this->mConn
) ) {
100 if ( $this->trxLevel() ) $this->commit();
107 * Generates a database file name. Explicitly public for installer.
108 * @param $dir String: Directory where database resides
109 * @param $dbName String: Database name
112 public static function generateFileName( $dir, $dbName ) {
113 return "$dir/$dbName.sqlite";
117 * Check if the searchindext table is FTS enabled.
118 * @returns false if not enabled.
120 function checkForEnabledSearch() {
121 if ( self
::$fulltextEnabled === null ) {
122 self
::$fulltextEnabled = false;
123 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = 'searchindex'", __METHOD__
);
125 $row = $res->fetchRow();
126 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
129 return self
::$fulltextEnabled;
133 * Returns version of currently supported SQLite fulltext search module or false if none present.
136 function getFulltextSearchModule() {
137 $table = 'dummy_search_test';
138 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
140 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
141 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
148 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
150 function doQuery( $sql ) {
151 $res = $this->mConn
->query( $sql );
152 if ( $res === false ) {
155 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
156 $this->mAffectedRows
= $r->rowCount();
157 $res = new ResultWrapper( $this, $r->fetchAll() );
162 function freeResult( $res ) {
163 if ( $res instanceof ResultWrapper
)
169 function fetchObject( $res ) {
170 if ( $res instanceof ResultWrapper
)
175 $cur = current( $r );
176 if ( is_array( $cur ) ) {
179 foreach ( $cur as $k => $v )
180 if ( !is_numeric( $k ) )
188 function fetchRow( $res ) {
189 if ( $res instanceof ResultWrapper
)
194 $cur = current( $r );
195 if ( is_array( $cur ) ) {
203 * The PDO::Statement class implements the array interface so count() will work
205 function numRows( $res ) {
206 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
210 function numFields( $res ) {
211 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
212 return is_array( $r ) ?
count( $r[0] ) : 0;
215 function fieldName( $res, $n ) {
216 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
217 if ( is_array( $r ) ) {
218 $keys = array_keys( $r[0] );
225 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
227 function tableName( $name ) {
228 return str_replace( '`', '', parent
::tableName( $name ) );
232 * Index names have DB scope
234 function indexName( $index ) {
239 * This must be called after nextSequenceVal
241 function insertId() {
242 return $this->mConn
->lastInsertId();
245 function dataSeek( $res, $row ) {
246 if ( $res instanceof ResultWrapper
)
252 for ( $i = 0; $i < $row; $i++
)
256 function lastError() {
257 if ( !is_object( $this->mConn
) )
258 return "Cannot return last error, no db connection";
259 $e = $this->mConn
->errorInfo();
260 return isset( $e[2] ) ?
$e[2] : '';
263 function lastErrno() {
264 if ( !is_object( $this->mConn
) ) {
265 return "Cannot return last error, no db connection";
267 $info = $this->mConn
->errorInfo();
272 function affectedRows() {
273 return $this->mAffectedRows
;
277 * Returns information about an index
278 * Returns false if the index does not exist
279 * - if errors are explicitly ignored, returns NULL on failure
281 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
282 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
283 $res = $this->query( $sql, $fname );
287 if ( $res->numRows() == 0 ) {
291 foreach ( $res as $row ) {
292 $info[] = $row->name
;
297 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
298 $row = $this->selectRow( 'sqlite_master', '*',
301 'name' => $this->indexName( $index ),
303 if ( !$row ||
!isset( $row->sql
) ) {
307 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
308 $indexPos = strpos( $row->sql
, 'INDEX' );
309 if ( $indexPos === false ) {
312 $firstPart = substr( $row->sql
, 0, $indexPos );
313 $options = explode( ' ', $firstPart );
314 return in_array( 'UNIQUE', $options );
318 * Filter the options used in SELECT statements
320 function makeSelectOptions( $options ) {
321 foreach ( $options as $k => $v )
322 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
324 return parent
::makeSelectOptions( $options );
328 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
330 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
331 if ( !count( $a ) ) return true;
332 if ( !is_array( $options ) ) $options = array( $options );
334 # SQLite uses OR IGNORE not just IGNORE
335 foreach ( $options as $k => $v )
336 if ( $v == 'IGNORE' )
337 $options[$k] = 'OR IGNORE';
339 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
340 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
342 foreach ( $a as $k => $v )
343 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
346 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
352 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
353 if ( !count( $rows ) ) return true;
355 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
356 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
358 foreach ( $rows as $k => $v )
359 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
362 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
369 * Returns the size of a text field, or -1 for "unlimited"
370 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
372 function textFieldSize( $table, $field ) {
376 function unionSupportsOrderAndLimit() {
380 function unionQueries( $sqls, $all ) {
381 $glue = $all ?
' UNION ALL ' : ' UNION ';
382 return implode( $glue, $sqls );
385 function wasDeadlock() {
386 return $this->lastErrno() == 5; // SQLITE_BUSY
389 function wasErrorReissuable() {
390 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
393 function wasReadOnlyError() {
394 return $this->lastErrno() == 8; // SQLITE_READONLY;
398 * @return string wikitext of a link to the server software's web site
400 function getSoftwareLink() {
401 return "[http://sqlite.org/ SQLite]";
405 * @return string Version information from the database
407 function getServerVersion() {
408 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
413 * Query whether a given column exists in the mediawiki schema
415 function fieldExists( $table, $field, $fname = '' ) {
416 $info = $this->fieldInfo( $table, $field );
421 * Get information about a given field
422 * Returns false if the field does not exist.
424 function fieldInfo( $table, $field ) {
425 $tableName = $this->tableName( $table );
426 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
427 $res = $this->query( $sql, __METHOD__
);
428 foreach ( $res as $row ) {
429 if ( $row->name
== $field ) {
430 return new SQLiteField( $row, $tableName );
436 function begin( $fname = '' ) {
437 if ( $this->mTrxLevel
== 1 ) $this->commit();
438 $this->mConn
->beginTransaction();
439 $this->mTrxLevel
= 1;
442 function commit( $fname = '' ) {
443 if ( $this->mTrxLevel
== 0 ) return;
444 $this->mConn
->commit();
445 $this->mTrxLevel
= 0;
448 function rollback( $fname = '' ) {
449 if ( $this->mTrxLevel
== 0 ) return;
450 $this->mConn
->rollBack();
451 $this->mTrxLevel
= 0;
454 function limitResultForUpdate( $sql, $num ) {
455 return $this->limitResult( $sql, $num );
458 function strencode( $s ) {
459 return substr( $this->addQuotes( $s ), 1, - 1 );
462 function encodeBlob( $b ) {
463 return new Blob( $b );
466 function decodeBlob( $b ) {
467 if ( $b instanceof Blob
) {
473 function addQuotes( $s ) {
474 if ( $s instanceof Blob
) {
475 return "x'" . bin2hex( $s->fetch() ) . "'";
477 return $this->mConn
->quote( $s );
481 function quote_ident( $s ) {
485 function buildLike() {
486 $params = func_get_args();
487 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
488 $params = $params[0];
490 return parent
::buildLike( $params ) . "ESCAPE '\' ";
494 * How lagged is this slave?
496 public function getLag() {
501 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
502 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
504 public function setup_database() {
507 # Process common MySQL/SQLite table definitions
508 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
509 if ( $err !== true ) {
510 echo " <b>FAILED</b></li>";
511 dieout( htmlspecialchars( $err ) );
515 # Use DatabasePostgres's code to populate interwiki from MySQL template
516 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
518 dieout( "Could not find the interwiki.sql file." );
521 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
522 while ( !feof( $f ) ) {
523 $line = fgets( $f, 1024 );
525 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
526 $this->query( "$sql $matches[1],$matches[2])" );
530 public function getSearchEngine() {
531 return "SearchSqlite";
535 * No-op version of deadlockLoop
537 public function deadlockLoop( /*...*/ ) {
538 $args = func_get_args();
539 $function = array_shift( $args );
540 return call_user_func_array( $function, $args );
543 protected function replaceVars( $s ) {
544 $s = parent
::replaceVars( $s );
545 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
546 // CREATE TABLE hacks to allow schema file sharing with MySQL
548 // binary/varbinary column type -> blob
549 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
550 // no such thing as unsigned
551 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
553 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\([\s\d]*\)|\b)/i', 'INTEGER', $s );
555 $s = preg_replace( '/\bvarchar\(\d+\)/i', 'TEXT', $s );
556 // TEXT normalization
557 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
558 // BLOB normalization
559 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
561 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
563 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
565 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
566 // binary collation type -> nothing
567 $s = preg_replace( '/\bbinary\b/i', '', $s );
568 // auto_increment -> autoincrement
569 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
570 // No explicit options
571 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
572 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
573 // No truncated indexes
574 $s = preg_replace( '/\(\d+\)/', '', $s );
576 $s = preg_replace( '/\bfulltext\b/i', '', $s );
582 * Build a concatenation list to feed into a SQL query
584 function buildConcat( $stringList ) {
585 return '(' . implode( ') || (', $stringList ) . ')';
588 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
589 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
590 $obj = $this->fetchObject( $res );
592 throw new MWException( "Couldn't retrieve structure for table $oldName" );
595 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
596 return $this->query( $sql, $fname );
599 } // end DatabaseSqlite class
602 * This class allows simple acccess to a SQLite database independently from main database settings
605 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
606 public function __construct( $fileName, $flags = 0 ) {
607 $this->mFlags
= $flags;
608 $this->openFile( $fileName );
616 private $info, $tableName;
617 function __construct( $info, $tableName ) {
619 $this->tableName
= $tableName;
623 return $this->info
->name
;
626 function tableName() {
627 return $this->tableName
;
630 function defaultValue() {
631 if ( is_string( $this->info
->dflt_value
) ) {
633 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
634 return str_replace( "''", "'", $this->info
->dflt_value
);
637 return $this->info
->dflt_value
;
640 function maxLength() {
644 function nullable() {
645 // SQLite dynamic types are always nullable
649 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
650 # Suggest removal from base class [TS]
653 return $this->info
->type
;