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