Merge "(bug 20189) Added 'Show/hide selected revisions' button and checkboxes to...
[lhc/web/wiklou.git] / includes / db / DatabaseSqlite.php
1 <?php
2 /**
3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @ingroup Database
23 */
24
25 /**
26 * @ingroup Database
27 */
28 class DatabaseSqlite extends DatabaseBase {
29
30 private static $fulltextEnabled = null;
31
32 var $mAffectedRows;
33 var $mLastResult;
34 var $mDatabaseFile;
35 var $mName;
36
37 /**
38 * @var PDO
39 */
40 protected $mConn;
41
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
50 */
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 );
59 }
60 }
61 }
62
63 /**
64 * @return string
65 */
66 function getType() {
67 return 'sqlite';
68 }
69
70 /**
71 * @todo: check if it should be true like parent class
72 *
73 * @return bool
74 */
75 function implicitGroupby() {
76 return false;
77 }
78
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
81 *
82 * @param $server
83 * @param $user
84 * @param $pass
85 * @param $dbName
86 *
87 * @return PDO
88 */
89 function open( $server, $user, $pass, $dbName ) {
90 global $wgSQLiteDataDir;
91
92 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
93 if ( !is_readable( $fileName ) ) {
94 $this->mConn = false;
95 throw new DBConnectionError( $this, "SQLite database not accessible" );
96 }
97 $this->openFile( $fileName );
98 return $this->mConn;
99 }
100
101 /**
102 * Opens a database file
103 *
104 * @param $fileName string
105 *
106 * @return PDO|bool SQL connection or false if failed
107 */
108 function openFile( $fileName ) {
109 $this->mDatabaseFile = $fileName;
110 try {
111 if ( $this->mFlags & DBO_PERSISTENT ) {
112 $this->mConn = new PDO( "sqlite:$fileName", '', '',
113 array( PDO::ATTR_PERSISTENT => true ) );
114 } else {
115 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
116 }
117 } catch ( PDOException $e ) {
118 $err = $e->getMessage();
119 }
120 if ( !$this->mConn ) {
121 wfDebug( "DB connection error: $err\n" );
122 throw new DBConnectionError( $this, $err );
123 }
124 $this->mOpened = !!$this->mConn;
125 # set error codes only, don't raise exceptions
126 if ( $this->mOpened ) {
127 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
128 return true;
129 }
130 }
131
132 /**
133 * Does not actually close the connection, just destroys the reference for GC to do its work
134 * @return bool
135 */
136 protected function closeConnection() {
137 $this->mConn = null;
138 return true;
139 }
140
141 /**
142 * Generates a database file name. Explicitly public for installer.
143 * @param $dir String: Directory where database resides
144 * @param $dbName String: Database name
145 * @return String
146 */
147 public static function generateFileName( $dir, $dbName ) {
148 return "$dir/$dbName.sqlite";
149 }
150
151 /**
152 * Check if the searchindext table is FTS enabled.
153 * @return bool False if not enabled.
154 */
155 function checkForEnabledSearch() {
156 if ( self::$fulltextEnabled === null ) {
157 self::$fulltextEnabled = false;
158 $table = $this->tableName( 'searchindex' );
159 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
160 if ( $res ) {
161 $row = $res->fetchRow();
162 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
163 }
164 }
165 return self::$fulltextEnabled;
166 }
167
168 /**
169 * Returns version of currently supported SQLite fulltext search module or false if none present.
170 * @return String
171 */
172 static function getFulltextSearchModule() {
173 static $cachedResult = null;
174 if ( $cachedResult !== null ) {
175 return $cachedResult;
176 }
177 $cachedResult = false;
178 $table = 'dummy_search_test';
179
180 $db = new DatabaseSqliteStandalone( ':memory:' );
181
182 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
183 $cachedResult = 'FTS3';
184 }
185 $db->close();
186 return $cachedResult;
187 }
188
189 /**
190 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
191 * for details.
192 *
193 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
194 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
195 * @param $fname String: calling function name
196 *
197 * @return ResultWrapper
198 */
199 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
200 global $wgSQLiteDataDir;
201 if ( !$file ) {
202 $file = self::generateFileName( $wgSQLiteDataDir, $name );
203 }
204 $file = $this->addQuotes( $file );
205 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
206 }
207
208 /**
209 * @see DatabaseBase::isWriteQuery()
210 *
211 * @param $sql string
212 *
213 * @return bool
214 */
215 function isWriteQuery( $sql ) {
216 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
217 }
218
219 /**
220 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
221 *
222 * @param $sql string
223 *
224 * @return ResultWrapper
225 */
226 protected function doQuery( $sql ) {
227 $res = $this->mConn->query( $sql );
228 if ( $res === false ) {
229 return false;
230 } else {
231 $r = $res instanceof ResultWrapper ? $res->result : $res;
232 $this->mAffectedRows = $r->rowCount();
233 $res = new ResultWrapper( $this, $r->fetchAll() );
234 }
235 return $res;
236 }
237
238 /**
239 * @param $res ResultWrapper
240 */
241 function freeResult( $res ) {
242 if ( $res instanceof ResultWrapper ) {
243 $res->result = null;
244 } else {
245 $res = null;
246 }
247 }
248
249 /**
250 * @param $res ResultWrapper
251 * @return
252 */
253 function fetchObject( $res ) {
254 if ( $res instanceof ResultWrapper ) {
255 $r =& $res->result;
256 } else {
257 $r =& $res;
258 }
259
260 $cur = current( $r );
261 if ( is_array( $cur ) ) {
262 next( $r );
263 $obj = new stdClass;
264 foreach ( $cur as $k => $v ) {
265 if ( !is_numeric( $k ) ) {
266 $obj->$k = $v;
267 }
268 }
269
270 return $obj;
271 }
272 return false;
273 }
274
275 /**
276 * @param $res ResultWrapper
277 * @return bool|mixed
278 */
279 function fetchRow( $res ) {
280 if ( $res instanceof ResultWrapper ) {
281 $r =& $res->result;
282 } else {
283 $r =& $res;
284 }
285 $cur = current( $r );
286 if ( is_array( $cur ) ) {
287 next( $r );
288 return $cur;
289 }
290 return false;
291 }
292
293 /**
294 * The PDO::Statement class implements the array interface so count() will work
295 *
296 * @param $res ResultWrapper
297 *
298 * @return int
299 */
300 function numRows( $res ) {
301 $r = $res instanceof ResultWrapper ? $res->result : $res;
302 return count( $r );
303 }
304
305 /**
306 * @param $res ResultWrapper
307 * @return int
308 */
309 function numFields( $res ) {
310 $r = $res instanceof ResultWrapper ? $res->result : $res;
311 return is_array( $r ) ? count( $r[0] ) : 0;
312 }
313
314 /**
315 * @param $res ResultWrapper
316 * @param $n
317 * @return bool
318 */
319 function fieldName( $res, $n ) {
320 $r = $res instanceof ResultWrapper ? $res->result : $res;
321 if ( is_array( $r ) ) {
322 $keys = array_keys( $r[0] );
323 return $keys[$n];
324 }
325 return false;
326 }
327
328 /**
329 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
330 *
331 * @param $name
332 * @param $format String
333 * @return string
334 */
335 function tableName( $name, $format = 'quoted' ) {
336 // table names starting with sqlite_ are reserved
337 if ( strpos( $name, 'sqlite_' ) === 0 ) {
338 return $name;
339 }
340 return str_replace( '"', '', parent::tableName( $name, $format ) );
341 }
342
343 /**
344 * Index names have DB scope
345 *
346 * @param $index string
347 *
348 * @return string
349 */
350 function indexName( $index ) {
351 return $index;
352 }
353
354 /**
355 * This must be called after nextSequenceVal
356 *
357 * @return int
358 */
359 function insertId() {
360 // PDO::lastInsertId yields a string :(
361 return intval( $this->mConn->lastInsertId() );
362 }
363
364 /**
365 * @param $res ResultWrapper
366 * @param $row
367 */
368 function dataSeek( $res, $row ) {
369 if ( $res instanceof ResultWrapper ) {
370 $r =& $res->result;
371 } else {
372 $r =& $res;
373 }
374 reset( $r );
375 if ( $row > 0 ) {
376 for ( $i = 0; $i < $row; $i++ ) {
377 next( $r );
378 }
379 }
380 }
381
382 /**
383 * @return string
384 */
385 function lastError() {
386 if ( !is_object( $this->mConn ) ) {
387 return "Cannot return last error, no db connection";
388 }
389 $e = $this->mConn->errorInfo();
390 return isset( $e[2] ) ? $e[2] : '';
391 }
392
393 /**
394 * @return string
395 */
396 function lastErrno() {
397 if ( !is_object( $this->mConn ) ) {
398 return "Cannot return last error, no db connection";
399 } else {
400 $info = $this->mConn->errorInfo();
401 return $info[1];
402 }
403 }
404
405 /**
406 * @return int
407 */
408 function affectedRows() {
409 return $this->mAffectedRows;
410 }
411
412 /**
413 * Returns information about an index
414 * Returns false if the index does not exist
415 * - if errors are explicitly ignored, returns NULL on failure
416 *
417 * @return array
418 */
419 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
420 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
421 $res = $this->query( $sql, $fname );
422 if ( !$res ) {
423 return null;
424 }
425 if ( $res->numRows() == 0 ) {
426 return false;
427 }
428 $info = array();
429 foreach ( $res as $row ) {
430 $info[] = $row->name;
431 }
432 return $info;
433 }
434
435 /**
436 * @param $table
437 * @param $index
438 * @param $fname string
439 * @return bool|null
440 */
441 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
442 $row = $this->selectRow( 'sqlite_master', '*',
443 array(
444 'type' => 'index',
445 'name' => $this->indexName( $index ),
446 ), $fname );
447 if ( !$row || !isset( $row->sql ) ) {
448 return null;
449 }
450
451 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
452 $indexPos = strpos( $row->sql, 'INDEX' );
453 if ( $indexPos === false ) {
454 return null;
455 }
456 $firstPart = substr( $row->sql, 0, $indexPos );
457 $options = explode( ' ', $firstPart );
458 return in_array( 'UNIQUE', $options );
459 }
460
461 /**
462 * Filter the options used in SELECT statements
463 *
464 * @param $options array
465 *
466 * @return array
467 */
468 function makeSelectOptions( $options ) {
469 foreach ( $options as $k => $v ) {
470 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
471 $options[$k] = '';
472 }
473 }
474 return parent::makeSelectOptions( $options );
475 }
476
477 /**
478 * @param $options array
479 * @return string
480 */
481 function makeUpdateOptions( $options ) {
482 $options = self::fixIgnore( $options );
483 return parent::makeUpdateOptions( $options );
484 }
485
486 /**
487 * @param $options array
488 * @return array
489 */
490 static function fixIgnore( $options ) {
491 # SQLite uses OR IGNORE not just IGNORE
492 foreach ( $options as $k => $v ) {
493 if ( $v == 'IGNORE' ) {
494 $options[$k] = 'OR IGNORE';
495 }
496 }
497 return $options;
498 }
499
500 /**
501 * @param $options array
502 * @return string
503 */
504 function makeInsertOptions( $options ) {
505 $options = self::fixIgnore( $options );
506 return parent::makeInsertOptions( $options );
507 }
508
509 /**
510 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
511 * @return bool
512 */
513 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
514 if ( !count( $a ) ) {
515 return true;
516 }
517
518 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
519 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
520 $ret = true;
521 foreach ( $a as $v ) {
522 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
523 $ret = false;
524 }
525 }
526 } else {
527 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
528 }
529
530 return $ret;
531 }
532
533 /**
534 * @param $table
535 * @param $uniqueIndexes
536 * @param $rows
537 * @param $fname string
538 * @return bool|ResultWrapper
539 */
540 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
541 if ( !count( $rows ) ) return true;
542
543 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
544 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
545 $ret = true;
546 foreach ( $rows as $v ) {
547 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
548 $ret = false;
549 }
550 }
551 } else {
552 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
553 }
554
555 return $ret;
556 }
557
558 /**
559 * Returns the size of a text field, or -1 for "unlimited"
560 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
561 *
562 * @return int
563 */
564 function textFieldSize( $table, $field ) {
565 return -1;
566 }
567
568 /**
569 * @return bool
570 */
571 function unionSupportsOrderAndLimit() {
572 return false;
573 }
574
575 /**
576 * @param $sqls
577 * @param $all
578 * @return string
579 */
580 function unionQueries( $sqls, $all ) {
581 $glue = $all ? ' UNION ALL ' : ' UNION ';
582 return implode( $glue, $sqls );
583 }
584
585 /**
586 * @return bool
587 */
588 function wasDeadlock() {
589 return $this->lastErrno() == 5; // SQLITE_BUSY
590 }
591
592 /**
593 * @return bool
594 */
595 function wasErrorReissuable() {
596 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
597 }
598
599 /**
600 * @return bool
601 */
602 function wasReadOnlyError() {
603 return $this->lastErrno() == 8; // SQLITE_READONLY;
604 }
605
606 /**
607 * @return string wikitext of a link to the server software's web site
608 */
609 public static function getSoftwareLink() {
610 return "[http://sqlite.org/ SQLite]";
611 }
612
613 /**
614 * @return string Version information from the database
615 */
616 function getServerVersion() {
617 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
618 return $ver;
619 }
620
621 /**
622 * @return string User-friendly database information
623 */
624 public function getServerInfo() {
625 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
626 }
627
628 /**
629 * Get information about a given field
630 * Returns false if the field does not exist.
631 *
632 * @param $table string
633 * @param $field string
634 * @return SQLiteField|bool False on failure
635 */
636 function fieldInfo( $table, $field ) {
637 $tableName = $this->tableName( $table );
638 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
639 $res = $this->query( $sql, __METHOD__ );
640 foreach ( $res as $row ) {
641 if ( $row->name == $field ) {
642 return new SQLiteField( $row, $tableName );
643 }
644 }
645 return false;
646 }
647
648 function begin( $fname = '' ) {
649 if ( $this->mTrxLevel == 1 ) {
650 $this->commit( __METHOD__ );
651 }
652 $this->mConn->beginTransaction();
653 $this->mTrxLevel = 1;
654 }
655
656 function commit( $fname = '' ) {
657 if ( $this->mTrxLevel == 0 ) {
658 return;
659 }
660 $this->mConn->commit();
661 $this->mTrxLevel = 0;
662 }
663
664 function rollback( $fname = '' ) {
665 if ( $this->mTrxLevel == 0 ) {
666 return;
667 }
668 $this->mConn->rollBack();
669 $this->mTrxLevel = 0;
670 }
671
672 /**
673 * @param $sql
674 * @param $num
675 * @return string
676 */
677 function limitResultForUpdate( $sql, $num ) {
678 return $this->limitResult( $sql, $num );
679 }
680
681 /**
682 * @param $s string
683 * @return string
684 */
685 function strencode( $s ) {
686 return substr( $this->addQuotes( $s ), 1, - 1 );
687 }
688
689 /**
690 * @param $b
691 * @return Blob
692 */
693 function encodeBlob( $b ) {
694 return new Blob( $b );
695 }
696
697 /**
698 * @param $b Blob|string
699 * @return string
700 */
701 function decodeBlob( $b ) {
702 if ( $b instanceof Blob ) {
703 $b = $b->fetch();
704 }
705 return $b;
706 }
707
708 /**
709 * @param $s Blob|string
710 * @return string
711 */
712 function addQuotes( $s ) {
713 if ( $s instanceof Blob ) {
714 return "x'" . bin2hex( $s->fetch() ) . "'";
715 } else {
716 return $this->mConn->quote( $s );
717 }
718 }
719
720 /**
721 * @return string
722 */
723 function buildLike() {
724 $params = func_get_args();
725 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
726 $params = $params[0];
727 }
728 return parent::buildLike( $params ) . "ESCAPE '\' ";
729 }
730
731 /**
732 * @return string
733 */
734 public function getSearchEngine() {
735 return "SearchSqlite";
736 }
737
738 /**
739 * No-op version of deadlockLoop
740 * @return mixed
741 */
742 public function deadlockLoop( /*...*/ ) {
743 $args = func_get_args();
744 $function = array_shift( $args );
745 return call_user_func_array( $function, $args );
746 }
747
748 /**
749 * @param $s string
750 * @return string
751 */
752 protected function replaceVars( $s ) {
753 $s = parent::replaceVars( $s );
754 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
755 // CREATE TABLE hacks to allow schema file sharing with MySQL
756
757 // binary/varbinary column type -> blob
758 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
759 // no such thing as unsigned
760 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
761 // INT -> INTEGER
762 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
763 // floating point types -> REAL
764 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
765 // varchar -> TEXT
766 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
767 // TEXT normalization
768 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
769 // BLOB normalization
770 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
771 // BOOL -> INTEGER
772 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
773 // DATETIME -> TEXT
774 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
775 // No ENUM type
776 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
777 // binary collation type -> nothing
778 $s = preg_replace( '/\bbinary\b/i', '', $s );
779 // auto_increment -> autoincrement
780 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
781 // No explicit options
782 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
783 // AUTOINCREMENT should immedidately follow PRIMARY KEY
784 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
785 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
786 // No truncated indexes
787 $s = preg_replace( '/\(\d+\)/', '', $s );
788 // No FULLTEXT
789 $s = preg_replace( '/\bfulltext\b/i', '', $s );
790 }
791 return $s;
792 }
793
794 /**
795 * Build a concatenation list to feed into a SQL query
796 *
797 * @param $stringList array
798 *
799 * @return string
800 */
801 function buildConcat( $stringList ) {
802 return '(' . implode( ') || (', $stringList ) . ')';
803 }
804
805 /**
806 * @throws MWException
807 * @param $oldName
808 * @param $newName
809 * @param $temporary bool
810 * @param $fname string
811 * @return bool|ResultWrapper
812 */
813 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
814 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
815 $obj = $this->fetchObject( $res );
816 if ( !$obj ) {
817 throw new MWException( "Couldn't retrieve structure for table $oldName" );
818 }
819 $sql = $obj->sql;
820 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
821 if ( $temporary ) {
822 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
823 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
824 } else {
825 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
826 }
827 }
828 return $this->query( $sql, $fname );
829 }
830
831
832 /**
833 * List all tables on the database
834 *
835 * @param $prefix string Only show tables with this prefix, e.g. mw_
836 * @param $fname String: calling function name
837 *
838 * @return array
839 */
840 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
841 $result = $this->select(
842 'sqlite_master',
843 'name',
844 "type='table'"
845 );
846
847 $endArray = array();
848
849 foreach( $result as $table ) {
850 $vars = get_object_vars($table);
851 $table = array_pop( $vars );
852
853 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
854 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
855 $endArray[] = $table;
856 }
857
858 }
859 }
860
861 return $endArray;
862 }
863
864 } // end DatabaseSqlite class
865
866 /**
867 * This class allows simple acccess to a SQLite database independently from main database settings
868 * @ingroup Database
869 */
870 class DatabaseSqliteStandalone extends DatabaseSqlite {
871 public function __construct( $fileName, $flags = 0 ) {
872 $this->mFlags = $flags;
873 $this->tablePrefix( null );
874 $this->openFile( $fileName );
875 }
876 }
877
878 /**
879 * @ingroup Database
880 */
881 class SQLiteField implements Field {
882 private $info, $tableName;
883 function __construct( $info, $tableName ) {
884 $this->info = $info;
885 $this->tableName = $tableName;
886 }
887
888 function name() {
889 return $this->info->name;
890 }
891
892 function tableName() {
893 return $this->tableName;
894 }
895
896 function defaultValue() {
897 if ( is_string( $this->info->dflt_value ) ) {
898 // Typically quoted
899 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
900 return str_replace( "''", "'", $this->info->dflt_value );
901 }
902 }
903 return $this->info->dflt_value;
904 }
905
906 /**
907 * @return bool
908 */
909 function isNullable() {
910 return !$this->info->notnull;
911 }
912
913 function type() {
914 return $this->info->type;
915 }
916
917 } // end SQLiteField