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