Go to the documentation of this file.
25 use Wikimedia\Timestamp\ConvertibleTimestamp;
26 use Wikimedia\WaitConditionLoop;
60 $this->keywordTableMap = isset(
$params[
'keywordTableMap'] )
82 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
83 "WHERE c.connamespace = n.oid AND conname = '" .
84 pg_escape_string( $conn,
$name ) .
"' AND n.nspname = '" .
91 public function open( $server,
$user, $password, $dbName ) {
92 # Test for Postgres support, to avoid suppressed fatal error
93 if ( !function_exists(
'pg_connect' ) ) {
96 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
97 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
98 "webserver and database)\n"
102 $this->mServer = $server;
103 $this->mUser =
$user;
104 $this->mPassword = $password;
105 $this->mDBname = $dbName;
110 'password' => $password
112 if ( $server !=
false && $server !=
'' ) {
113 $connectVars[
'host'] = $server;
115 if ( (
int)$this->
port > 0 ) {
116 $connectVars[
'port'] = (int)$this->
port;
119 $connectVars[
'sslmode'] = 1;
128 $this->mConn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
129 }
catch ( Exception $ex ) {
136 if ( !$this->mConn ) {
137 $this->queryLogger->debug(
138 "DB connection error\n" .
139 "Server: $server, Database: $dbName, User: $user, Password: " .
140 substr( $password, 0, 3 ) .
"...\n"
142 $this->queryLogger->debug( $this->
lastError() .
"\n" );
146 $this->mOpened =
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__ );
158 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
175 if ( $this->mDBname !== $db ) {
176 return (
bool)$this->
open( $this->mServer, $this->mUser, $this->mPassword, $db );
189 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
196 return $this->mConn ? pg_close( $this->mConn ) :
true;
202 $sql = mb_convert_encoding( $sql,
'UTF-8' );
204 while (
$res = pg_get_result( $conn ) ) {
205 pg_free_result(
$res );
207 if ( pg_send_query( $conn, $sql ) ===
false ) {
208 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
210 $this->mLastResult = pg_get_result( $conn );
211 $this->mAffectedRows =
null;
212 if ( pg_result_error( $this->mLastResult ) ) {
223 PGSQL_DIAG_MESSAGE_PRIMARY,
224 PGSQL_DIAG_MESSAGE_DETAIL,
225 PGSQL_DIAG_MESSAGE_HINT,
226 PGSQL_DIAG_STATEMENT_POSITION,
227 PGSQL_DIAG_INTERNAL_POSITION,
228 PGSQL_DIAG_INTERNAL_QUERY,
230 PGSQL_DIAG_SOURCE_FILE,
231 PGSQL_DIAG_SOURCE_LINE,
232 PGSQL_DIAG_SOURCE_FUNCTION
234 foreach ( $diags
as $d ) {
235 $this->queryLogger->debug( sprintf(
"PgSQL ERROR(%d): %s\n",
236 $d, pg_result_error_field( $this->mLastResult, $d ) ) );
243 if ( $errno ===
'23505' ) {
244 parent::reportQueryError( $error, $errno, $sql,
$fname, $tempIgnore );
250 if ( $this->mTrxLevel ) {
254 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
256 parent::reportQueryError( $error, $errno, $sql,
$fname,
false );
263 MediaWiki\suppressWarnings();
264 $ok = pg_free_result(
$res );
265 MediaWiki\restoreWarnings();
275 MediaWiki\suppressWarnings();
276 $row = pg_fetch_object(
$res );
277 MediaWiki\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 MediaWiki\suppressWarnings();
298 $row = pg_fetch_array(
$res );
299 MediaWiki\restoreWarnings();
302 if ( pg_last_error( $conn ) ) {
305 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
316 MediaWiki\suppressWarnings();
317 $n = pg_num_rows(
$res );
318 MediaWiki\restoreWarnings();
321 if ( pg_last_error( $conn ) ) {
324 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
336 return pg_num_fields(
$res );
344 return pg_field_name(
$res, $n );
362 return pg_result_seek(
$res, $row );
366 if ( $this->mConn ) {
367 if ( $this->mLastResult ) {
368 return pg_result_error( $this->mLastResult );
370 return pg_last_error();
378 if ( $this->mLastResult ) {
379 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
386 if ( !is_null( $this->mAffectedRows ) ) {
390 if ( empty( $this->mLastResult ) ) {
394 return pg_affected_rows( $this->mLastResult );
420 if ( preg_match(
'/rows=(\d+)/', $row[0], $count ) ) {
421 $rows = (int)$count[1];
429 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
434 foreach (
$res as $row ) {
435 if ( $row->indexname == $this->indexName( $index ) ) {
444 if ( $schema ===
false ) {
451 $sql = <<<__INDEXATTR__
455 i.indoption[s.g]
as option,
458 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
462 ON cis.oid=isub.indexrelid
464 ON cis.relnamespace = ns.oid
465 WHERE cis.relname=
'$index' AND ns.nspname=
'$schema') AS s,
471 ON ci.oid=i.indexrelid
473 ON ct.oid = i.indrelid
475 ON ci.relnamespace =
n.oid
477 ci.relname=
'$index' AND
n.nspname=
'$schema'
478 AND attrelid = ct.oid
479 AND i.indkey[s.g] = attnum
480 AND i.indclass[s.g] = opcls.oid
481 AND pg_am.oid = opcls.opcmethod
486 foreach (
$res as $row ) {
501 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
502 " AND indexdef LIKE 'CREATE UNIQUE%(" .
510 return $res->numRows() > 0;
524 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
525 if ( $forUpdateKey !==
false && $join_conds ) {
528 foreach ( $join_conds
as $table_cond => $join_cond ) {
529 if ( 0 === preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
530 $options[
'FOR UPDATE'][] = $table_cond;
561 if ( !isset( $this->numericVersion ) ) {
569 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
578 $savepoint = $olde =
null;
579 $numrowsinserted = 0;
580 if ( in_array(
'IGNORE',
$options ) ) {
582 $olde = error_reporting( 0 );
587 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
590 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
598 $sql .=
'(' . $this->
makeList( $row ) .
')';
606 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
609 $savepoint->savepoint();
612 $tempres = (bool)$this->
query( $tempsql,
$fname, $savepoint );
615 $bar = pg_result_error( $this->mLastResult );
616 if ( $bar !=
false ) {
617 $savepoint->rollback();
619 $savepoint->release();
634 $savepoint->savepoint();
640 $bar = pg_result_error( $this->mLastResult );
641 if ( $bar !=
false ) {
642 $savepoint->rollback();
644 $savepoint->release();
650 error_reporting( $olde );
651 $savepoint->commit();
654 $this->mAffectedRows = $numrowsinserted;
682 $destTable, $srcTable, $varMap, $conds,
$fname = __METHOD__,
683 $insertOptions = [], $selectOptions = []
685 $destTable = $this->
tableName( $destTable );
687 if ( !is_array( $insertOptions ) ) {
688 $insertOptions = [ $insertOptions ];
695 $savepoint = $olde =
null;
696 $numrowsinserted = 0;
697 if ( in_array(
'IGNORE', $insertOptions ) ) {
699 $olde = error_reporting( 0 );
700 $savepoint->savepoint();
703 if ( !is_array( $selectOptions ) ) {
704 $selectOptions = [ $selectOptions ];
706 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
708 if ( is_array( $srcTable ) ) {
709 $srcTable = implode(
',', array_map( [ $this,
'tableName' ], $srcTable ) );
711 $srcTable = $this->
tableName( $srcTable );
714 $sql =
"INSERT INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
')' .
715 " SELECT $startOpts " . implode(
',', $varMap ) .
716 " FROM $srcTable $useIndex $ignoreIndex ";
718 if ( $conds !=
'*' ) {
722 $sql .=
" $tailOpts";
726 $bar = pg_result_error( $this->mLastResult );
727 if ( $bar !=
false ) {
728 $savepoint->rollback();
730 $savepoint->release();
733 error_reporting( $olde );
734 $savepoint->commit();
737 $this->mAffectedRows = $numrowsinserted;
758 return isset( $this->keywordTableMap[
$name] ) ? $this->keywordTableMap[
$name] :
$name;
771 $safeseq = str_replace(
"'",
"''", $seqName );
772 $res = $this->
query(
"SELECT nextval('$safeseq')" );
774 $this->mInsertId = $row[0];
786 $safeseq = str_replace(
"'",
"''", $seqName );
787 $res = $this->
query(
"SELECT currval('$safeseq')" );
796 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
797 FROM pg_class c, pg_attribute a, pg_type t
798 WHERE relname='$table' AND a.attrelid=c.oid AND
799 a.atttypid=t.oid and a.attname='$field'";
802 if ( $row->ftype ==
'varchar' ) {
803 $size = $row->size - 4;
812 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
820 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
825 return $this->
query(
'CREATE ' . ( $temporary ?
'TEMPORARY ' :
'' ) .
" TABLE $newName " .
826 "(LIKE $oldName INCLUDING DEFAULTS)",
$fname );
832 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema",
$fname );
836 $vars = get_object_vars( $table );
837 $table = array_pop(
$vars );
838 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
839 $endArray[] = $table;
847 $ct =
new ConvertibleTimestamp( $ts );
849 return $ct->getTimestamp( TS_POSTGRES );
872 $limit = strlen( $text ) - 1;
875 if (
'{}' == $text ) {
879 if (
'{' != $text[$offset] ) {
880 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
881 $text, $match, 0, $offset );
882 $offset += strlen( $match[0] );
883 $output[] = (
'"' != $match[1][0]
885 : stripcslashes( substr( $match[1], 1, -1 ) ) );
886 if (
'},' == $match[3] ) {
892 }
while (
$limit > $offset );
902 return '[{{int:version-db-postgres-url}} PostgreSQL]';
913 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
930 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
949 $res = $this->
query(
"SHOW search_path", __METHOD__ );
954 return explode(
",", $row[0] );
965 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
983 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
985 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
986 $this->mCoreSchema = $desiredSchema;
987 $this->queryLogger->debug(
988 "Schema \"" . $desiredSchema .
"\" already in the search path\n" );
996 array_unshift( $search_path,
999 $this->mCoreSchema = $desiredSchema;
1000 $this->queryLogger->debug(
1001 "Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1005 $this->queryLogger->debug(
1006 "Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1007 $this->mCoreSchema .
"\"\n" );
1010 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
1024 if ( !isset( $this->numericVersion ) ) {
1026 $versionInfo = pg_version( $conn );
1027 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1029 $this->numericVersion =
'7.3 or earlier';
1030 } elseif ( isset( $versionInfo[
'server'] ) ) {
1032 $this->numericVersion = $versionInfo[
'server'];
1035 $this->numericVersion = pg_parameter_status( $conn,
'server_version' );
1051 if ( !is_array( $types ) ) {
1052 $types = [ $types ];
1054 if ( $schema ===
false ) {
1060 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1061 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1062 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1064 $count =
$res ?
$res->numRows() : 0;
1066 return (
bool)$count;
1086 SELECT 1
FROM pg_class, pg_namespace, pg_trigger
1087 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1088 AND tgrelid=pg_class.oid
1089 AND nspname=%s AND relname=%s AND tgname=%s
1102 $rows =
$res->numRows();
1108 $exists = $this->
selectField(
'pg_rules',
'rulename',
1110 'rulename' => $rule,
1111 'tablename' => $table,
1116 return $exists === $rule;
1120 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1121 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1130 $rows =
$res->numRows();
1141 if ( !strlen( $schema ) ) {
1146 '"pg_catalog"."pg_namespace"', 1, [
'nspname' => $schema ], __METHOD__ );
1148 return (
bool)$exists;
1157 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1158 [
'rolname' => $roleName ], __METHOD__ );
1160 return (
bool)$exists;
1183 return pg_field_type(
$res, $index );
1193 } elseif ( $b instanceof
Blob ) {
1197 return pg_unescape_bytea( $b );
1208 if ( is_null(
$s ) ) {
1210 } elseif ( is_bool(
$s ) ) {
1211 return intval(
$s );
1212 } elseif (
$s instanceof
Blob ) {
1216 $s = pg_escape_bytea( $conn,
$s->fetch() );
1221 return "'" . pg_escape_string( $conn, (
string)
$s ) .
"'";
1232 $ins = parent::replaceVars( $ins );
1234 if ( $this->numericVersion >= 8.3 ) {
1236 $ins = preg_replace(
"/to_tsvector\s*\(\s*'default'\s*,/",
'to_tsvector(', $ins );
1239 if ( $this->numericVersion <= 8.1 ) {
1240 $ins = str_replace(
'USING gin',
'USING gist', $ins );
1247 $preLimitTail = $postLimitTail =
'';
1248 $startOpts = $useIndex = $ignoreIndex =
'';
1252 if ( is_numeric( $key ) ) {
1253 $noKeyOptions[$option] =
true;
1261 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1262 $postLimitTail .=
' FOR UPDATE OF ' .
1263 implode(
', ', array_map( [ $this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1264 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1265 $postLimitTail .=
' FOR UPDATE';
1268 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1269 $startOpts .=
'DISTINCT';
1272 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1284 return implode(
' || ', $stringList );
1292 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1296 return $field .
'::text';
1300 # Allow dollar quoting for function declarations
1301 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1302 if ( $this->delimiter ) {
1303 $this->delimiter =
false;
1305 $this->delimiter =
';';
1309 return parent::streamStatementEnd( $sql, $newLine );
1314 foreach ( $write
as $table ) {
1315 $tablesWrite[] = $this->
tableName( $table );
1318 foreach ( $read
as $table ) {
1319 $tablesRead[] = $this->
tableName( $table );
1323 if ( $tablesWrite ) {
1325 'LOCK TABLE ONLY ' . implode(
',', $tablesWrite ) .
' IN EXCLUSIVE MODE',
1329 if ( $tablesRead ) {
1331 'LOCK TABLE ONLY ' . implode(
',', $tablesRead ) .
' IN SHARE MODE',
1342 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1343 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1346 return ( $row->lockstatus ===
't' );
1349 public function lock( $lockName, $method, $timeout = 5 ) {
1352 $loop =
new WaitConditionLoop(
1353 function ()
use ( $lockName, $key, $timeout, $method ) {
1354 $res = $this->
query(
"SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1356 if ( $row->lockstatus ===
't' ) {
1357 parent::lock( $lockName, $method, $timeout );
1361 return WaitConditionLoop::CONDITION_CONTINUE;
1366 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1369 public function unlock( $lockName, $method ) {
1372 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1375 if ( $row->lockstatus ===
't' ) {
1376 parent::unlock( $lockName, $method );
1380 $this->queryLogger->debug( __METHOD__ .
" failed to release lock\n" );
1390 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
freeResult( $res)
Free a result object returned by query() or select().
doLockTables(array $read, array $write, $method)
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)
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.
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
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. '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 '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! 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! 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
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
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
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
float string $numericVersion
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Allows to change the fields on the form that will be generated $name
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()
Return the result of the last call to nextSequenceValue(); This must be called after nextSequenceValu...
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.
roleExists( $roleName)
Returns true if a given role (i.e.
insert( $table, $args, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[])
INSERT SELECT wrapper $varMap must be an associative array of the form [ 'dest1' => 'source1',...
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 available (non-blocking)
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)
The DBMS-dependent part of query()
getDBname()
Get the current DB name.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers please use GetContentModels hook to make them known to core if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
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....
lastErrno()
Get the last error number.
This document describes the state of Postgres support in MediaWiki
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
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 result object.
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
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
strencode( $s)
Wrapper for addslashes()
Manage savepoints within a transaction.
int $mAffectedRows
The number of rows affected as an integer.
affectedRows()
Get the number of rows affected by the last write query.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
getServer()
Get the server hostname or IP address.
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)
Returns an appropriately quoted sequence value for inserting a new row.
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.
__construct(array $params)
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
constraintExists( $table, $constraint)
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
open( $server, $user, $password, $dbName)
Open a connection to the database.
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)
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.
selectDB( $db)
Postgres doesn't support selectDB in the same way MySQL does.
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.
reportQueryError( $error, $errno, $sql, $fname, $tempIgnore=false)
Report a query error.
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"...
replaceVars( $ins)
Postgres specific version of replaceVars.
wasDeadlock()
Determines if the last failure was due to a deadlock.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
the array() calling protocol came about after MediaWiki 1.4rc1.
print Searching for spam in $maxID pages n
indexAttributes( $index, $schema=false)