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