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
96 $this->mOpened
= false;
97 if ( is_object( $this->mConn
) ) {
98 if ( $this->trxLevel() ) $this->commit();
105 * Generates a database file name. Explicitly public for installer.
106 * @param $dir String: Directory where database resides
107 * @param $dbName String: Database name
110 public static function generateFileName( $dir, $dbName ) {
111 return "$dir/$dbName.sqlite";
115 * Check if the searchindext table is FTS enabled.
116 * @return false if not enabled.
118 function checkForEnabledSearch() {
119 if ( self
::$fulltextEnabled === null ) {
120 self
::$fulltextEnabled = false;
121 $table = $this->tableName( 'searchindex' );
122 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
124 $row = $res->fetchRow();
125 self
::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
128 return self
::$fulltextEnabled;
132 * Returns version of currently supported SQLite fulltext search module or false if none present.
135 static function getFulltextSearchModule() {
136 static $cachedResult = null;
137 if ( $cachedResult !== null ) {
138 return $cachedResult;
140 $cachedResult = false;
141 $table = 'dummy_search_test';
143 $db = new DatabaseSqliteStandalone( ':memory:' );
145 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
146 $cachedResult = 'FTS3';
149 return $cachedResult;
153 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
155 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
156 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
157 * @param $fname String: calling function name
159 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
160 global $wgSQLiteDataDir;
162 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
164 $file = $this->addQuotes( $file );
165 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
169 * @see DatabaseBase::isWriteQuery()
173 function isWriteQuery( $sql ) {
174 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
178 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
180 function doQuery( $sql ) {
181 $res = $this->mConn
->query( $sql );
182 if ( $res === false ) {
185 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
186 $this->mAffectedRows
= $r->rowCount();
187 $res = new ResultWrapper( $this, $r->fetchAll() );
192 function freeResult( $res ) {
193 if ( $res instanceof ResultWrapper
) {
200 function fetchObject( $res ) {
201 if ( $res instanceof ResultWrapper
) {
207 $cur = current( $r );
208 if ( is_array( $cur ) ) {
211 foreach ( $cur as $k => $v ) {
212 if ( !is_numeric( $k ) ) {
222 function fetchRow( $res ) {
223 if ( $res instanceof ResultWrapper
) {
228 $cur = current( $r );
229 if ( is_array( $cur ) ) {
237 * The PDO::Statement class implements the array interface so count() will work
239 function numRows( $res ) {
240 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
244 function numFields( $res ) {
245 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
246 return is_array( $r ) ?
count( $r[0] ) : 0;
249 function fieldName( $res, $n ) {
250 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
251 if ( is_array( $r ) ) {
252 $keys = array_keys( $r[0] );
259 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
261 function tableName( $name, $quoted = true ) {
262 // table names starting with sqlite_ are reserved
263 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
264 return str_replace( '"', '', parent
::tableName( $name, $quoted ) );
268 * Index names have DB scope
270 function indexName( $index ) {
275 * This must be called after nextSequenceVal
277 function insertId() {
278 return $this->mConn
->lastInsertId();
281 function dataSeek( $res, $row ) {
282 if ( $res instanceof ResultWrapper
) {
289 for ( $i = 0; $i < $row; $i++
) {
295 function lastError() {
296 if ( !is_object( $this->mConn
) ) {
297 return "Cannot return last error, no db connection";
299 $e = $this->mConn
->errorInfo();
300 return isset( $e[2] ) ?
$e[2] : '';
303 function lastErrno() {
304 if ( !is_object( $this->mConn
) ) {
305 return "Cannot return last error, no db connection";
307 $info = $this->mConn
->errorInfo();
312 function affectedRows() {
313 return $this->mAffectedRows
;
317 * Returns information about an index
318 * Returns false if the index does not exist
319 * - if errors are explicitly ignored, returns NULL on failure
321 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
322 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
323 $res = $this->query( $sql, $fname );
327 if ( $res->numRows() == 0 ) {
331 foreach ( $res as $row ) {
332 $info[] = $row->name
;
337 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
338 $row = $this->selectRow( 'sqlite_master', '*',
341 'name' => $this->indexName( $index ),
343 if ( !$row ||
!isset( $row->sql
) ) {
347 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
348 $indexPos = strpos( $row->sql
, 'INDEX' );
349 if ( $indexPos === false ) {
352 $firstPart = substr( $row->sql
, 0, $indexPos );
353 $options = explode( ' ', $firstPart );
354 return in_array( 'UNIQUE', $options );
358 * Filter the options used in SELECT statements
360 function makeSelectOptions( $options ) {
361 foreach ( $options as $k => $v ) {
362 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
366 return parent
::makeSelectOptions( $options );
370 * @param $options array
373 function makeUpdateOptions( $options ) {
374 $options = self
::fixIgnore( $options );
375 return parent
::makeUpdateOptions( $options );
379 * @param $options array
382 static function fixIgnore( $options ) {
383 # SQLite uses OR IGNORE not just IGNORE
384 foreach ( $options as $k => $v ) {
385 if ( $v == 'IGNORE' ) {
386 $options[$k] = 'OR IGNORE';
393 * @param $options array
396 function makeInsertOptions( $options ) {
397 $options = self
::fixIgnore( $options );
398 return parent
::makeInsertOptions( $options );
402 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
404 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
405 if ( !count( $a ) ) {
409 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
410 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
412 foreach ( $a as $v ) {
413 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
418 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
424 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
425 if ( !count( $rows ) ) return true;
427 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
428 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
430 foreach ( $rows as $v ) {
431 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
436 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
443 * Returns the size of a text field, or -1 for "unlimited"
444 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
446 function textFieldSize( $table, $field ) {
450 function unionSupportsOrderAndLimit() {
454 function unionQueries( $sqls, $all ) {
455 $glue = $all ?
' UNION ALL ' : ' UNION ';
456 return implode( $glue, $sqls );
459 function wasDeadlock() {
460 return $this->lastErrno() == 5; // SQLITE_BUSY
463 function wasErrorReissuable() {
464 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
467 function wasReadOnlyError() {
468 return $this->lastErrno() == 8; // SQLITE_READONLY;
472 * @return string wikitext of a link to the server software's web site
474 public static function getSoftwareLink() {
475 return "[http://sqlite.org/ SQLite]";
479 * @return string Version information from the database
481 function getServerVersion() {
482 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
487 * @return string User-friendly database information
489 public function getServerInfo() {
490 return wfMsg( self
::getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
494 * Get information about a given field
495 * Returns false if the field does not exist.
497 * @return SQLiteField|false
499 function fieldInfo( $table, $field ) {
500 $tableName = $this->tableName( $table );
501 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
502 $res = $this->query( $sql, __METHOD__
);
503 foreach ( $res as $row ) {
504 if ( $row->name
== $field ) {
505 return new SQLiteField( $row, $tableName );
511 function begin( $fname = '' ) {
512 if ( $this->mTrxLevel
== 1 ) $this->commit();
513 $this->mConn
->beginTransaction();
514 $this->mTrxLevel
= 1;
517 function commit( $fname = '' ) {
518 if ( $this->mTrxLevel
== 0 ) return;
519 $this->mConn
->commit();
520 $this->mTrxLevel
= 0;
523 function rollback( $fname = '' ) {
524 if ( $this->mTrxLevel
== 0 ) return;
525 $this->mConn
->rollBack();
526 $this->mTrxLevel
= 0;
529 function limitResultForUpdate( $sql, $num ) {
530 return $this->limitResult( $sql, $num );
533 function strencode( $s ) {
534 return substr( $this->addQuotes( $s ), 1, - 1 );
537 function encodeBlob( $b ) {
538 return new Blob( $b );
541 function decodeBlob( $b ) {
542 if ( $b instanceof Blob
) {
548 function addQuotes( $s ) {
549 if ( $s instanceof Blob
) {
550 return "x'" . bin2hex( $s->fetch() ) . "'";
552 return $this->mConn
->quote( $s );
556 function buildLike() {
557 $params = func_get_args();
558 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
559 $params = $params[0];
561 return parent
::buildLike( $params ) . "ESCAPE '\' ";
564 public function getSearchEngine() {
565 return "SearchSqlite";
569 * No-op version of deadlockLoop
571 public function deadlockLoop( /*...*/ ) {
572 $args = func_get_args();
573 $function = array_shift( $args );
574 return call_user_func_array( $function, $args );
581 protected function replaceVars( $s ) {
582 $s = parent
::replaceVars( $s );
583 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
584 // CREATE TABLE hacks to allow schema file sharing with MySQL
586 // binary/varbinary column type -> blob
587 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
588 // no such thing as unsigned
589 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
591 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
592 // floating point types -> REAL
593 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
595 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
596 // TEXT normalization
597 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
598 // BLOB normalization
599 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
601 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
603 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
605 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
606 // binary collation type -> nothing
607 $s = preg_replace( '/\bbinary\b/i', '', $s );
608 // auto_increment -> autoincrement
609 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
610 // No explicit options
611 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
612 // AUTOINCREMENT should immedidately follow PRIMARY KEY
613 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
614 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
615 // No truncated indexes
616 $s = preg_replace( '/\(\d+\)/', '', $s );
618 $s = preg_replace( '/\bfulltext\b/i', '', $s );
624 * Build a concatenation list to feed into a SQL query
628 function buildConcat( $stringList ) {
629 return '(' . implode( ') || (', $stringList ) . ')';
632 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
633 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
634 $obj = $this->fetchObject( $res );
636 throw new MWException( "Couldn't retrieve structure for table $oldName" );
639 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
641 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
642 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
644 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
647 return $this->query( $sql, $fname );
652 * List all tables on the database
654 * @param $prefix Only show tables with this prefix, e.g. mw_
655 * @param $fname String: calling function name
659 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
660 $result = $this->select(
668 foreach( $result as $table ) {
669 $vars = get_object_vars($table);
670 $table = array_pop( $vars );
672 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
673 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
674 $endArray[] = $table;
683 } // end DatabaseSqlite class
686 * This class allows simple acccess to a SQLite database independently from main database settings
689 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
690 public function __construct( $fileName, $flags = 0 ) {
691 $this->mFlags
= $flags;
692 $this->tablePrefix( null );
693 $this->openFile( $fileName );
700 class SQLiteField
implements Field
{
701 private $info, $tableName;
702 function __construct( $info, $tableName ) {
704 $this->tableName
= $tableName;
708 return $this->info
->name
;
711 function tableName() {
712 return $this->tableName
;
715 function defaultValue() {
716 if ( is_string( $this->info
->dflt_value
) ) {
718 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
719 return str_replace( "''", "'", $this->info
->dflt_value
);
722 return $this->info
->dflt_value
;
725 function isNullable() {
726 return !$this->info
->notnull
;
730 return $this->info
->type
;