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