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