Go to the documentation of this file.
25 use Wikimedia\Timestamp\ConvertibleTimestamp;
26 use Wikimedia\WaitConditionLoop;
58 $this->keywordTableMap = isset(
$params[
'keywordTableMap'] )
80 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
81 "WHERE c.connamespace = n.oid AND conname = '" .
82 pg_escape_string( $conn,
$name ) .
"' AND n.nspname = '" .
89 public function open( $server,
$user, $password, $dbName ) {
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"
100 $this->mServer = $server;
101 $this->mUser =
$user;
102 $this->mPassword = $password;
103 $this->mDBname = $dbName;
109 'dbname' => strlen( $dbName ) ? $dbName :
'postgres',
111 'password' => $password
113 if ( $server !=
false && $server !=
'' ) {
114 $connectVars[
'host'] = $server;
116 if ( (
int)$this->
port > 0 ) {
117 $connectVars[
'port'] = (int)$this->
port;
120 $connectVars[
'sslmode'] = 1;
129 $this->mConn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
130 }
catch ( Exception $ex ) {
137 if ( !$this->mConn ) {
138 $this->queryLogger->debug(
139 "DB connection error\n" .
140 "Server: $server, Database: $dbName, User: $user, Password: " .
141 substr( $password, 0, 3 ) .
"...\n"
143 $this->queryLogger->debug( $this->
lastError() .
"\n" );
147 $this->mOpened =
true;
149 # If called from the command-line (e.g. importDump), only show errors
150 if ( $this->cliMode ) {
151 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
154 $this->
query(
"SET client_encoding='UTF8'", __METHOD__ );
155 $this->
query(
"SET datestyle = 'ISO, YMD'", __METHOD__ );
156 $this->
query(
"SET timezone = 'GMT'", __METHOD__ );
157 $this->
query(
"SET standard_conforming_strings = on", __METHOD__ );
159 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
181 if ( $this->mDBname !== $db ) {
182 return (
bool)$this->
open( $this->mServer, $this->mUser, $this->mPassword, $db );
195 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
202 return $this->mConn ? pg_close( $this->mConn ) :
true;
208 $sql = mb_convert_encoding( $sql,
'UTF-8' );
210 while (
$res = pg_get_result( $conn ) ) {
211 pg_free_result(
$res );
213 if ( pg_send_query( $conn, $sql ) ===
false ) {
214 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
216 $this->mLastResult = pg_get_result( $conn );
217 $this->mAffectedRows =
null;
218 if ( pg_result_error( $this->mLastResult ) ) {
229 PGSQL_DIAG_MESSAGE_PRIMARY,
230 PGSQL_DIAG_MESSAGE_DETAIL,
231 PGSQL_DIAG_MESSAGE_HINT,
232 PGSQL_DIAG_STATEMENT_POSITION,
233 PGSQL_DIAG_INTERNAL_POSITION,
234 PGSQL_DIAG_INTERNAL_QUERY,
236 PGSQL_DIAG_SOURCE_FILE,
237 PGSQL_DIAG_SOURCE_LINE,
238 PGSQL_DIAG_SOURCE_FUNCTION
240 foreach ( $diags
as $d ) {
241 $this->queryLogger->debug( sprintf(
"PgSQL ERROR(%d): %s\n",
242 $d, pg_result_error_field( $this->mLastResult, $d ) ) );
249 if ( $errno ===
'23505' ) {
250 parent::reportQueryError( $error, $errno, $sql,
$fname, $tempIgnore );
256 if ( $this->mTrxLevel ) {
260 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
262 parent::reportQueryError( $error, $errno, $sql,
$fname,
false );
269 MediaWiki\suppressWarnings();
270 $ok = pg_free_result(
$res );
271 MediaWiki\restoreWarnings();
281 MediaWiki\suppressWarnings();
282 $row = pg_fetch_object(
$res );
283 MediaWiki\restoreWarnings();
284 # @todo FIXME: HACK HACK HACK HACK debug
286 # @todo hashar: not sure if the following test really trigger if the object
289 if ( pg_last_error( $conn ) ) {
292 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
303 MediaWiki\suppressWarnings();
304 $row = pg_fetch_array(
$res );
305 MediaWiki\restoreWarnings();
308 if ( pg_last_error( $conn ) ) {
311 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
322 MediaWiki\suppressWarnings();
323 $n = pg_num_rows(
$res );
324 MediaWiki\restoreWarnings();
327 if ( pg_last_error( $conn ) ) {
330 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
342 return pg_num_fields(
$res );
350 return pg_field_name(
$res, $n );
354 $res = $this->
query(
"SELECT lastval()" );
356 return is_null( $row[0] ) ? null : (int)$row[0];
364 return pg_result_seek(
$res, $row );
368 if ( $this->mConn ) {
369 if ( $this->mLastResult ) {
370 return pg_result_error( $this->mLastResult );
372 return pg_last_error();
380 if ( $this->mLastResult ) {
381 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
388 if ( !is_null( $this->mAffectedRows ) ) {
392 if ( empty( $this->mLastResult ) ) {
396 return pg_affected_rows( $this->mLastResult );
422 if ( preg_match(
'/rows=(\d+)/', $row[0], $count ) ) {
423 $rows = (int)$count[1];
431 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
436 foreach (
$res as $row ) {
437 if ( $row->indexname == $this->indexName( $index ) ) {
446 if ( $schema ===
false ) {
453 $sql = <<<__INDEXATTR__
457 i.indoption[s.g]
as option,
460 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
464 ON cis.oid=isub.indexrelid
466 ON cis.relnamespace = ns.oid
467 WHERE cis.relname=
'$index' AND ns.nspname=
'$schema') AS s,
473 ON ci.oid=i.indexrelid
475 ON ct.oid = i.indrelid
477 ON ci.relnamespace =
n.oid
479 ci.relname=
'$index' AND
n.nspname=
'$schema'
480 AND attrelid = ct.oid
481 AND i.indkey[s.g] = attnum
482 AND i.indclass[s.g] = opcls.oid
483 AND pg_am.oid = opcls.opcmethod
488 foreach (
$res as $row ) {
503 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
504 " AND indexdef LIKE 'CREATE UNIQUE%(" .
512 return $res->numRows() > 0;
530 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
531 if ( $forUpdateKey !==
false && $join_conds ) {
536 foreach ( $table
as $alias =>
$name ) {
537 if ( is_numeric( $alias ) ) {
540 if ( !isset( $join_conds[$alias] ) ) {
545 foreach ( $join_conds
as $table_cond => $join_cond ) {
546 if ( 0 === preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
547 $options[
'FOR UPDATE'][] = $table_cond;
583 if ( !isset( $this->numericVersion ) ) {
591 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
600 $savepoint = $olde =
null;
601 $numrowsinserted = 0;
602 if ( in_array(
'IGNORE',
$options ) ) {
604 $olde = error_reporting( 0 );
609 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
612 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
620 $sql .=
'(' . $this->
makeList( $row ) .
')';
628 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
631 $savepoint->savepoint();
634 $tempres = (bool)$this->
query( $tempsql,
$fname, $savepoint );
637 $bar = pg_result_error( $this->mLastResult );
638 if ( $bar !=
false ) {
639 $savepoint->rollback();
641 $savepoint->release();
656 $savepoint->savepoint();
662 $bar = pg_result_error( $this->mLastResult );
663 if ( $bar !=
false ) {
664 $savepoint->rollback();
666 $savepoint->release();
672 error_reporting( $olde );
673 $savepoint->commit();
676 $this->mAffectedRows = $numrowsinserted;
705 $destTable, $srcTable, $varMap, $conds,
$fname = __METHOD__,
706 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
708 if ( !is_array( $insertOptions ) ) {
709 $insertOptions = [ $insertOptions ];
716 $savepoint = $olde =
null;
717 $numrowsinserted = 0;
718 if ( in_array(
'IGNORE', $insertOptions ) ) {
720 $olde = error_reporting( 0 );
721 $savepoint->savepoint();
724 $res = parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
$fname,
725 $insertOptions, $selectOptions, $selectJoinConds );
728 $bar = pg_result_error( $this->mLastResult );
729 if ( $bar !=
false ) {
730 $savepoint->rollback();
732 $savepoint->release();
735 error_reporting( $olde );
736 $savepoint->commit();
739 $this->mAffectedRows = $numrowsinserted;
760 return isset( $this->keywordTableMap[
$name] ) ? $this->keywordTableMap[
$name] :
$name;
783 $safeseq = str_replace(
"'",
"''", $seqName );
784 $res = $this->
query(
"SELECT currval('$safeseq')" );
793 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
794 FROM pg_class c, pg_attribute a, pg_type t
795 WHERE relname='$table' AND a.attrelid=c.oid AND
796 a.atttypid=t.oid and a.attname='$field'";
799 if ( $row->ftype ==
'varchar' ) {
800 $size = $row->size - 4;
809 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
817 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
822 return $this->
query(
'CREATE ' . ( $temporary ?
'TEMPORARY ' :
'' ) .
" TABLE $newName " .
823 "(LIKE $oldName INCLUDING DEFAULTS INCLUDING INDEXES)",
$fname );
829 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema",
$fname );
833 $vars = get_object_vars( $table );
834 $table = array_pop(
$vars );
835 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
836 $endArray[] = $table;
844 $ct =
new ConvertibleTimestamp( $ts );
846 return $ct->getTimestamp( TS_POSTGRES );
868 if (
false === $limit ) {
869 $limit = strlen( $text ) - 1;
872 if (
'{}' == $text ) {
876 if (
'{' != $text[$offset] ) {
877 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
878 $text, $match, 0, $offset );
879 $offset += strlen( $match[0] );
880 $output[] = (
'"' != $match[1][0]
882 : stripcslashes( substr( $match[1], 1, -1 ) ) );
883 if (
'},' == $match[3] ) {
889 }
while ( $limit > $offset );
899 return '[{{int:version-db-postgres-url}} PostgreSQL]';
910 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
927 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
946 $res = $this->
query(
"SHOW search_path", __METHOD__ );
951 return explode(
",", $row[0] );
962 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
980 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
982 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
983 $this->mCoreSchema = $desiredSchema;
984 $this->queryLogger->debug(
985 "Schema \"" . $desiredSchema .
"\" already in the search path\n" );
993 array_unshift( $search_path,
996 $this->mCoreSchema = $desiredSchema;
997 $this->queryLogger->debug(
998 "Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1002 $this->queryLogger->debug(
1003 "Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1004 $this->mCoreSchema .
"\"\n" );
1007 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
1021 if ( !isset( $this->numericVersion ) ) {
1023 $versionInfo = pg_version( $conn );
1024 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1026 $this->numericVersion =
'7.3 or earlier';
1027 } elseif ( isset( $versionInfo[
'server'] ) ) {
1029 $this->numericVersion = $versionInfo[
'server'];
1032 $this->numericVersion = pg_parameter_status( $conn,
'server_version' );
1048 if ( !is_array( $types ) ) {
1049 $types = [ $types ];
1051 if ( $schema ===
false ) {
1057 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1058 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1059 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1061 $count =
$res ?
$res->numRows() : 0;
1063 return (
bool)$count;
1083 SELECT 1
FROM pg_class, pg_namespace, pg_trigger
1084 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1085 AND tgrelid=pg_class.oid
1086 AND nspname=%s AND relname=%s AND tgname=%s
1105 $exists = $this->
selectField(
'pg_rules',
'rulename',
1107 'rulename' => $rule,
1108 'tablename' => $table,
1113 return $exists === $rule;
1117 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1118 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1138 if ( !strlen( $schema ) ) {
1143 '"pg_catalog"."pg_namespace"', 1, [
'nspname' => $schema ], __METHOD__ );
1145 return (
bool)$exists;
1154 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1155 [
'rolname' => $roleName ], __METHOD__ );
1157 return (
bool)$exists;
1180 return pg_field_type(
$res, $index );
1190 } elseif ( $b instanceof
Blob ) {
1194 return pg_unescape_bytea( $b );
1205 if ( is_null(
$s ) ) {
1207 } elseif ( is_bool(
$s ) ) {
1208 return intval(
$s );
1209 } elseif (
$s instanceof
Blob ) {
1213 $s = pg_escape_bytea( $conn,
$s->fetch() );
1220 return "'" . pg_escape_string( $conn, (
string)
$s ) .
"'";
1231 $ins = parent::replaceVars( $ins );
1233 if ( $this->numericVersion >= 8.3 ) {
1235 $ins = preg_replace(
"/to_tsvector\s*\(\s*'default'\s*,/",
'to_tsvector(', $ins );
1238 if ( $this->numericVersion <= 8.1 ) {
1239 $ins = str_replace(
'USING gin',
'USING gist', $ins );
1246 $preLimitTail = $postLimitTail =
'';
1247 $startOpts = $useIndex = $ignoreIndex =
'';
1251 if ( is_numeric( $key ) ) {
1252 $noKeyOptions[$option] =
true;
1260 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1261 $postLimitTail .=
' FOR UPDATE OF ' .
1262 implode(
', ', array_map( [ $this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1263 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1264 $postLimitTail .=
' FOR UPDATE';
1267 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1268 $startOpts .=
'DISTINCT';
1271 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1283 return implode(
' || ', $stringList );
1291 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1295 return $field .
'::text';
1299 # Allow dollar quoting for function declarations
1300 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1301 if ( $this->delimiter ) {
1302 $this->delimiter =
false;
1304 $this->delimiter =
';';
1308 return parent::streamStatementEnd( $sql, $newLine );
1313 foreach ( $write
as $table ) {
1314 $tablesWrite[] = $this->
tableName( $table );
1317 foreach ( $read
as $table ) {
1318 $tablesRead[] = $this->
tableName( $table );
1322 if ( $tablesWrite ) {
1324 'LOCK TABLE ONLY ' . implode(
',', $tablesWrite ) .
' IN EXCLUSIVE MODE',
1328 if ( $tablesRead ) {
1330 'LOCK TABLE ONLY ' . implode(
',', $tablesRead ) .
' IN SHARE MODE',
1341 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1342 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1345 return ( $row->lockstatus ===
't' );
1348 public function lock( $lockName, $method, $timeout = 5 ) {
1351 $loop =
new WaitConditionLoop(
1352 function ()
use ( $lockName, $key, $timeout, $method ) {
1353 $res = $this->
query(
"SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1355 if ( $row->lockstatus ===
't' ) {
1356 parent::lock( $lockName, $method, $timeout );
1360 return WaitConditionLoop::CONDITION_CONTINUE;
1365 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1368 public function unlock( $lockName, $method ) {
1371 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1374 if ( $row->lockstatus ===
't' ) {
1375 parent::unlock( $lockName, $method );
1379 $this->queryLogger->debug( __METHOD__ .
" failed to release lock\n" );
1385 $res = $this->
query(
"SHOW default_transaction_read_only", __METHOD__ );
1388 return $row ? ( strtolower( $row->default_transaction_read_only ) ===
'on' ) :
false;
1396 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)
Helper function for lockTables() that handles the actual table locking.
numFields( $res)
Get the number of fields in a result object.
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
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)
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
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__)
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
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.
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=[])
INSERT wrapper, inserts an array into a table.
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.
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
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
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)
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)
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.
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.
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
print Searching for spam in $maxID pages n
indexAttributes( $index, $schema=false)