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