2e23d73dc2fd8e13c1d6dcdca10437eabb389ed0
3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
28 class DatabaseSqlite
extends DatabaseBase
{
29 /** @var bool Whether full text is enabled */
30 private static $fulltextEnabled = null;
32 /** @var string File name for SQLite database file */
33 public $mDatabaseFile;
35 /** @var int The number of rows affected as an integer */
36 protected $mAffectedRows;
39 protected $mLastResult;
44 /** @var FSLockManager (hopefully on the same server as the DB) */
47 function __construct( $p = null ) {
48 global $wgSharedDB, $wgSQLiteDataDir;
50 if ( !is_array( $p ) ) { // legacy calling pattern
51 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
52 $args = func_get_args();
54 'host' => isset( $args[0] ) ?
$args[0] : false,
55 'user' => isset( $args[1] ) ?
$args[1] : false,
56 'password' => isset( $args[2] ) ?
$args[2] : false,
57 'dbname' => isset( $args[3] ) ?
$args[3] : false,
58 'flags' => isset( $args[4] ) ?
$args[4] : 0,
59 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
60 'foreign' => isset( $args[6] ) ?
$args[6] : false
63 $this->mDBname
= $p['dbname'];
64 parent
::__construct( $p );
65 // parent doesn't open when $user is false, but we can work with $dbName
66 if ( $p['dbname'] && !$this->isOpen() ) {
67 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
69 $this->attachDatabase( $wgSharedDB );
74 $this->lockMgr
= new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
85 * @todo Check if it should be true like parent class
89 function implicitGroupby() {
93 /** Open an SQLite database and return a resource handle to it
94 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
96 * @param string $server
99 * @param string $dbName
101 * @throws DBConnectionError
104 function open( $server, $user, $pass, $dbName ) {
105 global $wgSQLiteDataDir;
108 $fileName = self
::generateFileName( $wgSQLiteDataDir, $dbName );
109 if ( !is_readable( $fileName ) ) {
110 $this->mConn
= false;
111 throw new DBConnectionError( $this, "SQLite database not accessible" );
113 $this->openFile( $fileName );
119 * Opens a database file
121 * @param string $fileName
122 * @throws DBConnectionError
123 * @return PDO|bool SQL connection or false if failed
125 function openFile( $fileName ) {
128 $this->mDatabaseFile
= $fileName;
130 if ( $this->mFlags
& DBO_PERSISTENT
) {
131 $this->mConn
= new PDO( "sqlite:$fileName", '', '',
132 array( PDO
::ATTR_PERSISTENT
=> true ) );
134 $this->mConn
= new PDO( "sqlite:$fileName", '', '' );
136 } catch ( PDOException
$e ) {
137 $err = $e->getMessage();
140 if ( !$this->mConn
) {
141 wfDebug( "DB connection error: $err\n" );
142 throw new DBConnectionError( $this, $err );
145 $this->mOpened
= !!$this->mConn
;
146 # set error codes only, don't raise exceptions
147 if ( $this->mOpened
) {
148 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
149 # Enforce LIKE to be case sensitive, just like MySQL
150 $this->query( 'PRAGMA case_sensitive_like = 1' );
159 * Does not actually close the connection, just destroys the reference for GC to do its work
162 protected function closeConnection() {
169 * Generates a database file name. Explicitly public for installer.
170 * @param string $dir Directory where database resides
171 * @param string $dbName Database name
174 public static function generateFileName( $dir, $dbName ) {
175 return "$dir/$dbName.sqlite";
179 * Check if the searchindext table is FTS enabled.
180 * @return bool False if not enabled.
182 function checkForEnabledSearch() {
183 if ( self
::$fulltextEnabled === null ) {
184 self
::$fulltextEnabled = false;
185 $table = $this->tableName( 'searchindex' );
186 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
188 $row = $res->fetchRow();
189 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
193 return self
::$fulltextEnabled;
197 * Returns version of currently supported SQLite fulltext search module or false if none present.
200 static function getFulltextSearchModule() {
201 static $cachedResult = null;
202 if ( $cachedResult !== null ) {
203 return $cachedResult;
205 $cachedResult = false;
206 $table = 'dummy_search_test';
208 $db = new DatabaseSqliteStandalone( ':memory:' );
210 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
211 $cachedResult = 'FTS3';
215 return $cachedResult;
219 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
222 * @param string $name Database name to be used in queries like
223 * SELECT foo FROM dbname.table
224 * @param bool|string $file Database file name. If omitted, will be generated
225 * using $name and $wgSQLiteDataDir
226 * @param string $fname Calling function name
227 * @return ResultWrapper
229 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
230 global $wgSQLiteDataDir;
232 $file = self
::generateFileName( $wgSQLiteDataDir, $name );
234 $file = $this->addQuotes( $file );
236 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
240 * @see DatabaseBase::isWriteQuery()
245 function isWriteQuery( $sql ) {
246 return parent
::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
250 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
253 * @return bool|ResultWrapper
255 protected function doQuery( $sql ) {
256 $res = $this->mConn
->query( $sql );
257 if ( $res === false ) {
260 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
261 $this->mAffectedRows
= $r->rowCount();
262 $res = new ResultWrapper( $this, $r->fetchAll() );
269 * @param ResultWrapper|mixed $res
271 function freeResult( $res ) {
272 if ( $res instanceof ResultWrapper
) {
280 * @param ResultWrapper|array $res
281 * @return stdClass|bool
283 function fetchObject( $res ) {
284 if ( $res instanceof ResultWrapper
) {
290 $cur = current( $r );
291 if ( is_array( $cur ) ) {
294 foreach ( $cur as $k => $v ) {
295 if ( !is_numeric( $k ) ) {
307 * @param ResultWrapper|mixed $res
310 function fetchRow( $res ) {
311 if ( $res instanceof ResultWrapper
) {
316 $cur = current( $r );
317 if ( is_array( $cur ) ) {
327 * The PDO::Statement class implements the array interface so count() will work
329 * @param ResultWrapper|array $res
332 function numRows( $res ) {
333 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
339 * @param ResultWrapper $res
342 function numFields( $res ) {
343 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
345 return is_array( $r ) ?
count( $r[0] ) : 0;
349 * @param ResultWrapper $res
353 function fieldName( $res, $n ) {
354 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
355 if ( is_array( $r ) ) {
356 $keys = array_keys( $r[0] );
365 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
367 * @param string $name
368 * @param string $format
371 function tableName( $name, $format = 'quoted' ) {
372 // table names starting with sqlite_ are reserved
373 if ( strpos( $name, 'sqlite_' ) === 0 ) {
377 return str_replace( '"', '', parent
::tableName( $name, $format ) );
381 * Index names have DB scope
383 * @param string $index
386 function indexName( $index ) {
391 * This must be called after nextSequenceVal
395 function insertId() {
396 // PDO::lastInsertId yields a string :(
397 return intval( $this->mConn
->lastInsertId() );
401 * @param ResultWrapper|array $res
404 function dataSeek( $res, $row ) {
405 if ( $res instanceof ResultWrapper
) {
412 for ( $i = 0; $i < $row; $i++
) {
421 function lastError() {
422 if ( !is_object( $this->mConn
) ) {
423 return "Cannot return last error, no db connection";
425 $e = $this->mConn
->errorInfo();
427 return isset( $e[2] ) ?
$e[2] : '';
433 function lastErrno() {
434 if ( !is_object( $this->mConn
) ) {
435 return "Cannot return last error, no db connection";
437 $info = $this->mConn
->errorInfo();
446 function affectedRows() {
447 return $this->mAffectedRows
;
451 * Returns information about an index
452 * Returns false if the index does not exist
453 * - if errors are explicitly ignored, returns NULL on failure
455 * @param string $table
456 * @param string $index
457 * @param string $fname
460 function indexInfo( $table, $index, $fname = __METHOD__
) {
461 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
462 $res = $this->query( $sql, $fname );
466 if ( $res->numRows() == 0 ) {
470 foreach ( $res as $row ) {
471 $info[] = $row->name
;
478 * @param string $table
479 * @param string $index
480 * @param string $fname
483 function indexUnique( $table, $index, $fname = __METHOD__
) {
484 $row = $this->selectRow( 'sqlite_master', '*',
487 'name' => $this->indexName( $index ),
489 if ( !$row ||
!isset( $row->sql
) ) {
493 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
494 $indexPos = strpos( $row->sql
, 'INDEX' );
495 if ( $indexPos === false ) {
498 $firstPart = substr( $row->sql
, 0, $indexPos );
499 $options = explode( ' ', $firstPart );
501 return in_array( 'UNIQUE', $options );
505 * Filter the options used in SELECT statements
507 * @param array $options
510 function makeSelectOptions( $options ) {
511 foreach ( $options as $k => $v ) {
512 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
517 return parent
::makeSelectOptions( $options );
521 * @param array $options
524 protected function makeUpdateOptions( $options ) {
525 $options = self
::fixIgnore( $options );
527 return parent
::makeUpdateOptions( $options );
531 * @param array $options
534 static function fixIgnore( $options ) {
535 # SQLite uses OR IGNORE not just IGNORE
536 foreach ( $options as $k => $v ) {
537 if ( $v == 'IGNORE' ) {
538 $options[$k] = 'OR IGNORE';
546 * @param array $options
549 function makeInsertOptions( $options ) {
550 $options = self
::fixIgnore( $options );
552 return parent
::makeInsertOptions( $options );
556 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
557 * @param string $table
559 * @param string $fname
560 * @param array $options
563 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
564 if ( !count( $a ) ) {
568 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
569 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
571 foreach ( $a as $v ) {
572 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
577 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
584 * @param string $table
585 * @param array $uniqueIndexes Unused
586 * @param string|array $rows
587 * @param string $fname
588 * @return bool|ResultWrapper
590 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
591 if ( !count( $rows ) ) {
595 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
596 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
598 foreach ( $rows as $v ) {
599 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
604 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
611 * Returns the size of a text field, or -1 for "unlimited"
612 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
614 * @param string $table
615 * @param string $field
618 function textFieldSize( $table, $field ) {
625 function unionSupportsOrderAndLimit() {
630 * @param string $sqls
631 * @param bool $all Whether to "UNION ALL" or not
634 function unionQueries( $sqls, $all ) {
635 $glue = $all ?
' UNION ALL ' : ' UNION ';
637 return implode( $glue, $sqls );
643 function wasDeadlock() {
644 return $this->lastErrno() == 5; // SQLITE_BUSY
650 function wasErrorReissuable() {
651 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
657 function wasReadOnlyError() {
658 return $this->lastErrno() == 8; // SQLITE_READONLY;
662 * @return string wikitext of a link to the server software's web site
664 public function getSoftwareLink() {
665 return "[{{int:version-db-sqlite-url}} SQLite]";
669 * @return string Version information from the database
671 function getServerVersion() {
672 $ver = $this->mConn
->getAttribute( PDO
::ATTR_SERVER_VERSION
);
678 * @return string User-friendly database information
680 public function getServerInfo() {
681 return wfMessage( self
::getFulltextSearchModule()
683 : 'sqlite-no-fts', $this->getServerVersion() )->text();
687 * Get information about a given field
688 * Returns false if the field does not exist.
690 * @param string $table
691 * @param string $field
692 * @return SQLiteField|bool False on failure
694 function fieldInfo( $table, $field ) {
695 $tableName = $this->tableName( $table );
696 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
697 $res = $this->query( $sql, __METHOD__
);
698 foreach ( $res as $row ) {
699 if ( $row->name
== $field ) {
700 return new SQLiteField( $row, $tableName );
707 protected function doBegin( $fname = '' ) {
708 if ( $this->mTrxLevel
== 1 ) {
709 $this->commit( __METHOD__
);
712 $this->mConn
->beginTransaction();
713 } catch ( PDOException
$e ) {
714 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
716 $this->mTrxLevel
= 1;
719 protected function doCommit( $fname = '' ) {
720 if ( $this->mTrxLevel
== 0 ) {
724 $this->mConn
->commit();
725 } catch ( PDOException
$e ) {
726 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
728 $this->mTrxLevel
= 0;
731 protected function doRollback( $fname = '' ) {
732 if ( $this->mTrxLevel
== 0 ) {
735 $this->mConn
->rollBack();
736 $this->mTrxLevel
= 0;
743 function strencode( $s ) {
744 return substr( $this->addQuotes( $s ), 1, -1 );
751 function encodeBlob( $b ) {
752 return new Blob( $b );
756 * @param $b Blob|string
759 function decodeBlob( $b ) {
760 if ( $b instanceof Blob
) {
768 * @param Blob|string $s
771 function addQuotes( $s ) {
772 if ( $s instanceof Blob
) {
773 return "x'" . bin2hex( $s->fetch() ) . "'";
774 } elseif ( is_bool( $s ) ) {
776 } elseif ( strpos( $s, "\0" ) !== false ) {
777 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
778 // This is a known limitation of SQLite's mprintf function which PDO should work around,
779 // but doesn't. I have reported this to php.net as bug #63419:
780 // https://bugs.php.net/bug.php?id=63419
781 // There was already a similar report for SQLite3::escapeString, bug #62361:
782 // https://bugs.php.net/bug.php?id=62361
783 return "x'" . bin2hex( $s ) . "'";
785 return $this->mConn
->quote( $s );
792 function buildLike() {
793 $params = func_get_args();
794 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
795 $params = $params[0];
798 return parent
::buildLike( $params ) . "ESCAPE '\' ";
804 public function getSearchEngine() {
805 return "SearchSqlite";
809 * No-op version of deadlockLoop
813 public function deadlockLoop( /*...*/ ) {
814 $args = func_get_args();
815 $function = array_shift( $args );
817 return call_user_func_array( $function, $args );
824 protected function replaceVars( $s ) {
825 $s = parent
::replaceVars( $s );
826 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
827 // CREATE TABLE hacks to allow schema file sharing with MySQL
829 // binary/varbinary column type -> blob
830 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
831 // no such thing as unsigned
832 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
834 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
835 // floating point types -> REAL
837 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
842 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
843 // TEXT normalization
844 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
845 // BLOB normalization
846 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
848 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
850 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
852 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
853 // binary collation type -> nothing
854 $s = preg_replace( '/\bbinary\b/i', '', $s );
855 // auto_increment -> autoincrement
856 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
857 // No explicit options
858 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
859 // AUTOINCREMENT should immedidately follow PRIMARY KEY
860 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
861 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
862 // No truncated indexes
863 $s = preg_replace( '/\(\d+\)/', '', $s );
865 $s = preg_replace( '/\bfulltext\b/i', '', $s );
866 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
867 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
868 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
874 public function lock( $lockName, $method, $timeout = 5 ) {
875 global $wgSQLiteDataDir;
877 if ( !is_dir( "$wgSQLiteDataDir/locks" ) ) { // create dir as needed
878 if ( !is_writable( $wgSQLiteDataDir ) ||
!mkdir( "$wgSQLiteDataDir/locks" ) ) {
879 throw new DBError( "Cannot create directory \"$wgSQLiteDataDir/locks\"." );
883 return $this->lockMgr
->lock( array( $lockName ), LockManager
::LOCK_EX
, $timeout )->isOK();
886 public function unlock( $lockName, $method ) {
887 return $this->lockMgr
->unlock( array( $lockName ), LockManager
::LOCK_EX
)->isOK();
891 * Build a concatenation list to feed into a SQL query
893 * @param string[] $stringList
896 function buildConcat( $stringList ) {
897 return '(' . implode( ') || (', $stringList ) . ')';
900 public function buildGroupConcatField(
901 $delim, $table, $field, $conds = '', $join_conds = array()
903 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
905 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
909 * @throws MWException
910 * @param string $oldName
911 * @param string $newName
912 * @param bool $temporary
913 * @param string $fname
914 * @return bool|ResultWrapper
916 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
917 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
918 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
919 $obj = $this->fetchObject( $res );
921 throw new MWException( "Couldn't retrieve structure for table $oldName" );
925 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
926 $this->addIdentifierQuotes( $newName ),
931 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
932 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
934 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
938 return $this->query( $sql, $fname );
942 * List all tables on the database
944 * @param string $prefix Only show tables with this prefix, e.g. mw_
945 * @param string $fname Calling function name
949 function listTables( $prefix = null, $fname = __METHOD__
) {
950 $result = $this->select(
958 foreach ( $result as $table ) {
959 $vars = get_object_vars( $table );
960 $table = array_pop( $vars );
962 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
963 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
964 $endArray[] = $table;
971 } // end DatabaseSqlite class
974 * This class allows simple acccess to a SQLite database independently from main database settings
977 class DatabaseSqliteStandalone
extends DatabaseSqlite
{
978 public function __construct( $fileName, $flags = 0 ) {
979 $this->mFlags
= $flags;
980 $this->tablePrefix( null );
981 $this->openFile( $fileName );
988 class SQLiteField
implements Field
{
989 private $info, $tableName;
991 function __construct( $info, $tableName ) {
993 $this->tableName
= $tableName;
997 return $this->info
->name
;
1000 function tableName() {
1001 return $this->tableName
;
1004 function defaultValue() {
1005 if ( is_string( $this->info
->dflt_value
) ) {
1007 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
1008 return str_replace( "''", "'", $this->info
->dflt_value
);
1012 return $this->info
->dflt_value
;
1018 function isNullable() {
1019 return !$this->info
->notnull
;
1023 return $this->info
->type
;
1025 } // end SQLiteField