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