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