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