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