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;
31 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
32 $this->attachDatabase( $wgSharedDB );
41 * @todo: check if it should be true like parent class
43 function implicitGroupby() { return false; }
45 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
46 return new DatabaseSqlite( $server, $user, $password, $dbName, $flags );
49 /** Open an SQLite database and return a resource handle to it
50 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
52 function open( $server, $user, $pass, $dbName ) {
53 global $wgSQLiteDataDir;
55 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
56 if ( !is_readable( $fileName ) ) {
58 throw new DBConnectionError( $this, "SQLite database not accessible" );
60 $this->openFile( $fileName );
65 * Opens a database file
66 * @return SQL connection or false if failed
68 function openFile( $fileName ) {
69 $this->mDatabaseFile
= $fileName;
71 if ( $this->mFlags
& DBO_PERSISTENT
) {
72 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
73 array( PDO
::ATTR_PERSISTENT
=> true ) );
75 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
77 } catch ( PDOException
$e ) {
78 $err = $e->getMessage();
80 if ( !$this->mConn
) {
81 wfDebug( "DB connection error: $err\n" );
82 throw new DBConnectionError( $this, $err );
84 $this->mOpened
= !!$this->mConn
;
85 # set error codes only, don't raise exceptions
86 if ( $this->mOpened
) {
87 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
93 * 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 * @returns 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 function getFulltextSearchModule() {
136 static $cachedResult = null;
137 if ( $cachedResult !== null ) {
138 return $cachedResult;
140 $cachedResult = false;
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__
);
146 $cachedResult = 'FTS3';
148 return $cachedResult;
152 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
154 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
155 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
156 * @param $fname String: calling function name
158 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
159 global $wgSQLiteDataDir;
161 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
163 $file = $this->addQuotes( $file );
164 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
168 * @see DatabaseBase::isWriteQuery()
170 function isWriteQuery( $sql ) {
171 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
175 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
177 function doQuery( $sql ) {
178 $res = $this->mConn
->query( $sql );
179 if ( $res === false ) {
182 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
183 $this->mAffectedRows
= $r->rowCount();
184 $res = new ResultWrapper( $this, $r->fetchAll() );
189 function freeResult( $res ) {
190 if ( $res instanceof ResultWrapper
) {
197 function fetchObject( $res ) {
198 if ( $res instanceof ResultWrapper
) {
204 $cur = current( $r );
205 if ( is_array( $cur ) ) {
208 foreach ( $cur as $k => $v ) {
209 if ( !is_numeric( $k ) ) {
219 function fetchRow( $res ) {
220 if ( $res instanceof ResultWrapper
) {
225 $cur = current( $r );
226 if ( is_array( $cur ) ) {
234 * The PDO::Statement class implements the array interface so count() will work
236 function numRows( $res ) {
237 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
241 function numFields( $res ) {
242 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
243 return is_array( $r ) ?
count( $r[0] ) : 0;
246 function fieldName( $res, $n ) {
247 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
248 if ( is_array( $r ) ) {
249 $keys = array_keys( $r[0] );
256 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
258 function tableName( $name ) {
259 // table names starting with sqlite_ are reserved
260 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
261 return str_replace( '`', '', parent
::tableName( $name ) );
265 * Index names have DB scope
267 function indexName( $index ) {
272 * This must be called after nextSequenceVal
274 function insertId() {
275 return $this->mConn
->lastInsertId();
278 function dataSeek( $res, $row ) {
279 if ( $res instanceof ResultWrapper
) {
286 for ( $i = 0; $i < $row; $i++
) {
292 function lastError() {
293 if ( !is_object( $this->mConn
) ) {
294 return "Cannot return last error, no db connection";
296 $e = $this->mConn
->errorInfo();
297 return isset( $e[2] ) ?
$e[2] : '';
300 function lastErrno() {
301 if ( !is_object( $this->mConn
) ) {
302 return "Cannot return last error, no db connection";
304 $info = $this->mConn
->errorInfo();
309 function affectedRows() {
310 return $this->mAffectedRows
;
314 * Returns information about an index
315 * Returns false if the index does not exist
316 * - if errors are explicitly ignored, returns NULL on failure
318 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
319 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
320 $res = $this->query( $sql, $fname );
324 if ( $res->numRows() == 0 ) {
328 foreach ( $res as $row ) {
329 $info[] = $row->name
;
334 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
335 $row = $this->selectRow( 'sqlite_master', '*',
338 'name' => $this->indexName( $index ),
340 if ( !$row ||
!isset( $row->sql
) ) {
344 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
345 $indexPos = strpos( $row->sql
, 'INDEX' );
346 if ( $indexPos === false ) {
349 $firstPart = substr( $row->sql
, 0, $indexPos );
350 $options = explode( ' ', $firstPart );
351 return in_array( 'UNIQUE', $options );
355 * Filter the options used in SELECT statements
357 function makeSelectOptions( $options ) {
358 foreach ( $options as $k => $v ) {
359 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
363 return parent
::makeSelectOptions( $options );
367 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
369 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
370 if ( !count( $a ) ) {
373 if ( !is_array( $options ) ) {
374 $options = array( $options );
377 # SQLite uses OR IGNORE not just IGNORE
378 foreach ( $options as $k => $v ) {
379 if ( $v == 'IGNORE' ) {
380 $options[$k] = 'OR IGNORE';
384 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
385 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
387 foreach ( $a as $v ) {
388 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
393 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
399 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
400 if ( !count( $rows ) ) return true;
402 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
403 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
405 foreach ( $rows as $v ) {
406 if ( !parent
::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
411 $ret = parent
::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
418 * Returns the size of a text field, or -1 for "unlimited"
419 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
421 function textFieldSize( $table, $field ) {
425 function unionSupportsOrderAndLimit() {
429 function unionQueries( $sqls, $all ) {
430 $glue = $all ?
' UNION ALL ' : ' UNION ';
431 return implode( $glue, $sqls );
434 public function unixTimestamp( $field ) {
438 function wasDeadlock() {
439 return $this->lastErrno() == 5; // SQLITE_BUSY
442 function wasErrorReissuable() {
443 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
446 function wasReadOnlyError() {
447 return $this->lastErrno() == 8; // SQLITE_READONLY;
451 * @return string wikitext of a link to the server software's web site
453 public static function getSoftwareLink() {
454 return "[http://sqlite.org/ SQLite]";
458 * @return string Version information from the database
460 function getServerVersion() {
461 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
466 * @return string User-friendly database information
468 public function getServerInfo() {
469 return wfMsg( $this->getFulltextSearchModule() ?
'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
473 * Get information about a given field
474 * Returns false if the field does not exist.
476 function fieldInfo( $table, $field ) {
477 $tableName = $this->tableName( $table );
478 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
479 $res = $this->query( $sql, __METHOD__
);
480 foreach ( $res as $row ) {
481 if ( $row->name
== $field ) {
482 return new SQLiteField( $row, $tableName );
488 function begin( $fname = '' ) {
489 if ( $this->mTrxLevel
== 1 ) $this->commit();
490 $this->mConn
->beginTransaction();
491 $this->mTrxLevel
= 1;
494 function commit( $fname = '' ) {
495 if ( $this->mTrxLevel
== 0 ) return;
496 $this->mConn
->commit();
497 $this->mTrxLevel
= 0;
500 function rollback( $fname = '' ) {
501 if ( $this->mTrxLevel
== 0 ) return;
502 $this->mConn
->rollBack();
503 $this->mTrxLevel
= 0;
506 function limitResultForUpdate( $sql, $num ) {
507 return $this->limitResult( $sql, $num );
510 function strencode( $s ) {
511 return substr( $this->addQuotes( $s ), 1, - 1 );
514 function encodeBlob( $b ) {
515 return new Blob( $b );
518 function decodeBlob( $b ) {
519 if ( $b instanceof Blob
) {
525 function addQuotes( $s ) {
526 if ( $s instanceof Blob
) {
527 return "x'" . bin2hex( $s->fetch() ) . "'";
529 return $this->mConn
->quote( $s );
533 function buildLike() {
534 $params = func_get_args();
535 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
536 $params = $params[0];
538 return parent
::buildLike( $params ) . "ESCAPE '\' ";
541 public function getSearchEngine() {
542 return "SearchSqlite";
546 * No-op version of deadlockLoop
548 public function deadlockLoop( /*...*/ ) {
549 $args = func_get_args();
550 $function = array_shift( $args );
551 return call_user_func_array( $function, $args );
554 protected function replaceVars( $s ) {
555 $s = parent
::replaceVars( $s );
556 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
557 // CREATE TABLE hacks to allow schema file sharing with MySQL
559 // binary/varbinary column type -> blob
560 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
561 // no such thing as unsigned
562 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
564 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
565 // floating point types -> REAL
566 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
568 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
569 // TEXT normalization
570 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
571 // BLOB normalization
572 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
574 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
576 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
578 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
579 // binary collation type -> nothing
580 $s = preg_replace( '/\bbinary\b/i', '', $s );
581 // auto_increment -> autoincrement
582 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
583 // No explicit options
584 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
585 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
586 // No truncated indexes
587 $s = preg_replace( '/\(\d+\)/', '', $s );
589 $s = preg_replace( '/\bfulltext\b/i', '', $s );
595 * Build a concatenation list to feed into a SQL query
597 function buildConcat( $stringList ) {
598 return '(' . implode( ') || (', $stringList ) . ')';
601 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
602 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
603 $obj = $this->fetchObject( $res );
605 throw new MWException( "Couldn't retrieve structure for table $oldName" );
608 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
609 return $this->query( $sql, $fname );
614 * List all tables on the database
616 * @param $prefix Only show tables with this prefix, e.g. mw_
617 * @param $fname String: calling function name
619 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
620 $result = $this->select(
628 foreach( $result as $table ) {
629 $vars = get_object_vars($table);
630 $table = array_pop( $vars );
632 if( strpos( $table, $prefix ) === 0 ||
is_null( $prefix ) ) {
633 $endArray[] = $table;
640 } // end DatabaseSqlite class
643 * This class allows simple acccess to a SQLite database independently from main database settings
646 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
647 public function __construct( $fileName, $flags = 0 ) {
648 $this->mFlags
= $flags;
649 $this->tablePrefix( null );
650 $this->openFile( $fileName );
657 class SQLiteField
implements Field
{
658 private $info, $tableName;
659 function __construct( $info, $tableName ) {
661 $this->tableName
= $tableName;
665 return $this->info
->name
;
668 function tableName() {
669 return $this->tableName
;
672 function defaultValue() {
673 if ( is_string( $this->info
->dflt_value
) ) {
675 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
676 return str_replace( "''", "'", $this->info
->dflt_value
);
679 return $this->info
->dflt_value
;
682 function isNullable() {
683 return !$this->info
->notnull
;
687 return $this->info
->type
;