30use InvalidArgumentException;
71 if ( isset( $p[
'dbFilePath'] ) ) {
72 $this->dbPath = $p[
'dbFilePath'];
73 $lockDomain = md5( $this->dbPath );
74 } elseif ( isset( $p[
'dbDirectory'] ) ) {
75 $this->dbDir = $p[
'dbDirectory'];
76 $lockDomain = $p[
'dbname'];
78 throw new InvalidArgumentException(
"Need 'dbDirectory' or 'dbFilePath' parameter." );
81 $this->trxMode = isset( $p[
'trxMode'] ) ? strtoupper( $p[
'trxMode'] ) :
null;
82 if ( $this->trxMode &&
83 !in_array( $this->trxMode, [
'DEFERRED',
'IMMEDIATE',
'EXCLUSIVE' ] )
85 $this->trxMode =
null;
86 $this->queryLogger->warning(
"Invalid SQLite transaction mode provided." );
90 'domain' => $lockDomain,
91 'lockDirectory' =>
"{$this->dbDir}/locks"
94 parent::__construct( $p );
98 return [ self::ATTR_DB_LEVEL_LOCKING =>
true ];
111 $p[
'dbFilePath'] = $filename;
112 $p[
'schema'] =
false;
113 $p[
'tablePrefix'] =
'';
121 if ( $this->dbPath !==
null ) {
123 $this->
openFile( $this->dbPath, $this->connectionParams[
'dbname'] );
124 } elseif ( $this->dbDir !==
null ) {
126 if ( strlen( $this->connectionParams[
'dbname'] ) ) {
128 $this->connectionParams[
'host'],
129 $this->connectionParams[
'user'],
130 $this->connectionParams[
'password'],
131 $this->connectionParams[
'dbname']
135 $this->connLogger->debug( __METHOD__ .
': no database opened.' );
138 throw new InvalidArgumentException(
"Need 'dbDirectory' or 'dbFilePath' parameter." );
172 if ( !is_readable( $fileName ) ) {
192 $this->dbPath = $fileName;
194 if ( $this->
flags & self::DBO_PERSISTENT ) {
195 $this->conn =
new PDO(
"sqlite:$fileName",
'',
'',
196 [ PDO::ATTR_PERSISTENT =>
true ] );
198 $this->conn =
new PDO(
"sqlite:$fileName",
'',
'' );
200 }
catch ( PDOException
$e ) {
201 $err =
$e->getMessage();
204 if ( !$this->conn ) {
205 $this->queryLogger->debug(
"DB connection error: $err\n" );
209 $this->opened = is_object( $this->conn );
210 if ( $this->opened ) {
212 # Set error codes only, don't raise exceptions
213 $this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
214 # Enforce LIKE to be case sensitive, just like MySQL
215 $this->
query(
'PRAGMA case_sensitive_like = 1' );
248 return "$dir/$dbName.sqlite";
256 if ( self::$fulltextEnabled ===
null ) {
257 self::$fulltextEnabled =
false;
258 $table = $this->
tableName(
'searchindex' );
259 $res = $this->
query(
"SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
261 $row =
$res->fetchRow();
262 self::$fulltextEnabled = stristr( $row[
'sql'],
'fts' ) !==
false;
274 static $cachedResult =
null;
275 if ( $cachedResult !==
null ) {
276 return $cachedResult;
278 $cachedResult =
false;
279 $table =
'dummy_search_test';
282 if ( $db->query(
"CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__,
true ) ) {
283 $cachedResult =
'FTS3';
287 return $cachedResult;
307 return $this->
query(
"ATTACH DATABASE $file AS $name",
$fname );
311 return parent::isWriteQuery( $sql ) && !preg_match(
'/^(ATTACH|PRAGMA)\b/i', $sql );
315 return parent::isTransactableQuery( $sql ) && !in_array(
317 [
'ATTACH',
'PRAGMA' ],
330 if (
$res ===
false ) {
335 $this->lastAffectedRowCount = $r->rowCount();
363 $cur = current( $r );
364 if ( is_array( $cur ) ) {
367 foreach ( $cur as $k => $v ) {
368 if ( !is_numeric( $k ) ) {
389 $cur = current( $r );
390 if ( is_array( $cur ) ) {
417 if ( is_array( $r ) && count( $r ) > 0 ) {
419 return count( $r[0] ) / 2;
433 if ( is_array( $r ) ) {
434 $keys = array_keys( $r[0] );
451 if ( strpos( $name,
'sqlite_' ) === 0 ) {
455 return str_replace(
'"',
'', parent::tableName( $name, $format ) );
480 for ( $i = 0; $i < $row; $i++ ) {
490 if ( !is_object( $this->conn ) ) {
491 return "Cannot return last error, no db connection";
493 $e = $this->conn->errorInfo();
495 return isset(
$e[2] ) ?
$e[2] :
'';
502 if ( !is_object( $this->conn ) ) {
503 return "Cannot return last error, no db connection";
505 $info = $this->conn->errorInfo();
531 if ( !
$res ||
$res->numRows() == 0 ) {
535 foreach (
$res as $row ) {
536 $info[] = $row->name;
549 $row = $this->
selectRow(
'sqlite_master',
'*',
554 if ( !$row || !isset( $row->sql ) ) {
559 $indexPos = strpos( $row->sql,
'INDEX' );
560 if ( $indexPos ===
false ) {
563 $firstPart = substr( $row->sql, 0, $indexPos );
564 $options = explode(
' ', $firstPart );
566 return in_array(
'UNIQUE',
$options );
577 if ( is_numeric( $k ) && ( $v ==
'FOR UPDATE' || $v ==
'LOCK IN SHARE MODE' ) ) {
582 return parent::makeSelectOptions(
$options );
601 # SQLite uses OR IGNORE not just IGNORE
603 if ( $v ==
'IGNORE' ) {
618 return parent::makeInsertOptions(
$options );
630 if ( !count( $a ) ) {
634 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
635 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
637 foreach ( $a as $v ) {
638 if ( !parent::insert( $table, $v,
"$fname/multi-row",
$options ) ) {
643 $ret = parent::insert( $table, $a,
"$fname/single-row",
$options );
657 if ( !count(
$rows ) ) {
661 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
662 if ( isset(
$rows[0] ) && is_array(
$rows[0] ) ) {
664 foreach (
$rows as $v ) {
665 if ( !$this->
nativeReplace( $table, $v,
"$fname/multi-row" ) ) {
701 $glue = $all ?
' UNION ALL ' :
' UNION ';
703 return implode( $glue, $sqls );
736 return "[{{int:version-db-sqlite-url}} SQLite]";
758 $sql =
'PRAGMA table_info(' . $this->
addQuotes( $tableName ) .
')';
760 foreach (
$res as $row ) {
761 if ( $row->name == $field ) {
770 if ( $this->trxMode ) {
791 return new Blob( $b );
799 if ( $b instanceof
Blob ) {
811 if (
$s instanceof
Blob ) {
812 return "x'" . bin2hex(
$s->fetch() ) .
"'";
813 } elseif ( is_bool(
$s ) ) {
815 } elseif ( strpos( (
string)
$s,
"\0" ) !==
false ) {
825 $this->queryLogger->debug(
827 ': Quoting value containing null byte. ' .
828 'For consistency all binary data should have been ' .
829 'first processed with self::encodeBlob()'
831 return "x'" . bin2hex( (
string)
$s ) .
"'";
840 if ( $length !==
null ) {
843 return 'SUBSTR(' . implode(
',',
$params ) .
')';
852 return 'CAST ( ' . $field .
' AS TEXT )';
861 $args = func_get_args();
862 $function = array_shift(
$args );
864 return call_user_func_array( $function,
$args );
872 $s = parent::replaceVars(
$s );
873 if ( preg_match(
'/^\s*(CREATE|ALTER) TABLE/i',
$s ) ) {
877 $s = preg_replace(
'/\b(var)?binary(\(\d+\))/i',
'BLOB',
$s );
879 $s = preg_replace(
'/\b(un)?signed\b/i',
'',
$s );
881 $s = preg_replace(
'/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i',
'INTEGER',
$s );
884 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
889 $s = preg_replace(
'/\b(var)?char\s*\(.*?\)/i',
'TEXT',
$s );
891 $s = preg_replace(
'/\b(tiny|medium|long)text\b/i',
'TEXT',
$s );
893 $s = preg_replace(
'/\b(tiny|small|medium|long|)blob\b/i',
'BLOB',
$s );
895 $s = preg_replace(
'/\bbool(ean)?\b/i',
'INTEGER',
$s );
897 $s = preg_replace(
'/\b(datetime|timestamp)\b/i',
'TEXT',
$s );
899 $s = preg_replace(
'/\benum\s*\([^)]*\)/i',
'TEXT',
$s );
901 $s = preg_replace(
'/\bbinary\b/i',
'',
$s );
903 $s = preg_replace(
'/\bauto_increment\b/i',
'AUTOINCREMENT',
$s );
905 $s = preg_replace(
'/\)[^);]*(;?)\s*$/',
')\1',
$s );
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 ) ) {
910 $s = preg_replace(
'/\(\d+\)/',
'',
$s );
912 $s = preg_replace(
'/\bfulltext\b/i',
'',
$s );
913 } elseif ( preg_match(
'/^\s*DROP INDEX/i',
$s ) ) {
915 $s = preg_replace(
'/\sON\s+[^\s]*/i',
'',
$s );
916 } elseif ( preg_match(
'/^\s*INSERT IGNORE\b/i',
$s ) ) {
918 $s = preg_replace(
'/^\s*INSERT IGNORE\b/i',
'INSERT OR IGNORE',
$s );
924 public function lock( $lockName, $method, $timeout = 5 ) {
925 if ( !is_dir(
"{$this->dbDir}/locks" ) ) {
926 if ( !is_writable( $this->dbDir ) || !mkdir(
"{$this->dbDir}/locks" ) ) {
927 throw new DBError( $this,
"Cannot create directory \"{$this->dbDir}/locks\"." );
934 public function unlock( $lockName, $method ) {
945 return '(' . implode(
') || (', $stringList ) .
')';
949 $delim, $table, $field, $conds =
'', $join_conds = []
951 $fld =
"group_concat($field," . $this->
addQuotes( $delim ) .
')';
953 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
965 $res = $this->
query(
"SELECT sql FROM sqlite_master WHERE tbl_name=" .
969 throw new RuntimeException(
"Couldn't retrieve structure for table $oldName" );
973 '/(?<=\W)"?' . preg_quote( trim( $this->
addIdentifierQuotes( $oldName ),
'"' ) ) .
'"?(?=\W)/',
979 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
980 $this->queryLogger->debug(
981 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
983 $sql = str_replace(
'CREATE TABLE',
'CREATE TEMPORARY TABLE', $sql );
990 $indexList = $this->
query(
'PRAGMA INDEX_LIST(' . $this->
addQuotes( $oldName ) .
')' );
991 foreach ( $indexList as $index ) {
992 if ( strpos( $index->name,
'sqlite_autoindex' ) === 0 ) {
996 if ( $index->unique ) {
997 $sql =
'CREATE UNIQUE INDEX';
999 $sql =
'CREATE INDEX';
1002 $indexName = $newName .
'_' . $index->name;
1003 $sql .=
' ' . $indexName .
' ON ' . $newName;
1005 $indexInfo = $this->
query(
'PRAGMA INDEX_INFO(' . $this->
addQuotes( $index->name ) .
')' );
1007 foreach ( $indexInfo as $indexInfoRow ) {
1008 $fields[$indexInfoRow->seqno] = $indexInfoRow->name;
1011 $sql .=
'(' . implode(
',', $fields ) .
')';
1013 $this->
query( $sql );
1036 foreach ( $result as $table ) {
1037 $vars = get_object_vars( $table );
1038 $table = array_pop(
$vars );
1040 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1041 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
1042 $endArray[] = $table;
1058 public function dropTable( $tableName, $fName = __METHOD__ ) {
1059 if ( !$this->
tableExists( $tableName, $fName ) ) {
1062 $sql =
"DROP TABLE " . $this->
tableName( $tableName );
1064 return $this->
query( $sql, $fName );
1068 parent::setTableAliases( $aliases );
1069 foreach ( $this->tableAliases as
$params ) {
1070 if ( isset( $this->alreadyAttached[
$params[
'dbname']] ) ) {
1074 $this->alreadyAttached[
$params[
'dbname']] =
true;
1081 $this->
query(
"DELETE FROM $encTable WHERE name = $encName",
$fname );
1092 return is_object( $this->conn )
1093 ?
'SQLite ' . (
string)$this->conn->getAttribute( PDO::ATTR_SERVER_VERSION )
1094 :
'(not connected)';
1101 return parent::getBindingHandle();
1105class_alias( DatabaseSqlite::class,
'DatabaseSqlite' );
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Simple version of LockManager based on using FS lock files.
Class for handling resource locking.
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like select() and insert() are usually more convenient. They take care of things like table prefixes and escaping for you. If you really need to make your own SQL
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database etc For and for historical it also represents a few features of articles that don t involve their such as access rights See also title txt Article Encapsulates access to the page table of the database The object represents a an and maintains state such as flags
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Allows to change the fields on the form that will be generated $name
returning false will NOT prevent logging $e
if(is_array($mode)) switch( $mode) $input