Merge "Make RecentChangesUpdateJob::updateActiveUsers more robust"
[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
26 /**
27 * @ingroup Database
28 */
29 class DatabaseSqlite extends Database {
30 /** @var bool Whether full text is enabled */
31 private static $fulltextEnabled = null;
32
33 /** @var string Directory */
34 protected $dbDir;
35 /** @var string File name for SQLite database file */
36 protected $dbPath;
37 /** @var string Transaction mode */
38 protected $trxMode;
39
40 /** @var int The number of rows affected as an integer */
41 protected $mAffectedRows;
42 /** @var resource */
43 protected $mLastResult;
44
45 /** @var PDO */
46 protected $mConn;
47
48 /** @var FSLockManager (hopefully on the same server as the DB) */
49 protected $lockMgr;
50
51 /**
52 * Additional params include:
53 * - dbDirectory : directory containing the DB and the lock file directory
54 * [defaults to $wgSQLiteDataDir]
55 * - dbFilePath : use this to force the path of the DB file
56 * - trxMode : one of (deferred, immediate, exclusive)
57 * @param array $p
58 */
59 function __construct( array $p ) {
60 if ( isset( $p['dbFilePath'] ) ) {
61 parent::__construct( $p );
62 // Standalone .sqlite file mode.
63 // Super doesn't open when $user is false, but we can work with $dbName,
64 // which is derived from the file path in this case.
65 $this->openFile( $p['dbFilePath'] );
66 $lockDomain = md5( $p['dbFilePath'] );
67 } elseif ( !isset( $p['dbDirectory'] ) ) {
68 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
69 } else {
70 $this->dbDir = $p['dbDirectory'];
71 $this->mDBname = $p['dbname'];
72 $lockDomain = $this->mDBname;
73 // Stock wiki mode using standard file names per DB.
74 parent::__construct( $p );
75 // Super doesn't open when $user is false, but we can work with $dbName
76 if ( $p['dbname'] && !$this->isOpen() ) {
77 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
78 $done = [];
79 foreach ( $this->tableAliases as $params ) {
80 if ( isset( $done[$params['dbname']] ) ) {
81 continue;
82 }
83 $this->attachDatabase( $params['dbname'] );
84 $done[$params['dbname']] = 1;
85 }
86 }
87 }
88 }
89
90 $this->trxMode = isset( $p['trxMode'] ) ? strtoupper( $p['trxMode'] ) : null;
91 if ( $this->trxMode &&
92 !in_array( $this->trxMode, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
93 ) {
94 $this->trxMode = null;
95 $this->queryLogger->warning( "Invalid SQLite transaction mode provided." );
96 }
97
98 $this->lockMgr = new FSLockManager( [
99 'domain' => $lockDomain,
100 'lockDirectory' => "{$this->dbDir}/locks"
101 ] );
102 }
103
104 /**
105 * @param string $filename
106 * @param array $p Options map; supports:
107 * - flags : (same as __construct counterpart)
108 * - trxMode : (same as __construct counterpart)
109 * - dbDirectory : (same as __construct counterpart)
110 * @return DatabaseSqlite
111 * @since 1.25
112 */
113 public static function newStandaloneInstance( $filename, array $p = [] ) {
114 $p['dbFilePath'] = $filename;
115 $p['schema'] = false;
116 $p['tablePrefix'] = '';
117
118 return Database::factory( 'sqlite', $p );
119 }
120
121 /**
122 * @return string
123 */
124 function getType() {
125 return 'sqlite';
126 }
127
128 /**
129 * @todo Check if it should be true like parent class
130 *
131 * @return bool
132 */
133 function implicitGroupby() {
134 return false;
135 }
136
137 /** Open an SQLite database and return a resource handle to it
138 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
139 *
140 * @param string $server
141 * @param string $user
142 * @param string $pass
143 * @param string $dbName
144 *
145 * @throws DBConnectionError
146 * @return bool
147 */
148 function open( $server, $user, $pass, $dbName ) {
149 $this->close();
150 $fileName = self::generateFileName( $this->dbDir, $dbName );
151 if ( !is_readable( $fileName ) ) {
152 $this->mConn = false;
153 throw new DBConnectionError( $this, "SQLite database not accessible" );
154 }
155 $this->openFile( $fileName );
156
157 return (bool)$this->mConn;
158 }
159
160 /**
161 * Opens a database file
162 *
163 * @param string $fileName
164 * @throws DBConnectionError
165 * @return PDO|bool SQL connection or false if failed
166 */
167 protected function openFile( $fileName ) {
168 $err = false;
169
170 $this->dbPath = $fileName;
171 try {
172 if ( $this->mFlags & self::DBO_PERSISTENT ) {
173 $this->mConn = new PDO( "sqlite:$fileName", '', '',
174 [ PDO::ATTR_PERSISTENT => true ] );
175 } else {
176 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
177 }
178 } catch ( PDOException $e ) {
179 $err = $e->getMessage();
180 }
181
182 if ( !$this->mConn ) {
183 $this->queryLogger->debug( "DB connection error: $err\n" );
184 throw new DBConnectionError( $this, $err );
185 }
186
187 $this->mOpened = !!$this->mConn;
188 if ( $this->mOpened ) {
189 # Set error codes only, don't raise exceptions
190 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
191 # Enforce LIKE to be case sensitive, just like MySQL
192 $this->query( 'PRAGMA case_sensitive_like = 1' );
193
194 return $this->mConn;
195 }
196
197 return false;
198 }
199
200 public function selectDB( $db ) {
201 return false; // doesn't make sense
202 }
203
204 /**
205 * @return string SQLite DB file path
206 * @since 1.25
207 */
208 public function getDbFilePath() {
209 return $this->dbPath;
210 }
211
212 /**
213 * Does not actually close the connection, just destroys the reference for GC to do its work
214 * @return bool
215 */
216 protected function closeConnection() {
217 $this->mConn = null;
218
219 return true;
220 }
221
222 /**
223 * Generates a database file name. Explicitly public for installer.
224 * @param string $dir Directory where database resides
225 * @param string $dbName Database name
226 * @return string
227 */
228 public static function generateFileName( $dir, $dbName ) {
229 return "$dir/$dbName.sqlite";
230 }
231
232 /**
233 * Check if the searchindext table is FTS enabled.
234 * @return bool False if not enabled.
235 */
236 function checkForEnabledSearch() {
237 if ( self::$fulltextEnabled === null ) {
238 self::$fulltextEnabled = false;
239 $table = $this->tableName( 'searchindex' );
240 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
241 if ( $res ) {
242 $row = $res->fetchRow();
243 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
244 }
245 }
246
247 return self::$fulltextEnabled;
248 }
249
250 /**
251 * Returns version of currently supported SQLite fulltext search module or false if none present.
252 * @return string
253 */
254 static function getFulltextSearchModule() {
255 static $cachedResult = null;
256 if ( $cachedResult !== null ) {
257 return $cachedResult;
258 }
259 $cachedResult = false;
260 $table = 'dummy_search_test';
261
262 $db = self::newStandaloneInstance( ':memory:' );
263 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
264 $cachedResult = 'FTS3';
265 }
266 $db->close();
267
268 return $cachedResult;
269 }
270
271 /**
272 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
273 * for details.
274 *
275 * @param string $name Database name to be used in queries like
276 * SELECT foo FROM dbname.table
277 * @param bool|string $file Database file name. If omitted, will be generated
278 * using $name and configured data directory
279 * @param string $fname Calling function name
280 * @return ResultWrapper
281 */
282 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
283 if ( !$file ) {
284 $file = self::generateFileName( $this->dbDir, $name );
285 }
286 $file = $this->addQuotes( $file );
287
288 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
289 }
290
291 function isWriteQuery( $sql ) {
292 return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
293 }
294
295 /**
296 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
297 *
298 * @param string $sql
299 * @return bool|ResultWrapper
300 */
301 protected function doQuery( $sql ) {
302 $res = $this->mConn->query( $sql );
303 if ( $res === false ) {
304 return false;
305 }
306
307 $r = $res instanceof ResultWrapper ? $res->result : $res;
308 $this->mAffectedRows = $r->rowCount();
309 $res = new ResultWrapper( $this, $r->fetchAll() );
310
311 return $res;
312 }
313
314 /**
315 * @param ResultWrapper|mixed $res
316 */
317 function freeResult( $res ) {
318 if ( $res instanceof ResultWrapper ) {
319 $res->result = null;
320 } else {
321 $res = null;
322 }
323 }
324
325 /**
326 * @param ResultWrapper|array $res
327 * @return stdClass|bool
328 */
329 function fetchObject( $res ) {
330 if ( $res instanceof ResultWrapper ) {
331 $r =& $res->result;
332 } else {
333 $r =& $res;
334 }
335
336 $cur = current( $r );
337 if ( is_array( $cur ) ) {
338 next( $r );
339 $obj = new stdClass;
340 foreach ( $cur as $k => $v ) {
341 if ( !is_numeric( $k ) ) {
342 $obj->$k = $v;
343 }
344 }
345
346 return $obj;
347 }
348
349 return false;
350 }
351
352 /**
353 * @param ResultWrapper|mixed $res
354 * @return array|bool
355 */
356 function fetchRow( $res ) {
357 if ( $res instanceof ResultWrapper ) {
358 $r =& $res->result;
359 } else {
360 $r =& $res;
361 }
362 $cur = current( $r );
363 if ( is_array( $cur ) ) {
364 next( $r );
365
366 return $cur;
367 }
368
369 return false;
370 }
371
372 /**
373 * The PDO::Statement class implements the array interface so count() will work
374 *
375 * @param ResultWrapper|array $res
376 * @return int
377 */
378 function numRows( $res ) {
379 $r = $res instanceof ResultWrapper ? $res->result : $res;
380
381 return count( $r );
382 }
383
384 /**
385 * @param ResultWrapper $res
386 * @return int
387 */
388 function numFields( $res ) {
389 $r = $res instanceof ResultWrapper ? $res->result : $res;
390 if ( is_array( $r ) && count( $r ) > 0 ) {
391 // The size of the result array is twice the number of fields. (Bug: 65578)
392 return count( $r[0] ) / 2;
393 } else {
394 // If the result is empty return 0
395 return 0;
396 }
397 }
398
399 /**
400 * @param ResultWrapper $res
401 * @param int $n
402 * @return bool
403 */
404 function fieldName( $res, $n ) {
405 $r = $res instanceof ResultWrapper ? $res->result : $res;
406 if ( is_array( $r ) ) {
407 $keys = array_keys( $r[0] );
408
409 return $keys[$n];
410 }
411
412 return false;
413 }
414
415 /**
416 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
417 *
418 * @param string $name
419 * @param string $format
420 * @return string
421 */
422 function tableName( $name, $format = 'quoted' ) {
423 // table names starting with sqlite_ are reserved
424 if ( strpos( $name, 'sqlite_' ) === 0 ) {
425 return $name;
426 }
427
428 return str_replace( '"', '', parent::tableName( $name, $format ) );
429 }
430
431 /**
432 * This must be called after nextSequenceVal
433 *
434 * @return int
435 */
436 function insertId() {
437 // PDO::lastInsertId yields a string :(
438 return intval( $this->mConn->lastInsertId() );
439 }
440
441 /**
442 * @param ResultWrapper|array $res
443 * @param int $row
444 */
445 function dataSeek( $res, $row ) {
446 if ( $res instanceof ResultWrapper ) {
447 $r =& $res->result;
448 } else {
449 $r =& $res;
450 }
451 reset( $r );
452 if ( $row > 0 ) {
453 for ( $i = 0; $i < $row; $i++ ) {
454 next( $r );
455 }
456 }
457 }
458
459 /**
460 * @return string
461 */
462 function lastError() {
463 if ( !is_object( $this->mConn ) ) {
464 return "Cannot return last error, no db connection";
465 }
466 $e = $this->mConn->errorInfo();
467
468 return isset( $e[2] ) ? $e[2] : '';
469 }
470
471 /**
472 * @return string
473 */
474 function lastErrno() {
475 if ( !is_object( $this->mConn ) ) {
476 return "Cannot return last error, no db connection";
477 } else {
478 $info = $this->mConn->errorInfo();
479
480 return $info[1];
481 }
482 }
483
484 /**
485 * @return int
486 */
487 function affectedRows() {
488 return $this->mAffectedRows;
489 }
490
491 /**
492 * Returns information about an index
493 * Returns false if the index does not exist
494 * - if errors are explicitly ignored, returns NULL on failure
495 *
496 * @param string $table
497 * @param string $index
498 * @param string $fname
499 * @return array|false
500 */
501 function indexInfo( $table, $index, $fname = __METHOD__ ) {
502 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
503 $res = $this->query( $sql, $fname );
504 if ( !$res || $res->numRows() == 0 ) {
505 return false;
506 }
507 $info = [];
508 foreach ( $res as $row ) {
509 $info[] = $row->name;
510 }
511
512 return $info;
513 }
514
515 /**
516 * @param string $table
517 * @param string $index
518 * @param string $fname
519 * @return bool|null
520 */
521 function indexUnique( $table, $index, $fname = __METHOD__ ) {
522 $row = $this->selectRow( 'sqlite_master', '*',
523 [
524 'type' => 'index',
525 'name' => $this->indexName( $index ),
526 ], $fname );
527 if ( !$row || !isset( $row->sql ) ) {
528 return null;
529 }
530
531 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
532 $indexPos = strpos( $row->sql, 'INDEX' );
533 if ( $indexPos === false ) {
534 return null;
535 }
536 $firstPart = substr( $row->sql, 0, $indexPos );
537 $options = explode( ' ', $firstPart );
538
539 return in_array( 'UNIQUE', $options );
540 }
541
542 /**
543 * Filter the options used in SELECT statements
544 *
545 * @param array $options
546 * @return array
547 */
548 function makeSelectOptions( $options ) {
549 foreach ( $options as $k => $v ) {
550 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
551 $options[$k] = '';
552 }
553 }
554
555 return parent::makeSelectOptions( $options );
556 }
557
558 /**
559 * @param array $options
560 * @return string
561 */
562 protected function makeUpdateOptionsArray( $options ) {
563 $options = parent::makeUpdateOptionsArray( $options );
564 $options = self::fixIgnore( $options );
565
566 return $options;
567 }
568
569 /**
570 * @param array $options
571 * @return array
572 */
573 static function fixIgnore( $options ) {
574 # SQLite uses OR IGNORE not just IGNORE
575 foreach ( $options as $k => $v ) {
576 if ( $v == 'IGNORE' ) {
577 $options[$k] = 'OR IGNORE';
578 }
579 }
580
581 return $options;
582 }
583
584 /**
585 * @param array $options
586 * @return string
587 */
588 function makeInsertOptions( $options ) {
589 $options = self::fixIgnore( $options );
590
591 return parent::makeInsertOptions( $options );
592 }
593
594 /**
595 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
596 * @param string $table
597 * @param array $a
598 * @param string $fname
599 * @param array $options
600 * @return bool
601 */
602 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
603 if ( !count( $a ) ) {
604 return true;
605 }
606
607 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
608 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
609 $ret = true;
610 foreach ( $a as $v ) {
611 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
612 $ret = false;
613 }
614 }
615 } else {
616 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
617 }
618
619 return $ret;
620 }
621
622 /**
623 * @param string $table
624 * @param array $uniqueIndexes Unused
625 * @param string|array $rows
626 * @param string $fname
627 * @return bool|ResultWrapper
628 */
629 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
630 if ( !count( $rows ) ) {
631 return true;
632 }
633
634 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
635 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
636 $ret = true;
637 foreach ( $rows as $v ) {
638 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
639 $ret = false;
640 }
641 }
642 } else {
643 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
644 }
645
646 return $ret;
647 }
648
649 /**
650 * Returns the size of a text field, or -1 for "unlimited"
651 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
652 *
653 * @param string $table
654 * @param string $field
655 * @return int
656 */
657 function textFieldSize( $table, $field ) {
658 return -1;
659 }
660
661 /**
662 * @return bool
663 */
664 function unionSupportsOrderAndLimit() {
665 return false;
666 }
667
668 /**
669 * @param string[] $sqls
670 * @param bool $all Whether to "UNION ALL" or not
671 * @return string
672 */
673 function unionQueries( $sqls, $all ) {
674 $glue = $all ? ' UNION ALL ' : ' UNION ';
675
676 return implode( $glue, $sqls );
677 }
678
679 /**
680 * @return bool
681 */
682 function wasDeadlock() {
683 return $this->lastErrno() == 5; // SQLITE_BUSY
684 }
685
686 /**
687 * @return bool
688 */
689 function wasErrorReissuable() {
690 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
691 }
692
693 /**
694 * @return bool
695 */
696 function wasReadOnlyError() {
697 return $this->lastErrno() == 8; // SQLITE_READONLY;
698 }
699
700 /**
701 * @return string Wikitext of a link to the server software's web site
702 */
703 public function getSoftwareLink() {
704 return "[{{int:version-db-sqlite-url}} SQLite]";
705 }
706
707 /**
708 * @return string Version information from the database
709 */
710 function getServerVersion() {
711 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
712
713 return $ver;
714 }
715
716 /**
717 * Get information about a given field
718 * Returns false if the field does not exist.
719 *
720 * @param string $table
721 * @param string $field
722 * @return SQLiteField|bool False on failure
723 */
724 function fieldInfo( $table, $field ) {
725 $tableName = $this->tableName( $table );
726 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
727 $res = $this->query( $sql, __METHOD__ );
728 foreach ( $res as $row ) {
729 if ( $row->name == $field ) {
730 return new SQLiteField( $row, $tableName );
731 }
732 }
733
734 return false;
735 }
736
737 protected function doBegin( $fname = '' ) {
738 if ( $this->trxMode ) {
739 $this->query( "BEGIN {$this->trxMode}", $fname );
740 } else {
741 $this->query( 'BEGIN', $fname );
742 }
743 $this->mTrxLevel = 1;
744 }
745
746 /**
747 * @param string $s
748 * @return string
749 */
750 function strencode( $s ) {
751 return substr( $this->addQuotes( $s ), 1, -1 );
752 }
753
754 /**
755 * @param string $b
756 * @return Blob
757 */
758 function encodeBlob( $b ) {
759 return new Blob( $b );
760 }
761
762 /**
763 * @param Blob|string $b
764 * @return string
765 */
766 function decodeBlob( $b ) {
767 if ( $b instanceof Blob ) {
768 $b = $b->fetch();
769 }
770
771 return $b;
772 }
773
774 /**
775 * @param string|int|null|bool|Blob $s
776 * @return string|int
777 */
778 function addQuotes( $s ) {
779 if ( $s instanceof Blob ) {
780 return "x'" . bin2hex( $s->fetch() ) . "'";
781 } elseif ( is_bool( $s ) ) {
782 return (int)$s;
783 } elseif ( strpos( $s, "\0" ) !== false ) {
784 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
785 // This is a known limitation of SQLite's mprintf function which PDO
786 // should work around, but doesn't. I have reported this to php.net as bug #63419:
787 // https://bugs.php.net/bug.php?id=63419
788 // There was already a similar report for SQLite3::escapeString, bug #62361:
789 // https://bugs.php.net/bug.php?id=62361
790 // There is an additional bug regarding sorting this data after insert
791 // on older versions of sqlite shipped with ubuntu 12.04
792 // https://phabricator.wikimedia.org/T74367
793 $this->queryLogger->debug(
794 __FUNCTION__ .
795 ': Quoting value containing null byte. ' .
796 'For consistency all binary data should have been ' .
797 'first processed with self::encodeBlob()'
798 );
799 return "x'" . bin2hex( $s ) . "'";
800 } else {
801 return $this->mConn->quote( $s );
802 }
803 }
804
805 /**
806 * @return string
807 */
808 function buildLike() {
809 $params = func_get_args();
810 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
811 $params = $params[0];
812 }
813
814 return parent::buildLike( $params ) . "ESCAPE '\' ";
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 protected function requiresDatabaseUser() {
1039 return false; // just a file
1040 }
1041
1042 /**
1043 * @return string
1044 */
1045 public function __toString() {
1046 return 'SQLite ' . (string)$this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
1047 }
1048 }