Merge "Revert "Setting up a way to have uploading by URL, but not on Special:Upload""
[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 wfMessage( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() )->text();
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 protected function doBegin( $fname = '' ) {
649 if ( $this->mTrxLevel == 1 ) {
650 $this->commit( __METHOD__ );
651 }
652 $this->mConn->beginTransaction();
653 $this->mTrxLevel = 1;
654 }
655
656 protected function doCommit( $fname = '' ) {
657 if ( $this->mTrxLevel == 0 ) {
658 return;
659 }
660 $this->mConn->commit();
661 $this->mTrxLevel = 0;
662 }
663
664 protected function doRollback( $fname = '' ) {
665 if ( $this->mTrxLevel == 0 ) {
666 return;
667 }
668 $this->mConn->rollBack();
669 $this->mTrxLevel = 0;
670 }
671
672 /**
673 * @param $s string
674 * @return string
675 */
676 function strencode( $s ) {
677 return substr( $this->addQuotes( $s ), 1, - 1 );
678 }
679
680 /**
681 * @param $b
682 * @return Blob
683 */
684 function encodeBlob( $b ) {
685 return new Blob( $b );
686 }
687
688 /**
689 * @param $b Blob|string
690 * @return string
691 */
692 function decodeBlob( $b ) {
693 if ( $b instanceof Blob ) {
694 $b = $b->fetch();
695 }
696 return $b;
697 }
698
699 /**
700 * @param $s Blob|string
701 * @return string
702 */
703 function addQuotes( $s ) {
704 if ( $s instanceof Blob ) {
705 return "x'" . bin2hex( $s->fetch() ) . "'";
706 } else {
707 return $this->mConn->quote( $s );
708 }
709 }
710
711 /**
712 * @return string
713 */
714 function buildLike() {
715 $params = func_get_args();
716 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
717 $params = $params[0];
718 }
719 return parent::buildLike( $params ) . "ESCAPE '\' ";
720 }
721
722 /**
723 * @return string
724 */
725 public function getSearchEngine() {
726 return "SearchSqlite";
727 }
728
729 /**
730 * No-op version of deadlockLoop
731 * @return mixed
732 */
733 public function deadlockLoop( /*...*/ ) {
734 $args = func_get_args();
735 $function = array_shift( $args );
736 return call_user_func_array( $function, $args );
737 }
738
739 /**
740 * @param $s string
741 * @return string
742 */
743 protected function replaceVars( $s ) {
744 $s = parent::replaceVars( $s );
745 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
746 // CREATE TABLE hacks to allow schema file sharing with MySQL
747
748 // binary/varbinary column type -> blob
749 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
750 // no such thing as unsigned
751 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
752 // INT -> INTEGER
753 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
754 // floating point types -> REAL
755 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
756 // varchar -> TEXT
757 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
758 // TEXT normalization
759 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
760 // BLOB normalization
761 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
762 // BOOL -> INTEGER
763 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
764 // DATETIME -> TEXT
765 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
766 // No ENUM type
767 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
768 // binary collation type -> nothing
769 $s = preg_replace( '/\bbinary\b/i', '', $s );
770 // auto_increment -> autoincrement
771 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
772 // No explicit options
773 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
774 // AUTOINCREMENT should immedidately follow PRIMARY KEY
775 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
776 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
777 // No truncated indexes
778 $s = preg_replace( '/\(\d+\)/', '', $s );
779 // No FULLTEXT
780 $s = preg_replace( '/\bfulltext\b/i', '', $s );
781 }
782 return $s;
783 }
784
785 /**
786 * Build a concatenation list to feed into a SQL query
787 *
788 * @param $stringList array
789 *
790 * @return string
791 */
792 function buildConcat( $stringList ) {
793 return '(' . implode( ') || (', $stringList ) . ')';
794 }
795
796 /**
797 * @throws MWException
798 * @param $oldName
799 * @param $newName
800 * @param $temporary bool
801 * @param $fname string
802 * @return bool|ResultWrapper
803 */
804 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
805 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
806 $obj = $this->fetchObject( $res );
807 if ( !$obj ) {
808 throw new MWException( "Couldn't retrieve structure for table $oldName" );
809 }
810 $sql = $obj->sql;
811 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
812 if ( $temporary ) {
813 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
814 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
815 } else {
816 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
817 }
818 }
819 return $this->query( $sql, $fname );
820 }
821
822
823 /**
824 * List all tables on the database
825 *
826 * @param $prefix string Only show tables with this prefix, e.g. mw_
827 * @param $fname String: calling function name
828 *
829 * @return array
830 */
831 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
832 $result = $this->select(
833 'sqlite_master',
834 'name',
835 "type='table'"
836 );
837
838 $endArray = array();
839
840 foreach( $result as $table ) {
841 $vars = get_object_vars($table);
842 $table = array_pop( $vars );
843
844 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
845 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
846 $endArray[] = $table;
847 }
848
849 }
850 }
851
852 return $endArray;
853 }
854
855 } // end DatabaseSqlite class
856
857 /**
858 * This class allows simple acccess to a SQLite database independently from main database settings
859 * @ingroup Database
860 */
861 class DatabaseSqliteStandalone extends DatabaseSqlite {
862 public function __construct( $fileName, $flags = 0 ) {
863 $this->mFlags = $flags;
864 $this->tablePrefix( null );
865 $this->openFile( $fileName );
866 }
867 }
868
869 /**
870 * @ingroup Database
871 */
872 class SQLiteField implements Field {
873 private $info, $tableName;
874 function __construct( $info, $tableName ) {
875 $this->info = $info;
876 $this->tableName = $tableName;
877 }
878
879 function name() {
880 return $this->info->name;
881 }
882
883 function tableName() {
884 return $this->tableName;
885 }
886
887 function defaultValue() {
888 if ( is_string( $this->info->dflt_value ) ) {
889 // Typically quoted
890 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
891 return str_replace( "''", "'", $this->info->dflt_value );
892 }
893 }
894 return $this->info->dflt_value;
895 }
896
897 /**
898 * @return bool
899 */
900 function isNullable() {
901 return !$this->info->notnull;
902 }
903
904 function type() {
905 return $this->info->type;
906 }
907
908 } // end SQLiteField