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