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