3 * This is the SQLite database abstraction layer.
4 * 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, $flags = 0 ) {
28 $this->mFlags
= $flags;
29 $this->mName
= $dbName;
32 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
33 $this->attachDatabase( $wgSharedDB );
43 * @todo: check if it should be true like parent class
45 function implicitGroupby() { return false; }
47 /** Open an SQLite database and return a resource handle to it
48 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
50 function open( $server, $user, $pass, $dbName ) {
51 global $wgSQLiteDataDir;
53 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
54 if ( !is_readable( $fileName ) ) {
56 throw new DBConnectionError( $this, "SQLite database not accessible" );
58 $this->openFile( $fileName );
63 * Opens a database file
64 * @return SQL connection or false if failed
66 function openFile( $fileName ) {
67 $this->mDatabaseFile
= $fileName;
69 if ( $this->mFlags
& DBO_PERSISTENT
) {
70 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
71 array( PDO
::ATTR_PERSISTENT
=> true ) );
73 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
75 } catch ( PDOException
$e ) {
76 $err = $e->getMessage();
78 if ( !$this->mConn
) {
79 wfDebug( "DB connection error: $err\n" );
80 throw new DBConnectionError( $this, $err );
82 $this->mOpened
= !!$this->mConn
;
83 # set error codes only, don't raise exceptions
84 if ( $this->mOpened
) {
85 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
91 * Close an SQLite database
94 $this->mOpened
= false;
95 if ( is_object( $this->mConn
) ) {
96 if ( $this->trxLevel() ) $this->commit();
103 * Generates a database file name. Explicitly public for installer.
104 * @param $dir String: Directory where database resides
105 * @param $dbName String: Database name
108 public static function generateFileName( $dir, $dbName ) {
109 return "$dir/$dbName.sqlite";
113 * Check if the searchindext table is FTS enabled.
114 * @returns false if not enabled.
116 function checkForEnabledSearch() {
117 if ( self
::$fulltextEnabled === null ) {
118 self
::$fulltextEnabled = false;
119 $table = $this->tableName( 'searchindex' );
120 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
122 $row = $res->fetchRow();
123 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
126 return self
::$fulltextEnabled;
130 * Returns version of currently supported SQLite fulltext search module or false if none present.
133 function getFulltextSearchModule() {
134 static $cachedResult = null;
135 if ( $cachedResult !== null ) {
136 return $cachedResult;
138 $cachedResult = false;
139 $table = 'dummy_search_test';
140 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
142 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
143 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__
);
144 $cachedResult = 'FTS3';
146 return $cachedResult;
150 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
152 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
153 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
154 * @param $fname String: calling function name
156 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
157 global $wgSQLiteDataDir;
159 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
161 $file = $this->addQuotes( $file );
162 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
166 * @see DatabaseBase::isWriteQuery()
168 function isWriteQuery( $sql ) {
169 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
173 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
175 function doQuery( $sql ) {
176 $res = $this->mConn
->query( $sql );
177 if ( $res === false ) {
180 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
181 $this->mAffectedRows
= $r->rowCount();
182 $res = new ResultWrapper( $this, $r->fetchAll() );
187 function freeResult( $res ) {
188 if ( $res instanceof ResultWrapper
) {
195 function fetchObject( $res ) {
196 if ( $res instanceof ResultWrapper
) {
202 $cur = current( $r );
203 if ( is_array( $cur ) ) {
206 foreach ( $cur as $k => $v ) {
207 if ( !is_numeric( $k ) ) {
217 function fetchRow( $res ) {
218 if ( $res instanceof ResultWrapper
) {
223 $cur = current( $r );
224 if ( is_array( $cur ) ) {
232 * The PDO::Statement class implements the array interface so count() will work
234 function numRows( $res ) {
235 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
239 function numFields( $res ) {
240 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
241 return is_array( $r ) ?
count( $r[0] ) : 0;
244 function fieldName( $res, $n ) {
245 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
246 if ( is_array( $r ) ) {
247 $keys = array_keys( $r[0] );
254 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
256 function tableName( $name ) {
257 // table names starting with sqlite_ are reserved
258 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
259 return str_replace( '`', '', parent
::tableName( $name ) );
263 * Index names have DB scope
265 function indexName( $index ) {
270 * This must be called after nextSequenceVal
272 function insertId() {
273 return $this->mConn
->lastInsertId();
276 function dataSeek( $res, $row ) {
277 if ( $res instanceof ResultWrapper
) {
284 for ( $i = 0; $i < $row; $i++
) {
290 function lastError() {
291 if ( !is_object( $this->mConn
) ) {
292 return "Cannot return last error, no db connection";
294 $e = $this->mConn
->errorInfo();
295 return isset( $e[2] ) ?
$e[2] : '';
298 function lastErrno() {
299 if ( !is_object( $this->mConn
) ) {
300 return "Cannot return last error, no db connection";
302 $info = $this->mConn
->errorInfo();
307 function affectedRows() {
308 return $this->mAffectedRows
;
312 * Returns information about an index
313 * Returns false if the index does not exist
314 * - if errors are explicitly ignored, returns NULL on failure
316 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
317 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
318 $res = $this->query( $sql, $fname );
322 if ( $res->numRows() == 0 ) {
326 foreach ( $res as $row ) {
327 $info[] = $row->name
;
332 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
333 $row = $this->selectRow( 'sqlite_master', '*',
336 'name' => $this->indexName( $index ),
338 if ( !$row ||
!isset( $row->sql
) ) {
342 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
343 $indexPos = strpos( $row->sql
, 'INDEX' );
344 if ( $indexPos === false ) {
347 $firstPart = substr( $row->sql
, 0, $indexPos );
348 $options = explode( ' ', $firstPart );
349 return in_array( 'UNIQUE', $options );
353 * Filter the options used in SELECT statements
355 function makeSelectOptions( $options ) {
356 foreach ( $options as $k => $v ) {
357 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
361 return parent
::makeSelectOptions( $options );
365 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
367 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
368 if ( !count( $a ) ) {
371 if ( !is_array( $options ) ) {
372 $options = array( $options );
375 # SQLite uses OR IGNORE not just IGNORE
376 foreach ( $options as $k => $v ) {
377 if ( $v == 'IGNORE' ) {
378 $options[$k] = 'OR IGNORE';
382 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
383 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
385 foreach ( $a as $v ) {
386 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
391 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
397 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
398 if ( !count( $rows ) ) return true;
400 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
401 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
403 foreach ( $rows as $v ) {
404 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
409 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
416 * Returns the size of a text field, or -1 for "unlimited"
417 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
419 function textFieldSize( $table, $field ) {
423 function unionSupportsOrderAndLimit() {
427 function unionQueries( $sqls, $all ) {
428 $glue = $all ?
' UNION ALL ' : ' UNION ';
429 return implode( $glue, $sqls );
432 function wasDeadlock() {
433 return $this->lastErrno() == 5; // SQLITE_BUSY
436 function wasErrorReissuable() {
437 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
440 function wasReadOnlyError() {
441 return $this->lastErrno() == 8; // SQLITE_READONLY;
445 * @return string wikitext of a link to the server software's web site
447 public static function getSoftwareLink() {
448 return "[http://sqlite.org/ SQLite]";
452 * @return string Version information from the database
454 function getServerVersion() {
455 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
460 * @return string User-friendly database information
462 public function getServerInfo() {
463 return wfMsg( $this->getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
467 * Get information about a given field
468 * Returns false if the field does not exist.
470 function fieldInfo( $table, $field ) {
471 $tableName = $this->tableName( $table );
472 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
473 $res = $this->query( $sql, __METHOD__
);
474 foreach ( $res as $row ) {
475 if ( $row->name
== $field ) {
476 return new SQLiteField( $row, $tableName );
482 function begin( $fname = '' ) {
483 if ( $this->mTrxLevel
== 1 ) $this->commit();
484 $this->mConn
->beginTransaction();
485 $this->mTrxLevel
= 1;
488 function commit( $fname = '' ) {
489 if ( $this->mTrxLevel
== 0 ) return;
490 $this->mConn
->commit();
491 $this->mTrxLevel
= 0;
494 function rollback( $fname = '' ) {
495 if ( $this->mTrxLevel
== 0 ) return;
496 $this->mConn
->rollBack();
497 $this->mTrxLevel
= 0;
500 function limitResultForUpdate( $sql, $num ) {
501 return $this->limitResult( $sql, $num );
504 function strencode( $s ) {
505 return substr( $this->addQuotes( $s ), 1, - 1 );
508 function encodeBlob( $b ) {
509 return new Blob( $b );
512 function decodeBlob( $b ) {
513 if ( $b instanceof Blob
) {
519 function addQuotes( $s ) {
520 if ( $s instanceof Blob
) {
521 return "x'" . bin2hex( $s->fetch() ) . "'";
523 return $this->mConn
->quote( $s );
527 function buildLike() {
528 $params = func_get_args();
529 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
530 $params = $params[0];
532 return parent
::buildLike( $params ) . "ESCAPE '\' ";
535 public function getSearchEngine() {
536 return "SearchSqlite";
540 * No-op version of deadlockLoop
542 public function deadlockLoop( /*...*/ ) {
543 $args = func_get_args();
544 $function = array_shift( $args );
545 return call_user_func_array( $function, $args );
548 protected function replaceVars( $s ) {
549 $s = parent
::replaceVars( $s );
550 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
551 // CREATE TABLE hacks to allow schema file sharing with MySQL
553 // binary/varbinary column type -> blob
554 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
555 // no such thing as unsigned
556 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
558 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
559 // floating point types -> REAL
560 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
562 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
563 // TEXT normalization
564 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
565 // BLOB normalization
566 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
568 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
570 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
572 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
573 // binary collation type -> nothing
574 $s = preg_replace( '/\bbinary\b/i', '', $s );
575 // auto_increment -> autoincrement
576 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
577 // No explicit options
578 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
579 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
580 // No truncated indexes
581 $s = preg_replace( '/\(\d+\)/', '', $s );
583 $s = preg_replace( '/\bfulltext\b/i', '', $s );
589 * Build a concatenation list to feed into a SQL query
591 function buildConcat( $stringList ) {
592 return '(' . implode( ') || (', $stringList ) . ')';
595 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
597 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
598 $obj = $this->fetchObject( $res );
600 throw new MWException( "Couldn't retrieve structure for table $oldName" );
603 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
604 return $this->query( $sql, $fname );
609 * List all tables on the database
611 * @param $prefix Only show tables with this prefix, e.g. mw_
612 * @param $fname String: calling function name
614 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
615 $result = $this->select(
623 foreach( $result as $table ) {
624 $vars = get_object_vars($table);
625 $table = array_pop( $vars );
627 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
628 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
629 $endArray[] = $table;
638 } // end DatabaseSqlite class
641 * This class allows simple acccess to a SQLite database independently from main database settings
644 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
645 public function __construct( $fileName, $flags = 0 ) {
646 $this->mFlags
= $flags;
647 $this->tablePrefix( null );
648 $this->openFile( $fileName );
655 class SQLiteField
implements Field
{
656 private $info, $tableName;
657 function __construct( $info, $tableName ) {
659 $this->tableName
= $tableName;
663 return $this->info
->name
;
666 function tableName() {
667 return $this->tableName
;
670 function defaultValue() {
671 if ( is_string( $this->info
->dflt_value
) ) {
673 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
674 return str_replace( "''", "'", $this->info
->dflt_value
);
677 return $this->info
->dflt_value
;
680 function isNullable() {
681 return !$this->info
->notnull
;
685 return $this->info
->type
;