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