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