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