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