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