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