Merge "rdbms: update return type comments for ConnectionManager to IDatabase"
[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 PDO;
27 use PDOException;
28 use Exception;
29 use LockManager;
30 use FSLockManager;
31 use InvalidArgumentException;
32 use RuntimeException;
33 use stdClass;
34
35 /**
36 * @ingroup Database
37 */
38 class DatabaseSqlite extends Database {
39 /** @var bool Whether full text is enabled */
40 private static $fulltextEnabled = null;
41
42 /** @var string Directory */
43 protected $dbDir;
44 /** @var string File name for SQLite database file */
45 protected $dbPath;
46 /** @var string Transaction mode */
47 protected $trxMode;
48
49 /** @var int The number of rows affected as an integer */
50 protected $lastAffectedRowCount;
51 /** @var resource */
52 protected $lastResultHandle;
53
54 /** @var PDO */
55 protected $conn;
56
57 /** @var FSLockManager (hopefully on the same server as the DB) */
58 protected $lockMgr;
59
60 /** @var array List of shared database already attached to this connection */
61 private $alreadyAttached = [];
62
63 /**
64 * Additional params include:
65 * - dbDirectory : directory containing the DB and the lock file directory
66 * [defaults to $wgSQLiteDataDir]
67 * - dbFilePath : use this to force the path of the DB file
68 * - trxMode : one of (deferred, immediate, exclusive)
69 * @param array $p
70 */
71 function __construct( array $p ) {
72 if ( isset( $p['dbFilePath'] ) ) {
73 $this->dbPath = $p['dbFilePath'];
74 $lockDomain = md5( $this->dbPath );
75 // Use "X" for things like X.sqlite and ":memory:" for RAM-only DBs
76 if ( !isset( $p['dbname'] ) || !strlen( $p['dbname'] ) ) {
77 $p['dbname'] = preg_replace( '/\.sqlite\d?$/', '', basename( $this->dbPath ) );
78 }
79 } elseif ( isset( $p['dbDirectory'] ) ) {
80 $this->dbDir = $p['dbDirectory'];
81 $lockDomain = $p['dbname'];
82 } else {
83 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
84 }
85
86 $this->trxMode = isset( $p['trxMode'] ) ? strtoupper( $p['trxMode'] ) : null;
87 if ( $this->trxMode &&
88 !in_array( $this->trxMode, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
89 ) {
90 $this->trxMode = null;
91 $this->queryLogger->warning( "Invalid SQLite transaction mode provided." );
92 }
93
94 $this->lockMgr = new FSLockManager( [
95 'domain' => $lockDomain,
96 'lockDirectory' => "{$this->dbDir}/locks"
97 ] );
98
99 parent::__construct( $p );
100 }
101
102 protected static function getAttributes() {
103 return [ self::ATTR_DB_LEVEL_LOCKING => true ];
104 }
105
106 /**
107 * @param string $filename
108 * @param array $p Options map; supports:
109 * - flags : (same as __construct counterpart)
110 * - trxMode : (same as __construct counterpart)
111 * - dbDirectory : (same as __construct counterpart)
112 * @return DatabaseSqlite
113 * @since 1.25
114 */
115 public static function newStandaloneInstance( $filename, array $p = [] ) {
116 $p['dbFilePath'] = $filename;
117 $p['schema'] = null;
118 $p['tablePrefix'] = '';
119 /** @var DatabaseSqlite $db */
120 $db = Database::factory( 'sqlite', $p );
121
122 return $db;
123 }
124
125 protected function doInitConnection() {
126 if ( $this->dbPath !== null ) {
127 // Standalone .sqlite file mode.
128 $this->openFile(
129 $this->dbPath,
130 $this->connectionParams['dbname'],
131 $this->connectionParams['tablePrefix']
132 );
133 } elseif ( $this->dbDir !== null ) {
134 // Stock wiki mode using standard file names per DB
135 if ( strlen( $this->connectionParams['dbname'] ) ) {
136 $this->open(
137 $this->connectionParams['host'],
138 $this->connectionParams['user'],
139 $this->connectionParams['password'],
140 $this->connectionParams['dbname'],
141 $this->connectionParams['schema'],
142 $this->connectionParams['tablePrefix']
143 );
144 } else {
145 // Caller will manually call open() later?
146 $this->connLogger->debug( __METHOD__ . ': no database opened.' );
147 }
148 } else {
149 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
150 }
151 }
152
153 /**
154 * @return string
155 */
156 function getType() {
157 return 'sqlite';
158 }
159
160 /**
161 * @todo Check if it should be true like parent class
162 *
163 * @return bool
164 */
165 function implicitGroupby() {
166 return false;
167 }
168
169 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
170 $this->close();
171
172 if ( $schema !== null ) {
173 throw new DBExpectedError( $this, __CLASS__ . ": domain schemas are not supported." );
174 }
175
176 $fileName = self::generateFileName( $this->dbDir, $dbName );
177 if ( !is_readable( $fileName ) ) {
178 $error = "SQLite database file not readable";
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 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
187 $this->openFile( $fileName, $dbName, $tablePrefix );
188 }
189
190 /**
191 * Opens a database file
192 *
193 * @param string $fileName
194 * @param string $dbName
195 * @param string $tablePrefix
196 * @throws DBConnectionError
197 */
198 protected function openFile( $fileName, $dbName, $tablePrefix ) {
199 $this->dbPath = $fileName;
200 try {
201 $this->conn = new PDO(
202 "sqlite:$fileName",
203 '',
204 '',
205 [ PDO::ATTR_PERSISTENT => (bool)( $this->flags & self::DBO_PERSISTENT ) ]
206 );
207 $error = 'unknown error';
208 } catch ( PDOException $e ) {
209 $error = $e->getMessage();
210 }
211
212 if ( !$this->conn ) {
213 $this->connLogger->error(
214 "Error connecting to {db_server}: {error}",
215 $this->getLogContext( [ 'method' => __METHOD__, 'error' => $error ] )
216 );
217 throw new DBConnectionError( $this, $error );
218 }
219
220 try {
221 // Set error codes only, don't raise exceptions
222 $this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
223
224 $this->currentDomain = new DatabaseDomain( $dbName, null, $tablePrefix );
225
226 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY;
227 // Enforce LIKE to be case sensitive, just like MySQL
228 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__, $flags );
229 // Apply an optimizations or requirements regarding fsync() usage
230 $sync = $this->connectionVariables['synchronous'] ?? null;
231 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
232 $this->query( "PRAGMA synchronous = $sync", __METHOD__ );
233 }
234 } catch ( Exception $e ) {
235 // Connection was not fully initialized and is not safe for use
236 $this->conn = false;
237 throw $e;
238 }
239 }
240
241 /**
242 * @return string SQLite DB file path
243 * @since 1.25
244 */
245 public function getDbFilePath() {
246 return $this->dbPath;
247 }
248
249 /**
250 * Does not actually close the connection, just destroys the reference for GC to do its work
251 * @return bool
252 */
253 protected function closeConnection() {
254 $this->conn = null;
255
256 return true;
257 }
258
259 /**
260 * Generates a database file name. Explicitly public for installer.
261 * @param string $dir Directory where database resides
262 * @param string $dbName Database name
263 * @return string
264 */
265 public static function generateFileName( $dir, $dbName ) {
266 return "$dir/$dbName.sqlite";
267 }
268
269 /**
270 * Check if the searchindext table is FTS enabled.
271 * @return bool False if not enabled.
272 */
273 public function checkForEnabledSearch() {
274 if ( self::$fulltextEnabled === null ) {
275 self::$fulltextEnabled = false;
276 $table = $this->tableName( 'searchindex' );
277 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
278 if ( $res ) {
279 $row = $res->fetchRow();
280 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
281 }
282 }
283
284 return self::$fulltextEnabled;
285 }
286
287 /**
288 * Returns version of currently supported SQLite fulltext search module or false if none present.
289 * @return string
290 */
291 static function getFulltextSearchModule() {
292 static $cachedResult = null;
293 if ( $cachedResult !== null ) {
294 return $cachedResult;
295 }
296 $cachedResult = false;
297 $table = 'dummy_search_test';
298
299 $db = self::newStandaloneInstance( ':memory:' );
300 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
301 $cachedResult = 'FTS3';
302 }
303 $db->close();
304
305 return $cachedResult;
306 }
307
308 /**
309 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
310 * for details.
311 *
312 * @param string $name Database name to be used in queries like
313 * SELECT foo FROM dbname.table
314 * @param bool|string $file Database file name. If omitted, will be generated
315 * using $name and configured data directory
316 * @param string $fname Calling function name
317 * @return IResultWrapper
318 */
319 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
320 if ( !$file ) {
321 $file = self::generateFileName( $this->dbDir, $name );
322 }
323 $file = $this->addQuotes( $file );
324
325 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
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 $r = $res instanceof ResultWrapper ? $res->result : $res;
353 $this->lastAffectedRowCount = $r->rowCount();
354 $res = new ResultWrapper( $this, $r->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->result = null;
365 } else {
366 $res = null;
367 }
368 }
369
370 /**
371 * @param IResultWrapper|array $res
372 * @return stdClass|bool
373 */
374 function fetchObject( $res ) {
375 if ( $res instanceof ResultWrapper ) {
376 $r =& $res->result;
377 } else {
378 $r =& $res;
379 }
380
381 $cur = current( $r );
382 if ( is_array( $cur ) ) {
383 next( $r );
384 $obj = new stdClass;
385 foreach ( $cur as $k => $v ) {
386 if ( !is_numeric( $k ) ) {
387 $obj->$k = $v;
388 }
389 }
390
391 return $obj;
392 }
393
394 return false;
395 }
396
397 /**
398 * @param IResultWrapper|mixed $res
399 * @return array|bool
400 */
401 function fetchRow( $res ) {
402 if ( $res instanceof ResultWrapper ) {
403 $r =& $res->result;
404 } else {
405 $r =& $res;
406 }
407 $cur = current( $r );
408 if ( is_array( $cur ) ) {
409 next( $r );
410
411 return $cur;
412 }
413
414 return false;
415 }
416
417 /**
418 * The PDO::Statement class implements the array interface so count() will work
419 *
420 * @param IResultWrapper|array|false $res
421 * @return int
422 */
423 function numRows( $res ) {
424 // false does not implement Countable
425 $r = $res instanceof ResultWrapper ? $res->result : $res;
426
427 return is_array( $r ) ? count( $r ) : 0;
428 }
429
430 /**
431 * @param IResultWrapper $res
432 * @return int
433 */
434 function numFields( $res ) {
435 $r = $res instanceof ResultWrapper ? $res->result : $res;
436 if ( is_array( $r ) && count( $r ) > 0 ) {
437 // The size of the result array is twice the number of fields. (T67578)
438 return count( $r[0] ) / 2;
439 } else {
440 // If the result is empty return 0
441 return 0;
442 }
443 }
444
445 /**
446 * @param IResultWrapper $res
447 * @param int $n
448 * @return bool
449 */
450 function fieldName( $res, $n ) {
451 $r = $res instanceof ResultWrapper ? $res->result : $res;
452 if ( is_array( $r ) ) {
453 $keys = array_keys( $r[0] );
454
455 return $keys[$n];
456 }
457
458 return false;
459 }
460
461 /**
462 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
463 *
464 * @param string $name
465 * @param string $format
466 * @return string
467 */
468 function tableName( $name, $format = 'quoted' ) {
469 // table names starting with sqlite_ are reserved
470 if ( strpos( $name, 'sqlite_' ) === 0 ) {
471 return $name;
472 }
473
474 return str_replace( '"', '', parent::tableName( $name, $format ) );
475 }
476
477 /**
478 * This must be called after nextSequenceVal
479 *
480 * @return int
481 */
482 function insertId() {
483 // PDO::lastInsertId yields a string :(
484 return intval( $this->getBindingHandle()->lastInsertId() );
485 }
486
487 /**
488 * @param IResultWrapper|array $res
489 * @param int $row
490 */
491 function dataSeek( $res, $row ) {
492 if ( $res instanceof ResultWrapper ) {
493 $r =& $res->result;
494 } else {
495 $r =& $res;
496 }
497 reset( $r );
498 if ( $row > 0 ) {
499 for ( $i = 0; $i < $row; $i++ ) {
500 next( $r );
501 }
502 }
503 }
504
505 /**
506 * @return string
507 */
508 function lastError() {
509 if ( !is_object( $this->conn ) ) {
510 return "Cannot return last error, no db connection";
511 }
512 $e = $this->conn->errorInfo();
513
514 return $e[2] ?? '';
515 }
516
517 /**
518 * @return string
519 */
520 function lastErrno() {
521 if ( !is_object( $this->conn ) ) {
522 return "Cannot return last error, no db connection";
523 } else {
524 $info = $this->conn->errorInfo();
525
526 return $info[1];
527 }
528 }
529
530 /**
531 * @return int
532 */
533 protected function fetchAffectedRowCount() {
534 return $this->lastAffectedRowCount;
535 }
536
537 function tableExists( $table, $fname = __METHOD__ ) {
538 $tableRaw = $this->tableName( $table, 'raw' );
539 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
540 return true; // already known to exist
541 }
542
543 $encTable = $this->addQuotes( $tableRaw );
544 $res = $this->query(
545 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
546
547 return $res->numRows() ? true : false;
548 }
549
550 /**
551 * Returns information about an index
552 * Returns false if the index does not exist
553 * - if errors are explicitly ignored, returns NULL on failure
554 *
555 * @param string $table
556 * @param string $index
557 * @param string $fname
558 * @return array|false
559 */
560 function indexInfo( $table, $index, $fname = __METHOD__ ) {
561 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
562 $res = $this->query( $sql, $fname );
563 if ( !$res || $res->numRows() == 0 ) {
564 return false;
565 }
566 $info = [];
567 foreach ( $res as $row ) {
568 $info[] = $row->name;
569 }
570
571 return $info;
572 }
573
574 /**
575 * @param string $table
576 * @param string $index
577 * @param string $fname
578 * @return bool|null
579 */
580 function indexUnique( $table, $index, $fname = __METHOD__ ) {
581 $row = $this->selectRow( 'sqlite_master', '*',
582 [
583 'type' => 'index',
584 'name' => $this->indexName( $index ),
585 ], $fname );
586 if ( !$row || !isset( $row->sql ) ) {
587 return null;
588 }
589
590 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
591 $indexPos = strpos( $row->sql, 'INDEX' );
592 if ( $indexPos === false ) {
593 return null;
594 }
595 $firstPart = substr( $row->sql, 0, $indexPos );
596 $options = explode( ' ', $firstPart );
597
598 return in_array( 'UNIQUE', $options );
599 }
600
601 /**
602 * Filter the options used in SELECT statements
603 *
604 * @param array $options
605 * @return array
606 */
607 function makeSelectOptions( $options ) {
608 foreach ( $options as $k => $v ) {
609 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
610 $options[$k] = '';
611 }
612 }
613
614 return parent::makeSelectOptions( $options );
615 }
616
617 /**
618 * @param array $options
619 * @return array
620 */
621 protected function makeUpdateOptionsArray( $options ) {
622 $options = parent::makeUpdateOptionsArray( $options );
623 $options = self::fixIgnore( $options );
624
625 return $options;
626 }
627
628 /**
629 * @param array $options
630 * @return array
631 */
632 static function fixIgnore( $options ) {
633 # SQLite uses OR IGNORE not just IGNORE
634 foreach ( $options as $k => $v ) {
635 if ( $v == 'IGNORE' ) {
636 $options[$k] = 'OR IGNORE';
637 }
638 }
639
640 return $options;
641 }
642
643 /**
644 * @param array $options
645 * @return string
646 */
647 function makeInsertOptions( $options ) {
648 $options = self::fixIgnore( $options );
649
650 return parent::makeInsertOptions( $options );
651 }
652
653 /**
654 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
655 * @param string $table
656 * @param array $a
657 * @param string $fname
658 * @param array $options
659 * @return bool
660 */
661 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
662 if ( !count( $a ) ) {
663 return true;
664 }
665
666 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
667 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
668 $affectedRowCount = 0;
669 try {
670 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
671 foreach ( $a as $v ) {
672 parent::insert( $table, $v, "$fname/multi-row", $options );
673 $affectedRowCount += $this->affectedRows();
674 }
675 $this->endAtomic( $fname );
676 } catch ( Exception $e ) {
677 $this->cancelAtomic( $fname );
678 throw $e;
679 }
680 $this->affectedRowCount = $affectedRowCount;
681 } else {
682 parent::insert( $table, $a, "$fname/single-row", $options );
683 }
684
685 return true;
686 }
687
688 /**
689 * @param string $table
690 * @param array $uniqueIndexes Unused
691 * @param string|array $rows
692 * @param string $fname
693 */
694 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
695 if ( !count( $rows ) ) {
696 return;
697 }
698
699 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
700 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
701 $affectedRowCount = 0;
702 try {
703 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
704 foreach ( $rows as $v ) {
705 $this->nativeReplace( $table, $v, "$fname/multi-row" );
706 $affectedRowCount += $this->affectedRows();
707 }
708 $this->endAtomic( $fname );
709 } catch ( Exception $e ) {
710 $this->cancelAtomic( $fname );
711 throw $e;
712 }
713 $this->affectedRowCount = $affectedRowCount;
714 } else {
715 $this->nativeReplace( $table, $rows, "$fname/single-row" );
716 }
717 }
718
719 /**
720 * Returns the size of a text field, or -1 for "unlimited"
721 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
722 *
723 * @param string $table
724 * @param string $field
725 * @return int
726 */
727 function textFieldSize( $table, $field ) {
728 return -1;
729 }
730
731 /**
732 * @return bool
733 */
734 function unionSupportsOrderAndLimit() {
735 return false;
736 }
737
738 /**
739 * @param string[] $sqls
740 * @param bool $all Whether to "UNION ALL" or not
741 * @return string
742 */
743 function unionQueries( $sqls, $all ) {
744 $glue = $all ? ' UNION ALL ' : ' UNION ';
745
746 return implode( $glue, $sqls );
747 }
748
749 /**
750 * @return bool
751 */
752 function wasDeadlock() {
753 return $this->lastErrno() == 5; // SQLITE_BUSY
754 }
755
756 /**
757 * @return bool
758 */
759 function wasReadOnlyError() {
760 return $this->lastErrno() == 8; // SQLITE_READONLY;
761 }
762
763 public function wasConnectionError( $errno ) {
764 return $errno == 17; // SQLITE_SCHEMA;
765 }
766
767 protected function wasKnownStatementRollbackError() {
768 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
769 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
770 // https://sqlite.org/lang_createtable.html#uniqueconst
771 // https://sqlite.org/lang_conflict.html
772 return false;
773 }
774
775 /**
776 * @return string Wikitext of a link to the server software's web site
777 */
778 public function getSoftwareLink() {
779 return "[{{int:version-db-sqlite-url}} SQLite]";
780 }
781
782 /**
783 * @return string Version information from the database
784 */
785 function getServerVersion() {
786 $ver = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
787
788 return $ver;
789 }
790
791 /**
792 * Get information about a given field
793 * Returns false if the field does not exist.
794 *
795 * @param string $table
796 * @param string $field
797 * @return SQLiteField|bool False on failure
798 */
799 function fieldInfo( $table, $field ) {
800 $tableName = $this->tableName( $table );
801 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
802 $res = $this->query( $sql, __METHOD__ );
803 foreach ( $res as $row ) {
804 if ( $row->name == $field ) {
805 return new SQLiteField( $row, $tableName );
806 }
807 }
808
809 return false;
810 }
811
812 protected function doBegin( $fname = '' ) {
813 if ( $this->trxMode ) {
814 $this->query( "BEGIN {$this->trxMode}", $fname );
815 } else {
816 $this->query( 'BEGIN', $fname );
817 }
818 }
819
820 /**
821 * @param string $s
822 * @return string
823 */
824 function strencode( $s ) {
825 return substr( $this->addQuotes( $s ), 1, -1 );
826 }
827
828 /**
829 * @param string $b
830 * @return Blob
831 */
832 function encodeBlob( $b ) {
833 return new Blob( $b );
834 }
835
836 /**
837 * @param Blob|string $b
838 * @return string
839 */
840 function decodeBlob( $b ) {
841 if ( $b instanceof Blob ) {
842 $b = $b->fetch();
843 }
844
845 return $b;
846 }
847
848 /**
849 * @param string|int|null|bool|Blob $s
850 * @return string|int
851 */
852 function addQuotes( $s ) {
853 if ( $s instanceof Blob ) {
854 return "x'" . bin2hex( $s->fetch() ) . "'";
855 } elseif ( is_bool( $s ) ) {
856 return (int)$s;
857 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
858 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
859 // This is a known limitation of SQLite's mprintf function which PDO
860 // should work around, but doesn't. I have reported this to php.net as bug #63419:
861 // https://bugs.php.net/bug.php?id=63419
862 // There was already a similar report for SQLite3::escapeString, bug #62361:
863 // https://bugs.php.net/bug.php?id=62361
864 // There is an additional bug regarding sorting this data after insert
865 // on older versions of sqlite shipped with ubuntu 12.04
866 // https://phabricator.wikimedia.org/T74367
867 $this->queryLogger->debug(
868 __FUNCTION__ .
869 ': Quoting value containing null byte. ' .
870 'For consistency all binary data should have been ' .
871 'first processed with self::encodeBlob()'
872 );
873 return "x'" . bin2hex( (string)$s ) . "'";
874 } else {
875 return $this->getBindingHandle()->quote( (string)$s );
876 }
877 }
878
879 public function buildSubstring( $input, $startPosition, $length = null ) {
880 $this->assertBuildSubstringParams( $startPosition, $length );
881 $params = [ $input, $startPosition ];
882 if ( $length !== null ) {
883 $params[] = $length;
884 }
885 return 'SUBSTR(' . implode( ',', $params ) . ')';
886 }
887
888 /**
889 * @param string $field Field or column to cast
890 * @return string
891 * @since 1.28
892 */
893 public function buildStringCast( $field ) {
894 return 'CAST ( ' . $field . ' AS TEXT )';
895 }
896
897 /**
898 * No-op version of deadlockLoop
899 *
900 * @return mixed
901 */
902 public function deadlockLoop( /*...*/ ) {
903 $args = func_get_args();
904 $function = array_shift( $args );
905
906 return $function( ...$args );
907 }
908
909 /**
910 * @param string $s
911 * @return string
912 */
913 protected function replaceVars( $s ) {
914 $s = parent::replaceVars( $s );
915 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
916 // CREATE TABLE hacks to allow schema file sharing with MySQL
917
918 // binary/varbinary column type -> blob
919 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
920 // no such thing as unsigned
921 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
922 // INT -> INTEGER
923 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
924 // floating point types -> REAL
925 $s = preg_replace(
926 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
927 'REAL',
928 $s
929 );
930 // varchar -> TEXT
931 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
932 // TEXT normalization
933 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
934 // BLOB normalization
935 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
936 // BOOL -> INTEGER
937 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
938 // DATETIME -> TEXT
939 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
940 // No ENUM type
941 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
942 // binary collation type -> nothing
943 $s = preg_replace( '/\bbinary\b/i', '', $s );
944 // auto_increment -> autoincrement
945 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
946 // No explicit options
947 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
948 // AUTOINCREMENT should immedidately follow PRIMARY KEY
949 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
950 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
951 // No truncated indexes
952 $s = preg_replace( '/\(\d+\)/', '', $s );
953 // No FULLTEXT
954 $s = preg_replace( '/\bfulltext\b/i', '', $s );
955 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
956 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
957 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
958 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
959 // INSERT IGNORE --> INSERT OR IGNORE
960 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
961 }
962
963 return $s;
964 }
965
966 public function lock( $lockName, $method, $timeout = 5 ) {
967 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
968 if ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) ) {
969 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
970 }
971 }
972
973 return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
974 }
975
976 public function unlock( $lockName, $method ) {
977 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isOK();
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 );
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( "DELETE FROM $encTable WHERE name = $encName", $fname );
1126 }
1127
1128 public function databasesAreIndependent() {
1129 return true;
1130 }
1131
1132 /**
1133 * @return PDO
1134 */
1135 protected function getBindingHandle() {
1136 return parent::getBindingHandle();
1137 }
1138 }
1139
1140 /**
1141 * @deprecated since 1.29
1142 */
1143 class_alias( DatabaseSqlite::class, 'DatabaseSqlite' );