74bd9b7a8d4c4fe1e5490e25c955dc37ef1cfa29
[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 $dir String: Directory where database resides
148 * @param $dbName String: 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 $name String: database name to be used in queries like SELECT foo FROM dbname.table
198 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
199 * @param $fname String: calling function name
200 *
201 * @return ResultWrapper
202 */
203 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
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 = 'DatabaseSqlite::indexExists' ) {
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 = 'DatabaseSqlite::indexUnique' ) {
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' ) {
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 = 'DatabaseSqlite::insert', $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 = 'DatabaseSqlite::replace' ) {
545 if ( !count( $rows ) ) return true;
546
547 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
548 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
549 $ret = true;
550 foreach ( $rows as $v ) {
551 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
552 $ret = false;
553 }
554 }
555 } else {
556 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
557 }
558
559 return $ret;
560 }
561
562 /**
563 * Returns the size of a text field, or -1 for "unlimited"
564 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
565 *
566 * @return int
567 */
568 function textFieldSize( $table, $field ) {
569 return -1;
570 }
571
572 /**
573 * @return bool
574 */
575 function unionSupportsOrderAndLimit() {
576 return false;
577 }
578
579 /**
580 * @param $sqls
581 * @param $all
582 * @return string
583 */
584 function unionQueries( $sqls, $all ) {
585 $glue = $all ? ' UNION ALL ' : ' UNION ';
586 return implode( $glue, $sqls );
587 }
588
589 /**
590 * @return bool
591 */
592 function wasDeadlock() {
593 return $this->lastErrno() == 5; // SQLITE_BUSY
594 }
595
596 /**
597 * @return bool
598 */
599 function wasErrorReissuable() {
600 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
601 }
602
603 /**
604 * @return bool
605 */
606 function wasReadOnlyError() {
607 return $this->lastErrno() == 8; // SQLITE_READONLY;
608 }
609
610 /**
611 * @return string wikitext of a link to the server software's web site
612 */
613 public static function getSoftwareLink() {
614 return "[http://sqlite.org/ SQLite]";
615 }
616
617 /**
618 * @return string Version information from the database
619 */
620 function getServerVersion() {
621 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
622 return $ver;
623 }
624
625 /**
626 * @return string User-friendly database information
627 */
628 public function getServerInfo() {
629 return wfMessage( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() )->text();
630 }
631
632 /**
633 * Get information about a given field
634 * Returns false if the field does not exist.
635 *
636 * @param $table string
637 * @param $field string
638 * @return SQLiteField|bool False on failure
639 */
640 function fieldInfo( $table, $field ) {
641 $tableName = $this->tableName( $table );
642 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
643 $res = $this->query( $sql, __METHOD__ );
644 foreach ( $res as $row ) {
645 if ( $row->name == $field ) {
646 return new SQLiteField( $row, $tableName );
647 }
648 }
649 return false;
650 }
651
652 protected function doBegin( $fname = '' ) {
653 if ( $this->mTrxLevel == 1 ) {
654 $this->commit( __METHOD__ );
655 }
656 $this->mConn->beginTransaction();
657 $this->mTrxLevel = 1;
658 }
659
660 protected function doCommit( $fname = '' ) {
661 if ( $this->mTrxLevel == 0 ) {
662 return;
663 }
664 $this->mConn->commit();
665 $this->mTrxLevel = 0;
666 }
667
668 protected function doRollback( $fname = '' ) {
669 if ( $this->mTrxLevel == 0 ) {
670 return;
671 }
672 $this->mConn->rollBack();
673 $this->mTrxLevel = 0;
674 }
675
676 /**
677 * @param $s string
678 * @return string
679 */
680 function strencode( $s ) {
681 return substr( $this->addQuotes( $s ), 1, - 1 );
682 }
683
684 /**
685 * @param $b
686 * @return Blob
687 */
688 function encodeBlob( $b ) {
689 return new Blob( $b );
690 }
691
692 /**
693 * @param $b Blob|string
694 * @return string
695 */
696 function decodeBlob( $b ) {
697 if ( $b instanceof Blob ) {
698 $b = $b->fetch();
699 }
700 return $b;
701 }
702
703 /**
704 * @param $s Blob|string
705 * @return string
706 */
707 function addQuotes( $s ) {
708 if ( $s instanceof Blob ) {
709 return "x'" . bin2hex( $s->fetch() ) . "'";
710 } else if ( strpos( $s, "\0" ) !== false ) {
711 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
712 // This is a known limitation of SQLite's mprintf function which PDO should work around,
713 // but doesn't. I have reported this to php.net as bug #63419:
714 // https://bugs.php.net/bug.php?id=63419
715 // There was already a similar report for SQLite3::escapeString, bug #62361:
716 // https://bugs.php.net/bug.php?id=62361
717 return "x'" . bin2hex( $s ) . "'";
718 } else {
719 return $this->mConn->quote( $s );
720 }
721 }
722
723 /**
724 * @return string
725 */
726 function buildLike() {
727 $params = func_get_args();
728 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
729 $params = $params[0];
730 }
731 return parent::buildLike( $params ) . "ESCAPE '\' ";
732 }
733
734 /**
735 * @return string
736 */
737 public function getSearchEngine() {
738 return "SearchSqlite";
739 }
740
741 /**
742 * No-op version of deadlockLoop
743 * @return mixed
744 */
745 public function deadlockLoop( /*...*/ ) {
746 $args = func_get_args();
747 $function = array_shift( $args );
748 return call_user_func_array( $function, $args );
749 }
750
751 /**
752 * @param $s string
753 * @return string
754 */
755 protected function replaceVars( $s ) {
756 $s = parent::replaceVars( $s );
757 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
758 // CREATE TABLE hacks to allow schema file sharing with MySQL
759
760 // binary/varbinary column type -> blob
761 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
762 // no such thing as unsigned
763 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
764 // INT -> INTEGER
765 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
766 // floating point types -> REAL
767 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
768 // varchar -> TEXT
769 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
770 // TEXT normalization
771 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
772 // BLOB normalization
773 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
774 // BOOL -> INTEGER
775 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
776 // DATETIME -> TEXT
777 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
778 // No ENUM type
779 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
780 // binary collation type -> nothing
781 $s = preg_replace( '/\bbinary\b/i', '', $s );
782 // auto_increment -> autoincrement
783 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
784 // No explicit options
785 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
786 // AUTOINCREMENT should immedidately follow PRIMARY KEY
787 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
788 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
789 // No truncated indexes
790 $s = preg_replace( '/\(\d+\)/', '', $s );
791 // No FULLTEXT
792 $s = preg_replace( '/\bfulltext\b/i', '', $s );
793 }
794 return $s;
795 }
796
797 /**
798 * Build a concatenation list to feed into a SQL query
799 *
800 * @param $stringList array
801 *
802 * @return string
803 */
804 function buildConcat( $stringList ) {
805 return '(' . implode( ') || (', $stringList ) . ')';
806 }
807
808 /**
809 * @throws MWException
810 * @param $oldName
811 * @param $newName
812 * @param $temporary bool
813 * @param $fname string
814 * @return bool|ResultWrapper
815 */
816 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
817 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
818 $obj = $this->fetchObject( $res );
819 if ( !$obj ) {
820 throw new MWException( "Couldn't retrieve structure for table $oldName" );
821 }
822 $sql = $obj->sql;
823 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
824 if ( $temporary ) {
825 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
826 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
827 } else {
828 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
829 }
830 }
831 return $this->query( $sql, $fname );
832 }
833
834
835 /**
836 * List all tables on the database
837 *
838 * @param $prefix string Only show tables with this prefix, e.g. mw_
839 * @param $fname String: calling function name
840 *
841 * @return array
842 */
843 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
844 $result = $this->select(
845 'sqlite_master',
846 'name',
847 "type='table'"
848 );
849
850 $endArray = array();
851
852 foreach( $result as $table ) {
853 $vars = get_object_vars( $table );
854 $table = array_pop( $vars );
855
856 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
857 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
858 $endArray[] = $table;
859 }
860
861 }
862 }
863
864 return $endArray;
865 }
866
867 } // end DatabaseSqlite class
868
869 /**
870 * This class allows simple acccess to a SQLite database independently from main database settings
871 * @ingroup Database
872 */
873 class DatabaseSqliteStandalone extends DatabaseSqlite {
874 public function __construct( $fileName, $flags = 0 ) {
875 $this->mFlags = $flags;
876 $this->tablePrefix( null );
877 $this->openFile( $fileName );
878 }
879 }
880
881 /**
882 * @ingroup Database
883 */
884 class SQLiteField implements Field {
885 private $info, $tableName;
886 function __construct( $info, $tableName ) {
887 $this->info = $info;
888 $this->tableName = $tableName;
889 }
890
891 function name() {
892 return $this->info->name;
893 }
894
895 function tableName() {
896 return $this->tableName;
897 }
898
899 function defaultValue() {
900 if ( is_string( $this->info->dflt_value ) ) {
901 // Typically quoted
902 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
903 return str_replace( "''", "'", $this->info->dflt_value );
904 }
905 }
906 return $this->info->dflt_value;
907 }
908
909 /**
910 * @return bool
911 */
912 function isNullable() {
913 return !$this->info->notnull;
914 }
915
916 function type() {
917 return $this->info->type;
918 }
919
920 } // end SQLiteField