Make the indexName functions more obviously laid out
[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 * This must be called after nextSequenceVal
435 *
436 * @return int
437 */
438 function insertId() {
439 // PDO::lastInsertId yields a string :(
440 return intval( $this->mConn->lastInsertId() );
441 }
442
443 /**
444 * @param ResultWrapper|array $res
445 * @param int $row
446 */
447 function dataSeek( $res, $row ) {
448 if ( $res instanceof ResultWrapper ) {
449 $r =& $res->result;
450 } else {
451 $r =& $res;
452 }
453 reset( $r );
454 if ( $row > 0 ) {
455 for ( $i = 0; $i < $row; $i++ ) {
456 next( $r );
457 }
458 }
459 }
460
461 /**
462 * @return string
463 */
464 function lastError() {
465 if ( !is_object( $this->mConn ) ) {
466 return "Cannot return last error, no db connection";
467 }
468 $e = $this->mConn->errorInfo();
469
470 return isset( $e[2] ) ? $e[2] : '';
471 }
472
473 /**
474 * @return string
475 */
476 function lastErrno() {
477 if ( !is_object( $this->mConn ) ) {
478 return "Cannot return last error, no db connection";
479 } else {
480 $info = $this->mConn->errorInfo();
481
482 return $info[1];
483 }
484 }
485
486 /**
487 * @return int
488 */
489 function affectedRows() {
490 return $this->mAffectedRows;
491 }
492
493 /**
494 * Returns information about an index
495 * Returns false if the index does not exist
496 * - if errors are explicitly ignored, returns NULL on failure
497 *
498 * @param string $table
499 * @param string $index
500 * @param string $fname
501 * @return array|false
502 */
503 function indexInfo( $table, $index, $fname = __METHOD__ ) {
504 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
505 $res = $this->query( $sql, $fname );
506 if ( !$res || $res->numRows() == 0 ) {
507 return false;
508 }
509 $info = [];
510 foreach ( $res as $row ) {
511 $info[] = $row->name;
512 }
513
514 return $info;
515 }
516
517 /**
518 * @param string $table
519 * @param string $index
520 * @param string $fname
521 * @return bool|null
522 */
523 function indexUnique( $table, $index, $fname = __METHOD__ ) {
524 $row = $this->selectRow( 'sqlite_master', '*',
525 [
526 'type' => 'index',
527 'name' => $this->indexName( $index ),
528 ], $fname );
529 if ( !$row || !isset( $row->sql ) ) {
530 return null;
531 }
532
533 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
534 $indexPos = strpos( $row->sql, 'INDEX' );
535 if ( $indexPos === false ) {
536 return null;
537 }
538 $firstPart = substr( $row->sql, 0, $indexPos );
539 $options = explode( ' ', $firstPart );
540
541 return in_array( 'UNIQUE', $options );
542 }
543
544 /**
545 * Filter the options used in SELECT statements
546 *
547 * @param array $options
548 * @return array
549 */
550 function makeSelectOptions( $options ) {
551 foreach ( $options as $k => $v ) {
552 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
553 $options[$k] = '';
554 }
555 }
556
557 return parent::makeSelectOptions( $options );
558 }
559
560 /**
561 * @param array $options
562 * @return string
563 */
564 protected function makeUpdateOptionsArray( $options ) {
565 $options = parent::makeUpdateOptionsArray( $options );
566 $options = self::fixIgnore( $options );
567
568 return $options;
569 }
570
571 /**
572 * @param array $options
573 * @return array
574 */
575 static function fixIgnore( $options ) {
576 # SQLite uses OR IGNORE not just IGNORE
577 foreach ( $options as $k => $v ) {
578 if ( $v == 'IGNORE' ) {
579 $options[$k] = 'OR IGNORE';
580 }
581 }
582
583 return $options;
584 }
585
586 /**
587 * @param array $options
588 * @return string
589 */
590 function makeInsertOptions( $options ) {
591 $options = self::fixIgnore( $options );
592
593 return parent::makeInsertOptions( $options );
594 }
595
596 /**
597 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
598 * @param string $table
599 * @param array $a
600 * @param string $fname
601 * @param array $options
602 * @return bool
603 */
604 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
605 if ( !count( $a ) ) {
606 return true;
607 }
608
609 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
610 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
611 $ret = true;
612 foreach ( $a as $v ) {
613 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
614 $ret = false;
615 }
616 }
617 } else {
618 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
619 }
620
621 return $ret;
622 }
623
624 /**
625 * @param string $table
626 * @param array $uniqueIndexes Unused
627 * @param string|array $rows
628 * @param string $fname
629 * @return bool|ResultWrapper
630 */
631 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
632 if ( !count( $rows ) ) {
633 return true;
634 }
635
636 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
637 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
638 $ret = true;
639 foreach ( $rows as $v ) {
640 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
641 $ret = false;
642 }
643 }
644 } else {
645 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
646 }
647
648 return $ret;
649 }
650
651 /**
652 * Returns the size of a text field, or -1 for "unlimited"
653 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
654 *
655 * @param string $table
656 * @param string $field
657 * @return int
658 */
659 function textFieldSize( $table, $field ) {
660 return -1;
661 }
662
663 /**
664 * @return bool
665 */
666 function unionSupportsOrderAndLimit() {
667 return false;
668 }
669
670 /**
671 * @param string[] $sqls
672 * @param bool $all Whether to "UNION ALL" or not
673 * @return string
674 */
675 function unionQueries( $sqls, $all ) {
676 $glue = $all ? ' UNION ALL ' : ' UNION ';
677
678 return implode( $glue, $sqls );
679 }
680
681 /**
682 * @return bool
683 */
684 function wasDeadlock() {
685 return $this->lastErrno() == 5; // SQLITE_BUSY
686 }
687
688 /**
689 * @return bool
690 */
691 function wasErrorReissuable() {
692 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
693 }
694
695 /**
696 * @return bool
697 */
698 function wasReadOnlyError() {
699 return $this->lastErrno() == 8; // SQLITE_READONLY;
700 }
701
702 /**
703 * @return string Wikitext of a link to the server software's web site
704 */
705 public function getSoftwareLink() {
706 return "[{{int:version-db-sqlite-url}} SQLite]";
707 }
708
709 /**
710 * @return string Version information from the database
711 */
712 function getServerVersion() {
713 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
714
715 return $ver;
716 }
717
718 /**
719 * Get information about a given field
720 * Returns false if the field does not exist.
721 *
722 * @param string $table
723 * @param string $field
724 * @return SQLiteField|bool False on failure
725 */
726 function fieldInfo( $table, $field ) {
727 $tableName = $this->tableName( $table );
728 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
729 $res = $this->query( $sql, __METHOD__ );
730 foreach ( $res as $row ) {
731 if ( $row->name == $field ) {
732 return new SQLiteField( $row, $tableName );
733 }
734 }
735
736 return false;
737 }
738
739 protected function doBegin( $fname = '' ) {
740 if ( $this->trxMode ) {
741 $this->query( "BEGIN {$this->trxMode}", $fname );
742 } else {
743 $this->query( 'BEGIN', $fname );
744 }
745 $this->mTrxLevel = 1;
746 }
747
748 /**
749 * @param string $s
750 * @return string
751 */
752 function strencode( $s ) {
753 return substr( $this->addQuotes( $s ), 1, -1 );
754 }
755
756 /**
757 * @param string $b
758 * @return Blob
759 */
760 function encodeBlob( $b ) {
761 return new Blob( $b );
762 }
763
764 /**
765 * @param Blob|string $b
766 * @return string
767 */
768 function decodeBlob( $b ) {
769 if ( $b instanceof Blob ) {
770 $b = $b->fetch();
771 }
772
773 return $b;
774 }
775
776 /**
777 * @param string|int|null|bool|Blob $s
778 * @return string|int
779 */
780 function addQuotes( $s ) {
781 if ( $s instanceof Blob ) {
782 return "x'" . bin2hex( $s->fetch() ) . "'";
783 } elseif ( is_bool( $s ) ) {
784 return (int)$s;
785 } elseif ( strpos( $s, "\0" ) !== false ) {
786 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
787 // This is a known limitation of SQLite's mprintf function which PDO
788 // should work around, but doesn't. I have reported this to php.net as bug #63419:
789 // https://bugs.php.net/bug.php?id=63419
790 // There was already a similar report for SQLite3::escapeString, bug #62361:
791 // https://bugs.php.net/bug.php?id=62361
792 // There is an additional bug regarding sorting this data after insert
793 // on older versions of sqlite shipped with ubuntu 12.04
794 // https://phabricator.wikimedia.org/T74367
795 $this->queryLogger->debug(
796 __FUNCTION__ .
797 ': Quoting value containing null byte. ' .
798 'For consistency all binary data should have been ' .
799 'first processed with self::encodeBlob()'
800 );
801 return "x'" . bin2hex( $s ) . "'";
802 } else {
803 return $this->mConn->quote( $s );
804 }
805 }
806
807 /**
808 * @return string
809 */
810 function buildLike() {
811 $params = func_get_args();
812 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
813 $params = $params[0];
814 }
815
816 return parent::buildLike( $params ) . "ESCAPE '\' ";
817 }
818
819 /**
820 * @param string $field Field or column to cast
821 * @return string
822 * @since 1.28
823 */
824 public function buildStringCast( $field ) {
825 return 'CAST ( ' . $field . ' AS TEXT )';
826 }
827
828 /**
829 * No-op version of deadlockLoop
830 *
831 * @return mixed
832 */
833 public function deadlockLoop( /*...*/ ) {
834 $args = func_get_args();
835 $function = array_shift( $args );
836
837 return call_user_func_array( $function, $args );
838 }
839
840 /**
841 * @param string $s
842 * @return string
843 */
844 protected function replaceVars( $s ) {
845 $s = parent::replaceVars( $s );
846 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
847 // CREATE TABLE hacks to allow schema file sharing with MySQL
848
849 // binary/varbinary column type -> blob
850 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
851 // no such thing as unsigned
852 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
853 // INT -> INTEGER
854 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
855 // floating point types -> REAL
856 $s = preg_replace(
857 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
858 'REAL',
859 $s
860 );
861 // varchar -> TEXT
862 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
863 // TEXT normalization
864 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
865 // BLOB normalization
866 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
867 // BOOL -> INTEGER
868 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
869 // DATETIME -> TEXT
870 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
871 // No ENUM type
872 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
873 // binary collation type -> nothing
874 $s = preg_replace( '/\bbinary\b/i', '', $s );
875 // auto_increment -> autoincrement
876 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
877 // No explicit options
878 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
879 // AUTOINCREMENT should immedidately follow PRIMARY KEY
880 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
881 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
882 // No truncated indexes
883 $s = preg_replace( '/\(\d+\)/', '', $s );
884 // No FULLTEXT
885 $s = preg_replace( '/\bfulltext\b/i', '', $s );
886 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
887 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
888 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
889 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
890 // INSERT IGNORE --> INSERT OR IGNORE
891 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
892 }
893
894 return $s;
895 }
896
897 public function lock( $lockName, $method, $timeout = 5 ) {
898 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
899 if ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) ) {
900 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
901 }
902 }
903
904 return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
905 }
906
907 public function unlock( $lockName, $method ) {
908 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isOK();
909 }
910
911 /**
912 * Build a concatenation list to feed into a SQL query
913 *
914 * @param string[] $stringList
915 * @return string
916 */
917 function buildConcat( $stringList ) {
918 return '(' . implode( ') || (', $stringList ) . ')';
919 }
920
921 public function buildGroupConcatField(
922 $delim, $table, $field, $conds = '', $join_conds = []
923 ) {
924 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
925
926 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
927 }
928
929 /**
930 * @param string $oldName
931 * @param string $newName
932 * @param bool $temporary
933 * @param string $fname
934 * @return bool|ResultWrapper
935 * @throws RuntimeException
936 */
937 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
938 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
939 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
940 $obj = $this->fetchObject( $res );
941 if ( !$obj ) {
942 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
943 }
944 $sql = $obj->sql;
945 $sql = preg_replace(
946 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
947 $this->addIdentifierQuotes( $newName ),
948 $sql,
949 1
950 );
951 if ( $temporary ) {
952 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
953 $this->queryLogger->debug(
954 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
955 } else {
956 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
957 }
958 }
959
960 $res = $this->query( $sql, $fname );
961
962 // Take over indexes
963 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
964 foreach ( $indexList as $index ) {
965 if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
966 continue;
967 }
968
969 if ( $index->unique ) {
970 $sql = 'CREATE UNIQUE INDEX';
971 } else {
972 $sql = 'CREATE INDEX';
973 }
974 // Try to come up with a new index name, given indexes have database scope in SQLite
975 $indexName = $newName . '_' . $index->name;
976 $sql .= ' ' . $indexName . ' ON ' . $newName;
977
978 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
979 $fields = [];
980 foreach ( $indexInfo as $indexInfoRow ) {
981 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
982 }
983
984 $sql .= '(' . implode( ',', $fields ) . ')';
985
986 $this->query( $sql );
987 }
988
989 return $res;
990 }
991
992 /**
993 * List all tables on the database
994 *
995 * @param string $prefix Only show tables with this prefix, e.g. mw_
996 * @param string $fname Calling function name
997 *
998 * @return array
999 */
1000 function listTables( $prefix = null, $fname = __METHOD__ ) {
1001 $result = $this->select(
1002 'sqlite_master',
1003 'name',
1004 "type='table'"
1005 );
1006
1007 $endArray = [];
1008
1009 foreach ( $result as $table ) {
1010 $vars = get_object_vars( $table );
1011 $table = array_pop( $vars );
1012
1013 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1014 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1015 $endArray[] = $table;
1016 }
1017 }
1018 }
1019
1020 return $endArray;
1021 }
1022
1023 /**
1024 * Override due to no CASCADE support
1025 *
1026 * @param string $tableName
1027 * @param string $fName
1028 * @return bool|ResultWrapper
1029 * @throws DBReadOnlyError
1030 */
1031 public function dropTable( $tableName, $fName = __METHOD__ ) {
1032 if ( !$this->tableExists( $tableName, $fName ) ) {
1033 return false;
1034 }
1035 $sql = "DROP TABLE " . $this->tableName( $tableName );
1036
1037 return $this->query( $sql, $fName );
1038 }
1039
1040 protected function requiresDatabaseUser() {
1041 return false; // just a file
1042 }
1043
1044 /**
1045 * @return string
1046 */
1047 public function __toString() {
1048 return 'SQLite ' . (string)$this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
1049 }
1050 }