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