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