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