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