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 ) {
27 $this->mName
= $dbName;
28 parent
::__construct( $server, $user, $password, $dbName, $flags );
29 // parent doesn't open when $user is false, but we can work with $dbName
30 if( !$user && $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 static function getFulltextSearchModule() {
134 static $cachedResult = null;
135 if ( $cachedResult !== null ) {
136 return $cachedResult;
138 $cachedResult = false;
139 $table = 'dummy_search_test';
141 $db = new DatabaseSqliteStandalone( ':memory:' );
143 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
144 $cachedResult = 'FTS3';
147 return $cachedResult;
151 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
153 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
154 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
155 * @param $fname String: calling function name
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 * @see DatabaseBase::isWriteQuery()
169 function isWriteQuery( $sql ) {
170 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
174 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
176 function doQuery( $sql ) {
177 $res = $this->mConn
->query( $sql );
178 if ( $res === false ) {
181 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
182 $this->mAffectedRows
= $r->rowCount();
183 $res = new ResultWrapper( $this, $r->fetchAll() );
188 function freeResult( $res ) {
189 if ( $res instanceof ResultWrapper
) {
196 function fetchObject( $res ) {
197 if ( $res instanceof ResultWrapper
) {
203 $cur = current( $r );
204 if ( is_array( $cur ) ) {
207 foreach ( $cur as $k => $v ) {
208 if ( !is_numeric( $k ) ) {
218 function fetchRow( $res ) {
219 if ( $res instanceof ResultWrapper
) {
224 $cur = current( $r );
225 if ( is_array( $cur ) ) {
233 * The PDO::Statement class implements the array interface so count() will work
235 function numRows( $res ) {
236 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
240 function numFields( $res ) {
241 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
242 return is_array( $r ) ?
count( $r[0] ) : 0;
245 function fieldName( $res, $n ) {
246 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
247 if ( is_array( $r ) ) {
248 $keys = array_keys( $r[0] );
255 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
257 function tableName( $name ) {
258 // table names starting with sqlite_ are reserved
259 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
260 return str_replace( '`', '', parent
::tableName( $name ) );
264 * Index names have DB scope
266 function indexName( $index ) {
271 * This must be called after nextSequenceVal
273 function insertId() {
274 return $this->mConn
->lastInsertId();
277 function dataSeek( $res, $row ) {
278 if ( $res instanceof ResultWrapper
) {
285 for ( $i = 0; $i < $row; $i++
) {
291 function lastError() {
292 if ( !is_object( $this->mConn
) ) {
293 return "Cannot return last error, no db connection";
295 $e = $this->mConn
->errorInfo();
296 return isset( $e[2] ) ?
$e[2] : '';
299 function lastErrno() {
300 if ( !is_object( $this->mConn
) ) {
301 return "Cannot return last error, no db connection";
303 $info = $this->mConn
->errorInfo();
308 function affectedRows() {
309 return $this->mAffectedRows
;
313 * Returns information about an index
314 * Returns false if the index does not exist
315 * - if errors are explicitly ignored, returns NULL on failure
317 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
318 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
319 $res = $this->query( $sql, $fname );
323 if ( $res->numRows() == 0 ) {
327 foreach ( $res as $row ) {
328 $info[] = $row->name
;
333 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
334 $row = $this->selectRow( 'sqlite_master', '*',
337 'name' => $this->indexName( $index ),
339 if ( !$row ||
!isset( $row->sql
) ) {
343 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
344 $indexPos = strpos( $row->sql
, 'INDEX' );
345 if ( $indexPos === false ) {
348 $firstPart = substr( $row->sql
, 0, $indexPos );
349 $options = explode( ' ', $firstPart );
350 return in_array( 'UNIQUE', $options );
354 * Filter the options used in SELECT statements
356 function makeSelectOptions( $options ) {
357 foreach ( $options as $k => $v ) {
358 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
362 return parent
::makeSelectOptions( $options );
366 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
368 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
369 if ( !count( $a ) ) {
372 if ( !is_array( $options ) ) {
373 $options = array( $options );
376 # SQLite uses OR IGNORE not just IGNORE
377 foreach ( $options as $k => $v ) {
378 if ( $v == 'IGNORE' ) {
379 $options[$k] = 'OR IGNORE';
383 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
384 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
386 foreach ( $a as $v ) {
387 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
392 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
398 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
399 if ( !count( $rows ) ) return true;
401 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
402 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
404 foreach ( $rows as $v ) {
405 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
410 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
417 * Returns the size of a text field, or -1 for "unlimited"
418 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
420 function textFieldSize( $table, $field ) {
424 function unionSupportsOrderAndLimit() {
428 function unionQueries( $sqls, $all ) {
429 $glue = $all ?
' UNION ALL ' : ' UNION ';
430 return implode( $glue, $sqls );
433 function wasDeadlock() {
434 return $this->lastErrno() == 5; // SQLITE_BUSY
437 function wasErrorReissuable() {
438 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
441 function wasReadOnlyError() {
442 return $this->lastErrno() == 8; // SQLITE_READONLY;
446 * @return string wikitext of a link to the server software's web site
448 public static function getSoftwareLink() {
449 return "[http://sqlite.org/ SQLite]";
453 * @return string Version information from the database
455 function getServerVersion() {
456 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
461 * @return string User-friendly database information
463 public function getServerInfo() {
464 return wfMsg( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
468 * Get information about a given field
469 * Returns false if the field does not exist.
471 function fieldInfo( $table, $field ) {
472 $tableName = $this->tableName( $table );
473 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
474 $res = $this->query( $sql, __METHOD__
);
475 foreach ( $res as $row ) {
476 if ( $row->name
== $field ) {
477 return new SQLiteField( $row, $tableName );
483 function begin( $fname = '' ) {
484 if ( $this->mTrxLevel
== 1 ) $this->commit();
485 $this->mConn
->beginTransaction();
486 $this->mTrxLevel
= 1;
489 function commit( $fname = '' ) {
490 if ( $this->mTrxLevel
== 0 ) return;
491 $this->mConn
->commit();
492 $this->mTrxLevel
= 0;
495 function rollback( $fname = '' ) {
496 if ( $this->mTrxLevel
== 0 ) return;
497 $this->mConn
->rollBack();
498 $this->mTrxLevel
= 0;
501 function limitResultForUpdate( $sql, $num ) {
502 return $this->limitResult( $sql, $num );
505 function strencode( $s ) {
506 return substr( $this->addQuotes( $s ), 1, - 1 );
509 function encodeBlob( $b ) {
510 return new Blob( $b );
513 function decodeBlob( $b ) {
514 if ( $b instanceof Blob
) {
520 function addQuotes( $s ) {
521 if ( $s instanceof Blob
) {
522 return "x'" . bin2hex( $s->fetch() ) . "'";
524 return $this->mConn
->quote( $s );
528 function buildLike() {
529 $params = func_get_args();
530 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
531 $params = $params[0];
533 return parent
::buildLike( $params ) . "ESCAPE '\' ";
536 public function getSearchEngine() {
537 return "SearchSqlite";
541 * No-op version of deadlockLoop
543 public function deadlockLoop( /*...*/ ) {
544 $args = func_get_args();
545 $function = array_shift( $args );
546 return call_user_func_array( $function, $args );
549 protected function replaceVars( $s ) {
550 $s = parent
::replaceVars( $s );
551 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
552 // CREATE TABLE hacks to allow schema file sharing with MySQL
554 // binary/varbinary column type -> blob
555 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
556 // no such thing as unsigned
557 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
559 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
560 // floating point types -> REAL
561 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
563 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
564 // TEXT normalization
565 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
566 // BLOB normalization
567 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
569 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
571 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
573 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
574 // binary collation type -> nothing
575 $s = preg_replace( '/\bbinary\b/i', '', $s );
576 // auto_increment -> autoincrement
577 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
578 // No explicit options
579 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
580 // AUTOINCREMENT should immedidately follow PRIMARY KEY
581 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
582 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
583 // No truncated indexes
584 $s = preg_replace( '/\(\d+\)/', '', $s );
586 $s = preg_replace( '/\bfulltext\b/i', '', $s );
592 * Build a concatenation list to feed into a SQL query
594 function buildConcat( $stringList ) {
595 return '(' . implode( ') || (', $stringList ) . ')';
598 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
600 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
601 $obj = $this->fetchObject( $res );
603 throw new MWException( "Couldn't retrieve structure for table $oldName" );
606 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
608 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
609 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
611 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
614 return $this->query( $sql, $fname );
619 * List all tables on the database
621 * @param $prefix Only show tables with this prefix, e.g. mw_
622 * @param $fname String: calling function name
624 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
625 $result = $this->select(
633 foreach( $result as $table ) {
634 $vars = get_object_vars($table);
635 $table = array_pop( $vars );
637 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
638 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
639 $endArray[] = $table;
648 } // end DatabaseSqlite class
651 * This class allows simple acccess to a SQLite database independently from main database settings
654 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
655 public function __construct( $fileName, $flags = 0 ) {
656 $this->mFlags
= $flags;
657 $this->tablePrefix( null );
658 $this->openFile( $fileName );
665 class SQLiteField
implements Field
{
666 private $info, $tableName;
667 function __construct( $info, $tableName ) {
669 $this->tableName
= $tableName;
673 return $this->info
->name
;
676 function tableName() {
677 return $this->tableName
;
680 function defaultValue() {
681 if ( is_string( $this->info
->dflt_value
) ) {
683 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
684 return str_replace( "''", "'", $this->info
->dflt_value
);
687 return $this->info
->dflt_value
;
690 function isNullable() {
691 return !$this->info
->notnull
;
695 return $this->info
->type
;