(bug 35565) Special:Log/patrol doesn't indicate whether patrolling was automatic
[mediawiki.git] / includes / db / DatabaseSqlite.php
blob3aa21b84fe87d1b743c0d92218d0369c72f2ba4e
1 <?php
2 /**
3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * @file
7 * @ingroup Database
8 */
10 /**
11 * @ingroup Database
13 class DatabaseSqlite extends DatabaseBase {
15 private static $fulltextEnabled = null;
17 var $mAffectedRows;
18 var $mLastResult;
19 var $mDatabaseFile;
20 var $mName;
22 /**
23 * @var PDO
25 protected $mConn;
27 /**
28 * Constructor.
29 * Parameters $server, $user and $password are not used.
30 * @param $server string
31 * @param $user string
32 * @param $password string
33 * @param $dbName string
34 * @param $flags int
36 function __construct( $server = false, $user = false, $password = false, $dbName = false, $flags = 0 ) {
37 $this->mName = $dbName;
38 parent::__construct( $server, $user, $password, $dbName, $flags );
39 // parent doesn't open when $user is false, but we can work with $dbName
40 if( $dbName ) {
41 global $wgSharedDB;
42 if( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
43 $this->attachDatabase( $wgSharedDB );
48 /**
49 * @return string
51 function getType() {
52 return 'sqlite';
55 /**
56 * @todo: check if it should be true like parent class
58 * @return bool
60 function implicitGroupby() {
61 return false;
64 /** Open an SQLite database and return a resource handle to it
65 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
67 * @param $server
68 * @param $user
69 * @param $pass
70 * @param $dbName
72 * @return PDO
74 function open( $server, $user, $pass, $dbName ) {
75 global $wgSQLiteDataDir;
77 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
78 if ( !is_readable( $fileName ) ) {
79 $this->mConn = false;
80 throw new DBConnectionError( $this, "SQLite database not accessible" );
82 $this->openFile( $fileName );
83 return $this->mConn;
86 /**
87 * Opens a database file
89 * @param $fileName string
91 * @return PDO|bool SQL connection or false if failed
93 function openFile( $fileName ) {
94 $this->mDatabaseFile = $fileName;
95 try {
96 if ( $this->mFlags & DBO_PERSISTENT ) {
97 $this->mConn = new PDO( "sqlite:$fileName", '', '',
98 array( PDO::ATTR_PERSISTENT => true ) );
99 } else {
100 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
102 } catch ( PDOException $e ) {
103 $err = $e->getMessage();
105 if ( !$this->mConn ) {
106 wfDebug( "DB connection error: $err\n" );
107 throw new DBConnectionError( $this, $err );
109 $this->mOpened = !!$this->mConn;
110 # set error codes only, don't raise exceptions
111 if ( $this->mOpened ) {
112 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
113 return true;
118 * Does not actually close the connection, just destroys the reference for GC to do its work
119 * @return bool
121 protected function closeConnection() {
122 $this->mConn = null;
123 return true;
127 * Generates a database file name. Explicitly public for installer.
128 * @param $dir String: Directory where database resides
129 * @param $dbName String: Database name
130 * @return String
132 public static function generateFileName( $dir, $dbName ) {
133 return "$dir/$dbName.sqlite";
137 * Check if the searchindext table is FTS enabled.
138 * @return bool False if not enabled.
140 function checkForEnabledSearch() {
141 if ( self::$fulltextEnabled === null ) {
142 self::$fulltextEnabled = false;
143 $table = $this->tableName( 'searchindex' );
144 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
145 if ( $res ) {
146 $row = $res->fetchRow();
147 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
150 return self::$fulltextEnabled;
154 * Returns version of currently supported SQLite fulltext search module or false if none present.
155 * @return String
157 static function getFulltextSearchModule() {
158 static $cachedResult = null;
159 if ( $cachedResult !== null ) {
160 return $cachedResult;
162 $cachedResult = false;
163 $table = 'dummy_search_test';
165 $db = new DatabaseSqliteStandalone( ':memory:' );
167 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
168 $cachedResult = 'FTS3';
170 $db->close();
171 return $cachedResult;
175 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
176 * for details.
178 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
179 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
180 * @param $fname String: calling function name
182 * @return ResultWrapper
184 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
185 global $wgSQLiteDataDir;
186 if ( !$file ) {
187 $file = self::generateFileName( $wgSQLiteDataDir, $name );
189 $file = $this->addQuotes( $file );
190 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
194 * @see DatabaseBase::isWriteQuery()
196 * @param $sql string
198 * @return bool
200 function isWriteQuery( $sql ) {
201 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
205 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
207 * @param $sql string
209 * @return ResultWrapper
211 protected function doQuery( $sql ) {
212 $res = $this->mConn->query( $sql );
213 if ( $res === false ) {
214 return false;
215 } else {
216 $r = $res instanceof ResultWrapper ? $res->result : $res;
217 $this->mAffectedRows = $r->rowCount();
218 $res = new ResultWrapper( $this, $r->fetchAll() );
220 return $res;
224 * @param $res ResultWrapper
226 function freeResult( $res ) {
227 if ( $res instanceof ResultWrapper ) {
228 $res->result = null;
229 } else {
230 $res = null;
235 * @param $res ResultWrapper
236 * @return
238 function fetchObject( $res ) {
239 if ( $res instanceof ResultWrapper ) {
240 $r =& $res->result;
241 } else {
242 $r =& $res;
245 $cur = current( $r );
246 if ( is_array( $cur ) ) {
247 next( $r );
248 $obj = new stdClass;
249 foreach ( $cur as $k => $v ) {
250 if ( !is_numeric( $k ) ) {
251 $obj->$k = $v;
255 return $obj;
257 return false;
261 * @param $res ResultWrapper
262 * @return bool|mixed
264 function fetchRow( $res ) {
265 if ( $res instanceof ResultWrapper ) {
266 $r =& $res->result;
267 } else {
268 $r =& $res;
270 $cur = current( $r );
271 if ( is_array( $cur ) ) {
272 next( $r );
273 return $cur;
275 return false;
279 * The PDO::Statement class implements the array interface so count() will work
281 * @param $res ResultWrapper
283 * @return int
285 function numRows( $res ) {
286 $r = $res instanceof ResultWrapper ? $res->result : $res;
287 return count( $r );
291 * @param $res ResultWrapper
292 * @return int
294 function numFields( $res ) {
295 $r = $res instanceof ResultWrapper ? $res->result : $res;
296 return is_array( $r ) ? count( $r[0] ) : 0;
300 * @param $res ResultWrapper
301 * @param $n
302 * @return bool
304 function fieldName( $res, $n ) {
305 $r = $res instanceof ResultWrapper ? $res->result : $res;
306 if ( is_array( $r ) ) {
307 $keys = array_keys( $r[0] );
308 return $keys[$n];
310 return false;
314 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
316 * @param $name
317 * @param $format String
318 * @return string
320 function tableName( $name, $format = 'quoted' ) {
321 // table names starting with sqlite_ are reserved
322 if ( strpos( $name, 'sqlite_' ) === 0 ) {
323 return $name;
325 return str_replace( '"', '', parent::tableName( $name, $format ) );
329 * Index names have DB scope
331 * @param $index string
333 * @return string
335 function indexName( $index ) {
336 return $index;
340 * This must be called after nextSequenceVal
342 * @return int
344 function insertId() {
345 return $this->mConn->lastInsertId();
349 * @param $res ResultWrapper
350 * @param $row
352 function dataSeek( $res, $row ) {
353 if ( $res instanceof ResultWrapper ) {
354 $r =& $res->result;
355 } else {
356 $r =& $res;
358 reset( $r );
359 if ( $row > 0 ) {
360 for ( $i = 0; $i < $row; $i++ ) {
361 next( $r );
367 * @return string
369 function lastError() {
370 if ( !is_object( $this->mConn ) ) {
371 return "Cannot return last error, no db connection";
373 $e = $this->mConn->errorInfo();
374 return isset( $e[2] ) ? $e[2] : '';
378 * @return string
380 function lastErrno() {
381 if ( !is_object( $this->mConn ) ) {
382 return "Cannot return last error, no db connection";
383 } else {
384 $info = $this->mConn->errorInfo();
385 return $info[1];
390 * @return int
392 function affectedRows() {
393 return $this->mAffectedRows;
397 * Returns information about an index
398 * Returns false if the index does not exist
399 * - if errors are explicitly ignored, returns NULL on failure
401 * @return array
403 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
404 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
405 $res = $this->query( $sql, $fname );
406 if ( !$res ) {
407 return null;
409 if ( $res->numRows() == 0 ) {
410 return false;
412 $info = array();
413 foreach ( $res as $row ) {
414 $info[] = $row->name;
416 return $info;
420 * @param $table
421 * @param $index
422 * @param $fname string
423 * @return bool|null
425 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
426 $row = $this->selectRow( 'sqlite_master', '*',
427 array(
428 'type' => 'index',
429 'name' => $this->indexName( $index ),
430 ), $fname );
431 if ( !$row || !isset( $row->sql ) ) {
432 return null;
435 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
436 $indexPos = strpos( $row->sql, 'INDEX' );
437 if ( $indexPos === false ) {
438 return null;
440 $firstPart = substr( $row->sql, 0, $indexPos );
441 $options = explode( ' ', $firstPart );
442 return in_array( 'UNIQUE', $options );
446 * Filter the options used in SELECT statements
448 * @param $options array
450 * @return array
452 function makeSelectOptions( $options ) {
453 foreach ( $options as $k => $v ) {
454 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
455 $options[$k] = '';
458 return parent::makeSelectOptions( $options );
462 * @param $options array
463 * @return string
465 function makeUpdateOptions( $options ) {
466 $options = self::fixIgnore( $options );
467 return parent::makeUpdateOptions( $options );
471 * @param $options array
472 * @return array
474 static function fixIgnore( $options ) {
475 # SQLite uses OR IGNORE not just IGNORE
476 foreach ( $options as $k => $v ) {
477 if ( $v == 'IGNORE' ) {
478 $options[$k] = 'OR IGNORE';
481 return $options;
485 * @param $options array
486 * @return string
488 function makeInsertOptions( $options ) {
489 $options = self::fixIgnore( $options );
490 return parent::makeInsertOptions( $options );
494 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
495 * @return bool
497 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
498 if ( !count( $a ) ) {
499 return true;
502 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
503 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
504 $ret = true;
505 foreach ( $a as $v ) {
506 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
507 $ret = false;
510 } else {
511 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
514 return $ret;
518 * @param $table
519 * @param $uniqueIndexes
520 * @param $rows
521 * @param $fname string
522 * @return bool|ResultWrapper
524 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
525 if ( !count( $rows ) ) return true;
527 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
528 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
529 $ret = true;
530 foreach ( $rows as $v ) {
531 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
532 $ret = false;
535 } else {
536 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
539 return $ret;
543 * Returns the size of a text field, or -1 for "unlimited"
544 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
546 * @return int
548 function textFieldSize( $table, $field ) {
549 return -1;
553 * @return bool
555 function unionSupportsOrderAndLimit() {
556 return false;
560 * @param $sqls
561 * @param $all
562 * @return string
564 function unionQueries( $sqls, $all ) {
565 $glue = $all ? ' UNION ALL ' : ' UNION ';
566 return implode( $glue, $sqls );
570 * @return bool
572 function wasDeadlock() {
573 return $this->lastErrno() == 5; // SQLITE_BUSY
577 * @return bool
579 function wasErrorReissuable() {
580 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
584 * @return bool
586 function wasReadOnlyError() {
587 return $this->lastErrno() == 8; // SQLITE_READONLY;
591 * @return string wikitext of a link to the server software's web site
593 public static function getSoftwareLink() {
594 return "[http://sqlite.org/ SQLite]";
598 * @return string Version information from the database
600 function getServerVersion() {
601 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
602 return $ver;
606 * @return string User-friendly database information
608 public function getServerInfo() {
609 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
613 * Get information about a given field
614 * Returns false if the field does not exist.
616 * @param $table string
617 * @param $field string
618 * @return SQLiteField|bool False on failure
620 function fieldInfo( $table, $field ) {
621 $tableName = $this->tableName( $table );
622 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
623 $res = $this->query( $sql, __METHOD__ );
624 foreach ( $res as $row ) {
625 if ( $row->name == $field ) {
626 return new SQLiteField( $row, $tableName );
629 return false;
632 function begin( $fname = '' ) {
633 if ( $this->mTrxLevel == 1 ) {
634 $this->commit( __METHOD__ );
636 $this->mConn->beginTransaction();
637 $this->mTrxLevel = 1;
640 function commit( $fname = '' ) {
641 if ( $this->mTrxLevel == 0 ) {
642 return;
644 $this->mConn->commit();
645 $this->mTrxLevel = 0;
648 function rollback( $fname = '' ) {
649 if ( $this->mTrxLevel == 0 ) {
650 return;
652 $this->mConn->rollBack();
653 $this->mTrxLevel = 0;
657 * @param $sql
658 * @param $num
659 * @return string
661 function limitResultForUpdate( $sql, $num ) {
662 return $this->limitResult( $sql, $num );
666 * @param $s string
667 * @return string
669 function strencode( $s ) {
670 return substr( $this->addQuotes( $s ), 1, - 1 );
674 * @param $b
675 * @return Blob
677 function encodeBlob( $b ) {
678 return new Blob( $b );
682 * @param $b Blob|string
683 * @return string
685 function decodeBlob( $b ) {
686 if ( $b instanceof Blob ) {
687 $b = $b->fetch();
689 return $b;
693 * @param $s Blob|string
694 * @return string
696 function addQuotes( $s ) {
697 if ( $s instanceof Blob ) {
698 return "x'" . bin2hex( $s->fetch() ) . "'";
699 } else {
700 return $this->mConn->quote( $s );
705 * @return string
707 function buildLike() {
708 $params = func_get_args();
709 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
710 $params = $params[0];
712 return parent::buildLike( $params ) . "ESCAPE '\' ";
716 * @return string
718 public function getSearchEngine() {
719 return "SearchSqlite";
723 * No-op version of deadlockLoop
724 * @return mixed
726 public function deadlockLoop( /*...*/ ) {
727 $args = func_get_args();
728 $function = array_shift( $args );
729 return call_user_func_array( $function, $args );
733 * @param $s string
734 * @return string
736 protected function replaceVars( $s ) {
737 $s = parent::replaceVars( $s );
738 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
739 // CREATE TABLE hacks to allow schema file sharing with MySQL
741 // binary/varbinary column type -> blob
742 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
743 // no such thing as unsigned
744 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
745 // INT -> INTEGER
746 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
747 // floating point types -> REAL
748 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
749 // varchar -> TEXT
750 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
751 // TEXT normalization
752 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
753 // BLOB normalization
754 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
755 // BOOL -> INTEGER
756 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
757 // DATETIME -> TEXT
758 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
759 // No ENUM type
760 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
761 // binary collation type -> nothing
762 $s = preg_replace( '/\bbinary\b/i', '', $s );
763 // auto_increment -> autoincrement
764 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
765 // No explicit options
766 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
767 // AUTOINCREMENT should immedidately follow PRIMARY KEY
768 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
769 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
770 // No truncated indexes
771 $s = preg_replace( '/\(\d+\)/', '', $s );
772 // No FULLTEXT
773 $s = preg_replace( '/\bfulltext\b/i', '', $s );
775 return $s;
779 * Build a concatenation list to feed into a SQL query
781 * @param $stringList array
783 * @return string
785 function buildConcat( $stringList ) {
786 return '(' . implode( ') || (', $stringList ) . ')';
790 * @throws MWException
791 * @param $oldName
792 * @param $newName
793 * @param $temporary bool
794 * @param $fname string
795 * @return bool|ResultWrapper
797 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
798 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
799 $obj = $this->fetchObject( $res );
800 if ( !$obj ) {
801 throw new MWException( "Couldn't retrieve structure for table $oldName" );
803 $sql = $obj->sql;
804 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
805 if ( $temporary ) {
806 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
807 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
808 } else {
809 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
812 return $this->query( $sql, $fname );
817 * List all tables on the database
819 * @param $prefix string Only show tables with this prefix, e.g. mw_
820 * @param $fname String: calling function name
822 * @return array
824 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
825 $result = $this->select(
826 'sqlite_master',
827 'name',
828 "type='table'"
831 $endArray = array();
833 foreach( $result as $table ) {
834 $vars = get_object_vars($table);
835 $table = array_pop( $vars );
837 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
838 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
839 $endArray[] = $table;
845 return $endArray;
848 } // end DatabaseSqlite class
851 * This class allows simple acccess to a SQLite database independently from main database settings
852 * @ingroup Database
854 class DatabaseSqliteStandalone extends DatabaseSqlite {
855 public function __construct( $fileName, $flags = 0 ) {
856 $this->mFlags = $flags;
857 $this->tablePrefix( null );
858 $this->openFile( $fileName );
863 * @ingroup Database
865 class SQLiteField implements Field {
866 private $info, $tableName;
867 function __construct( $info, $tableName ) {
868 $this->info = $info;
869 $this->tableName = $tableName;
872 function name() {
873 return $this->info->name;
876 function tableName() {
877 return $this->tableName;
880 function defaultValue() {
881 if ( is_string( $this->info->dflt_value ) ) {
882 // Typically quoted
883 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
884 return str_replace( "''", "'", $this->info->dflt_value );
887 return $this->info->dflt_value;
891 * @return bool
893 function isNullable() {
894 return !$this->info->notnull;
897 function type() {
898 return $this->info->type;
901 } // end SQLiteField