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