Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / db / DatabaseSqlite.php
blob9d0a0f71240153dc84f70f8afd773a89b2fe75a4
1 <?php
2 /**
3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
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.
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.
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
21 * @file
22 * @ingroup Database
25 /**
26 * @ingroup Database
28 class DatabaseSqlite extends Database {
29 /** @var bool Whether full text is enabled */
30 private static $fulltextEnabled = null;
32 /** @var string Directory */
33 protected $dbDir;
35 /** @var string File name for SQLite database file */
36 protected $dbPath;
38 /** @var string Transaction mode */
39 protected $trxMode;
41 /** @var int The number of rows affected as an integer */
42 protected $mAffectedRows;
44 /** @var resource */
45 protected $mLastResult;
47 /** @var PDO */
48 protected $mConn;
50 /** @var FSLockManager (hopefully on the same server as the DB) */
51 protected $lockMgr;
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
61 function __construct( array $p ) {
62 global $wgSharedDB, $wgSQLiteDataDir;
64 $this->dbDir = isset( $p['dbDirectory'] ) ? $p['dbDirectory'] : $wgSQLiteDataDir;
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 } else {
73 $this->mDBname = $p['dbname'];
74 // Stock wiki mode using standard file names per DB.
75 parent::__construct( $p );
76 // Super doesn't open when $user is false, but we can work with $dbName
77 if ( $p['dbname'] && !$this->isOpen() ) {
78 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
79 if ( $wgSharedDB ) {
80 $this->attachDatabase( $wgSharedDB );
86 $this->trxMode = isset( $p['trxMode'] ) ? strtoupper( $p['trxMode'] ) : null;
87 if ( $this->trxMode &&
88 !in_array( $this->trxMode, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
89 ) {
90 $this->trxMode = null;
91 wfWarn( "Invalid SQLite transaction mode provided." );
94 $this->lockMgr = new FSLockManager( [ 'lockDirectory' => "{$this->dbDir}/locks" ] );
97 /**
98 * @param string $filename
99 * @param array $p Options map; supports:
100 * - flags : (same as __construct counterpart)
101 * - trxMode : (same as __construct counterpart)
102 * - dbDirectory : (same as __construct counterpart)
103 * @return DatabaseSqlite
104 * @since 1.25
106 public static function newStandaloneInstance( $filename, array $p = [] ) {
107 $p['dbFilePath'] = $filename;
108 $p['schema'] = false;
109 $p['tablePrefix'] = '';
111 return DatabaseBase::factory( 'sqlite', $p );
115 * @return string
117 function getType() {
118 return 'sqlite';
122 * @todo Check if it should be true like parent class
124 * @return bool
126 function implicitGroupby() {
127 return false;
130 /** Open an SQLite database and return a resource handle to it
131 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
133 * @param string $server
134 * @param string $user
135 * @param string $pass
136 * @param string $dbName
138 * @throws DBConnectionError
139 * @return PDO
141 function open( $server, $user, $pass, $dbName ) {
142 $this->close();
143 $fileName = self::generateFileName( $this->dbDir, $dbName );
144 if ( !is_readable( $fileName ) ) {
145 $this->mConn = false;
146 throw new DBConnectionError( $this, "SQLite database not accessible" );
148 $this->openFile( $fileName );
150 return $this->mConn;
154 * Opens a database file
156 * @param string $fileName
157 * @throws DBConnectionError
158 * @return PDO|bool SQL connection or false if failed
160 protected function openFile( $fileName ) {
161 $err = false;
163 $this->dbPath = $fileName;
164 try {
165 if ( $this->mFlags & DBO_PERSISTENT ) {
166 $this->mConn = new PDO( "sqlite:$fileName", '', '',
167 [ PDO::ATTR_PERSISTENT => true ] );
168 } else {
169 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
171 } catch ( PDOException $e ) {
172 $err = $e->getMessage();
175 if ( !$this->mConn ) {
176 wfDebug( "DB connection error: $err\n" );
177 throw new DBConnectionError( $this, $err );
180 $this->mOpened = !!$this->mConn;
181 if ( $this->mOpened ) {
182 # Set error codes only, don't raise exceptions
183 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
184 # Enforce LIKE to be case sensitive, just like MySQL
185 $this->query( 'PRAGMA case_sensitive_like = 1' );
187 return $this->mConn;
190 return false;
194 * @return string SQLite DB file path
195 * @since 1.25
197 public function getDbFilePath() {
198 return $this->dbPath;
202 * Does not actually close the connection, just destroys the reference for GC to do its work
203 * @return bool
205 protected function closeConnection() {
206 $this->mConn = null;
208 return true;
212 * Generates a database file name. Explicitly public for installer.
213 * @param string $dir Directory where database resides
214 * @param string $dbName Database name
215 * @return string
217 public static function generateFileName( $dir, $dbName ) {
218 return "$dir/$dbName.sqlite";
222 * Check if the searchindext table is FTS enabled.
223 * @return bool False if not enabled.
225 function checkForEnabledSearch() {
226 if ( self::$fulltextEnabled === null ) {
227 self::$fulltextEnabled = false;
228 $table = $this->tableName( 'searchindex' );
229 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
230 if ( $res ) {
231 $row = $res->fetchRow();
232 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
236 return self::$fulltextEnabled;
240 * Returns version of currently supported SQLite fulltext search module or false if none present.
241 * @return string
243 static function getFulltextSearchModule() {
244 static $cachedResult = null;
245 if ( $cachedResult !== null ) {
246 return $cachedResult;
248 $cachedResult = false;
249 $table = 'dummy_search_test';
251 $db = self::newStandaloneInstance( ':memory:' );
252 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
253 $cachedResult = 'FTS3';
255 $db->close();
257 return $cachedResult;
261 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
262 * for details.
264 * @param string $name Database name to be used in queries like
265 * SELECT foo FROM dbname.table
266 * @param bool|string $file Database file name. If omitted, will be generated
267 * using $name and configured data directory
268 * @param string $fname Calling function name
269 * @return ResultWrapper
271 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
272 if ( !$file ) {
273 $file = self::generateFileName( $this->dbDir, $name );
275 $file = $this->addQuotes( $file );
277 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
281 * @see DatabaseBase::isWriteQuery()
283 * @param string $sql
284 * @return bool
286 function isWriteQuery( $sql ) {
287 return parent::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
291 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
293 * @param string $sql
294 * @return bool|ResultWrapper
296 protected function doQuery( $sql ) {
297 $res = $this->mConn->query( $sql );
298 if ( $res === false ) {
299 return false;
300 } else {
301 $r = $res instanceof ResultWrapper ? $res->result : $res;
302 $this->mAffectedRows = $r->rowCount();
303 $res = new ResultWrapper( $this, $r->fetchAll() );
306 return $res;
310 * @param ResultWrapper|mixed $res
312 function freeResult( $res ) {
313 if ( $res instanceof ResultWrapper ) {
314 $res->result = null;
315 } else {
316 $res = null;
321 * @param ResultWrapper|array $res
322 * @return stdClass|bool
324 function fetchObject( $res ) {
325 if ( $res instanceof ResultWrapper ) {
326 $r =& $res->result;
327 } else {
328 $r =& $res;
331 $cur = current( $r );
332 if ( is_array( $cur ) ) {
333 next( $r );
334 $obj = new stdClass;
335 foreach ( $cur as $k => $v ) {
336 if ( !is_numeric( $k ) ) {
337 $obj->$k = $v;
341 return $obj;
344 return false;
348 * @param ResultWrapper|mixed $res
349 * @return array|bool
351 function fetchRow( $res ) {
352 if ( $res instanceof ResultWrapper ) {
353 $r =& $res->result;
354 } else {
355 $r =& $res;
357 $cur = current( $r );
358 if ( is_array( $cur ) ) {
359 next( $r );
361 return $cur;
364 return false;
368 * The PDO::Statement class implements the array interface so count() will work
370 * @param ResultWrapper|array $res
371 * @return int
373 function numRows( $res ) {
374 $r = $res instanceof ResultWrapper ? $res->result : $res;
376 return count( $r );
380 * @param ResultWrapper $res
381 * @return int
383 function numFields( $res ) {
384 $r = $res instanceof ResultWrapper ? $res->result : $res;
385 if ( is_array( $r ) && count( $r ) > 0 ) {
386 // The size of the result array is twice the number of fields. (Bug: 65578)
387 return count( $r[0] ) / 2;
388 } else {
389 // If the result is empty return 0
390 return 0;
395 * @param ResultWrapper $res
396 * @param int $n
397 * @return bool
399 function fieldName( $res, $n ) {
400 $r = $res instanceof ResultWrapper ? $res->result : $res;
401 if ( is_array( $r ) ) {
402 $keys = array_keys( $r[0] );
404 return $keys[$n];
407 return false;
411 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
413 * @param string $name
414 * @param string $format
415 * @return string
417 function tableName( $name, $format = 'quoted' ) {
418 // table names starting with sqlite_ are reserved
419 if ( strpos( $name, 'sqlite_' ) === 0 ) {
420 return $name;
423 return str_replace( '"', '', parent::tableName( $name, $format ) );
427 * Index names have DB scope
429 * @param string $index
430 * @return string
432 protected function indexName( $index ) {
433 return $index;
437 * This must be called after nextSequenceVal
439 * @return int
441 function insertId() {
442 // PDO::lastInsertId yields a string :(
443 return intval( $this->mConn->lastInsertId() );
447 * @param ResultWrapper|array $res
448 * @param int $row
450 function dataSeek( $res, $row ) {
451 if ( $res instanceof ResultWrapper ) {
452 $r =& $res->result;
453 } else {
454 $r =& $res;
456 reset( $r );
457 if ( $row > 0 ) {
458 for ( $i = 0; $i < $row; $i++ ) {
459 next( $r );
465 * @return string
467 function lastError() {
468 if ( !is_object( $this->mConn ) ) {
469 return "Cannot return last error, no db connection";
471 $e = $this->mConn->errorInfo();
473 return isset( $e[2] ) ? $e[2] : '';
477 * @return string
479 function lastErrno() {
480 if ( !is_object( $this->mConn ) ) {
481 return "Cannot return last error, no db connection";
482 } else {
483 $info = $this->mConn->errorInfo();
485 return $info[1];
490 * @return int
492 function affectedRows() {
493 return $this->mAffectedRows;
497 * Returns information about an index
498 * Returns false if the index does not exist
499 * - if errors are explicitly ignored, returns NULL on failure
501 * @param string $table
502 * @param string $index
503 * @param string $fname
504 * @return array
506 function indexInfo( $table, $index, $fname = __METHOD__ ) {
507 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
508 $res = $this->query( $sql, $fname );
509 if ( !$res ) {
510 return null;
512 if ( $res->numRows() == 0 ) {
513 return false;
515 $info = [];
516 foreach ( $res as $row ) {
517 $info[] = $row->name;
520 return $info;
524 * @param string $table
525 * @param string $index
526 * @param string $fname
527 * @return bool|null
529 function indexUnique( $table, $index, $fname = __METHOD__ ) {
530 $row = $this->selectRow( 'sqlite_master', '*',
532 'type' => 'index',
533 'name' => $this->indexName( $index ),
534 ], $fname );
535 if ( !$row || !isset( $row->sql ) ) {
536 return null;
539 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
540 $indexPos = strpos( $row->sql, 'INDEX' );
541 if ( $indexPos === false ) {
542 return null;
544 $firstPart = substr( $row->sql, 0, $indexPos );
545 $options = explode( ' ', $firstPart );
547 return in_array( 'UNIQUE', $options );
551 * Filter the options used in SELECT statements
553 * @param array $options
554 * @return array
556 function makeSelectOptions( $options ) {
557 foreach ( $options as $k => $v ) {
558 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
559 $options[$k] = '';
563 return parent::makeSelectOptions( $options );
567 * @param array $options
568 * @return string
570 protected function makeUpdateOptionsArray( $options ) {
571 $options = parent::makeUpdateOptionsArray( $options );
572 $options = self::fixIgnore( $options );
574 return $options;
578 * @param array $options
579 * @return array
581 static function fixIgnore( $options ) {
582 # SQLite uses OR IGNORE not just IGNORE
583 foreach ( $options as $k => $v ) {
584 if ( $v == 'IGNORE' ) {
585 $options[$k] = 'OR IGNORE';
589 return $options;
593 * @param array $options
594 * @return string
596 function makeInsertOptions( $options ) {
597 $options = self::fixIgnore( $options );
599 return parent::makeInsertOptions( $options );
603 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
604 * @param string $table
605 * @param array $a
606 * @param string $fname
607 * @param array $options
608 * @return bool
610 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
611 if ( !count( $a ) ) {
612 return true;
615 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
616 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
617 $ret = true;
618 foreach ( $a as $v ) {
619 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
620 $ret = false;
623 } else {
624 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
627 return $ret;
631 * @param string $table
632 * @param array $uniqueIndexes Unused
633 * @param string|array $rows
634 * @param string $fname
635 * @return bool|ResultWrapper
637 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
638 if ( !count( $rows ) ) {
639 return true;
642 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
643 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
644 $ret = true;
645 foreach ( $rows as $v ) {
646 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
647 $ret = false;
650 } else {
651 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
654 return $ret;
658 * Returns the size of a text field, or -1 for "unlimited"
659 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
661 * @param string $table
662 * @param string $field
663 * @return int
665 function textFieldSize( $table, $field ) {
666 return -1;
670 * @return bool
672 function unionSupportsOrderAndLimit() {
673 return false;
677 * @param string $sqls
678 * @param bool $all Whether to "UNION ALL" or not
679 * @return string
681 function unionQueries( $sqls, $all ) {
682 $glue = $all ? ' UNION ALL ' : ' UNION ';
684 return implode( $glue, $sqls );
688 * @return bool
690 function wasDeadlock() {
691 return $this->lastErrno() == 5; // SQLITE_BUSY
695 * @return bool
697 function wasErrorReissuable() {
698 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
702 * @return bool
704 function wasReadOnlyError() {
705 return $this->lastErrno() == 8; // SQLITE_READONLY;
709 * @return string Wikitext of a link to the server software's web site
711 public function getSoftwareLink() {
712 return "[{{int:version-db-sqlite-url}} SQLite]";
716 * @return string Version information from the database
718 function getServerVersion() {
719 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
721 return $ver;
725 * @return string User-friendly database information
727 public function getServerInfo() {
728 return wfMessage( self::getFulltextSearchModule()
729 ? 'sqlite-has-fts'
730 : 'sqlite-no-fts', $this->getServerVersion() )->text();
734 * Get information about a given field
735 * Returns false if the field does not exist.
737 * @param string $table
738 * @param string $field
739 * @return SQLiteField|bool False on failure
741 function fieldInfo( $table, $field ) {
742 $tableName = $this->tableName( $table );
743 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
744 $res = $this->query( $sql, __METHOD__ );
745 foreach ( $res as $row ) {
746 if ( $row->name == $field ) {
747 return new SQLiteField( $row, $tableName );
751 return false;
754 protected function doBegin( $fname = '' ) {
755 if ( $this->trxMode ) {
756 $this->query( "BEGIN {$this->trxMode}", $fname );
757 } else {
758 $this->query( 'BEGIN', $fname );
760 $this->mTrxLevel = 1;
764 * @param string $s
765 * @return string
767 function strencode( $s ) {
768 return substr( $this->addQuotes( $s ), 1, -1 );
772 * @param string $b
773 * @return Blob
775 function encodeBlob( $b ) {
776 return new Blob( $b );
780 * @param Blob|string $b
781 * @return string
783 function decodeBlob( $b ) {
784 if ( $b instanceof Blob ) {
785 $b = $b->fetch();
788 return $b;
792 * @param Blob|string $s
793 * @return string
795 function addQuotes( $s ) {
796 if ( $s instanceof Blob ) {
797 return "x'" . bin2hex( $s->fetch() ) . "'";
798 } elseif ( is_bool( $s ) ) {
799 return (int)$s;
800 } elseif ( strpos( $s, "\0" ) !== false ) {
801 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
802 // This is a known limitation of SQLite's mprintf function which PDO
803 // should work around, but doesn't. I have reported this to php.net as bug #63419:
804 // https://bugs.php.net/bug.php?id=63419
805 // There was already a similar report for SQLite3::escapeString, bug #62361:
806 // https://bugs.php.net/bug.php?id=62361
807 // There is an additional bug regarding sorting this data after insert
808 // on older versions of sqlite shipped with ubuntu 12.04
809 // https://phabricator.wikimedia.org/T74367
810 wfDebugLog(
811 __CLASS__,
812 __FUNCTION__ .
813 ': Quoting value containing null byte. ' .
814 'For consistency all binary data should have been ' .
815 'first processed with self::encodeBlob()'
817 return "x'" . bin2hex( $s ) . "'";
818 } else {
819 return $this->mConn->quote( $s );
824 * @return string
826 function buildLike() {
827 $params = func_get_args();
828 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
829 $params = $params[0];
832 return parent::buildLike( $params ) . "ESCAPE '\' ";
836 * @return string
838 public function getSearchEngine() {
839 return "SearchSqlite";
843 * No-op version of deadlockLoop
845 * @return mixed
847 public function deadlockLoop( /*...*/ ) {
848 $args = func_get_args();
849 $function = array_shift( $args );
851 return call_user_func_array( $function, $args );
855 * @param string $s
856 * @return string
858 protected function replaceVars( $s ) {
859 $s = parent::replaceVars( $s );
860 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
861 // CREATE TABLE hacks to allow schema file sharing with MySQL
863 // binary/varbinary column type -> blob
864 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
865 // no such thing as unsigned
866 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
867 // INT -> INTEGER
868 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
869 // floating point types -> REAL
870 $s = preg_replace(
871 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
872 'REAL',
875 // varchar -> TEXT
876 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
877 // TEXT normalization
878 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
879 // BLOB normalization
880 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
881 // BOOL -> INTEGER
882 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
883 // DATETIME -> TEXT
884 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
885 // No ENUM type
886 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
887 // binary collation type -> nothing
888 $s = preg_replace( '/\bbinary\b/i', '', $s );
889 // auto_increment -> autoincrement
890 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
891 // No explicit options
892 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
893 // AUTOINCREMENT should immedidately follow PRIMARY KEY
894 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
895 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
896 // No truncated indexes
897 $s = preg_replace( '/\(\d+\)/', '', $s );
898 // No FULLTEXT
899 $s = preg_replace( '/\bfulltext\b/i', '', $s );
900 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
901 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
902 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
903 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
904 // INSERT IGNORE --> INSERT OR IGNORE
905 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
908 return $s;
911 public function lock( $lockName, $method, $timeout = 5 ) {
912 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
913 if ( !is_writable( $this->dbDir ) || !mkdir( "{$this->dbDir}/locks" ) ) {
914 throw new DBError( "Cannot create directory \"{$this->dbDir}/locks\"." );
918 return $this->lockMgr->lock( [ $lockName ], LockManager::LOCK_EX, $timeout )->isOK();
921 public function unlock( $lockName, $method ) {
922 return $this->lockMgr->unlock( [ $lockName ], LockManager::LOCK_EX )->isOK();
926 * Build a concatenation list to feed into a SQL query
928 * @param string[] $stringList
929 * @return string
931 function buildConcat( $stringList ) {
932 return '(' . implode( ') || (', $stringList ) . ')';
935 public function buildGroupConcatField(
936 $delim, $table, $field, $conds = '', $join_conds = []
938 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
940 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
944 * @throws MWException
945 * @param string $oldName
946 * @param string $newName
947 * @param bool $temporary
948 * @param string $fname
949 * @return bool|ResultWrapper
951 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
952 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
953 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
954 $obj = $this->fetchObject( $res );
955 if ( !$obj ) {
956 throw new MWException( "Couldn't retrieve structure for table $oldName" );
958 $sql = $obj->sql;
959 $sql = preg_replace(
960 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
961 $this->addIdentifierQuotes( $newName ),
962 $sql,
965 if ( $temporary ) {
966 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
967 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
968 } else {
969 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
973 $res = $this->query( $sql, $fname );
975 // Take over indexes
976 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
977 foreach ( $indexList as $index ) {
978 if ( strpos( $index->name, 'sqlite_autoindex' ) === 0 ) {
979 continue;
982 if ( $index->unique ) {
983 $sql = 'CREATE UNIQUE INDEX';
984 } else {
985 $sql = 'CREATE INDEX';
987 // Try to come up with a new index name, given indexes have database scope in SQLite
988 $indexName = $newName . '_' . $index->name;
989 $sql .= ' ' . $indexName . ' ON ' . $newName;
991 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name ) . ')' );
992 $fields = [];
993 foreach ( $indexInfo as $indexInfoRow ) {
994 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
997 $sql .= '(' . implode( ',', $fields ) . ')';
999 $this->query( $sql );
1002 return $res;
1006 * List all tables on the database
1008 * @param string $prefix Only show tables with this prefix, e.g. mw_
1009 * @param string $fname Calling function name
1011 * @return array
1013 function listTables( $prefix = null, $fname = __METHOD__ ) {
1014 $result = $this->select(
1015 'sqlite_master',
1016 'name',
1017 "type='table'"
1020 $endArray = [];
1022 foreach ( $result as $table ) {
1023 $vars = get_object_vars( $table );
1024 $table = array_pop( $vars );
1026 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1027 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1028 $endArray[] = $table;
1033 return $endArray;
1037 * @return string
1039 public function __toString() {
1040 return 'SQLite ' . (string)$this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
1043 } // end DatabaseSqlite class
1046 * @ingroup Database
1048 class SQLiteField implements Field {
1049 private $info, $tableName;
1051 function __construct( $info, $tableName ) {
1052 $this->info = $info;
1053 $this->tableName = $tableName;
1056 function name() {
1057 return $this->info->name;
1060 function tableName() {
1061 return $this->tableName;
1064 function defaultValue() {
1065 if ( is_string( $this->info->dflt_value ) ) {
1066 // Typically quoted
1067 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
1068 return str_replace( "''", "'", $this->info->dflt_value );
1072 return $this->info->dflt_value;
1076 * @return bool
1078 function isNullable() {
1079 return !$this->info->notnull;
1082 function type() {
1083 return $this->info->type;
1085 } // end SQLiteField