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