Merge "Revert "Remove old remapping hacks from Database::indexName()""
[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 use Wikimedia\Rdbms\Blob;
25 use Wikimedia\Rdbms\SQLiteField;
26 use Wikimedia\Rdbms\ResultWrapper;
27
28 /**
29 * @ingroup Database
30 */
31 class DatabaseSqlite extends Database {
32 /** @var bool Whether full text is enabled */
33 private static $fulltextEnabled = null;
34
35 /** @var string Directory */
36 protected $dbDir;
37 /** @var string File name for SQLite database file */
38 protected $dbPath;
39 /** @var string Transaction mode */
40 protected $trxMode;
41
42 /** @var int The number of rows affected as an integer */
43 protected $mAffectedRows;
44 /** @var resource */
45 protected $mLastResult;
46
47 /** @var PDO */
48 protected $mConn;
49
50 /** @var FSLockManager (hopefully on the same server as the DB) */
51 protected $lockMgr;
52
53 /**
54 * Additional params include:
55 * - dbDirectory : directory containing the DB and the lock file directory
56 * [defaults to $wgSQLiteDataDir]
57 * - dbFilePath : use this to force the path of the DB file
58 * - trxMode : one of (deferred, immediate, exclusive)
59 * @param array $p
60 */
61 function __construct( array $p ) {
62 if ( isset( $p['dbFilePath'] ) ) {
63 parent::__construct( $p );
64 // Standalone .sqlite file mode.
65 // Super doesn't open when $user is false, but we can work with $dbName,
66 // which is derived from the file path in this case.
67 $this->openFile( $p['dbFilePath'] );
68 $lockDomain = md5( $p['dbFilePath'] );
69 } elseif ( !isset( $p['dbDirectory'] ) ) {
70 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
71 } else {
72 $this->dbDir = $p['dbDirectory'];
73 $this->mDBname = $p['dbname'];
74 $lockDomain = $this->mDBname;
75 // Stock wiki mode using standard file names per DB.
76 parent::__construct( $p );
77 // Super doesn't open when $user is false, but we can work with $dbName
78 if ( $p['dbname'] && !$this->isOpen() ) {
79 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
80 $done = [];
81 foreach ( $this->tableAliases as $params ) {
82 if ( isset( $done[$params['dbname']] ) ) {
83 continue;
84 }
85 $this->attachDatabase( $params['dbname'] );
86 $done[$params['dbname']] = 1;
87 }
88 }
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
120 return Database::factory( 'sqlite', $p );
121 }
122
123 /**
124 * @return string
125 */
126 function getType() {
127 return 'sqlite';
128 }
129
130 /**
131 * @todo Check if it should be true like parent class
132 *
133 * @return bool
134 */
135 function implicitGroupby() {
136 return false;
137 }
138
139 /** Open an SQLite database and return a resource handle to it
140 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
141 *
142 * @param string $server
143 * @param string $user
144 * @param string $pass
145 * @param string $dbName
146 *
147 * @throws DBConnectionError
148 * @return bool
149 */
150 function open( $server, $user, $pass, $dbName ) {
151 $this->close();
152 $fileName = self::generateFileName( $this->dbDir, $dbName );
153 if ( !is_readable( $fileName ) ) {
154 $this->mConn = false;
155 throw new DBConnectionError( $this, "SQLite database not accessible" );
156 }
157 $this->openFile( $fileName );
158
159 return (bool)$this->mConn;
160 }
161
162 /**
163 * Opens a database file
164 *
165 * @param string $fileName
166 * @throws DBConnectionError
167 * @return PDO|bool SQL connection or false if failed
168 */
169 protected function openFile( $fileName ) {
170 $err = false;
171
172 $this->dbPath = $fileName;
173 try {
174 if ( $this->mFlags & self::DBO_PERSISTENT ) {
175 $this->mConn = new PDO( "sqlite:$fileName", '', '',
176 [ PDO::ATTR_PERSISTENT => true ] );
177 } else {
178 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
179 }
180 } catch ( PDOException $e ) {
181 $err = $e->getMessage();
182 }
183
184 if ( !$this->mConn ) {
185 $this->queryLogger->debug( "DB connection error: $err\n" );
186 throw new DBConnectionError( $this, $err );
187 }
188
189 $this->mOpened = !!$this->mConn;
190 if ( $this->mOpened ) {
191 # Set error codes only, don't raise exceptions
192 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
193 # Enforce LIKE to be case sensitive, just like MySQL
194 $this->query( 'PRAGMA case_sensitive_like = 1' );
195
196 return $this->mConn;
197 }
198
199 return false;
200 }
201
202 public function selectDB( $db ) {
203 return false; // doesn't make sense
204 }
205
206 /**
207 * @return string SQLite DB file path
208 * @since 1.25
209 */
210 public function getDbFilePath() {
211 return $this->dbPath;
212 }
213
214 /**
215 * Does not actually close the connection, just destroys the reference for GC to do its work
216 * @return bool
217 */
218 protected function closeConnection() {
219 $this->mConn = null;
220
221 return true;
222 }
223
224 /**
225 * Generates a database file name. Explicitly public for installer.
226 * @param string $dir Directory where database resides
227 * @param string $dbName Database name
228 * @return string
229 */
230 public static function generateFileName( $dir, $dbName ) {
231 return "$dir/$dbName.sqlite";
232 }
233
234 /**
235 * Check if the searchindext table is FTS enabled.
236 * @return bool False if not enabled.
237 */
238 function checkForEnabledSearch() {
239 if ( self::$fulltextEnabled === null ) {
240 self::$fulltextEnabled = false;
241 $table = $this->tableName( 'searchindex' );
242 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
243 if ( $res ) {
244 $row = $res->fetchRow();
245 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
246 }
247 }
248
249 return self::$fulltextEnabled;
250 }
251
252 /**
253 * Returns version of currently supported SQLite fulltext search module or false if none present.
254 * @return string
255 */
256 static function getFulltextSearchModule() {
257 static $cachedResult = null;
258 if ( $cachedResult !== null ) {
259 return $cachedResult;
260 }
261 $cachedResult = false;
262 $table = 'dummy_search_test';
263
264 $db = self::newStandaloneInstance( ':memory:' );
265 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
266 $cachedResult = 'FTS3';
267 }
268 $db->close();
269
270 return $cachedResult;
271 }
272
273 /**
274 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
275 * for details.
276 *
277 * @param string $name Database name to be used in queries like
278 * SELECT foo FROM dbname.table
279 * @param bool|string $file Database file name. If omitted, will be generated
280 * using $name and configured data directory
281 * @param string $fname Calling function name
282 * @return ResultWrapper
283 */
284 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
285 if ( !$file ) {
286 $file = self::generateFileName( $this->dbDir, $name );
287 }
288 $file = $this->addQuotes( $file );
289
290 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
291 }
292
293 function isWriteQuery( $sql ) {
294 return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
295 }
296
297 /**
298 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
299 *
300 * @param string $sql
301 * @return bool|ResultWrapper
302 */
303 protected function doQuery( $sql ) {
304 $res = $this->mConn->query( $sql );
305 if ( $res === false ) {
306 return false;
307 }
308
309 $r = $res instanceof ResultWrapper ? $res->result : $res;
310 $this->mAffectedRows = $r->rowCount();
311 $res = new ResultWrapper( $this, $r->fetchAll() );
312
313 return $res;
314 }
315
316 /**
317 * @param ResultWrapper|mixed $res
318 */
319 function freeResult( $res ) {
320 if ( $res instanceof ResultWrapper ) {
321 $res->result = null;
322 } else {
323 $res = null;
324 }
325 }
326
327 /**
328 * @param ResultWrapper|array $res
329 * @return stdClass|bool
330 */
331 function fetchObject( $res ) {
332 if ( $res instanceof ResultWrapper ) {
333 $r =& $res->result;
334 } else {
335 $r =& $res;
336 }
337
338 $cur = current( $r );
339 if ( is_array( $cur ) ) {
340 next( $r );
341 $obj = new stdClass;
342 foreach ( $cur as $k => $v ) {
343 if ( !is_numeric( $k ) ) {
344 $obj->$k = $v;
345 }
346 }
347
348 return $obj;
349 }
350
351 return false;
352 }
353
354 /**
355 * @param ResultWrapper|mixed $res
356 * @return array|bool
357 */
358 function fetchRow( $res ) {
359 if ( $res instanceof ResultWrapper ) {
360 $r =& $res->result;
361 } else {
362 $r =& $res;
363 }
364 $cur = current( $r );
365 if ( is_array( $cur ) ) {
366 next( $r );
367
368 return $cur;
369 }
370
371 return false;
372 }
373
374 /**
375 * The PDO::Statement class implements the array interface so count() will work
376 *
377 * @param ResultWrapper|array $res
378 * @return int
379 */
380 function numRows( $res ) {
381 $r = $res instanceof ResultWrapper ? $res->result : $res;
382
383 return count( $r );
384 }
385
386 /**
387 * @param ResultWrapper $res
388 * @return int
389 */
390 function numFields( $res ) {
391 $r = $res instanceof ResultWrapper ? $res->result : $res;
392 if ( is_array( $r ) && count( $r ) > 0 ) {
393 // The size of the result array is twice the number of fields. (Bug: 65578)
394 return count( $r[0] ) / 2;
395 } else {
396 // If the result is empty return 0
397 return 0;
398 }
399 }
400
401 /**
402 * @param ResultWrapper $res
403 * @param int $n
404 * @return bool
405 */
406 function fieldName( $res, $n ) {
407 $r = $res instanceof ResultWrapper ? $res->result : $res;
408 if ( is_array( $r ) ) {
409 $keys = array_keys( $r[0] );
410
411 return $keys[$n];
412 }
413
414 return false;
415 }
416
417 /**
418 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
419 *
420 * @param string $name
421 * @param string $format
422 * @return string
423 */
424 function tableName( $name, $format = 'quoted' ) {
425 // table names starting with sqlite_ are reserved
426 if ( strpos( $name, 'sqlite_' ) === 0 ) {
427 return $name;
428 }
429
430 return str_replace( '"', '', parent::tableName( $name, $format ) );
431 }
432
433 /**
434 * Index names have DB scope
435 *
436 * @param string $index
437 * @return string
438 */
439 protected function indexName( $index ) {
440 return $index;
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->mConn->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->mConn ) ) {
476 return "Cannot return last error, no db connection";
477 }
478 $e = $this->mConn->errorInfo();
479
480 return isset( $e[2] ) ? $e[2] : '';
481 }
482
483 /**
484 * @return string
485 */
486 function lastErrno() {
487 if ( !is_object( $this->mConn ) ) {
488 return "Cannot return last error, no db connection";
489 } else {
490 $info = $this->mConn->errorInfo();
491
492 return $info[1];
493 }
494 }
495
496 /**
497 * @return int
498 */
499 function affectedRows() {
500 return $this->mAffectedRows;
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 string
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->mConn->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->mTrxLevel = 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( $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( $s ) . "'";
812 } else {
813 return $this->mConn->quote( $s );
814 }
815 }
816
817 /**
818 * @return string
819 */
820 function buildLike() {
821 $params = func_get_args();
822 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
823 $params = $params[0];
824 }
825
826 return parent::buildLike( $params ) . "ESCAPE '\' ";
827 }
828
829 /**
830 * @param string $field Field or column to cast
831 * @return string
832 * @since 1.28
833 */
834 public function buildStringCast( $field ) {
835 return 'CAST ( ' . $field . ' AS TEXT )';
836 }
837
838 /**
839 * No-op version of deadlockLoop
840 *
841 * @return mixed
842 */
843 public function deadlockLoop( /*...*/ ) {
844 $args = func_get_args();
845 $function = array_shift( $args );
846
847 return call_user_func_array( $function, $args );
848 }
849
850 /**
851 * @param string $s
852 * @return string
853 */
854 protected function replaceVars( $s ) {
855 $s = parent::replaceVars( $s );
856 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
857 // CREATE TABLE hacks to allow schema file sharing with MySQL
858
859 // binary/varbinary column type -> blob
860 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
861 // no such thing as unsigned
862 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
863 // INT -> INTEGER
864 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
865 // floating point types -> REAL
866 $s = preg_replace(
867 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
868 'REAL',
869 $s
870 );
871 // varchar -> TEXT
872 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
873 // TEXT normalization
874 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
875 // BLOB normalization
876 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
877 // BOOL -> INTEGER
878 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
879 // DATETIME -> TEXT
880 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
881 // No ENUM type
882 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
883 // binary collation type -> nothing
884 $s = preg_replace( '/\bbinary\b/i', '', $s );
885 // auto_increment -> autoincrement
886 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
887 // No explicit options
888 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
889 // AUTOINCREMENT should immedidately follow PRIMARY KEY
890 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
891 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
892 // No truncated indexes
893 $s = preg_replace( '/\(\d+\)/', '', $s );
894 // No FULLTEXT
895 $s = preg_replace( '/\bfulltext\b/i', '', $s );
896 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
897 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
898 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
899 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
900 // INSERT IGNORE --> INSERT OR IGNORE
901 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
902 }
903
904 return $s;
905 }
906
907 public function lock( $lockName, $method, $timeout = 5 ) {
908 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
909 if ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) ) {
910 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
911 }
912 }
913
914 return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
915 }
916
917 public function unlock( $lockName, $method ) {
918 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isOK();
919 }
920
921 /**
922 * Build a concatenation list to feed into a SQL query
923 *
924 * @param string[] $stringList
925 * @return string
926 */
927 function buildConcat( $stringList ) {
928 return '(' . implode( ') || (', $stringList ) . ')';
929 }
930
931 public function buildGroupConcatField(
932 $delim, $table, $field, $conds = '', $join_conds = []
933 ) {
934 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
935
936 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
937 }
938
939 /**
940 * @param string $oldName
941 * @param string $newName
942 * @param bool $temporary
943 * @param string $fname
944 * @return bool|ResultWrapper
945 * @throws RuntimeException
946 */
947 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
948 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
949 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
950 $obj = $this->fetchObject( $res );
951 if ( !$obj ) {
952 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
953 }
954 $sql = $obj->sql;
955 $sql = preg_replace(
956 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
957 $this->addIdentifierQuotes( $newName ),
958 $sql,
959 1
960 );
961 if ( $temporary ) {
962 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
963 $this->queryLogger->debug(
964 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
965 } else {
966 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
967 }
968 }
969
970 $res = $this->query( $sql, $fname );
971
972 // Take over indexes
973 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
974 foreach ( $indexList as $index ) {
975 if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
976 continue;
977 }
978
979 if ( $index->unique ) {
980 $sql = 'CREATE UNIQUE INDEX';
981 } else {
982 $sql = 'CREATE INDEX';
983 }
984 // Try to come up with a new index name, given indexes have database scope in SQLite
985 $indexName = $newName . '_' . $index->name;
986 $sql .= ' ' . $indexName . ' ON ' . $newName;
987
988 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
989 $fields = [];
990 foreach ( $indexInfo as $indexInfoRow ) {
991 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
992 }
993
994 $sql .= '(' . implode( ',', $fields ) . ')';
995
996 $this->query( $sql );
997 }
998
999 return $res;
1000 }
1001
1002 /**
1003 * List all tables on the database
1004 *
1005 * @param string $prefix Only show tables with this prefix, e.g. mw_
1006 * @param string $fname Calling function name
1007 *
1008 * @return array
1009 */
1010 function listTables( $prefix = null, $fname = __METHOD__ ) {
1011 $result = $this->select(
1012 'sqlite_master',
1013 'name',
1014 "type='table'"
1015 );
1016
1017 $endArray = [];
1018
1019 foreach ( $result as $table ) {
1020 $vars = get_object_vars( $table );
1021 $table = array_pop( $vars );
1022
1023 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1024 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1025 $endArray[] = $table;
1026 }
1027 }
1028 }
1029
1030 return $endArray;
1031 }
1032
1033 /**
1034 * Override due to no CASCADE support
1035 *
1036 * @param string $tableName
1037 * @param string $fName
1038 * @return bool|ResultWrapper
1039 * @throws DBReadOnlyError
1040 */
1041 public function dropTable( $tableName, $fName = __METHOD__ ) {
1042 if ( !$this->tableExists( $tableName, $fName ) ) {
1043 return false;
1044 }
1045 $sql = "DROP TABLE " . $this->tableName( $tableName );
1046
1047 return $this->query( $sql, $fName );
1048 }
1049
1050 protected function requiresDatabaseUser() {
1051 return false; // just a file
1052 }
1053
1054 /**
1055 * @return string
1056 */
1057 public function __toString() {
1058 return 'SQLite ' . (string)$this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
1059 }
1060 }