Go to the documentation of this file.
25 use Wikimedia\Timestamp\ConvertibleTimestamp;
26 use Wikimedia\WaitConditionLoop;
57 $this->
port = $params[
'port'] ??
false;
58 $this->keywordTableMap =
$params[
'keywordTableMap'] ?? [];
77 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
78 "WHERE c.connamespace = n.oid AND conname = " .
90 # Test for Postgres support, to avoid suppressed fatal error
91 if ( !function_exists(
'pg_connect' ) ) {
94 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
95 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
96 "webserver and database)\n"
108 'dbname' => strlen( $dbName ) ? $dbName :
'postgres',
113 $connectVars[
'host'] =
$server;
115 if ( (
int)$this->
port > 0 ) {
116 $connectVars[
'port'] = (int)$this->
port;
119 $connectVars[
'sslmode'] = 1;
128 $this->conn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
129 }
catch ( Exception $ex ) {
136 if ( !$this->conn ) {
137 $this->queryLogger->debug(
138 "DB connection error\n" .
139 "Server: $server, Database: $dbName, User: $user, Password: " .
142 $this->queryLogger->debug( $this->
lastError() .
"\n" );
146 $this->opened =
true;
148 # If called from the command-line (e.g. importDump), only show errors
149 if ( $this->cliMode ) {
150 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
153 $this->
query(
"SET client_encoding='UTF8'", __METHOD__ );
154 $this->
query(
"SET datestyle = 'ISO, YMD'", __METHOD__ );
155 $this->
query(
"SET timezone = 'GMT'", __METHOD__ );
156 $this->
query(
"SET standard_conforming_strings = on", __METHOD__ );
157 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
160 $this->currentDomain =
new DatabaseDomain( $dbName, $schema, $tablePrefix );
166 if ( $this->coreSchema === $this->currentDomain->getSchema() ) {
171 return parent::relationSchemaQualifier();
191 $this->currentDomain = $domain;
204 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
211 return $this->conn ? pg_close( $this->conn ) :
true;
215 return parent::isTransactableQuery( $sql ) &&
216 !preg_match(
'/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
222 $sql = mb_convert_encoding( $sql,
'UTF-8' );
224 while (
$res = pg_get_result(
$conn ) ) {
225 pg_free_result(
$res );
227 if ( pg_send_query(
$conn, $sql ) ===
false ) {
228 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
230 $this->lastResultHandle = pg_get_result(
$conn );
231 if ( pg_result_error( $this->lastResultHandle ) ) {
242 PGSQL_DIAG_MESSAGE_PRIMARY,
243 PGSQL_DIAG_MESSAGE_DETAIL,
244 PGSQL_DIAG_MESSAGE_HINT,
245 PGSQL_DIAG_STATEMENT_POSITION,
246 PGSQL_DIAG_INTERNAL_POSITION,
247 PGSQL_DIAG_INTERNAL_QUERY,
249 PGSQL_DIAG_SOURCE_FILE,
250 PGSQL_DIAG_SOURCE_LINE,
251 PGSQL_DIAG_SOURCE_FUNCTION
253 foreach ( $diags
as $d ) {
254 $this->queryLogger->debug( sprintf(
"PgSQL ERROR(%d): %s\n",
255 $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
263 Wikimedia\suppressWarnings();
264 $ok = pg_free_result(
$res );
265 Wikimedia\restoreWarnings();
275 Wikimedia\suppressWarnings();
276 $row = pg_fetch_object(
$res );
277 Wikimedia\restoreWarnings();
278 # @todo FIXME: HACK HACK HACK HACK debug
280 # @todo hashar: not sure if the following test really trigger if the object
283 if ( pg_last_error(
$conn ) ) {
286 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
297 Wikimedia\suppressWarnings();
298 $row = pg_fetch_array(
$res );
299 Wikimedia\restoreWarnings();
302 if ( pg_last_error(
$conn ) ) {
305 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
313 if (
$res ===
false ) {
320 Wikimedia\suppressWarnings();
321 $n = pg_num_rows(
$res );
322 Wikimedia\restoreWarnings();
325 if ( pg_last_error(
$conn ) ) {
328 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
340 return pg_num_fields(
$res );
348 return pg_field_name(
$res, $n );
352 $res = $this->
query(
"SELECT lastval()" );
354 return is_null( $row[0] ) ? null : (int)$row[0];
362 return pg_result_seek(
$res, $row );
367 if ( $this->lastResultHandle ) {
368 return pg_result_error( $this->lastResultHandle );
370 return pg_last_error();
378 if ( $this->lastResultHandle ) {
379 return pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
386 if ( !$this->lastResultHandle ) {
390 return pg_affected_rows( $this->lastResultHandle );
413 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
414 $conds[] =
"$column IS NOT NULL";
423 if ( preg_match(
'/rows=(\d+)/', $row[0], $count ) ) {
424 $rows = (int)$count[1];
432 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
437 foreach (
$res as $row ) {
438 if ( $row->indexname == $this->indexName( $index ) ) {
447 if ( $schema ===
false ) {
450 $schemas = [ $schema ];
455 foreach ( $schemas
as $schema ) {
461 $sql = <<<__INDEXATTR__
465 i.indoption[s.g]
as option,
468 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
472 ON cis.oid=isub.indexrelid
474 ON cis.relnamespace = ns.oid
475 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
481 ON ci.oid=i.indexrelid
483 ON ct.oid = i.indrelid
485 ON ci.relnamespace =
n.oid
487 ci.relname=$eindex AND
n.nspname=$eschema
488 AND attrelid = ct.oid
489 AND i.indkey[s.g] = attnum
490 AND i.indclass[s.g] = opcls.oid
491 AND pg_am.oid = opcls.opcmethod
496 foreach (
$res as $row ) {
510 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
511 " AND indexdef LIKE 'CREATE UNIQUE%(" .
519 return $res->numRows() > 0;
537 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
538 if ( $forUpdateKey !==
false && $join_conds ) {
545 $alias =
key( $toCheck );
546 $name = $toCheck[$alias];
547 unset( $toCheck[$alias] );
549 $hasAlias = !is_numeric( $alias );
550 if ( !$hasAlias && is_string(
$name ) ) {
554 if ( !isset( $join_conds[$alias] ) ||
555 !preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
557 if ( is_array(
$name ) ) {
559 $toCheck = array_merge( $toCheck,
$name );
583 if ( !isset( $this->numericVersion ) ) {
591 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
599 $ignore = in_array(
'IGNORE',
$options );
601 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
603 if ( $this->numericVersion >= 9.5 || !$ignore ) {
612 $sql .=
'(' . $this->
makeList( $row ) .
')';
615 $sql .=
' ON CONFLICT DO NOTHING';
621 $numrowsinserted = 0;
623 $tok = $this->
startAtomic(
"$fname (outer)", self::ATOMIC_CANCELABLE );
627 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
629 $this->
startAtomic(
"$fname (inner)", self::ATOMIC_CANCELABLE );
638 if ( $e->errno !==
'23505' ) {
643 }
catch ( Exception
$e ) {
650 $this->affectedRowCount = $numrowsinserted;
665 return parent::makeUpdateOptionsArray(
$options );
688 $destTable, $srcTable, $varMap, $conds,
$fname = __METHOD__,
689 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
691 if ( !is_array( $insertOptions ) ) {
692 $insertOptions = [ $insertOptions ];
695 if ( in_array(
'IGNORE', $insertOptions ) ) {
698 $destTable = $this->
tableName( $destTable );
702 array_values( $varMap ),
709 $sql =
"INSERT INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
') ' .
710 $selectSql .
' ON CONFLICT DO NOTHING';
716 $destTable, $srcTable, $varMap, $conds,
$fname,
717 $insertOptions, $selectOptions, $selectJoinConds
722 return parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
$fname,
723 $insertOptions, $selectOptions, $selectJoinConds );
738 return $this->keywordTableMap[
$name] ??
$name;
761 $safeseq = str_replace(
"'",
"''", $seqName );
762 $res = $this->
query(
"SELECT currval('$safeseq')" );
771 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
772 FROM pg_class c, pg_attribute a, pg_type t
773 WHERE relname='$table' AND a.attrelid=c.oid AND
774 a.atttypid=t.oid and a.attname='$field'";
777 if ( $row->ftype ==
'varchar' ) {
778 $size = $row->size - 4;
787 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
802 static $codes = [
'08000',
'08003',
'08006',
'08001',
'08004',
'57P01',
'57P03',
'53300' ];
804 return in_array( $errno, $codes,
true );
812 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
817 $temporary = $temporary ?
'TEMPORARY' :
'';
819 $ret = $this->
query(
"CREATE $temporary TABLE $newNameE " .
820 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
$fname );
825 $res = $this->
query(
'SELECT attname FROM pg_class c'
826 .
' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
827 .
' JOIN pg_attribute a ON (a.attrelid = c.oid)'
828 .
' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
829 .
' WHERE relkind = \'r\''
831 .
' AND relname = ' . $this->
addQuotes( $oldName )
832 .
' AND adsrc LIKE \'nextval(%\'',
837 $field = $row->attname;
838 $newSeq =
"{$newName}_{$field}_seq";
842 $this->
query(
"CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
$fname );
844 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
853 $table = $this->
tableName( $table,
'raw' );
856 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
857 .
' WHERE relkind = \'r\''
858 .
' AND nspname = ' . $this->
addQuotes( $schema )
859 .
' AND relname = ' . $this->
addQuotes( $table ),
867 $res = $this->
query(
'SELECT adsrc FROM pg_attribute a'
868 .
' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
869 .
" WHERE a.attrelid = $oid"
870 .
' AND adsrc LIKE \'nextval(%\'',
876 'SELECT ' . preg_replace(
'/^nextval\((.+)\)$/',
'setval($1,1,false)', $row->adsrc ),
891 $eschemas = implode(
',', array_map( [ $this,
'addQuotes' ], $this->
getCoreSchemas() ) );
893 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
$fname );
897 $vars = get_object_vars( $table );
898 $table = array_pop(
$vars );
899 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
900 $endArray[] = $table;
908 $ct =
new ConvertibleTimestamp( $ts );
910 return $ct->getTimestamp( TS_POSTGRES );
932 if (
false === $limit ) {
933 $limit = strlen( $text ) - 1;
936 if (
'{}' == $text ) {
940 if (
'{' != $text[$offset] ) {
941 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
942 $text, $match, 0, $offset );
943 $offset += strlen( $match[0] );
944 $output[] = (
'"' != $match[1][0]
946 : stripcslashes( substr( $match[1], 1, -1 ) ) );
947 if (
'},' == $match[3] ) {
953 }
while ( $limit > $offset );
963 return '[{{int:version-db-postgres-url}} PostgreSQL]';
974 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
991 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
1010 $res = $this->
query(
"SHOW search_path", __METHOD__ );
1015 return explode(
",", $row[0] );
1026 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
1044 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
1046 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
1047 $this->coreSchema = $desiredSchema;
1048 $this->queryLogger->debug(
1049 "Schema \"" . $desiredSchema .
"\" already in the search path\n" );
1057 array_unshift( $search_path,
1060 $this->coreSchema = $desiredSchema;
1061 $this->queryLogger->debug(
1062 "Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1066 $this->queryLogger->debug(
1067 "Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1068 $this->coreSchema .
"\"\n" );
1071 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
1091 if ( $this->tempSchema ) {
1096 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1100 $this->tempSchema = $row->nspname;
1108 if ( !isset( $this->numericVersion ) ) {
1110 $versionInfo = pg_version(
$conn );
1111 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1113 $this->numericVersion =
'7.3 or earlier';
1114 } elseif ( isset( $versionInfo[
'server'] ) ) {
1116 $this->numericVersion = $versionInfo[
'server'];
1119 $this->numericVersion = pg_parameter_status(
$conn,
'server_version' );
1135 if ( !is_array( $types ) ) {
1136 $types = [ $types ];
1138 if ( $schema ===
false ) {
1141 $schemas = [ $schema ];
1145 foreach ( $schemas
as $schema ) {
1147 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1148 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1149 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1176 SELECT 1
FROM pg_class, pg_namespace, pg_trigger
1177 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1178 AND tgrelid=pg_class.oid
1179 AND nspname=%s AND relname=%s AND tgname=%s
1199 $exists = $this->
selectField(
'pg_rules',
'rulename',
1201 'rulename' => $rule,
1202 'tablename' => $table,
1207 return $exists === $rule;
1212 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1213 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1232 if ( !strlen( $schema ) ) {
1237 '"pg_catalog"."pg_namespace"', 1, [
'nspname' => $schema ], __METHOD__ );
1239 return (
bool)$exists;
1248 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1249 [
'rolname' => $roleName ], __METHOD__ );
1251 return (
bool)$exists;
1274 return pg_field_type(
$res, $index );
1284 } elseif ( $b instanceof
Blob ) {
1288 return pg_unescape_bytea( $b );
1299 if ( is_null(
$s ) ) {
1301 } elseif ( is_bool(
$s ) ) {
1302 return intval(
$s );
1303 } elseif (
$s instanceof
Blob ) {
1307 $s = pg_escape_bytea(
$conn,
$s->fetch() );
1314 return "'" . pg_escape_string(
$conn, (
string)
$s ) .
"'";
1318 $preLimitTail = $postLimitTail =
'';
1319 $startOpts = $useIndex = $ignoreIndex =
'';
1323 if ( is_numeric( $key ) ) {
1324 $noKeyOptions[$option] =
true;
1332 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1333 $postLimitTail .=
' FOR UPDATE OF ' .
1334 implode(
', ', array_map( [ $this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1335 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1336 $postLimitTail .=
' FOR UPDATE';
1339 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1340 $startOpts .=
'DISTINCT';
1343 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1351 return implode(
' || ', $stringList );
1359 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1363 return $field .
'::text';
1367 # Allow dollar quoting for function declarations
1368 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1369 if ( $this->delimiter ) {
1370 $this->delimiter =
false;
1372 $this->delimiter =
';';
1376 return parent::streamStatementEnd( $sql, $newLine );
1381 foreach ( $write
as $table ) {
1382 $tablesWrite[] = $this->
tableName( $table );
1385 foreach ( $read
as $table ) {
1386 $tablesRead[] = $this->
tableName( $table );
1390 if ( $tablesWrite ) {
1392 'LOCK TABLE ONLY ' . implode(
',', $tablesWrite ) .
' IN EXCLUSIVE MODE',
1396 if ( $tablesRead ) {
1398 'LOCK TABLE ONLY ' . implode(
',', $tablesRead ) .
' IN SHARE MODE',
1407 if ( !parent::lockIsFree( $lockName, $method ) ) {
1412 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1413 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1416 return ( $row->lockstatus ===
't' );
1419 public function lock( $lockName, $method, $timeout = 5 ) {
1422 $loop =
new WaitConditionLoop(
1423 function ()
use ( $lockName, $key, $timeout, $method ) {
1424 $res = $this->
query(
"SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1426 if ( $row->lockstatus ===
't' ) {
1427 parent::lock( $lockName, $method, $timeout );
1431 return WaitConditionLoop::CONDITION_CONTINUE;
1436 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1439 public function unlock( $lockName, $method ) {
1442 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1445 if ( $row->lockstatus ===
't' ) {
1446 parent::unlock( $lockName, $method );
1450 $this->queryLogger->debug( __METHOD__ .
" failed to release lock\n" );
1456 $res = $this->
query(
"SHOW default_transaction_read_only", __METHOD__ );
1459 return $row ? ( strtolower( $row->default_transaction_read_only ) ===
'on' ) :
false;
1467 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
freeResult( $res)
Free a result object returned by query() or select().
resetSequenceForTable( $table, $fname=__METHOD__)
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
numFields( $res)
Get the number of fields in a result object.
bigintFromLockName( $lockName)
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
getSoftwareLink()
Returns a wikitext link to the DB's website, e.g., return "[https://www.mysql.com/ MySQL]"; Should at...
closeConnection()
Closes underlying database connection.
relationExists( $table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given)
makeUpdateOptionsArray( $options)
Make UPDATE options array for Database::makeUpdateOptions.
getSchemas()
Return list of schemas which are accessible without schema name This is list does not contain magic k...
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
remappedTableName( $name)
addQuotes( $s)
Adds quotes and backslashes.
string $connectString
Connect string to open a PostgreSQL connection.
getCoreSchemas()
Return schema names for temporary tables and core application tables.
while(( $__line=Maintenance::readconsole()) !==false) print n
fieldInfo( $table, $field)
unlock( $lockName, $method)
Release a lock.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
fieldType( $res, $index)
pg_field_type() wrapper
float string $numericVersion
makeSelectOptions( $options)
Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the quer...
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".
indexUnique( $table, $index, $fname=__METHOD__)
insertId()
Get the inserted value of an auto-increment row.
fetchObject( $res)
Fetch the next row from the given result object, in object form.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
roleExists( $roleName)
Returns true if a given role (i.e.
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper $varMap must be an associative array of the form [ 'dest1' => 'source1',...
insert( $table, $args, $fname=__METHOD__, $options=[])
@inheritDoc
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to and or sell copies of the and to permit persons to whom the Software is furnished to do subject to the following WITHOUT WARRANTY OF ANY EXPRESS OR INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER WHETHER IN AN ACTION OF TORT OR ARISING FROM
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
makeConnectionString( $vars)
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
schemaExists( $schema)
Query whether a given schema exists.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
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
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.
static fromText(DatabasePostgres $db, $table, $field)
doQuery( $sql)
Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
pg_array_parse( $text, &$output, $limit=false, $offset=1)
Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12 to https://secure.php.net/manual/en/ref....
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
lastErrno()
Get the last error number.
resource $lastResultHandle
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
The equivalent of IDatabase::select() except that the constructed SQL is returned,...
numRows( $res)
Get the number of rows in a query result.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
storage can be distributed across multiple and multiple web servers can use the same cache cluster *********************W A R N I N G ***********************Memcached has no security or authentication Please ensure that your server is appropriately and that the port(s) used for memcached servers are not publicly accessible. Otherwise
strencode( $s)
Wrapper for addslashes()
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Allows to change the fields on the form that will be generated $name
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
relationSchemaQualifier()
getServer()
Get the server hostname or IP address.
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
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
realTableName( $name, $format='quoted')
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
getServerVersion()
A string describing the current software version, like from mysql_get_server_info().
lastError()
Get a description of the last error.
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
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
__construct(array $params)
constraintExists( $table, $constraint)
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
sequenceExists( $sequence, $schema=false)
tableExists( $table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.
string[] $keywordTableMap
Map of (reserved table name => alternate table name)
buildGroupConcatField( $delimiter, $table, $field, $conds='', $options=[], $join_conds=[])
dataSeek( $res, $row)
Change the position of the cursor in a result object.
ruleExists( $table, $rule)
wasKnownStatementRollbackError()
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
fieldName( $res, $n)
Get a field name in a result object.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
determineCoreSchema( $desiredSchema)
Determine default schema for the current application Adjust this session schema search path if desire...
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
getCoreSchema()
Return schema name for core application tables.
Class to handle database/prefix specification for IDatabase domains.
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.
triggerExists( $table, $trigger)
currentSequenceValue( $seqName)
Return the current value of a sequence.
setSearchPath( $search_path)
Update search_path, values should already be sanitized Values may contain magic keywords like "$user"...
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break but it is *strongly *advised not to try any more intrusive changes to get MediaWiki to conform more closely to your filesystem hierarchy Any such attempt will almost certainly result in unnecessary bugs The standard recommended location to install relative to the web is it should be possible to enable the appropriate rewrite rules by if you can reconfigure the web server
wasDeadlock()
Determines if the last failure was due to a deadlock.
doSelectDomain(DatabaseDomain $domain)
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
listTables( $prefix=null, $fname=__METHOD__)
@suppress SecurityCheck-SQLInjection array_map not recognized T204911
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
indexAttributes( $index, $schema=false)