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