Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / db / DatabaseSqlite.php
blob6692fa40ac9fecab054b744b9e20fe5c791ec742
1 <?php
2 /**
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
21 * @file
22 * @ingroup Database
25 /**
26 * @ingroup Database
28 class DatabaseSqlite extends DatabaseBase {
30 private static $fulltextEnabled = null;
32 var $mAffectedRows;
33 var $mLastResult;
34 var $mDatabaseFile;
35 var $mName;
37 /**
38 * @var PDO
40 protected $mConn;
42 /**
43 * Constructor.
44 * Parameters $server, $user and $password are not used.
45 * @param $server string
46 * @param $user string
47 * @param $password string
48 * @param $dbName string
49 * @param $flags int
51 function __construct( $server = false, $user = false, $password = false, $dbName = false, $flags = 0 ) {
52 $this->mName = $dbName;
53 parent::__construct( $server, $user, $password, $dbName, $flags );
54 // parent doesn't open when $user is false, but we can work with $dbName
55 if ( $dbName ) {
56 global $wgSharedDB;
57 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
58 $this->attachDatabase( $wgSharedDB );
63 /**
64 * @return string
66 function getType() {
67 return 'sqlite';
70 /**
71 * @todo Check if it should be true like parent class
73 * @return bool
75 function implicitGroupby() {
76 return false;
79 /** Open an SQLite database and return a resource handle to it
80 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
82 * @param string $server
83 * @param string $user
84 * @param string $pass
85 * @param string $dbName
87 * @throws DBConnectionError
88 * @return PDO
90 function open( $server, $user, $pass, $dbName ) {
91 global $wgSQLiteDataDir;
93 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
94 if ( !is_readable( $fileName ) ) {
95 $this->mConn = false;
96 throw new DBConnectionError( $this, "SQLite database not accessible" );
98 $this->openFile( $fileName );
99 return $this->mConn;
103 * Opens a database file
105 * @param $fileName string
107 * @throws DBConnectionError
108 * @return PDO|bool SQL connection or false if failed
110 function openFile( $fileName ) {
111 $this->mDatabaseFile = $fileName;
112 try {
113 if ( $this->mFlags & DBO_PERSISTENT ) {
114 $this->mConn = new PDO( "sqlite:$fileName", '', '',
115 array( PDO::ATTR_PERSISTENT => true ) );
116 } else {
117 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
119 } catch ( PDOException $e ) {
120 $err = $e->getMessage();
122 if ( !$this->mConn ) {
123 wfDebug( "DB connection error: $err\n" );
124 throw new DBConnectionError( $this, $err );
126 $this->mOpened = !!$this->mConn;
127 # set error codes only, don't raise exceptions
128 if ( $this->mOpened ) {
129 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
130 # Enforce LIKE to be case sensitive, just like MySQL
131 $this->query( 'PRAGMA case_sensitive_like = 1' );
132 return true;
137 * Does not actually close the connection, just destroys the reference for GC to do its work
138 * @return bool
140 protected function closeConnection() {
141 $this->mConn = null;
142 return true;
146 * Generates a database file name. Explicitly public for installer.
147 * @param string $dir Directory where database resides
148 * @param string $dbName Database name
149 * @return String
151 public static function generateFileName( $dir, $dbName ) {
152 return "$dir/$dbName.sqlite";
156 * Check if the searchindext table is FTS enabled.
157 * @return bool False if not enabled.
159 function checkForEnabledSearch() {
160 if ( self::$fulltextEnabled === null ) {
161 self::$fulltextEnabled = false;
162 $table = $this->tableName( 'searchindex' );
163 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
164 if ( $res ) {
165 $row = $res->fetchRow();
166 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
169 return self::$fulltextEnabled;
173 * Returns version of currently supported SQLite fulltext search module or false if none present.
174 * @return String
176 static function getFulltextSearchModule() {
177 static $cachedResult = null;
178 if ( $cachedResult !== null ) {
179 return $cachedResult;
181 $cachedResult = false;
182 $table = 'dummy_search_test';
184 $db = new DatabaseSqliteStandalone( ':memory:' );
186 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
187 $cachedResult = 'FTS3';
189 $db->close();
190 return $cachedResult;
194 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
195 * for details.
197 * @param string $name database name to be used in queries like SELECT foo FROM dbname.table
198 * @param string $file database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
199 * @param string $fname calling function name
201 * @return ResultWrapper
203 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
204 global $wgSQLiteDataDir;
205 if ( !$file ) {
206 $file = self::generateFileName( $wgSQLiteDataDir, $name );
208 $file = $this->addQuotes( $file );
209 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
213 * @see DatabaseBase::isWriteQuery()
215 * @param $sql string
217 * @return bool
219 function isWriteQuery( $sql ) {
220 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
224 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
226 * @param $sql string
228 * @return ResultWrapper
230 protected function doQuery( $sql ) {
231 $res = $this->mConn->query( $sql );
232 if ( $res === false ) {
233 return false;
234 } else {
235 $r = $res instanceof ResultWrapper ? $res->result : $res;
236 $this->mAffectedRows = $r->rowCount();
237 $res = new ResultWrapper( $this, $r->fetchAll() );
239 return $res;
243 * @param $res ResultWrapper
245 function freeResult( $res ) {
246 if ( $res instanceof ResultWrapper ) {
247 $res->result = null;
248 } else {
249 $res = null;
254 * @param $res ResultWrapper
255 * @return object|bool
257 function fetchObject( $res ) {
258 if ( $res instanceof ResultWrapper ) {
259 $r =& $res->result;
260 } else {
261 $r =& $res;
264 $cur = current( $r );
265 if ( is_array( $cur ) ) {
266 next( $r );
267 $obj = new stdClass;
268 foreach ( $cur as $k => $v ) {
269 if ( !is_numeric( $k ) ) {
270 $obj->$k = $v;
274 return $obj;
276 return false;
280 * @param $res ResultWrapper
281 * @return array|bool
283 function fetchRow( $res ) {
284 if ( $res instanceof ResultWrapper ) {
285 $r =& $res->result;
286 } else {
287 $r =& $res;
289 $cur = current( $r );
290 if ( is_array( $cur ) ) {
291 next( $r );
292 return $cur;
294 return false;
298 * The PDO::Statement class implements the array interface so count() will work
300 * @param $res ResultWrapper
302 * @return int
304 function numRows( $res ) {
305 $r = $res instanceof ResultWrapper ? $res->result : $res;
306 return count( $r );
310 * @param $res ResultWrapper
311 * @return int
313 function numFields( $res ) {
314 $r = $res instanceof ResultWrapper ? $res->result : $res;
315 return is_array( $r ) ? count( $r[0] ) : 0;
319 * @param $res ResultWrapper
320 * @param $n
321 * @return bool
323 function fieldName( $res, $n ) {
324 $r = $res instanceof ResultWrapper ? $res->result : $res;
325 if ( is_array( $r ) ) {
326 $keys = array_keys( $r[0] );
327 return $keys[$n];
329 return false;
333 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
335 * @param $name
336 * @param $format String
337 * @return string
339 function tableName( $name, $format = 'quoted' ) {
340 // table names starting with sqlite_ are reserved
341 if ( strpos( $name, 'sqlite_' ) === 0 ) {
342 return $name;
344 return str_replace( '"', '', parent::tableName( $name, $format ) );
348 * Index names have DB scope
350 * @param $index string
352 * @return string
354 function indexName( $index ) {
355 return $index;
359 * This must be called after nextSequenceVal
361 * @return int
363 function insertId() {
364 // PDO::lastInsertId yields a string :(
365 return intval( $this->mConn->lastInsertId() );
369 * @param $res ResultWrapper
370 * @param $row
372 function dataSeek( $res, $row ) {
373 if ( $res instanceof ResultWrapper ) {
374 $r =& $res->result;
375 } else {
376 $r =& $res;
378 reset( $r );
379 if ( $row > 0 ) {
380 for ( $i = 0; $i < $row; $i++ ) {
381 next( $r );
387 * @return string
389 function lastError() {
390 if ( !is_object( $this->mConn ) ) {
391 return "Cannot return last error, no db connection";
393 $e = $this->mConn->errorInfo();
394 return isset( $e[2] ) ? $e[2] : '';
398 * @return string
400 function lastErrno() {
401 if ( !is_object( $this->mConn ) ) {
402 return "Cannot return last error, no db connection";
403 } else {
404 $info = $this->mConn->errorInfo();
405 return $info[1];
410 * @return int
412 function affectedRows() {
413 return $this->mAffectedRows;
417 * Returns information about an index
418 * Returns false if the index does not exist
419 * - if errors are explicitly ignored, returns NULL on failure
421 * @return array
423 function indexInfo( $table, $index, $fname = __METHOD__ ) {
424 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
425 $res = $this->query( $sql, $fname );
426 if ( !$res ) {
427 return null;
429 if ( $res->numRows() == 0 ) {
430 return false;
432 $info = array();
433 foreach ( $res as $row ) {
434 $info[] = $row->name;
436 return $info;
440 * @param $table
441 * @param $index
442 * @param $fname string
443 * @return bool|null
445 function indexUnique( $table, $index, $fname = __METHOD__ ) {
446 $row = $this->selectRow( 'sqlite_master', '*',
447 array(
448 'type' => 'index',
449 'name' => $this->indexName( $index ),
450 ), $fname );
451 if ( !$row || !isset( $row->sql ) ) {
452 return null;
455 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
456 $indexPos = strpos( $row->sql, 'INDEX' );
457 if ( $indexPos === false ) {
458 return null;
460 $firstPart = substr( $row->sql, 0, $indexPos );
461 $options = explode( ' ', $firstPart );
462 return in_array( 'UNIQUE', $options );
466 * Filter the options used in SELECT statements
468 * @param $options array
470 * @return array
472 function makeSelectOptions( $options ) {
473 foreach ( $options as $k => $v ) {
474 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
475 $options[$k] = '';
478 return parent::makeSelectOptions( $options );
482 * @param $options array
483 * @return string
485 function makeUpdateOptions( $options ) {
486 $options = self::fixIgnore( $options );
487 return parent::makeUpdateOptions( $options );
491 * @param $options array
492 * @return array
494 static function fixIgnore( $options ) {
495 # SQLite uses OR IGNORE not just IGNORE
496 foreach ( $options as $k => $v ) {
497 if ( $v == 'IGNORE' ) {
498 $options[$k] = 'OR IGNORE';
501 return $options;
505 * @param $options array
506 * @return string
508 function makeInsertOptions( $options ) {
509 $options = self::fixIgnore( $options );
510 return parent::makeInsertOptions( $options );
514 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
515 * @return bool
517 function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
518 if ( !count( $a ) ) {
519 return true;
522 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
523 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
524 $ret = true;
525 foreach ( $a as $v ) {
526 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
527 $ret = false;
530 } else {
531 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
534 return $ret;
538 * @param $table
539 * @param $uniqueIndexes
540 * @param $rows
541 * @param $fname string
542 * @return bool|ResultWrapper
544 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
545 if ( !count( $rows ) ) {
546 return true;
549 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
550 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
551 $ret = true;
552 foreach ( $rows as $v ) {
553 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
554 $ret = false;
557 } else {
558 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
561 return $ret;
565 * Returns the size of a text field, or -1 for "unlimited"
566 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
568 * @return int
570 function textFieldSize( $table, $field ) {
571 return -1;
575 * @return bool
577 function unionSupportsOrderAndLimit() {
578 return false;
582 * @param $sqls
583 * @param $all
584 * @return string
586 function unionQueries( $sqls, $all ) {
587 $glue = $all ? ' UNION ALL ' : ' UNION ';
588 return implode( $glue, $sqls );
592 * @return bool
594 function wasDeadlock() {
595 return $this->lastErrno() == 5; // SQLITE_BUSY
599 * @return bool
601 function wasErrorReissuable() {
602 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
606 * @return bool
608 function wasReadOnlyError() {
609 return $this->lastErrno() == 8; // SQLITE_READONLY;
613 * @return string wikitext of a link to the server software's web site
615 public function getSoftwareLink() {
616 return "[http://sqlite.org/ SQLite]";
620 * @return string Version information from the database
622 function getServerVersion() {
623 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
624 return $ver;
628 * @return string User-friendly database information
630 public function getServerInfo() {
631 return wfMessage( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() )->text();
635 * Get information about a given field
636 * Returns false if the field does not exist.
638 * @param $table string
639 * @param $field string
640 * @return SQLiteField|bool False on failure
642 function fieldInfo( $table, $field ) {
643 $tableName = $this->tableName( $table );
644 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
645 $res = $this->query( $sql, __METHOD__ );
646 foreach ( $res as $row ) {
647 if ( $row->name == $field ) {
648 return new SQLiteField( $row, $tableName );
651 return false;
654 protected function doBegin( $fname = '' ) {
655 if ( $this->mTrxLevel == 1 ) {
656 $this->commit( __METHOD__ );
658 $this->mConn->beginTransaction();
659 $this->mTrxLevel = 1;
662 protected function doCommit( $fname = '' ) {
663 if ( $this->mTrxLevel == 0 ) {
664 return;
666 $this->mConn->commit();
667 $this->mTrxLevel = 0;
670 protected function doRollback( $fname = '' ) {
671 if ( $this->mTrxLevel == 0 ) {
672 return;
674 $this->mConn->rollBack();
675 $this->mTrxLevel = 0;
679 * @param $s string
680 * @return string
682 function strencode( $s ) {
683 return substr( $this->addQuotes( $s ), 1, - 1 );
687 * @param $b
688 * @return Blob
690 function encodeBlob( $b ) {
691 return new Blob( $b );
695 * @param $b Blob|string
696 * @return string
698 function decodeBlob( $b ) {
699 if ( $b instanceof Blob ) {
700 $b = $b->fetch();
702 return $b;
706 * @param $s Blob|string
707 * @return string
709 function addQuotes( $s ) {
710 if ( $s instanceof Blob ) {
711 return "x'" . bin2hex( $s->fetch() ) . "'";
712 } elseif ( strpos( $s, "\0" ) !== false ) {
713 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
714 // This is a known limitation of SQLite's mprintf function which PDO should work around,
715 // but doesn't. I have reported this to php.net as bug #63419:
716 // https://bugs.php.net/bug.php?id=63419
717 // There was already a similar report for SQLite3::escapeString, bug #62361:
718 // https://bugs.php.net/bug.php?id=62361
719 return "x'" . bin2hex( $s ) . "'";
720 } else {
721 return $this->mConn->quote( $s );
726 * @return string
728 function buildLike() {
729 $params = func_get_args();
730 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
731 $params = $params[0];
733 return parent::buildLike( $params ) . "ESCAPE '\' ";
737 * @return string
739 public function getSearchEngine() {
740 return "SearchSqlite";
744 * No-op version of deadlockLoop
745 * @return mixed
747 public function deadlockLoop( /*...*/ ) {
748 $args = func_get_args();
749 $function = array_shift( $args );
750 return call_user_func_array( $function, $args );
754 * @param $s string
755 * @return string
757 protected function replaceVars( $s ) {
758 $s = parent::replaceVars( $s );
759 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
760 // CREATE TABLE hacks to allow schema file sharing with MySQL
762 // binary/varbinary column type -> blob
763 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
764 // no such thing as unsigned
765 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
766 // INT -> INTEGER
767 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
768 // floating point types -> REAL
769 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
770 // varchar -> TEXT
771 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
772 // TEXT normalization
773 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
774 // BLOB normalization
775 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
776 // BOOL -> INTEGER
777 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
778 // DATETIME -> TEXT
779 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
780 // No ENUM type
781 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
782 // binary collation type -> nothing
783 $s = preg_replace( '/\bbinary\b/i', '', $s );
784 // auto_increment -> autoincrement
785 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
786 // No explicit options
787 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
788 // AUTOINCREMENT should immedidately follow PRIMARY KEY
789 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
790 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
791 // No truncated indexes
792 $s = preg_replace( '/\(\d+\)/', '', $s );
793 // No FULLTEXT
794 $s = preg_replace( '/\bfulltext\b/i', '', $s );
796 return $s;
800 * Build a concatenation list to feed into a SQL query
802 * @param $stringList array
804 * @return string
806 function buildConcat( $stringList ) {
807 return '(' . implode( ') || (', $stringList ) . ')';
811 * @throws MWException
812 * @param $oldName
813 * @param $newName
814 * @param $temporary bool
815 * @param $fname string
816 * @return bool|ResultWrapper
818 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
819 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
820 $obj = $this->fetchObject( $res );
821 if ( !$obj ) {
822 throw new MWException( "Couldn't retrieve structure for table $oldName" );
824 $sql = $obj->sql;
825 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
826 if ( $temporary ) {
827 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
828 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
829 } else {
830 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
833 return $this->query( $sql, $fname );
837 * List all tables on the database
839 * @param string $prefix Only show tables with this prefix, e.g. mw_
840 * @param string $fname calling function name
842 * @return array
844 function listTables( $prefix = null, $fname = __METHOD__ ) {
845 $result = $this->select(
846 'sqlite_master',
847 'name',
848 "type='table'"
851 $endArray = array();
853 foreach ( $result as $table ) {
854 $vars = get_object_vars( $table );
855 $table = array_pop( $vars );
857 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
858 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
859 $endArray[] = $table;
865 return $endArray;
868 } // end DatabaseSqlite class
871 * This class allows simple acccess to a SQLite database independently from main database settings
872 * @ingroup Database
874 class DatabaseSqliteStandalone extends DatabaseSqlite {
875 public function __construct( $fileName, $flags = 0 ) {
876 $this->mFlags = $flags;
877 $this->tablePrefix( null );
878 $this->openFile( $fileName );
883 * @ingroup Database
885 class SQLiteField implements Field {
886 private $info, $tableName;
887 function __construct( $info, $tableName ) {
888 $this->info = $info;
889 $this->tableName = $tableName;
892 function name() {
893 return $this->info->name;
896 function tableName() {
897 return $this->tableName;
900 function defaultValue() {
901 if ( is_string( $this->info->dflt_value ) ) {
902 // Typically quoted
903 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
904 return str_replace( "''", "'", $this->info->dflt_value );
907 return $this->info->dflt_value;
911 * @return bool
913 function isNullable() {
914 return !$this->info->notnull;
917 function type() {
918 return $this->info->type;
921 } // end SQLiteField