Merge "Typography update to Vector skin"
[mediawiki.git] / includes / db / DatabaseSqlite.php
blob3313d25841afb1d2c8b8bffeadd4c7a4cba49d2e
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 {
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;
38 /** @var resource */
39 protected $mLastResult;
41 /** @var PDO */
42 protected $mConn;
44 /** @var FSLockManager (hopefully on the same server as the DB) */
45 protected $lockMgr;
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();
53 $p = array(
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 'schema' => 'get from global',
61 'foreign' => isset( $args[6] ) ? $args[6] : false
64 $this->mDBname = $p['dbname'];
65 parent::__construct( $p );
66 // parent doesn't open when $user is false, but we can work with $dbName
67 if ( $p['dbname'] && !$this->isOpen() ) {
68 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
69 if ( $wgSharedDB ) {
70 $this->attachDatabase( $wgSharedDB );
75 $this->lockMgr = new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
78 /**
79 * @return string
81 function getType() {
82 return 'sqlite';
85 /**
86 * @todo Check if it should be true like parent class
88 * @return bool
90 function implicitGroupby() {
91 return false;
94 /** Open an SQLite database and return a resource handle to it
95 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
97 * @param string $server
98 * @param string $user
99 * @param string $pass
100 * @param string $dbName
102 * @throws DBConnectionError
103 * @return PDO
105 function open( $server, $user, $pass, $dbName ) {
106 global $wgSQLiteDataDir;
108 $this->close();
109 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
110 if ( !is_readable( $fileName ) ) {
111 $this->mConn = false;
112 throw new DBConnectionError( $this, "SQLite database not accessible" );
114 $this->openFile( $fileName );
116 return $this->mConn;
120 * Opens a database file
122 * @param string $fileName
123 * @throws DBConnectionError
124 * @return PDO|bool SQL connection or false if failed
126 function openFile( $fileName ) {
127 $err = false;
129 $this->mDatabaseFile = $fileName;
130 try {
131 if ( $this->mFlags & DBO_PERSISTENT ) {
132 $this->mConn = new PDO( "sqlite:$fileName", '', '',
133 array( PDO::ATTR_PERSISTENT => true ) );
134 } else {
135 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
137 } catch ( PDOException $e ) {
138 $err = $e->getMessage();
141 if ( !$this->mConn ) {
142 wfDebug( "DB connection error: $err\n" );
143 throw new DBConnectionError( $this, $err );
146 $this->mOpened = !!$this->mConn;
147 # set error codes only, don't raise exceptions
148 if ( $this->mOpened ) {
149 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
150 # Enforce LIKE to be case sensitive, just like MySQL
151 $this->query( 'PRAGMA case_sensitive_like = 1' );
153 return $this->mConn;
156 return false;
160 * Does not actually close the connection, just destroys the reference for GC to do its work
161 * @return bool
163 protected function closeConnection() {
164 $this->mConn = null;
166 return true;
170 * Generates a database file name. Explicitly public for installer.
171 * @param string $dir Directory where database resides
172 * @param string $dbName Database name
173 * @return string
175 public static function generateFileName( $dir, $dbName ) {
176 return "$dir/$dbName.sqlite";
180 * Check if the searchindext table is FTS enabled.
181 * @return bool False if not enabled.
183 function checkForEnabledSearch() {
184 if ( self::$fulltextEnabled === null ) {
185 self::$fulltextEnabled = false;
186 $table = $this->tableName( 'searchindex' );
187 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
188 if ( $res ) {
189 $row = $res->fetchRow();
190 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
194 return self::$fulltextEnabled;
198 * Returns version of currently supported SQLite fulltext search module or false if none present.
199 * @return string
201 static function getFulltextSearchModule() {
202 static $cachedResult = null;
203 if ( $cachedResult !== null ) {
204 return $cachedResult;
206 $cachedResult = false;
207 $table = 'dummy_search_test';
209 $db = new DatabaseSqliteStandalone( ':memory:' );
211 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
212 $cachedResult = 'FTS3';
214 $db->close();
216 return $cachedResult;
220 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
221 * for details.
223 * @param string $name Database name to be used in queries like
224 * SELECT foo FROM dbname.table
225 * @param bool|string $file Database file name. If omitted, will be generated
226 * using $name and $wgSQLiteDataDir
227 * @param string $fname Calling function name
228 * @return ResultWrapper
230 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
231 global $wgSQLiteDataDir;
232 if ( !$file ) {
233 $file = self::generateFileName( $wgSQLiteDataDir, $name );
235 $file = $this->addQuotes( $file );
237 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
241 * @see DatabaseBase::isWriteQuery()
243 * @param $sql string
244 * @return bool
246 function isWriteQuery( $sql ) {
247 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
251 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
253 * @param string $sql
254 * @return bool|ResultWrapper
256 protected function doQuery( $sql ) {
257 $res = $this->mConn->query( $sql );
258 if ( $res === false ) {
259 return false;
260 } else {
261 $r = $res instanceof ResultWrapper ? $res->result : $res;
262 $this->mAffectedRows = $r->rowCount();
263 $res = new ResultWrapper( $this, $r->fetchAll() );
266 return $res;
270 * @param ResultWrapper|mixed $res
272 function freeResult( $res ) {
273 if ( $res instanceof ResultWrapper ) {
274 $res->result = null;
275 } else {
276 $res = null;
281 * @param ResultWrapper|array $res
282 * @return stdClass|bool
284 function fetchObject( $res ) {
285 if ( $res instanceof ResultWrapper ) {
286 $r =& $res->result;
287 } else {
288 $r =& $res;
291 $cur = current( $r );
292 if ( is_array( $cur ) ) {
293 next( $r );
294 $obj = new stdClass;
295 foreach ( $cur as $k => $v ) {
296 if ( !is_numeric( $k ) ) {
297 $obj->$k = $v;
301 return $obj;
304 return false;
308 * @param ResultWrapper|mixed $res
309 * @return array|bool
311 function fetchRow( $res ) {
312 if ( $res instanceof ResultWrapper ) {
313 $r =& $res->result;
314 } else {
315 $r =& $res;
317 $cur = current( $r );
318 if ( is_array( $cur ) ) {
319 next( $r );
321 return $cur;
324 return false;
328 * The PDO::Statement class implements the array interface so count() will work
330 * @param ResultWrapper|array $res
331 * @return int
333 function numRows( $res ) {
334 $r = $res instanceof ResultWrapper ? $res->result : $res;
336 return count( $r );
340 * @param ResultWrapper $res
341 * @return int
343 function numFields( $res ) {
344 $r = $res instanceof ResultWrapper ? $res->result : $res;
346 return is_array( $r ) ? count( $r[0] ) : 0;
350 * @param ResultWrapper $res
351 * @param $n
352 * @return bool
354 function fieldName( $res, $n ) {
355 $r = $res instanceof ResultWrapper ? $res->result : $res;
356 if ( is_array( $r ) ) {
357 $keys = array_keys( $r[0] );
359 return $keys[$n];
362 return false;
366 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
368 * @param string $name
369 * @param string $format
370 * @return string
372 function tableName( $name, $format = 'quoted' ) {
373 // table names starting with sqlite_ are reserved
374 if ( strpos( $name, 'sqlite_' ) === 0 ) {
375 return $name;
378 return str_replace( '"', '', parent::tableName( $name, $format ) );
382 * Index names have DB scope
384 * @param string $index
385 * @return string
387 function indexName( $index ) {
388 return $index;
392 * This must be called after nextSequenceVal
394 * @return int
396 function insertId() {
397 // PDO::lastInsertId yields a string :(
398 return intval( $this->mConn->lastInsertId() );
402 * @param ResultWrapper|array $res
403 * @param int $row
405 function dataSeek( $res, $row ) {
406 if ( $res instanceof ResultWrapper ) {
407 $r =& $res->result;
408 } else {
409 $r =& $res;
411 reset( $r );
412 if ( $row > 0 ) {
413 for ( $i = 0; $i < $row; $i++ ) {
414 next( $r );
420 * @return string
422 function lastError() {
423 if ( !is_object( $this->mConn ) ) {
424 return "Cannot return last error, no db connection";
426 $e = $this->mConn->errorInfo();
428 return isset( $e[2] ) ? $e[2] : '';
432 * @return string
434 function lastErrno() {
435 if ( !is_object( $this->mConn ) ) {
436 return "Cannot return last error, no db connection";
437 } else {
438 $info = $this->mConn->errorInfo();
440 return $info[1];
445 * @return int
447 function affectedRows() {
448 return $this->mAffectedRows;
452 * Returns information about an index
453 * Returns false if the index does not exist
454 * - if errors are explicitly ignored, returns NULL on failure
456 * @param string $table
457 * @param string $index
458 * @param string $fname
459 * @return array
461 function indexInfo( $table, $index, $fname = __METHOD__ ) {
462 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
463 $res = $this->query( $sql, $fname );
464 if ( !$res ) {
465 return null;
467 if ( $res->numRows() == 0 ) {
468 return false;
470 $info = array();
471 foreach ( $res as $row ) {
472 $info[] = $row->name;
475 return $info;
479 * @param string $table
480 * @param string $index
481 * @param string $fname
482 * @return bool|null
484 function indexUnique( $table, $index, $fname = __METHOD__ ) {
485 $row = $this->selectRow( 'sqlite_master', '*',
486 array(
487 'type' => 'index',
488 'name' => $this->indexName( $index ),
489 ), $fname );
490 if ( !$row || !isset( $row->sql ) ) {
491 return null;
494 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
495 $indexPos = strpos( $row->sql, 'INDEX' );
496 if ( $indexPos === false ) {
497 return null;
499 $firstPart = substr( $row->sql, 0, $indexPos );
500 $options = explode( ' ', $firstPart );
502 return in_array( 'UNIQUE', $options );
506 * Filter the options used in SELECT statements
508 * @param array $options
509 * @return array
511 function makeSelectOptions( $options ) {
512 foreach ( $options as $k => $v ) {
513 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
514 $options[$k] = '';
518 return parent::makeSelectOptions( $options );
522 * @param array $options
523 * @return string
525 protected function makeUpdateOptionsArray( $options ) {
526 $options = parent::makeUpdateOptionsArray( $options );
527 $options = self::fixIgnore( $options );
529 return $options;
533 * @param array $options
534 * @return array
536 static function fixIgnore( $options ) {
537 # SQLite uses OR IGNORE not just IGNORE
538 foreach ( $options as $k => $v ) {
539 if ( $v == 'IGNORE' ) {
540 $options[$k] = 'OR IGNORE';
544 return $options;
548 * @param array $options
549 * @return string
551 function makeInsertOptions( $options ) {
552 $options = self::fixIgnore( $options );
554 return parent::makeInsertOptions( $options );
558 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
559 * @param string $table
560 * @param array $a
561 * @param string $fname
562 * @param array $options
563 * @return bool
565 function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
566 if ( !count( $a ) ) {
567 return true;
570 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
571 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
572 $ret = true;
573 foreach ( $a as $v ) {
574 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
575 $ret = false;
578 } else {
579 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
582 return $ret;
586 * @param string $table
587 * @param array $uniqueIndexes Unused
588 * @param string|array $rows
589 * @param string $fname
590 * @return bool|ResultWrapper
592 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
593 if ( !count( $rows ) ) {
594 return true;
597 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
598 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
599 $ret = true;
600 foreach ( $rows as $v ) {
601 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
602 $ret = false;
605 } else {
606 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
609 return $ret;
613 * Returns the size of a text field, or -1 for "unlimited"
614 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
616 * @param string $table
617 * @param string $field
618 * @return int
620 function textFieldSize( $table, $field ) {
621 return -1;
625 * @return bool
627 function unionSupportsOrderAndLimit() {
628 return false;
632 * @param string $sqls
633 * @param bool $all Whether to "UNION ALL" or not
634 * @return string
636 function unionQueries( $sqls, $all ) {
637 $glue = $all ? ' UNION ALL ' : ' UNION ';
639 return implode( $glue, $sqls );
643 * @return bool
645 function wasDeadlock() {
646 return $this->lastErrno() == 5; // SQLITE_BUSY
650 * @return bool
652 function wasErrorReissuable() {
653 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
657 * @return bool
659 function wasReadOnlyError() {
660 return $this->lastErrno() == 8; // SQLITE_READONLY;
664 * @return string wikitext of a link to the server software's web site
666 public function getSoftwareLink() {
667 return "[{{int:version-db-sqlite-url}} SQLite]";
671 * @return string Version information from the database
673 function getServerVersion() {
674 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
676 return $ver;
680 * @return string User-friendly database information
682 public function getServerInfo() {
683 return wfMessage( self::getFulltextSearchModule()
684 ? 'sqlite-has-fts'
685 : 'sqlite-no-fts', $this->getServerVersion() )->text();
689 * Get information about a given field
690 * Returns false if the field does not exist.
692 * @param string $table
693 * @param string $field
694 * @return SQLiteField|bool False on failure
696 function fieldInfo( $table, $field ) {
697 $tableName = $this->tableName( $table );
698 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
699 $res = $this->query( $sql, __METHOD__ );
700 foreach ( $res as $row ) {
701 if ( $row->name == $field ) {
702 return new SQLiteField( $row, $tableName );
706 return false;
709 protected function doBegin( $fname = '' ) {
710 if ( $this->mTrxLevel == 1 ) {
711 $this->commit( __METHOD__ );
713 try {
714 $this->mConn->beginTransaction();
715 } catch ( PDOException $e ) {
716 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
718 $this->mTrxLevel = 1;
721 protected function doCommit( $fname = '' ) {
722 if ( $this->mTrxLevel == 0 ) {
723 return;
725 try {
726 $this->mConn->commit();
727 } catch ( PDOException $e ) {
728 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
730 $this->mTrxLevel = 0;
733 protected function doRollback( $fname = '' ) {
734 if ( $this->mTrxLevel == 0 ) {
735 return;
737 $this->mConn->rollBack();
738 $this->mTrxLevel = 0;
742 * @param string $s
743 * @return string
745 function strencode( $s ) {
746 return substr( $this->addQuotes( $s ), 1, -1 );
750 * @param $b
751 * @return Blob
753 function encodeBlob( $b ) {
754 return new Blob( $b );
758 * @param $b Blob|string
759 * @return string
761 function decodeBlob( $b ) {
762 if ( $b instanceof Blob ) {
763 $b = $b->fetch();
766 return $b;
770 * @param Blob|string $s
771 * @return string
773 function addQuotes( $s ) {
774 if ( $s instanceof Blob ) {
775 return "x'" . bin2hex( $s->fetch() ) . "'";
776 } elseif ( is_bool( $s ) ) {
777 return (int)$s;
778 } elseif ( strpos( $s, "\0" ) !== false ) {
779 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
780 // This is a known limitation of SQLite's mprintf function which PDO should work around,
781 // but doesn't. I have reported this to php.net as bug #63419:
782 // https://bugs.php.net/bug.php?id=63419
783 // There was already a similar report for SQLite3::escapeString, bug #62361:
784 // https://bugs.php.net/bug.php?id=62361
785 return "x'" . bin2hex( $s ) . "'";
786 } else {
787 return $this->mConn->quote( $s );
792 * @return string
794 function buildLike() {
795 $params = func_get_args();
796 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
797 $params = $params[0];
800 return parent::buildLike( $params ) . "ESCAPE '\' ";
804 * @return string
806 public function getSearchEngine() {
807 return "SearchSqlite";
811 * No-op version of deadlockLoop
813 * @return mixed
815 public function deadlockLoop( /*...*/ ) {
816 $args = func_get_args();
817 $function = array_shift( $args );
819 return call_user_func_array( $function, $args );
823 * @param string $s
824 * @return string
826 protected function replaceVars( $s ) {
827 $s = parent::replaceVars( $s );
828 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
829 // CREATE TABLE hacks to allow schema file sharing with MySQL
831 // binary/varbinary column type -> blob
832 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
833 // no such thing as unsigned
834 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
835 // INT -> INTEGER
836 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
837 // floating point types -> REAL
838 $s = preg_replace(
839 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
840 'REAL',
843 // varchar -> TEXT
844 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
845 // TEXT normalization
846 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
847 // BLOB normalization
848 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
849 // BOOL -> INTEGER
850 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
851 // DATETIME -> TEXT
852 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
853 // No ENUM type
854 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
855 // binary collation type -> nothing
856 $s = preg_replace( '/\bbinary\b/i', '', $s );
857 // auto_increment -> autoincrement
858 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
859 // No explicit options
860 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
861 // AUTOINCREMENT should immedidately follow PRIMARY KEY
862 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
863 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
864 // No truncated indexes
865 $s = preg_replace( '/\(\d+\)/', '', $s );
866 // No FULLTEXT
867 $s = preg_replace( '/\bfulltext\b/i', '', $s );
868 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
869 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
870 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
873 return $s;
876 public function lock( $lockName, $method, $timeout = 5 ) {
877 global $wgSQLiteDataDir;
879 if ( !is_dir( "$wgSQLiteDataDir/locks" ) ) { // create dir as needed
880 if ( !is_writable( $wgSQLiteDataDir ) || !mkdir( "$wgSQLiteDataDir/locks" ) ) {
881 throw new DBError( "Cannot create directory \"$wgSQLiteDataDir/locks\"." );
885 return $this->lockMgr->lock( array( $lockName ), LockManager::LOCK_EX, $timeout )->isOK();
888 public function unlock( $lockName, $method ) {
889 return $this->lockMgr->unlock( array( $lockName ), LockManager::LOCK_EX )->isOK();
893 * Build a concatenation list to feed into a SQL query
895 * @param string[] $stringList
896 * @return string
898 function buildConcat( $stringList ) {
899 return '(' . implode( ') || (', $stringList ) . ')';
902 public function buildGroupConcatField(
903 $delim, $table, $field, $conds = '', $join_conds = array()
905 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
907 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
911 * @throws MWException
912 * @param string $oldName
913 * @param string $newName
914 * @param bool $temporary
915 * @param string $fname
916 * @return bool|ResultWrapper
918 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
919 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
920 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
921 $obj = $this->fetchObject( $res );
922 if ( !$obj ) {
923 throw new MWException( "Couldn't retrieve structure for table $oldName" );
925 $sql = $obj->sql;
926 $sql = preg_replace(
927 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
928 $this->addIdentifierQuotes( $newName ),
929 $sql,
932 if ( $temporary ) {
933 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
934 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
935 } else {
936 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
940 return $this->query( $sql, $fname );
944 * List all tables on the database
946 * @param string $prefix Only show tables with this prefix, e.g. mw_
947 * @param string $fname Calling function name
949 * @return array
951 function listTables( $prefix = null, $fname = __METHOD__ ) {
952 $result = $this->select(
953 'sqlite_master',
954 'name',
955 "type='table'"
958 $endArray = array();
960 foreach ( $result as $table ) {
961 $vars = get_object_vars( $table );
962 $table = array_pop( $vars );
964 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
965 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
966 $endArray[] = $table;
971 return $endArray;
973 } // end DatabaseSqlite class
976 * This class allows simple acccess to a SQLite database independently from main database settings
977 * @ingroup Database
979 class DatabaseSqliteStandalone extends DatabaseSqlite {
980 public function __construct( $fileName, $flags = 0 ) {
981 $this->mFlags = $flags;
982 $this->tablePrefix( null );
983 $this->openFile( $fileName );
988 * @ingroup Database
990 class SQLiteField implements Field {
991 private $info, $tableName;
993 function __construct( $info, $tableName ) {
994 $this->info = $info;
995 $this->tableName = $tableName;
998 function name() {
999 return $this->info->name;
1002 function tableName() {
1003 return $this->tableName;
1006 function defaultValue() {
1007 if ( is_string( $this->info->dflt_value ) ) {
1008 // Typically quoted
1009 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
1010 return str_replace( "''", "'", $this->info->dflt_value );
1014 return $this->info->dflt_value;
1018 * @return bool
1020 function isNullable() {
1021 return !$this->info->notnull;
1024 function type() {
1025 return $this->info->type;
1027 } // end SQLiteField