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