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