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 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
48 return new DatabaseSqlite( $server, $user, $password, $dbName, $flags );
51 /** Open an SQLite database and return a resource handle to it
52 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
54 function open( $server, $user, $pass, $dbName ) {
55 global $wgSQLiteDataDir;
57 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
58 if ( !is_readable( $fileName ) ) {
60 throw new DBConnectionError( $this, "SQLite database not accessible" );
62 $this->openFile( $fileName );
67 * Opens a database file
68 * @return SQL connection or false if failed
70 function openFile( $fileName ) {
71 $this->mDatabaseFile = $fileName;
73 if ( $this->mFlags & DBO_PERSISTENT ) {
74 $this->mConn = new PDO( "sqlite:$fileName", '', '',
75 array( PDO::ATTR_PERSISTENT => true ) );
77 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
79 } catch ( PDOException $e ) {
80 $err = $e->getMessage();
82 if ( !$this->mConn ) {
83 wfDebug( "DB connection error: $err\n" );
84 throw new DBConnectionError( $this, $err );
86 $this->mOpened = !!$this->mConn;
87 # set error codes only, don't raise exceptions
88 if ( $this->mOpened ) {
89 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
95 * Close an SQLite database
98 $this->mOpened = false;
99 if ( is_object( $this->mConn ) ) {
100 if ( $this->trxLevel() ) $this->commit();
107 * Generates a database file name. Explicitly public for installer.
108 * @param $dir String: Directory where database resides
109 * @param $dbName String: Database name
112 public static function generateFileName( $dir, $dbName ) {
113 return "$dir/$dbName.sqlite";
117 * Check if the searchindext table is FTS enabled.
118 * @returns false if not enabled.
120 function checkForEnabledSearch() {
121 if ( self::$fulltextEnabled === null ) {
122 self::$fulltextEnabled = false;
123 $table = $this->tableName( 'searchindex' );
124 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
126 $row = $res->fetchRow();
127 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
130 return self::$fulltextEnabled;
134 * Returns version of currently supported SQLite fulltext search module or false if none present.
137 static function getFulltextSearchModule() {
138 static $cachedResult = null;
139 if ( $cachedResult !== null ) {
140 return $cachedResult;
142 $cachedResult = false;
143 $table = 'dummy_search_test';
145 $db = new DatabaseSqliteStandalone( ':memory:' );
147 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
148 $cachedResult = 'FTS3';
151 return $cachedResult;
155 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
157 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
158 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
159 * @param $fname String: calling function name
161 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
162 global $wgSQLiteDataDir;
164 $file = self::generateFileName( $wgSQLiteDataDir, $name );
166 $file = $this->addQuotes( $file );
167 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
171 * @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 ) {
262 // table names starting with sqlite_ are reserved
263 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
264 return str_replace( '`', '', parent::tableName( $name ) );
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 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
372 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
373 if ( !count( $a ) ) {
376 if ( !is_array( $options ) ) {
377 $options = array( $options );
380 # SQLite uses OR IGNORE not just IGNORE
381 foreach ( $options as $k => $v ) {
382 if ( $v == 'IGNORE' ) {
383 $options[$k] = 'OR IGNORE';
387 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
388 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
390 foreach ( $a as $v ) {
391 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
396 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
402 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
403 if ( !count( $rows ) ) return true;
405 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
406 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
408 foreach ( $rows as $v ) {
409 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
414 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
421 * Returns the size of a text field, or -1 for "unlimited"
422 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
424 function textFieldSize( $table, $field ) {
428 function unionSupportsOrderAndLimit() {
432 function unionQueries( $sqls, $all ) {
433 $glue = $all ? ' UNION ALL ' : ' UNION ';
434 return implode( $glue, $sqls );
437 public function unixTimestamp( $field ) {
441 function wasDeadlock() {
442 return $this->lastErrno() == 5; // SQLITE_BUSY
445 function wasErrorReissuable() {
446 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
449 function wasReadOnlyError() {
450 return $this->lastErrno() == 8; // SQLITE_READONLY;
454 * @return string wikitext of a link to the server software's web site
456 public static function getSoftwareLink() {
457 return "[http://sqlite.org/ SQLite]";
461 * @return string Version information from the database
463 function getServerVersion() {
464 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
469 * @return string User-friendly database information
471 public function getServerInfo() {
472 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
476 * Get information about a given field
477 * Returns false if the field does not exist.
479 function fieldInfo( $table, $field ) {
480 $tableName = $this->tableName( $table );
481 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
482 $res = $this->query( $sql, __METHOD__ );
483 foreach ( $res as $row ) {
484 if ( $row->name == $field ) {
485 return new SQLiteField( $row, $tableName );
491 function begin( $fname = '' ) {
492 if ( $this->mTrxLevel == 1 ) $this->commit();
493 $this->mConn->beginTransaction();
494 $this->mTrxLevel = 1;
497 function commit( $fname = '' ) {
498 if ( $this->mTrxLevel == 0 ) return;
499 $this->mConn->commit();
500 $this->mTrxLevel = 0;
503 function rollback( $fname = '' ) {
504 if ( $this->mTrxLevel == 0 ) return;
505 $this->mConn->rollBack();
506 $this->mTrxLevel = 0;
509 function limitResultForUpdate( $sql, $num ) {
510 return $this->limitResult( $sql, $num );
513 function strencode( $s ) {
514 return substr( $this->addQuotes( $s ), 1, - 1 );
517 function encodeBlob( $b ) {
518 return new Blob( $b );
521 function decodeBlob( $b ) {
522 if ( $b instanceof Blob ) {
528 function addQuotes( $s ) {
529 if ( $s instanceof Blob ) {
530 return "x'" . bin2hex( $s->fetch() ) . "'";
532 return $this->mConn->quote( $s );
536 function buildLike() {
537 $params = func_get_args();
538 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
539 $params = $params[0];
541 return parent::buildLike( $params ) . "ESCAPE '\' ";
544 public function getSearchEngine() {
545 return "SearchSqlite";
549 * No-op version of deadlockLoop
551 public function deadlockLoop( /*...*/ ) {
552 $args = func_get_args();
553 $function = array_shift( $args );
554 return call_user_func_array( $function, $args );
557 protected function replaceVars( $s ) {
558 $s = parent::replaceVars( $s );
559 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
560 // CREATE TABLE hacks to allow schema file sharing with MySQL
562 // binary/varbinary column type -> blob
563 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
564 // no such thing as unsigned
565 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
567 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
568 // floating point types -> REAL
569 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
571 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
572 // TEXT normalization
573 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
574 // BLOB normalization
575 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
577 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
579 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
581 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
582 // binary collation type -> nothing
583 $s = preg_replace( '/\bbinary\b/i', '', $s );
584 // auto_increment -> autoincrement
585 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
586 // No explicit options
587 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
588 // AUTOINCREMENT should immedidately follow PRIMARY KEY
589 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
590 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
591 // No truncated indexes
592 $s = preg_replace( '/\(\d+\)/', '', $s );
594 $s = preg_replace( '/\bfulltext\b/i', '', $s );
600 * Build a concatenation list to feed into a SQL query
602 function buildConcat( $stringList ) {
603 return '(' . implode( ') || (', $stringList ) . ')';
606 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
607 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
608 $obj = $this->fetchObject( $res );
610 throw new MWException( "Couldn't retrieve structure for table $oldName" );
613 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
614 return $this->query( $sql, $fname );
617 } // end DatabaseSqlite class
620 * This class allows simple acccess to a SQLite database independently from main database settings
623 class DatabaseSqliteStandalone extends DatabaseSqlite {
624 public function __construct( $fileName, $flags = 0 ) {
625 $this->mFlags = $flags;
626 $this->tablePrefix( null );
627 $this->openFile( $fileName );
634 class SQLiteField implements Field {
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 isNullable() {
660 return !$this->info->notnull;
664 return $this->info->type;