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