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