Followup to r86053 - fix special page cases
[mediawiki.git] / includes / db / DatabaseSqlite.php
blobb2eb1c6bd8f064d4c0fff8b7a850a2226f1b3aa0
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|false 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 * Close an SQLite database
120 * @return bool
122 function close() {
123 $this->mOpened = false;
124 if ( is_object( $this->mConn ) ) {
125 if ( $this->trxLevel() ) $this->commit();
126 $this->mConn = null;
128 return true;
132 * Generates a database file name. Explicitly public for installer.
133 * @param $dir String: Directory where database resides
134 * @param $dbName String: Database name
135 * @return String
137 public static function generateFileName( $dir, $dbName ) {
138 return "$dir/$dbName.sqlite";
142 * Check if the searchindext table is FTS enabled.
143 * @return false if not enabled.
145 function checkForEnabledSearch() {
146 if ( self::$fulltextEnabled === null ) {
147 self::$fulltextEnabled = false;
148 $table = $this->tableName( 'searchindex' );
149 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
150 if ( $res ) {
151 $row = $res->fetchRow();
152 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
155 return self::$fulltextEnabled;
159 * Returns version of currently supported SQLite fulltext search module or false if none present.
160 * @return String
162 static function getFulltextSearchModule() {
163 static $cachedResult = null;
164 if ( $cachedResult !== null ) {
165 return $cachedResult;
167 $cachedResult = false;
168 $table = 'dummy_search_test';
170 $db = new DatabaseSqliteStandalone( ':memory:' );
172 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
173 $cachedResult = 'FTS3';
175 $db->close();
176 return $cachedResult;
180 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
181 * for details.
183 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
184 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
185 * @param $fname String: calling function name
187 * @return ResultWrapper
189 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
190 global $wgSQLiteDataDir;
191 if ( !$file ) {
192 $file = self::generateFileName( $wgSQLiteDataDir, $name );
194 $file = $this->addQuotes( $file );
195 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
199 * @see DatabaseBase::isWriteQuery()
201 * @param $sql string
203 * @return bool
205 function isWriteQuery( $sql ) {
206 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
210 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
212 * @param $sql string
214 * @return ResultWrapper
216 protected function doQuery( $sql ) {
217 $res = $this->mConn->query( $sql );
218 if ( $res === false ) {
219 return false;
220 } else {
221 $r = $res instanceof ResultWrapper ? $res->result : $res;
222 $this->mAffectedRows = $r->rowCount();
223 $res = new ResultWrapper( $this, $r->fetchAll() );
225 return $res;
229 * @param $res ResultWrapper
231 function freeResult( $res ) {
232 if ( $res instanceof ResultWrapper ) {
233 $res->result = null;
234 } else {
235 $res = null;
240 * @param $res ResultWrapper
241 * @return
243 function fetchObject( $res ) {
244 if ( $res instanceof ResultWrapper ) {
245 $r =& $res->result;
246 } else {
247 $r =& $res;
250 $cur = current( $r );
251 if ( is_array( $cur ) ) {
252 next( $r );
253 $obj = new stdClass;
254 foreach ( $cur as $k => $v ) {
255 if ( !is_numeric( $k ) ) {
256 $obj->$k = $v;
260 return $obj;
262 return false;
266 * @param $res ResultWrapper
267 * @return bool|mixed
269 function fetchRow( $res ) {
270 if ( $res instanceof ResultWrapper ) {
271 $r =& $res->result;
272 } else {
273 $r =& $res;
275 $cur = current( $r );
276 if ( is_array( $cur ) ) {
277 next( $r );
278 return $cur;
280 return false;
284 * The PDO::Statement class implements the array interface so count() will work
286 * @param $res ResultWrapper
288 * @return int
290 function numRows( $res ) {
291 $r = $res instanceof ResultWrapper ? $res->result : $res;
292 return count( $r );
296 * @param $res ResultWrapper
297 * @return int
299 function numFields( $res ) {
300 $r = $res instanceof ResultWrapper ? $res->result : $res;
301 return is_array( $r ) ? count( $r[0] ) : 0;
305 * @param $res ResultWrapper
306 * @param $n
307 * @return bool
309 function fieldName( $res, $n ) {
310 $r = $res instanceof ResultWrapper ? $res->result : $res;
311 if ( is_array( $r ) ) {
312 $keys = array_keys( $r[0] );
313 return $keys[$n];
315 return false;
319 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
321 * @param $name
322 * @param $format String
323 * @return string
325 function tableName( $name, $format = 'quoted' ) {
326 // table names starting with sqlite_ are reserved
327 if ( strpos( $name, 'sqlite_' ) === 0 ) {
328 return $name;
330 return str_replace( '"', '', parent::tableName( $name, $format ) );
334 * Index names have DB scope
336 * @param $index string
338 * @return string
340 function indexName( $index ) {
341 return $index;
345 * This must be called after nextSequenceVal
347 * @return int
349 function insertId() {
350 return $this->mConn->lastInsertId();
354 * @param $res ResultWrapper
355 * @param $row
357 function dataSeek( $res, $row ) {
358 if ( $res instanceof ResultWrapper ) {
359 $r =& $res->result;
360 } else {
361 $r =& $res;
363 reset( $r );
364 if ( $row > 0 ) {
365 for ( $i = 0; $i < $row; $i++ ) {
366 next( $r );
372 * @return string
374 function lastError() {
375 if ( !is_object( $this->mConn ) ) {
376 return "Cannot return last error, no db connection";
378 $e = $this->mConn->errorInfo();
379 return isset( $e[2] ) ? $e[2] : '';
383 * @return string
385 function lastErrno() {
386 if ( !is_object( $this->mConn ) ) {
387 return "Cannot return last error, no db connection";
388 } else {
389 $info = $this->mConn->errorInfo();
390 return $info[1];
395 * @return int
397 function affectedRows() {
398 return $this->mAffectedRows;
402 * Returns information about an index
403 * Returns false if the index does not exist
404 * - if errors are explicitly ignored, returns NULL on failure
406 * @return array
408 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
409 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
410 $res = $this->query( $sql, $fname );
411 if ( !$res ) {
412 return null;
414 if ( $res->numRows() == 0 ) {
415 return false;
417 $info = array();
418 foreach ( $res as $row ) {
419 $info[] = $row->name;
421 return $info;
425 * @param $table
426 * @param $index
427 * @param $fname string
428 * @return bool|null
430 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
431 $row = $this->selectRow( 'sqlite_master', '*',
432 array(
433 'type' => 'index',
434 'name' => $this->indexName( $index ),
435 ), $fname );
436 if ( !$row || !isset( $row->sql ) ) {
437 return null;
440 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
441 $indexPos = strpos( $row->sql, 'INDEX' );
442 if ( $indexPos === false ) {
443 return null;
445 $firstPart = substr( $row->sql, 0, $indexPos );
446 $options = explode( ' ', $firstPart );
447 return in_array( 'UNIQUE', $options );
451 * Filter the options used in SELECT statements
453 * @param $options array
455 * @return array
457 function makeSelectOptions( $options ) {
458 foreach ( $options as $k => $v ) {
459 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
460 $options[$k] = '';
463 return parent::makeSelectOptions( $options );
467 * @param $options array
468 * @return string
470 function makeUpdateOptions( $options ) {
471 $options = self::fixIgnore( $options );
472 return parent::makeUpdateOptions( $options );
476 * @param $options array
477 * @return array
479 static function fixIgnore( $options ) {
480 # SQLite uses OR IGNORE not just IGNORE
481 foreach ( $options as $k => $v ) {
482 if ( $v == 'IGNORE' ) {
483 $options[$k] = 'OR IGNORE';
486 return $options;
490 * @param $options array
491 * @return string
493 function makeInsertOptions( $options ) {
494 $options = self::fixIgnore( $options );
495 return parent::makeInsertOptions( $options );
499 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
501 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
502 if ( !count( $a ) ) {
503 return true;
506 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
507 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
508 $ret = true;
509 foreach ( $a as $v ) {
510 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
511 $ret = false;
514 } else {
515 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
518 return $ret;
522 * @param $table
523 * @param $uniqueIndexes
524 * @param $rows
525 * @param $fname string
526 * @return bool|ResultWrapper
528 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
529 if ( !count( $rows ) ) return true;
531 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
532 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
533 $ret = true;
534 foreach ( $rows as $v ) {
535 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
536 $ret = false;
539 } else {
540 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
543 return $ret;
547 * Returns the size of a text field, or -1 for "unlimited"
548 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
550 * @return int
552 function textFieldSize( $table, $field ) {
553 return -1;
557 * @return bool
559 function unionSupportsOrderAndLimit() {
560 return false;
564 * @param $sqls
565 * @param $all
566 * @return string
568 function unionQueries( $sqls, $all ) {
569 $glue = $all ? ' UNION ALL ' : ' UNION ';
570 return implode( $glue, $sqls );
574 * @return bool
576 function wasDeadlock() {
577 return $this->lastErrno() == 5; // SQLITE_BUSY
581 * @return bool
583 function wasErrorReissuable() {
584 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
588 * @return bool
590 function wasReadOnlyError() {
591 return $this->lastErrno() == 8; // SQLITE_READONLY;
595 * @return string wikitext of a link to the server software's web site
597 public static function getSoftwareLink() {
598 return "[http://sqlite.org/ SQLite]";
602 * @return string Version information from the database
604 function getServerVersion() {
605 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
606 return $ver;
610 * @return string User-friendly database information
612 public function getServerInfo() {
613 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
617 * Get information about a given field
618 * Returns false if the field does not exist.
620 * @return SQLiteField|false
622 function fieldInfo( $table, $field ) {
623 $tableName = $this->tableName( $table );
624 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
625 $res = $this->query( $sql, __METHOD__ );
626 foreach ( $res as $row ) {
627 if ( $row->name == $field ) {
628 return new SQLiteField( $row, $tableName );
631 return false;
634 function begin( $fname = '' ) {
635 if ( $this->mTrxLevel == 1 ) {
636 $this->commit();
638 $this->mConn->beginTransaction();
639 $this->mTrxLevel = 1;
642 function commit( $fname = '' ) {
643 if ( $this->mTrxLevel == 0 ) {
644 return;
646 $this->mConn->commit();
647 $this->mTrxLevel = 0;
650 function rollback( $fname = '' ) {
651 if ( $this->mTrxLevel == 0 ) {
652 return;
654 $this->mConn->rollBack();
655 $this->mTrxLevel = 0;
659 * @param $sql
660 * @param $num
661 * @return string
663 function limitResultForUpdate( $sql, $num ) {
664 return $this->limitResult( $sql, $num );
668 * @param $s string
669 * @return string
671 function strencode( $s ) {
672 return substr( $this->addQuotes( $s ), 1, - 1 );
676 * @param $b
677 * @return Blob
679 function encodeBlob( $b ) {
680 return new Blob( $b );
684 * @param $b Blob|string
685 * @return string
687 function decodeBlob( $b ) {
688 if ( $b instanceof Blob ) {
689 $b = $b->fetch();
691 return $b;
695 * @param $s Blob|string
696 * @return string
698 function addQuotes( $s ) {
699 if ( $s instanceof Blob ) {
700 return "x'" . bin2hex( $s->fetch() ) . "'";
701 } else {
702 return $this->mConn->quote( $s );
707 * @return string
709 function buildLike() {
710 $params = func_get_args();
711 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
712 $params = $params[0];
714 return parent::buildLike( $params ) . "ESCAPE '\' ";
718 * @return string
720 public function getSearchEngine() {
721 return "SearchSqlite";
725 * No-op version of deadlockLoop
727 public function deadlockLoop( /*...*/ ) {
728 $args = func_get_args();
729 $function = array_shift( $args );
730 return call_user_func_array( $function, $args );
734 * @param $s string
735 * @return string
737 protected function replaceVars( $s ) {
738 $s = parent::replaceVars( $s );
739 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
740 // CREATE TABLE hacks to allow schema file sharing with MySQL
742 // binary/varbinary column type -> blob
743 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
744 // no such thing as unsigned
745 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
746 // INT -> INTEGER
747 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
748 // floating point types -> REAL
749 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
750 // varchar -> TEXT
751 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
752 // TEXT normalization
753 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
754 // BLOB normalization
755 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
756 // BOOL -> INTEGER
757 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
758 // DATETIME -> TEXT
759 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
760 // No ENUM type
761 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
762 // binary collation type -> nothing
763 $s = preg_replace( '/\bbinary\b/i', '', $s );
764 // auto_increment -> autoincrement
765 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
766 // No explicit options
767 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
768 // AUTOINCREMENT should immedidately follow PRIMARY KEY
769 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
770 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
771 // No truncated indexes
772 $s = preg_replace( '/\(\d+\)/', '', $s );
773 // No FULLTEXT
774 $s = preg_replace( '/\bfulltext\b/i', '', $s );
776 return $s;
780 * Build a concatenation list to feed into a SQL query
782 * @param $stringList array
784 * @return string
786 function buildConcat( $stringList ) {
787 return '(' . implode( ') || (', $stringList ) . ')';
791 * @throws MWException
792 * @param $oldName
793 * @param $newName
794 * @param $temporary bool
795 * @param $fname string
796 * @return bool|ResultWrapper
798 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
799 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
800 $obj = $this->fetchObject( $res );
801 if ( !$obj ) {
802 throw new MWException( "Couldn't retrieve structure for table $oldName" );
804 $sql = $obj->sql;
805 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
806 if ( $temporary ) {
807 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
808 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
809 } else {
810 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
813 return $this->query( $sql, $fname );
818 * List all tables on the database
820 * @param $prefix Only show tables with this prefix, e.g. mw_
821 * @param $fname String: calling function name
823 * @return array
825 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
826 $result = $this->select(
827 'sqlite_master',
828 'name',
829 "type='table'"
832 $endArray = array();
834 foreach( $result as $table ) {
835 $vars = get_object_vars($table);
836 $table = array_pop( $vars );
838 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
839 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
840 $endArray[] = $table;
846 return $endArray;
849 } // end DatabaseSqlite class
852 * This class allows simple acccess to a SQLite database independently from main database settings
853 * @ingroup Database
855 class DatabaseSqliteStandalone extends DatabaseSqlite {
856 public function __construct( $fileName, $flags = 0 ) {
857 $this->mFlags = $flags;
858 $this->tablePrefix( null );
859 $this->openFile( $fileName );
864 * @ingroup Database
866 class SQLiteField implements Field {
867 private $info, $tableName;
868 function __construct( $info, $tableName ) {
869 $this->info = $info;
870 $this->tableName = $tableName;
873 function name() {
874 return $this->info->name;
877 function tableName() {
878 return $this->tableName;
881 function defaultValue() {
882 if ( is_string( $this->info->dflt_value ) ) {
883 // Typically quoted
884 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
885 return str_replace( "''", "'", $this->info->dflt_value );
888 return $this->info->dflt_value;
892 * @return bool
894 function isNullable() {
895 return !$this->info->notnull;
898 function type() {
899 return $this->info->type;
902 } // end SQLiteField