Merge "Remove JavaScript global variable wgLoadScript"
[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 $r = $res instanceof ResultWrapper ? $res->result : $res;
359 $this->lastAffectedRowCount = $r->rowCount();
360 $res = new ResultWrapper( $this, $r->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->result = null;
371 } else {
372 $res = null;
373 }
374 }
375
376 /**
377 * @param IResultWrapper|array $res
378 * @return stdClass|bool
379 */
380 function fetchObject( $res ) {
381 if ( $res instanceof ResultWrapper ) {
382 $r =& $res->result;
383 } else {
384 $r =& $res;
385 }
386
387 $cur = current( $r );
388 if ( is_array( $cur ) ) {
389 next( $r );
390 $obj = new stdClass;
391 foreach ( $cur as $k => $v ) {
392 if ( !is_numeric( $k ) ) {
393 $obj->$k = $v;
394 }
395 }
396
397 return $obj;
398 }
399
400 return false;
401 }
402
403 /**
404 * @param IResultWrapper|mixed $res
405 * @return array|bool
406 */
407 function fetchRow( $res ) {
408 if ( $res instanceof ResultWrapper ) {
409 $r =& $res->result;
410 } else {
411 $r =& $res;
412 }
413 $cur = current( $r );
414 if ( is_array( $cur ) ) {
415 next( $r );
416
417 return $cur;
418 }
419
420 return false;
421 }
422
423 /**
424 * The PDO::Statement class implements the array interface so count() will work
425 *
426 * @param IResultWrapper|array|false $res
427 * @return int
428 */
429 function numRows( $res ) {
430 // false does not implement Countable
431 $r = $res instanceof ResultWrapper ? $res->result : $res;
432
433 return is_array( $r ) ? count( $r ) : 0;
434 }
435
436 /**
437 * @param IResultWrapper $res
438 * @return int
439 */
440 function numFields( $res ) {
441 $r = $res instanceof ResultWrapper ? $res->result : $res;
442 if ( is_array( $r ) && count( $r ) > 0 ) {
443 // The size of the result array is twice the number of fields. (T67578)
444 return count( $r[0] ) / 2;
445 } else {
446 // If the result is empty return 0
447 return 0;
448 }
449 }
450
451 /**
452 * @param IResultWrapper $res
453 * @param int $n
454 * @return bool
455 */
456 function fieldName( $res, $n ) {
457 $r = $res instanceof ResultWrapper ? $res->result : $res;
458 if ( is_array( $r ) ) {
459 $keys = array_keys( $r[0] );
460
461 return $keys[$n];
462 }
463
464 return false;
465 }
466
467 /**
468 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
469 *
470 * @param string $name
471 * @param string $format
472 * @return string
473 */
474 function tableName( $name, $format = 'quoted' ) {
475 // table names starting with sqlite_ are reserved
476 if ( strpos( $name, 'sqlite_' ) === 0 ) {
477 return $name;
478 }
479
480 return str_replace( '"', '', parent::tableName( $name, $format ) );
481 }
482
483 /**
484 * This must be called after nextSequenceVal
485 *
486 * @return int
487 */
488 function insertId() {
489 // PDO::lastInsertId yields a string :(
490 return intval( $this->getBindingHandle()->lastInsertId() );
491 }
492
493 /**
494 * @param IResultWrapper|array $res
495 * @param int $row
496 */
497 function dataSeek( $res, $row ) {
498 if ( $res instanceof ResultWrapper ) {
499 $r =& $res->result;
500 } else {
501 $r =& $res;
502 }
503 reset( $r );
504 if ( $row > 0 ) {
505 for ( $i = 0; $i < $row; $i++ ) {
506 next( $r );
507 }
508 }
509 }
510
511 /**
512 * @return string
513 */
514 function lastError() {
515 if ( !is_object( $this->conn ) ) {
516 return "Cannot return last error, no db connection";
517 }
518 $e = $this->conn->errorInfo();
519
520 return $e[2] ?? '';
521 }
522
523 /**
524 * @return string
525 */
526 function lastErrno() {
527 if ( !is_object( $this->conn ) ) {
528 return "Cannot return last error, no db connection";
529 } else {
530 $info = $this->conn->errorInfo();
531
532 return $info[1];
533 }
534 }
535
536 /**
537 * @return int
538 */
539 protected function fetchAffectedRowCount() {
540 return $this->lastAffectedRowCount;
541 }
542
543 function tableExists( $table, $fname = __METHOD__ ) {
544 $tableRaw = $this->tableName( $table, 'raw' );
545 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
546 return true; // already known to exist
547 }
548
549 $encTable = $this->addQuotes( $tableRaw );
550 $res = $this->query(
551 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
552
553 return $res->numRows() ? true : false;
554 }
555
556 /**
557 * Returns information about an index
558 * Returns false if the index does not exist
559 * - if errors are explicitly ignored, returns NULL on failure
560 *
561 * @param string $table
562 * @param string $index
563 * @param string $fname
564 * @return array|false
565 */
566 function indexInfo( $table, $index, $fname = __METHOD__ ) {
567 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
568 $res = $this->query( $sql, $fname );
569 if ( !$res || $res->numRows() == 0 ) {
570 return false;
571 }
572 $info = [];
573 foreach ( $res as $row ) {
574 $info[] = $row->name;
575 }
576
577 return $info;
578 }
579
580 /**
581 * @param string $table
582 * @param string $index
583 * @param string $fname
584 * @return bool|null
585 */
586 function indexUnique( $table, $index, $fname = __METHOD__ ) {
587 $row = $this->selectRow( 'sqlite_master', '*',
588 [
589 'type' => 'index',
590 'name' => $this->indexName( $index ),
591 ], $fname );
592 if ( !$row || !isset( $row->sql ) ) {
593 return null;
594 }
595
596 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
597 $indexPos = strpos( $row->sql, 'INDEX' );
598 if ( $indexPos === false ) {
599 return null;
600 }
601 $firstPart = substr( $row->sql, 0, $indexPos );
602 $options = explode( ' ', $firstPart );
603
604 return in_array( 'UNIQUE', $options );
605 }
606
607 /**
608 * Filter the options used in SELECT statements
609 *
610 * @param array $options
611 * @return array
612 */
613 function makeSelectOptions( $options ) {
614 foreach ( $options as $k => $v ) {
615 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
616 $options[$k] = '';
617 }
618 }
619
620 return parent::makeSelectOptions( $options );
621 }
622
623 /**
624 * @param array $options
625 * @return array
626 */
627 protected function makeUpdateOptionsArray( $options ) {
628 $options = parent::makeUpdateOptionsArray( $options );
629 $options = self::fixIgnore( $options );
630
631 return $options;
632 }
633
634 /**
635 * @param array $options
636 * @return array
637 */
638 static function fixIgnore( $options ) {
639 # SQLite uses OR IGNORE not just IGNORE
640 foreach ( $options as $k => $v ) {
641 if ( $v == 'IGNORE' ) {
642 $options[$k] = 'OR IGNORE';
643 }
644 }
645
646 return $options;
647 }
648
649 /**
650 * @param array $options
651 * @return string
652 */
653 function makeInsertOptions( $options ) {
654 $options = self::fixIgnore( $options );
655
656 return parent::makeInsertOptions( $options );
657 }
658
659 /**
660 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
661 * @param string $table
662 * @param array $a
663 * @param string $fname
664 * @param array $options
665 * @return bool
666 */
667 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
668 if ( !count( $a ) ) {
669 return true;
670 }
671
672 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
673 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
674 $affectedRowCount = 0;
675 try {
676 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
677 foreach ( $a as $v ) {
678 parent::insert( $table, $v, "$fname/multi-row", $options );
679 $affectedRowCount += $this->affectedRows();
680 }
681 $this->endAtomic( $fname );
682 } catch ( Exception $e ) {
683 $this->cancelAtomic( $fname );
684 throw $e;
685 }
686 $this->affectedRowCount = $affectedRowCount;
687 } else {
688 parent::insert( $table, $a, "$fname/single-row", $options );
689 }
690
691 return true;
692 }
693
694 /**
695 * @param string $table
696 * @param array $uniqueIndexes Unused
697 * @param string|array $rows
698 * @param string $fname
699 */
700 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
701 if ( !count( $rows ) ) {
702 return;
703 }
704
705 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
706 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
707 $affectedRowCount = 0;
708 try {
709 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
710 foreach ( $rows as $v ) {
711 $this->nativeReplace( $table, $v, "$fname/multi-row" );
712 $affectedRowCount += $this->affectedRows();
713 }
714 $this->endAtomic( $fname );
715 } catch ( Exception $e ) {
716 $this->cancelAtomic( $fname );
717 throw $e;
718 }
719 $this->affectedRowCount = $affectedRowCount;
720 } else {
721 $this->nativeReplace( $table, $rows, "$fname/single-row" );
722 }
723 }
724
725 /**
726 * Returns the size of a text field, or -1 for "unlimited"
727 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
728 *
729 * @param string $table
730 * @param string $field
731 * @return int
732 */
733 function textFieldSize( $table, $field ) {
734 return -1;
735 }
736
737 /**
738 * @return bool
739 */
740 function unionSupportsOrderAndLimit() {
741 return false;
742 }
743
744 /**
745 * @param string[] $sqls
746 * @param bool $all Whether to "UNION ALL" or not
747 * @return string
748 */
749 function unionQueries( $sqls, $all ) {
750 $glue = $all ? ' UNION ALL ' : ' UNION ';
751
752 return implode( $glue, $sqls );
753 }
754
755 /**
756 * @return bool
757 */
758 function wasDeadlock() {
759 return $this->lastErrno() == 5; // SQLITE_BUSY
760 }
761
762 /**
763 * @return bool
764 */
765 function wasReadOnlyError() {
766 return $this->lastErrno() == 8; // SQLITE_READONLY;
767 }
768
769 public function wasConnectionError( $errno ) {
770 return $errno == 17; // SQLITE_SCHEMA;
771 }
772
773 protected function wasKnownStatementRollbackError() {
774 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
775 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
776 // https://sqlite.org/lang_createtable.html#uniqueconst
777 // https://sqlite.org/lang_conflict.html
778 return false;
779 }
780
781 public function serverIsReadOnly() {
782 return ( !$this->hasProcessMemoryPath() && !is_writable( $this->dbPath ) );
783 }
784
785 /**
786 * @return bool
787 */
788 private function hasProcessMemoryPath() {
789 return ( strpos( $this->dbPath, ':memory:' ) === 0 );
790 }
791
792 /**
793 * @return string Wikitext of a link to the server software's web site
794 */
795 public function getSoftwareLink() {
796 return "[{{int:version-db-sqlite-url}} SQLite]";
797 }
798
799 /**
800 * @return string Version information from the database
801 */
802 function getServerVersion() {
803 $ver = $this->getBindingHandle()->getAttribute( PDO::ATTR_SERVER_VERSION );
804
805 return $ver;
806 }
807
808 /**
809 * Get information about a given field
810 * Returns false if the field does not exist.
811 *
812 * @param string $table
813 * @param string $field
814 * @return SQLiteField|bool False on failure
815 */
816 function fieldInfo( $table, $field ) {
817 $tableName = $this->tableName( $table );
818 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
819 $res = $this->query( $sql, __METHOD__ );
820 foreach ( $res as $row ) {
821 if ( $row->name == $field ) {
822 return new SQLiteField( $row, $tableName );
823 }
824 }
825
826 return false;
827 }
828
829 protected function doBegin( $fname = '' ) {
830 if ( $this->trxMode ) {
831 $this->query( "BEGIN {$this->trxMode}", $fname );
832 } else {
833 $this->query( 'BEGIN', $fname );
834 }
835 }
836
837 /**
838 * @param string $s
839 * @return string
840 */
841 function strencode( $s ) {
842 return substr( $this->addQuotes( $s ), 1, -1 );
843 }
844
845 /**
846 * @param string $b
847 * @return Blob
848 */
849 function encodeBlob( $b ) {
850 return new Blob( $b );
851 }
852
853 /**
854 * @param Blob|string $b
855 * @return string
856 */
857 function decodeBlob( $b ) {
858 if ( $b instanceof Blob ) {
859 $b = $b->fetch();
860 }
861
862 return $b;
863 }
864
865 /**
866 * @param string|int|null|bool|Blob $s
867 * @return string|int
868 */
869 function addQuotes( $s ) {
870 if ( $s instanceof Blob ) {
871 return "x'" . bin2hex( $s->fetch() ) . "'";
872 } elseif ( is_bool( $s ) ) {
873 return (int)$s;
874 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
875 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
876 // This is a known limitation of SQLite's mprintf function which PDO
877 // should work around, but doesn't. I have reported this to php.net as bug #63419:
878 // https://bugs.php.net/bug.php?id=63419
879 // There was already a similar report for SQLite3::escapeString, bug #62361:
880 // https://bugs.php.net/bug.php?id=62361
881 // There is an additional bug regarding sorting this data after insert
882 // on older versions of sqlite shipped with ubuntu 12.04
883 // https://phabricator.wikimedia.org/T74367
884 $this->queryLogger->debug(
885 __FUNCTION__ .
886 ': Quoting value containing null byte. ' .
887 'For consistency all binary data should have been ' .
888 'first processed with self::encodeBlob()'
889 );
890 return "x'" . bin2hex( (string)$s ) . "'";
891 } else {
892 return $this->getBindingHandle()->quote( (string)$s );
893 }
894 }
895
896 public function buildSubstring( $input, $startPosition, $length = null ) {
897 $this->assertBuildSubstringParams( $startPosition, $length );
898 $params = [ $input, $startPosition ];
899 if ( $length !== null ) {
900 $params[] = $length;
901 }
902 return 'SUBSTR(' . implode( ',', $params ) . ')';
903 }
904
905 /**
906 * @param string $field Field or column to cast
907 * @return string
908 * @since 1.28
909 */
910 public function buildStringCast( $field ) {
911 return 'CAST ( ' . $field . ' AS TEXT )';
912 }
913
914 /**
915 * No-op version of deadlockLoop
916 *
917 * @return mixed
918 */
919 public function deadlockLoop( /*...*/ ) {
920 $args = func_get_args();
921 $function = array_shift( $args );
922
923 return $function( ...$args );
924 }
925
926 /**
927 * @param string $s
928 * @return string
929 */
930 protected function replaceVars( $s ) {
931 $s = parent::replaceVars( $s );
932 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
933 // CREATE TABLE hacks to allow schema file sharing with MySQL
934
935 // binary/varbinary column type -> blob
936 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
937 // no such thing as unsigned
938 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
939 // INT -> INTEGER
940 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
941 // floating point types -> REAL
942 $s = preg_replace(
943 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
944 'REAL',
945 $s
946 );
947 // varchar -> TEXT
948 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
949 // TEXT normalization
950 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
951 // BLOB normalization
952 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
953 // BOOL -> INTEGER
954 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
955 // DATETIME -> TEXT
956 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
957 // No ENUM type
958 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
959 // binary collation type -> nothing
960 $s = preg_replace( '/\bbinary\b/i', '', $s );
961 // auto_increment -> autoincrement
962 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
963 // No explicit options
964 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
965 // AUTOINCREMENT should immedidately follow PRIMARY KEY
966 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
967 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
968 // No truncated indexes
969 $s = preg_replace( '/\(\d+\)/', '', $s );
970 // No FULLTEXT
971 $s = preg_replace( '/\bfulltext\b/i', '', $s );
972 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
973 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
974 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
975 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
976 // INSERT IGNORE --> INSERT OR IGNORE
977 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
978 }
979
980 return $s;
981 }
982
983 public function lock( $lockName, $method, $timeout = 5 ) {
984 // Give better error message for permission problems than just returning false
985 if (
986 !is_dir( "{$this->dbDir}/locks" ) &&
987 ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) )
988 ) {
989 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
990 }
991
992 return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
993 }
994
995 public function unlock( $lockName, $method ) {
996 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isGood();
997 }
998
999 /**
1000 * Build a concatenation list to feed into a SQL query
1001 *
1002 * @param string[] $stringList
1003 * @return string
1004 */
1005 function buildConcat( $stringList ) {
1006 return '(' . implode( ') || (', $stringList ) . ')';
1007 }
1008
1009 public function buildGroupConcatField(
1010 $delim, $table, $field, $conds = '', $join_conds = []
1011 ) {
1012 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
1013
1014 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1015 }
1016
1017 /**
1018 * @param string $oldName
1019 * @param string $newName
1020 * @param bool $temporary
1021 * @param string $fname
1022 * @return bool|IResultWrapper
1023 * @throws RuntimeException
1024 */
1025 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1026 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
1027 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
1028 $obj = $this->fetchObject( $res );
1029 if ( !$obj ) {
1030 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
1031 }
1032 $sql = $obj->sql;
1033 $sql = preg_replace(
1034 '/(?<=\W)"?' .
1035 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
1036 '"?(?=\W)/',
1037 $this->addIdentifierQuotes( $newName ),
1038 $sql,
1039 1
1040 );
1041 if ( $temporary ) {
1042 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
1043 $this->queryLogger->debug(
1044 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1045 } else {
1046 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1047 }
1048 }
1049
1050 $res = $this->query( $sql, $fname, self::QUERY_PSEUDO_PERMANENT );
1051
1052 // Take over indexes
1053 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1054 foreach ( $indexList as $index ) {
1055 if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
1056 continue;
1057 }
1058
1059 if ( $index->unique ) {
1060 $sql = 'CREATE UNIQUE INDEX';
1061 } else {
1062 $sql = 'CREATE INDEX';
1063 }
1064 // Try to come up with a new index name, given indexes have database scope in SQLite
1065 $indexName = $newName . '_' . $index->name;
1066 $sql .= ' ' . $indexName . ' ON ' . $newName;
1067
1068 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
1069 $fields = [];
1070 foreach ( $indexInfo as $indexInfoRow ) {
1071 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
1072 }
1073
1074 $sql .= '(' . implode( ',', $fields ) . ')';
1075
1076 $this->query( $sql );
1077 }
1078
1079 return $res;
1080 }
1081
1082 /**
1083 * List all tables on the database
1084 *
1085 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1086 * @param string $fname Calling function name
1087 *
1088 * @return array
1089 */
1090 function listTables( $prefix = null, $fname = __METHOD__ ) {
1091 $result = $this->select(
1092 'sqlite_master',
1093 'name',
1094 "type='table'"
1095 );
1096
1097 $endArray = [];
1098
1099 foreach ( $result as $table ) {
1100 $vars = get_object_vars( $table );
1101 $table = array_pop( $vars );
1102
1103 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1104 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1105 $endArray[] = $table;
1106 }
1107 }
1108 }
1109
1110 return $endArray;
1111 }
1112
1113 /**
1114 * Override due to no CASCADE support
1115 *
1116 * @param string $tableName
1117 * @param string $fName
1118 * @return bool|IResultWrapper
1119 * @throws DBReadOnlyError
1120 */
1121 public function dropTable( $tableName, $fName = __METHOD__ ) {
1122 if ( !$this->tableExists( $tableName, $fName ) ) {
1123 return false;
1124 }
1125 $sql = "DROP TABLE " . $this->tableName( $tableName );
1126
1127 return $this->query( $sql, $fName );
1128 }
1129
1130 public function setTableAliases( array $aliases ) {
1131 parent::setTableAliases( $aliases );
1132 foreach ( $this->tableAliases as $params ) {
1133 if ( isset( $this->alreadyAttached[$params['dbname']] ) ) {
1134 continue;
1135 }
1136 $this->attachDatabase( $params['dbname'] );
1137 $this->alreadyAttached[$params['dbname']] = true;
1138 }
1139 }
1140
1141 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
1142 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1143 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1144 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1145 }
1146
1147 public function databasesAreIndependent() {
1148 return true;
1149 }
1150
1151 /**
1152 * @return PDO
1153 */
1154 protected function getBindingHandle() {
1155 return parent::getBindingHandle();
1156 }
1157 }
1158
1159 /**
1160 * @deprecated since 1.29
1161 */
1162 class_alias( DatabaseSqlite::class, 'DatabaseSqlite' );