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