Merge "revision: rename various $wikiId fields/parameters to $dbDomain"
[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 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
177 $this->openFile( self::generateFileName( $this->dbDir, $dbName ), $dbName, $tablePrefix );
178 }
179
180 /**
181 * Opens a database file
182 *
183 * @param string $fileName
184 * @param string $dbName
185 * @param string $tablePrefix
186 * @throws DBConnectionError
187 */
188 protected function openFile( $fileName, $dbName, $tablePrefix ) {
189 if ( !$this->hasMemoryPath() && !is_readable( $fileName ) ) {
190 $error = "SQLite database file not readable";
191 $this->connLogger->error(
192 "Error connecting to {db_server}: {error}",
193 $this->getLogContext( [ 'method' => __METHOD__, 'error' => $error ] )
194 );
195 throw new DBConnectionError( $this, $error );
196 }
197
198 $this->dbPath = $fileName;
199 try {
200 $this->conn = new PDO(
201 "sqlite:$fileName",
202 '',
203 '',
204 [ PDO::ATTR_PERSISTENT => (bool)( $this->flags & self::DBO_PERSISTENT ) ]
205 );
206 $error = 'unknown error';
207 } catch ( PDOException $e ) {
208 $error = $e->getMessage();
209 }
210
211 if ( !$this->conn ) {
212 $this->connLogger->error(
213 "Error connecting to {db_server}: {error}",
214 $this->getLogContext( [ 'method' => __METHOD__, 'error' => $error ] )
215 );
216 throw new DBConnectionError( $this, $error );
217 }
218
219 try {
220 // Set error codes only, don't raise exceptions
221 $this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
222
223 $this->currentDomain = new DatabaseDomain( $dbName, null, $tablePrefix );
224
225 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY;
226 // Enforce LIKE to be case sensitive, just like MySQL
227 $this->query( 'PRAGMA case_sensitive_like = 1', __METHOD__, $flags );
228 // Apply an optimizations or requirements regarding fsync() usage
229 $sync = $this->connectionVariables['synchronous'] ?? null;
230 if ( in_array( $sync, [ 'EXTRA', 'FULL', 'NORMAL', 'OFF' ], true ) ) {
231 $this->query( "PRAGMA synchronous = $sync", __METHOD__ );
232 }
233 } catch ( Exception $e ) {
234 // Connection was not fully initialized and is not safe for use
235 $this->conn = false;
236 throw $e;
237 }
238 }
239
240 /**
241 * @return string SQLite DB file path
242 * @since 1.25
243 */
244 public function getDbFilePath() {
245 return $this->dbPath;
246 }
247
248 /**
249 * Does not actually close the connection, just destroys the reference for GC to do its work
250 * @return bool
251 */
252 protected function closeConnection() {
253 $this->conn = null;
254
255 return true;
256 }
257
258 /**
259 * Generates a database file name. Explicitly public for installer.
260 * @param string $dir Directory where database resides
261 * @param string $dbName Database name
262 * @return string
263 */
264 public static function generateFileName( $dir, $dbName ) {
265 return "$dir/$dbName.sqlite";
266 }
267
268 /**
269 * Check if the searchindext table is FTS enabled.
270 * @return bool False if not enabled.
271 */
272 public function checkForEnabledSearch() {
273 if ( self::$fulltextEnabled === null ) {
274 self::$fulltextEnabled = false;
275 $table = $this->tableName( 'searchindex' );
276 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
277 if ( $res ) {
278 $row = $res->fetchRow();
279 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
280 }
281 }
282
283 return self::$fulltextEnabled;
284 }
285
286 /**
287 * Returns version of currently supported SQLite fulltext search module or false if none present.
288 * @return string
289 */
290 static function getFulltextSearchModule() {
291 static $cachedResult = null;
292 if ( $cachedResult !== null ) {
293 return $cachedResult;
294 }
295 $cachedResult = false;
296 $table = 'dummy_search_test';
297
298 $db = self::newStandaloneInstance( ':memory:' );
299 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
300 $cachedResult = 'FTS3';
301 }
302 $db->close();
303
304 return $cachedResult;
305 }
306
307 /**
308 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
309 * for details.
310 *
311 * @param string $name Database name to be used in queries like
312 * SELECT foo FROM dbname.table
313 * @param bool|string $file Database file name. If omitted, will be generated
314 * using $name and configured data directory
315 * @param string $fname Calling function name
316 * @return IResultWrapper
317 */
318 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
319 if ( !$file ) {
320 $file = self::generateFileName( $this->dbDir, $name );
321 }
322 $file = $this->addQuotes( $file );
323
324 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
325 }
326
327 protected function isWriteQuery( $sql ) {
328 return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
329 }
330
331 protected function isTransactableQuery( $sql ) {
332 return parent::isTransactableQuery( $sql ) && !in_array(
333 $this->getQueryVerb( $sql ),
334 [ 'ATTACH', 'PRAGMA' ],
335 true
336 );
337 }
338
339 /**
340 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
341 *
342 * @param string $sql
343 * @return bool|IResultWrapper
344 */
345 protected function doQuery( $sql ) {
346 $res = $this->getBindingHandle()->query( $sql );
347 if ( $res === false ) {
348 return false;
349 }
350
351 $r = $res instanceof ResultWrapper ? $res->result : $res;
352 $this->lastAffectedRowCount = $r->rowCount();
353 $res = new ResultWrapper( $this, $r->fetchAll() );
354
355 return $res;
356 }
357
358 /**
359 * @param IResultWrapper|mixed $res
360 */
361 function freeResult( $res ) {
362 if ( $res instanceof ResultWrapper ) {
363 $res->result = null;
364 } else {
365 $res = null;
366 }
367 }
368
369 /**
370 * @param IResultWrapper|array $res
371 * @return stdClass|bool
372 */
373 function fetchObject( $res ) {
374 if ( $res instanceof ResultWrapper ) {
375 $r =& $res->result;
376 } else {
377 $r =& $res;
378 }
379
380 $cur = current( $r );
381 if ( is_array( $cur ) ) {
382 next( $r );
383 $obj = new stdClass;
384 foreach ( $cur as $k => $v ) {
385 if ( !is_numeric( $k ) ) {
386 $obj->$k = $v;
387 }
388 }
389
390 return $obj;
391 }
392
393 return false;
394 }
395
396 /**
397 * @param IResultWrapper|mixed $res
398 * @return array|bool
399 */
400 function fetchRow( $res ) {
401 if ( $res instanceof ResultWrapper ) {
402 $r =& $res->result;
403 } else {
404 $r =& $res;
405 }
406 $cur = current( $r );
407 if ( is_array( $cur ) ) {
408 next( $r );
409
410 return $cur;
411 }
412
413 return false;
414 }
415
416 /**
417 * The PDO::Statement class implements the array interface so count() will work
418 *
419 * @param IResultWrapper|array|false $res
420 * @return int
421 */
422 function numRows( $res ) {
423 // false does not implement Countable
424 $r = $res instanceof ResultWrapper ? $res->result : $res;
425
426 return is_array( $r ) ? count( $r ) : 0;
427 }
428
429 /**
430 * @param IResultWrapper $res
431 * @return int
432 */
433 function numFields( $res ) {
434 $r = $res instanceof ResultWrapper ? $res->result : $res;
435 if ( is_array( $r ) && count( $r ) > 0 ) {
436 // The size of the result array is twice the number of fields. (T67578)
437 return count( $r[0] ) / 2;
438 } else {
439 // If the result is empty return 0
440 return 0;
441 }
442 }
443
444 /**
445 * @param IResultWrapper $res
446 * @param int $n
447 * @return bool
448 */
449 function fieldName( $res, $n ) {
450 $r = $res instanceof ResultWrapper ? $res->result : $res;
451 if ( is_array( $r ) ) {
452 $keys = array_keys( $r[0] );
453
454 return $keys[$n];
455 }
456
457 return false;
458 }
459
460 /**
461 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
462 *
463 * @param string $name
464 * @param string $format
465 * @return string
466 */
467 function tableName( $name, $format = 'quoted' ) {
468 // table names starting with sqlite_ are reserved
469 if ( strpos( $name, 'sqlite_' ) === 0 ) {
470 return $name;
471 }
472
473 return str_replace( '"', '', parent::tableName( $name, $format ) );
474 }
475
476 /**
477 * This must be called after nextSequenceVal
478 *
479 * @return int
480 */
481 function insertId() {
482 // PDO::lastInsertId yields a string :(
483 return intval( $this->getBindingHandle()->lastInsertId() );
484 }
485
486 /**
487 * @param IResultWrapper|array $res
488 * @param int $row
489 */
490 function dataSeek( $res, $row ) {
491 if ( $res instanceof ResultWrapper ) {
492 $r =& $res->result;
493 } else {
494 $r =& $res;
495 }
496 reset( $r );
497 if ( $row > 0 ) {
498 for ( $i = 0; $i < $row; $i++ ) {
499 next( $r );
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 return ( !$this->hasMemoryPath() && !is_writable( $this->dbPath ) );
776 }
777
778 /**
779 * @return bool
780 */
781 private function hasMemoryPath() {
782 return ( strpos( $this->dbPath, ':memory:' ) === 0 );
783 }
784
785 /**
786 * @return string Wikitext of a link to the server software's web site
787 */
788 public function getSoftwareLink() {
789 return "[{{int:version-db-sqlite-url}} SQLite]";
790 }
791
792 /**
793 * @return string Version information from the database
794 */
795 function getServerVersion() {
796 $ver = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
797
798 return $ver;
799 }
800
801 /**
802 * Get information about a given field
803 * Returns false if the field does not exist.
804 *
805 * @param string $table
806 * @param string $field
807 * @return SQLiteField|bool False on failure
808 */
809 function fieldInfo( $table, $field ) {
810 $tableName = $this->tableName( $table );
811 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
812 $res = $this->query( $sql, __METHOD__ );
813 foreach ( $res as $row ) {
814 if ( $row->name == $field ) {
815 return new SQLiteField( $row, $tableName );
816 }
817 }
818
819 return false;
820 }
821
822 protected function doBegin( $fname = '' ) {
823 if ( $this->trxMode ) {
824 $this->query( "BEGIN {$this->trxMode}", $fname );
825 } else {
826 $this->query( 'BEGIN', $fname );
827 }
828 }
829
830 /**
831 * @param string $s
832 * @return string
833 */
834 function strencode( $s ) {
835 return substr( $this->addQuotes( $s ), 1, -1 );
836 }
837
838 /**
839 * @param string $b
840 * @return Blob
841 */
842 function encodeBlob( $b ) {
843 return new Blob( $b );
844 }
845
846 /**
847 * @param Blob|string $b
848 * @return string
849 */
850 function decodeBlob( $b ) {
851 if ( $b instanceof Blob ) {
852 $b = $b->fetch();
853 }
854
855 return $b;
856 }
857
858 /**
859 * @param string|int|null|bool|Blob $s
860 * @return string|int
861 */
862 function addQuotes( $s ) {
863 if ( $s instanceof Blob ) {
864 return "x'" . bin2hex( $s->fetch() ) . "'";
865 } elseif ( is_bool( $s ) ) {
866 return (int)$s;
867 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
868 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
869 // This is a known limitation of SQLite's mprintf function which PDO
870 // should work around, but doesn't. I have reported this to php.net as bug #63419:
871 // https://bugs.php.net/bug.php?id=63419
872 // There was already a similar report for SQLite3::escapeString, bug #62361:
873 // https://bugs.php.net/bug.php?id=62361
874 // There is an additional bug regarding sorting this data after insert
875 // on older versions of sqlite shipped with ubuntu 12.04
876 // https://phabricator.wikimedia.org/T74367
877 $this->queryLogger->debug(
878 __FUNCTION__ .
879 ': Quoting value containing null byte. ' .
880 'For consistency all binary data should have been ' .
881 'first processed with self::encodeBlob()'
882 );
883 return "x'" . bin2hex( (string)$s ) . "'";
884 } else {
885 return $this->getBindingHandle()->quote( (string)$s );
886 }
887 }
888
889 public function buildSubstring( $input, $startPosition, $length = null ) {
890 $this->assertBuildSubstringParams( $startPosition, $length );
891 $params = [ $input, $startPosition ];
892 if ( $length !== null ) {
893 $params[] = $length;
894 }
895 return 'SUBSTR(' . implode( ',', $params ) . ')';
896 }
897
898 /**
899 * @param string $field Field or column to cast
900 * @return string
901 * @since 1.28
902 */
903 public function buildStringCast( $field ) {
904 return 'CAST ( ' . $field . ' AS TEXT )';
905 }
906
907 /**
908 * No-op version of deadlockLoop
909 *
910 * @return mixed
911 */
912 public function deadlockLoop( /*...*/ ) {
913 $args = func_get_args();
914 $function = array_shift( $args );
915
916 return $function( ...$args );
917 }
918
919 /**
920 * @param string $s
921 * @return string
922 */
923 protected function replaceVars( $s ) {
924 $s = parent::replaceVars( $s );
925 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
926 // CREATE TABLE hacks to allow schema file sharing with MySQL
927
928 // binary/varbinary column type -> blob
929 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
930 // no such thing as unsigned
931 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
932 // INT -> INTEGER
933 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
934 // floating point types -> REAL
935 $s = preg_replace(
936 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
937 'REAL',
938 $s
939 );
940 // varchar -> TEXT
941 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
942 // TEXT normalization
943 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
944 // BLOB normalization
945 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
946 // BOOL -> INTEGER
947 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
948 // DATETIME -> TEXT
949 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
950 // No ENUM type
951 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
952 // binary collation type -> nothing
953 $s = preg_replace( '/\bbinary\b/i', '', $s );
954 // auto_increment -> autoincrement
955 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
956 // No explicit options
957 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
958 // AUTOINCREMENT should immedidately follow PRIMARY KEY
959 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
960 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
961 // No truncated indexes
962 $s = preg_replace( '/\(\d+\)/', '', $s );
963 // No FULLTEXT
964 $s = preg_replace( '/\bfulltext\b/i', '', $s );
965 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
966 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
967 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
968 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
969 // INSERT IGNORE --> INSERT OR IGNORE
970 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
971 }
972
973 return $s;
974 }
975
976 public function lock( $lockName, $method, $timeout = 5 ) {
977 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
978 if ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) ) {
979 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
980 }
981 }
982
983 return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
984 }
985
986 public function unlock( $lockName, $method ) {
987 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isOK();
988 }
989
990 /**
991 * Build a concatenation list to feed into a SQL query
992 *
993 * @param string[] $stringList
994 * @return string
995 */
996 function buildConcat( $stringList ) {
997 return '(' . implode( ') || (', $stringList ) . ')';
998 }
999
1000 public function buildGroupConcatField(
1001 $delim, $table, $field, $conds = '', $join_conds = []
1002 ) {
1003 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1004
1005 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1006 }
1007
1008 /**
1009 * @param string $oldName
1010 * @param string $newName
1011 * @param bool $temporary
1012 * @param string $fname
1013 * @return bool|IResultWrapper
1014 * @throws RuntimeException
1015 */
1016 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1017 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1018 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1019 $obj = $this->fetchObject( $res );
1020 if ( !$obj ) {
1021 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1022 }
1023 $sql = $obj->sql;
1024 $sql = preg_replace(
1025 '/(?<=\W)"?' .
1026 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1027 '"?(?=\W)/',
1028 $this->addIdentifierQuotes( $newName ),
1029 $sql,
1030 1
1031 );
1032 if ( $temporary ) {
1033 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1034 $this->queryLogger->debug(
1035 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1036 } else {
1037 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1038 }
1039 }
1040
1041 $res = $this->query( $sql, $fname, self::QUERY_PSEUDO_PERMANENT );
1042
1043 // Take over indexes
1044 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1045 foreach ( $indexList as $index ) {
1046 if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
1047 continue;
1048 }
1049
1050 if ( $index->unique ) {
1051 $sql = 'CREATE UNIQUE INDEX';
1052 } else {
1053 $sql = 'CREATE INDEX';
1054 }
1055 // Try to come up with a new index name, given indexes have database scope in SQLite
1056 $indexName = $newName . '_' . $index->name;
1057 $sql .= ' ' . $indexName . ' ON ' . $newName;
1058
1059 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
1060 $fields = [];
1061 foreach ( $indexInfo as $indexInfoRow ) {
1062 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
1063 }
1064
1065 $sql .= '(' . implode( ',', $fields ) . ')';
1066
1067 $this->query( $sql );
1068 }
1069
1070 return $res;
1071 }
1072
1073 /**
1074 * List all tables on the database
1075 *
1076 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1077 * @param string $fname Calling function name
1078 *
1079 * @return array
1080 */
1081 function listTables( $prefix = null, $fname = __METHOD__ ) {
1082 $result = $this->select(
1083 'sqlite_master',
1084 'name',
1085 "type='table'"
1086 );
1087
1088 $endArray = [];
1089
1090 foreach ( $result as $table ) {
1091 $vars = get_object_vars( $table );
1092 $table = array_pop( $vars );
1093
1094 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1095 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1096 $endArray[] = $table;
1097 }
1098 }
1099 }
1100
1101 return $endArray;
1102 }
1103
1104 /**
1105 * Override due to no CASCADE support
1106 *
1107 * @param string $tableName
1108 * @param string $fName
1109 * @return bool|IResultWrapper
1110 * @throws DBReadOnlyError
1111 */
1112 public function dropTable( $tableName, $fName = __METHOD__ ) {
1113 if ( !$this->tableExists( $tableName, $fName ) ) {
1114 return false;
1115 }
1116 $sql = "DROP TABLE " . $this->tableName( $tableName );
1117
1118 return $this->query( $sql, $fName );
1119 }
1120
1121 public function setTableAliases( array $aliases ) {
1122 parent::setTableAliases( $aliases );
1123 foreach ( $this->tableAliases as $params ) {
1124 if ( isset( $this->alreadyAttached[$params['dbname']] ) ) {
1125 continue;
1126 }
1127 $this->attachDatabase( $params['dbname'] );
1128 $this->alreadyAttached[$params['dbname']] = true;
1129 }
1130 }
1131
1132 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
1133 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1134 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1135 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1136 }
1137
1138 public function databasesAreIndependent() {
1139 return true;
1140 }
1141
1142 /**
1143 * @return PDO
1144 */
1145 protected function getBindingHandle() {
1146 return parent::getBindingHandle();
1147 }
1148 }
1149
1150 /**
1151 * @deprecated since 1.29
1152 */
1153 class_alias( DatabaseSqlite::class, 'DatabaseSqlite' );