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 ) {
28 $this->mFailFunction
= $failFunction;
29 $this->mFlags
= $flags;
30 $this->mName
= $dbName;
32 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
33 $this->attachDatabase( $wgSharedDB );
42 * @todo: check if it should be true like parent class
44 function implicitGroupby() { return false; }
46 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
47 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
50 /** Open an SQLite database and return a resource handle to it
51 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
53 function open( $server, $user, $pass, $dbName ) {
54 global $wgSQLiteDataDir;
56 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
57 if ( !is_readable( $fileName ) ) {
58 throw new DBConnectionError( $this, "SQLite database not accessible" );
61 $this->openFile( $fileName );
66 * Opens a database file
67 * @return SQL connection or false if failed
69 function openFile( $fileName ) {
70 $this->mDatabaseFile
= $fileName;
72 if ( $this->mFlags
& DBO_PERSISTENT
) {
73 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
74 array( PDO
::ATTR_PERSISTENT
=> true ) );
76 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
78 } catch ( PDOException
$e ) {
79 $err = $e->getMessage();
81 if ( $this->mConn
=== false ) {
82 wfDebug( "DB connection error: $err\n" );
83 if ( !$this->mFailFunction
) {
84 throw new DBConnectionError( $this, $err );
90 $this->mOpened
= !!$this->mConn
;
91 # set error codes only, don't raise exceptions
92 if ( $this->mOpened
) {
93 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
99 * Close an SQLite database
102 $this->mOpened
= false;
103 if ( is_object( $this->mConn
) ) {
104 if ( $this->trxLevel() ) $this->commit();
111 * Generates a database file name. Explicitly public for installer.
112 * @param $dir String: Directory where database resides
113 * @param $dbName String: Database name
116 public static function generateFileName( $dir, $dbName ) {
117 return "$dir/$dbName.sqlite";
121 * Check if the searchindext table is FTS enabled.
122 * @returns false if not enabled.
124 function checkForEnabledSearch() {
125 if ( self
::$fulltextEnabled === null ) {
126 self
::$fulltextEnabled = false;
127 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = 'searchindex'", __METHOD__
);
129 $row = $res->fetchRow();
130 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
133 return self
::$fulltextEnabled;
137 * Returns version of currently supported SQLite fulltext search module or false if none present.
140 function getFulltextSearchModule() {
141 $table = 'dummy_search_test';
142 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
144 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
145 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
152 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
154 * @param $name: Database name to be used in queries like SELECT foo FROM dbname.table
155 * @param $file: Database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
157 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
158 global $wgSQLiteDataDir;
160 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
162 $file = $this->addQuotes( $file );
163 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
167 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
169 function doQuery( $sql ) {
170 $res = $this->mConn
->query( $sql );
171 if ( $res === false ) {
174 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
175 $this->mAffectedRows
= $r->rowCount();
176 $res = new ResultWrapper( $this, $r->fetchAll() );
181 function freeResult( $res ) {
182 if ( $res instanceof ResultWrapper
)
188 function fetchObject( $res ) {
189 if ( $res instanceof ResultWrapper
)
194 $cur = current( $r );
195 if ( is_array( $cur ) ) {
198 foreach ( $cur as $k => $v )
199 if ( !is_numeric( $k ) )
207 function fetchRow( $res ) {
208 if ( $res instanceof ResultWrapper
)
213 $cur = current( $r );
214 if ( is_array( $cur ) ) {
222 * The PDO::Statement class implements the array interface so count() will work
224 function numRows( $res ) {
225 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
229 function numFields( $res ) {
230 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
231 return is_array( $r ) ?
count( $r[0] ) : 0;
234 function fieldName( $res, $n ) {
235 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
236 if ( is_array( $r ) ) {
237 $keys = array_keys( $r[0] );
244 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
246 function tableName( $name ) {
247 return str_replace( '`', '', parent
::tableName( $name ) );
251 * Index names have DB scope
253 function indexName( $index ) {
258 * This must be called after nextSequenceVal
260 function insertId() {
261 return $this->mConn
->lastInsertId();
264 function dataSeek( $res, $row ) {
265 if ( $res instanceof ResultWrapper
)
271 for ( $i = 0; $i < $row; $i++
)
275 function lastError() {
276 if ( !is_object( $this->mConn
) )
277 return "Cannot return last error, no db connection";
278 $e = $this->mConn
->errorInfo();
279 return isset( $e[2] ) ?
$e[2] : '';
282 function lastErrno() {
283 if ( !is_object( $this->mConn
) ) {
284 return "Cannot return last error, no db connection";
286 $info = $this->mConn
->errorInfo();
291 function affectedRows() {
292 return $this->mAffectedRows
;
296 * Returns information about an index
297 * Returns false if the index does not exist
298 * - if errors are explicitly ignored, returns NULL on failure
300 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
301 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
302 $res = $this->query( $sql, $fname );
306 if ( $res->numRows() == 0 ) {
310 foreach ( $res as $row ) {
311 $info[] = $row->name
;
316 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
317 $row = $this->selectRow( 'sqlite_master', '*',
320 'name' => $this->indexName( $index ),
322 if ( !$row ||
!isset( $row->sql
) ) {
326 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
327 $indexPos = strpos( $row->sql
, 'INDEX' );
328 if ( $indexPos === false ) {
331 $firstPart = substr( $row->sql
, 0, $indexPos );
332 $options = explode( ' ', $firstPart );
333 return in_array( 'UNIQUE', $options );
337 * Filter the options used in SELECT statements
339 function makeSelectOptions( $options ) {
340 foreach ( $options as $k => $v )
341 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
343 return parent
::makeSelectOptions( $options );
347 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
349 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
350 if ( !count( $a ) ) return true;
351 if ( !is_array( $options ) ) $options = array( $options );
353 # SQLite uses OR IGNORE not just IGNORE
354 foreach ( $options as $k => $v )
355 if ( $v == 'IGNORE' )
356 $options[$k] = 'OR IGNORE';
358 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
359 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
361 foreach ( $a as $k => $v )
362 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) )
365 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
371 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
372 if ( !count( $rows ) ) return true;
374 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
375 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
377 foreach ( $rows as $k => $v )
378 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
381 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
388 * Returns the size of a text field, or -1 for "unlimited"
389 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
391 function textFieldSize( $table, $field ) {
395 function unionSupportsOrderAndLimit() {
399 function unionQueries( $sqls, $all ) {
400 $glue = $all ?
' UNION ALL ' : ' UNION ';
401 return implode( $glue, $sqls );
404 function wasDeadlock() {
405 return $this->lastErrno() == 5; // SQLITE_BUSY
408 function wasErrorReissuable() {
409 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
412 function wasReadOnlyError() {
413 return $this->lastErrno() == 8; // SQLITE_READONLY;
417 * @return string wikitext of a link to the server software's web site
419 function getSoftwareLink() {
420 return "[http://sqlite.org/ SQLite]";
424 * @return string Version information from the database
426 function getServerVersion() {
427 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
432 * Query whether a given column exists in the mediawiki schema
434 function fieldExists( $table, $field, $fname = '' ) {
435 $info = $this->fieldInfo( $table, $field );
440 * Get information about a given field
441 * Returns false if the field does not exist.
443 function fieldInfo( $table, $field ) {
444 $tableName = $this->tableName( $table );
445 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
446 $res = $this->query( $sql, __METHOD__
);
447 foreach ( $res as $row ) {
448 if ( $row->name
== $field ) {
449 return new SQLiteField( $row, $tableName );
455 function begin( $fname = '' ) {
456 if ( $this->mTrxLevel
== 1 ) $this->commit();
457 $this->mConn
->beginTransaction();
458 $this->mTrxLevel
= 1;
461 function commit( $fname = '' ) {
462 if ( $this->mTrxLevel
== 0 ) return;
463 $this->mConn
->commit();
464 $this->mTrxLevel
= 0;
467 function rollback( $fname = '' ) {
468 if ( $this->mTrxLevel
== 0 ) return;
469 $this->mConn
->rollBack();
470 $this->mTrxLevel
= 0;
473 function limitResultForUpdate( $sql, $num ) {
474 return $this->limitResult( $sql, $num );
477 function strencode( $s ) {
478 return substr( $this->addQuotes( $s ), 1, - 1 );
481 function encodeBlob( $b ) {
482 return new Blob( $b );
485 function decodeBlob( $b ) {
486 if ( $b instanceof Blob
) {
492 function addQuotes( $s ) {
493 if ( $s instanceof Blob
) {
494 return "x'" . bin2hex( $s->fetch() ) . "'";
496 return $this->mConn
->quote( $s );
500 function quote_ident( $s ) {
504 function buildLike() {
505 $params = func_get_args();
506 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
507 $params = $params[0];
509 return parent
::buildLike( $params ) . "ESCAPE '\' ";
513 * How lagged is this slave?
515 public function getLag() {
520 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
521 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
523 public function setup_database() {
526 # Process common MySQL/SQLite table definitions
527 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
528 if ( $err !== true ) {
529 echo " <b>FAILED</b></li>";
530 dieout( htmlspecialchars( $err ) );
534 # Use DatabasePostgres's code to populate interwiki from MySQL template
535 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
537 dieout( "Could not find the interwiki.sql file." );
540 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
541 while ( !feof( $f ) ) {
542 $line = fgets( $f, 1024 );
544 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
545 $this->query( "$sql $matches[1],$matches[2])" );
549 public function getSearchEngine() {
550 return "SearchSqlite";
554 * No-op version of deadlockLoop
556 public function deadlockLoop( /*...*/ ) {
557 $args = func_get_args();
558 $function = array_shift( $args );
559 return call_user_func_array( $function, $args );
562 protected function replaceVars( $s ) {
563 $s = parent
::replaceVars( $s );
564 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
565 // CREATE TABLE hacks to allow schema file sharing with MySQL
567 // binary/varbinary column type -> blob
568 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
569 // no such thing as unsigned
570 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
572 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\([\s\d]*\)|\b)/i', 'INTEGER', $s );
574 $s = preg_replace( '/\bvarchar\(\d+\)/i', 'TEXT', $s );
575 // TEXT normalization
576 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
577 // BLOB normalization
578 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
580 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
582 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
584 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
585 // binary collation type -> nothing
586 $s = preg_replace( '/\bbinary\b/i', '', $s );
587 // auto_increment -> autoincrement
588 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
589 // No explicit options
590 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
591 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
592 // No truncated indexes
593 $s = preg_replace( '/\(\d+\)/', '', $s );
595 $s = preg_replace( '/\bfulltext\b/i', '', $s );
601 * Build a concatenation list to feed into a SQL query
603 function buildConcat( $stringList ) {
604 return '(' . implode( ') || (', $stringList ) . ')';
607 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
608 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
609 $obj = $this->fetchObject( $res );
611 throw new MWException( "Couldn't retrieve structure for table $oldName" );
614 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
615 return $this->query( $sql, $fname );
618 } // end DatabaseSqlite class
621 * This class allows simple acccess to a SQLite database independently from main database settings
624 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
625 public function __construct( $fileName, $flags = 0 ) {
626 $this->mFlags
= $flags;
627 $this->openFile( $fileName );
635 private $info, $tableName;
636 function __construct( $info, $tableName ) {
638 $this->tableName
= $tableName;
642 return $this->info
->name
;
645 function tableName() {
646 return $this->tableName
;
649 function defaultValue() {
650 if ( is_string( $this->info
->dflt_value
) ) {
652 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
653 return str_replace( "''", "'", $this->info
->dflt_value
);
656 return $this->info
->dflt_value
;
659 function maxLength() {
663 function nullable() {
664 // SQLite dynamic types are always nullable
668 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
669 # Suggest removal from base class [TS]
672 return $this->info
->type
;