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