]> granicus.if.org Git - postgresql/log
postgresql
4 years agoStamp 11.5. REL_11_5
Tom Lane [Mon, 5 Aug 2019 21:14:59 +0000 (17:14 -0400)]
Stamp 11.5.

4 years agoLast-minute updates for release notes.
Tom Lane [Mon, 5 Aug 2019 15:49:14 +0000 (11:49 -0400)]
Last-minute updates for release notes.

Security: CVE-2019-10208, CVE-2019-10209

4 years agoFix choice of comparison operators for cross-type hashed subplans.
Tom Lane [Mon, 5 Aug 2019 15:20:21 +0000 (11:20 -0400)]
Fix choice of comparison operators for cross-type hashed subplans.

Commit bf6c614a2 rearranged the lookup of the comparison operators
needed in a hashed subplan, and in so doing, broke the cross-type
case: it caused the original LHS-vs-RHS operator to be used to compare
hash table entries too (which of course are all of the RHS type).
This leads to C functions being passed a Datum that is not of the
type they expect, with the usual hazards of crashes and unauthorized
server memory disclosure.

For the set of hashable cross-type operators present in v11 core
Postgres, this bug is nearly harmless on 64-bit machines, which
may explain why it escaped earlier detection.  But it is a live
security hazard on 32-bit machines; and of course there may be
extensions that add more hashable cross-type operators, which
would increase the risk.

Reported by Andreas Seltenreich.  Back-patch to v11 where the
problem came in.

Security: CVE-2019-10209

4 years agoRequire the schema qualification in pg_temp.type_name(arg).
Noah Misch [Mon, 5 Aug 2019 14:48:41 +0000 (07:48 -0700)]
Require the schema qualification in pg_temp.type_name(arg).

Commit aa27977fe21a7dfa4da4376ad66ae37cb8f0d0b5 introduced this
restriction for pg_temp.function_name(arg); do likewise for types
created in temporary schemas.  Programs that this breaks should add
"pg_temp." schema qualification or switch to arg::type_name syntax.
Back-patch to 9.4 (all supported versions).

Reviewed by Tom Lane.  Reported by Tom Lane.

Security: CVE-2019-10208

4 years agoTranslation updates
Peter Eisentraut [Mon, 5 Aug 2019 13:50:23 +0000 (15:50 +0200)]
Translation updates

Source-Git-URL: https://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 6e5b36ec437a93cda602c581c48641e77a240f74

4 years agoFix tab completion for ALTER LANGUAGE in psql
Michael Paquier [Mon, 5 Aug 2019 05:30:16 +0000 (14:30 +0900)]
Fix tab completion for ALTER LANGUAGE in psql

OWNER_TO was used for the completion, which is not a supported grammar,
but OWNER TO is.

This error has been introduced by d37b816, so backpatch down to 9.6.

Author: Alexander Lakhin
Discussion: https://postgr.es/m/7ab243e0-116d-3e44-d120-76b3df7abefd@gmail.com
Backpatch-through: 9.6

4 years agoRelease notes for 11.5, 10.10, 9.6.15, 9.5.19, 9.4.24.
Tom Lane [Sun, 4 Aug 2019 21:08:41 +0000 (17:08 -0400)]
Release notes for 11.5, 10.10, 9.6.15, 9.5.19, 9.4.24.

4 years agoFix handling of "undef" in contrib/jsonb_plperl.
Tom Lane [Sun, 4 Aug 2019 18:05:35 +0000 (14:05 -0400)]
Fix handling of "undef" in contrib/jsonb_plperl.

Perl has multiple internal representations of "undef", and just
testing for SvTYPE(x) == SVt_NULL doesn't recognize all of them,
leading to "cannot transform this Perl type to jsonb" errors.
Use the approved test SvOK() instead.

Report and patch by Ivan Panchenko.  Back-patch to v11 where
this module was added.

Discussion: https://postgr.es/m/1564783533.324795401@f193.i.mail.ru

4 years agoAvoid picking already-bound TCP ports in kerberos and ldap test suites.
Tom Lane [Sun, 4 Aug 2019 17:07:12 +0000 (13:07 -0400)]
Avoid picking already-bound TCP ports in kerberos and ldap test suites.

src/test/kerberos and src/test/ldap need to run a private authentication
server of the relevant type, for which they need a free TCP port.
They were just picking a random port number in 48K-64K, which works
except when something's already using the particular port.  Notably,
the probability of failure rises dramatically if one simply runs those
tests in a tight loop, because each test cycle leaves behind a bunch of
high ports that are transiently in TIME_WAIT state.

To fix, split out the code that PostgresNode.pm already had for
identifying a free TCP port number, so that it can be invoked to choose
a port for the KDC or LDAP server.  This isn't 100% bulletproof, since
conceivably something else on the machine could grab the port between
the time we check and the time we actually start the server.  But that's
a pretty short window, so in practice this should be good enough.

Back-patch to v11 where these test suites were added.

Patch by me, reviewed by Andrew Dunstan.

Discussion: https://postgr.es/m/3397.1564872168@sss.pgh.pa.us

4 years agoImprove pruning of a default partition
Alvaro Herrera [Sun, 4 Aug 2019 15:18:45 +0000 (11:18 -0400)]
Improve pruning of a default partition

When querying a partitioned table containing a default partition, we
were wrongly deciding to include it in the scan too early in the
process, failing to exclude it in some cases.  If we reinterpret the
PruneStepResult.scan_default flag slightly, we can do a better job at
detecting that it can be excluded.  The change is that we avoid setting
the flag for that pruning step unless the step absolutely requires the
default partition to be scanned (in contrast with the previous
arrangement, which was to set it unless the step was able to prune it).
So get_matching_partitions() must explicitly check the partition that
each returned bound value corresponds to in order to determine whether
the default one needs to be included, rather than relying on the flag
from the final step result.

Author: Yuzuko Hosoya <hosoya.yuzuko@lab.ntt.co.jp>
Reviewed-by: Amit Langote <Langote_Amit_f8@lab.ntt.co.jp>
Discussion: https://postgr.es/m/00e601d4ca86$932b8bc0$b982a340$@lab.ntt.co.jp

4 years agoFirst-draft release notes for 11.5.
Tom Lane [Fri, 2 Aug 2019 20:18:46 +0000 (16:18 -0400)]
First-draft release notes for 11.5.

As usual, the release notes for other branches will be made by cutting
these down, but put them up for community review first.

4 years agoFix handling of previous password hooks in passwordcheck
Michael Paquier [Thu, 1 Aug 2019 00:38:02 +0000 (09:38 +0900)]
Fix handling of previous password hooks in passwordcheck

When piling up loading of modules using check_password_hook_type,
loading passwordcheck would remove any trace of a previously-loaded
hook.  Unloading the module would also cause previous hooks to be
entirely gone.

Reported-by: Rafael Castro
Author: Michael Paquier
Reviewed-by: Daniel Gustafsson
Discussion: https://postgr.es/m/15932-78f48f9ef166778c@postgresql.org
Backpatch-through: 9.4

4 years agoFix pg_dump's handling of dependencies for custom opclasses.
Tom Lane [Wed, 31 Jul 2019 19:42:50 +0000 (15:42 -0400)]
Fix pg_dump's handling of dependencies for custom opclasses.

Since pg_dump doesn't treat the member operators and functions of operator
classes/families (that is, the pg_amop and pg_amproc entries, not the
underlying operators/functions) as separate dumpable objects, it missed
their dependency information.  I think this was safe when the code was
designed, because the default object sorting rule emits operators and
functions before opclasses, and there were no dependency types that could
mess that up.  However, the introduction of range types in 9.2 broke it:
now a type can have a dependency on an opclass, allowing dependency rules
to push the opclass before the type and hence before custom operators.
Lacking any information showing that it shouldn't do so, pg_dump emitted
the objects in the wrong order.

Fix by teaching getDependencies() to translate pg_depend entries for
pg_amop/amproc rows to look like dependencies for their parent opfamily.

I added a regression test for this in HEAD/v12, but not further back;
life is too short to fight with 002_pg_dump.pl.

Per bug #15934 from Tom Gottfried.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/15934-58b8c8ab7a09ea15@postgresql.org

4 years agoPrint WAL position correctly in pg_rewind error message.
Heikki Linnakangas [Tue, 30 Jul 2019 18:14:14 +0000 (21:14 +0300)]
Print WAL position correctly in pg_rewind error message.

This has been wrong ever since pg_rewind was added. The if-branch just
above this, where we print the same error with an extra message supplied
by XLogReadRecord() got this right, but the variable name was wrong in the
else-branch. As a consequence, the error printed the WAL position as
0/0 if there was an error reading a WAL file.

Backpatch to 9.5, where pg_rewind was added.

4 years agoDon't build extended statistics on inheritance trees
Tomas Vondra [Tue, 30 Jul 2019 17:17:12 +0000 (19:17 +0200)]
Don't build extended statistics on inheritance trees

When performing ANALYZE on inheritance trees, we collect two samples for
each relation - one for the relation alone, and one for the inheritance
subtree (relation and its child relations). And then we build statistics
on each sample, so for each relation we get two sets of statistics.

For regular (per-column) statistics this works fine, because the catalog
includes a flag differentiating statistics built from those two samples.
But we don't have such flag in the extended statistics catalogs, and we
ended up updating the same row twice, triggering this error:

  ERROR:  tuple already updated by self

The simplest solution is to disable extended statistics on inheritance
trees, which is what this commit is doing. In the future we may need to
do something similar to per-column statistics, but that requires adding a
flag to the catalog - and that's not backpatchable. Moreover, the current
selectivity estimation code only works with individual relations, so
building statistics on inheritance trees would be pointless anyway.

Author: Tomas Vondra
Backpatch-to: 10-
Discussion: https://postgr.es/m/20190618231233.GA27470@telsasoft.com
Reported-by: Justin Pryzby
4 years agoFix busted logic for parallel lock grouping in TopoSort().
Tom Lane [Mon, 29 Jul 2019 22:49:04 +0000 (18:49 -0400)]
Fix busted logic for parallel lock grouping in TopoSort().

A "break" statement erroneously left behind by commit a1c1af2a1
caused TopoSort to do the wrong thing if a lock's wait list
contained multiple members of the same locking group.

Because parallel workers don't normally need any locks not already
taken by their leader, this is very hard --- maybe impossible ---
to hit in production.  Still, if it did happen, the queries involved
in an otherwise-resolvable deadlock would block until canceled.

In addition to removing the bogus "break", add an Assert showing
that the conflicting uses of the beforeConstraints[] array (for both
counts and flags) don't overlap, and add some commentary explaining
why not; because it's not obvious without explanation, IMHO.

Original report and patch from Rui Hai Jiang; additional assert
and commentary by me.  Back-patch to 9.6 where the bug came in.

Discussion: https://postgr.es/m/CAEri+mLd3bpHLyW+a9pSe1y=aEkeuJpwBSwvo-+m4n7-ceRmXw@mail.gmail.com

4 years agoAvoid macro clash with LLVM 9.
Thomas Munro [Sun, 28 Jul 2019 22:12:37 +0000 (10:12 +1200)]
Avoid macro clash with LLVM 9.

Early previews of LLVM 9 reveal that our Min() macro causes compiler
errors in LLVM headers reached by the #include directives in
llvmjit_inline.cpp.  Let's just undefine it.  Per buildfarm animal
seawasp.  Back-patch to 11.

Reviewed-by: Fabien Coelho, Tom Lane
Discussion: https://postgr.es/m/20190606173216.GA6306%40alvherre.pgsql

4 years agoDoc: Fix event trigger firing table
Michael Paquier [Sun, 28 Jul 2019 13:02:34 +0000 (22:02 +0900)]
Doc: Fix event trigger firing table

The table has not been updated for some commands introduced in recent
releases, so refresh it.  While on it, reorder entries alphabetically.

Backpatch all the way down for all the commands which have gone
missing.

Reported-by: Jeremy Smith
Discussion: https://postgr.es/m/15883-afff0ea3cc2dbbb6@postgresql.org
Backpatch-through: 9.4

4 years agoDon't uselessly escape a string that doesn't need escaping
Alvaro Herrera [Fri, 26 Jul 2019 21:46:40 +0000 (17:46 -0400)]
Don't uselessly escape a string that doesn't need escaping

Per gripe from Ian Barwick

Co-authored-by: Ian Barwick <ian@2ndquadrant.com>
Discussion: https://postgr.es/m/CABvVfJWNnNKb8cHsTLhkTsvL1+G6BVcV+57+w1JZ61p8YGPdWQ@mail.gmail.com

4 years agoFix possible lockup in pgbench with -R.
Tom Lane [Fri, 26 Jul 2019 19:17:03 +0000 (15:17 -0400)]
Fix possible lockup in pgbench with -R.

pgbench would sometimes get stuck waiting forever after its last
client thread terminated, due to failing to check for there being
nothing more to wait for.

Bug introduced during refactoring in v10 (I didn't bother to try to
assign blame to a specific commit).  It's already repaired in
HEAD/v12 thanks to commit 3bac77c48, but v10 and v11 need this fix.

Fabien Coelho, per report from Tomas Vondra; reviewed by
Yoshikazu Imai

Discussion: https://postgr.es/m/cc5d76c1-6144-bbed-ad1b-961d13d88f3b@2ndquadrant.com

4 years agoTweak our special-case logic for the IANA "Factory" timezone.
Tom Lane [Fri, 26 Jul 2019 17:07:08 +0000 (13:07 -0400)]
Tweak our special-case logic for the IANA "Factory" timezone.

pg_timezone_names() tries to avoid showing the "Factory" zone in
the view, mainly because that has traditionally had a very long
"abbreviation" such as "Local time zone must be set--see zic manual page",
so that showing it messes up psql's formatting of the whole view.
Since tzdb version 2016g, IANA instead uses the abbreviation "-00",
which is sane enough that there's no reason to discriminate against it.

On the other hand, it emerges that FreeBSD and possibly other packagers
are so wedded to backwards compatibility that they hack the IANA data
to keep the old spelling --- and not just that old spelling, but even
older spellings that IANA used back in the stone age.  This caused the
filter logic to fail to suppress "Factory" at all on such platforms,
though the formatting problem is definitely real in that case.

To solve both problems, get rid of the hard-wired assumption about
exactly what Factory's abbreviation is, and instead reject abbreviations
exceeding 31 characters.  This will allow Factory to appear in the view
if and only if it's using the modern abbreviation.

In passing, simplify the code we add to zic.c to support "zic -P"
to remove its now-obsolete hacks to not print the Factory zone's
abbreviation.  Unlike pg_timezone_names(), there's no reason for
that code to support old/nonstandard timezone data.

Since we generally prefer to keep timezone-related behavior the
same in all branches, and since this is arguably a bug fix,
back-patch to all supported branches.

Discussion: https://postgr.es/m/3961.1564086915@sss.pgh.pa.us

4 years agoAvoid choosing "localtime" or "posixrules" as TimeZone during initdb.
Tom Lane [Fri, 26 Jul 2019 16:45:32 +0000 (12:45 -0400)]
Avoid choosing "localtime" or "posixrules" as TimeZone during initdb.

Some platforms create a file named "localtime" in the system
timezone directory, making it a copy or link to the active time
zone file.  If Postgres is built with --with-system-tzdata, initdb
will see that file as an exact match to localtime(3)'s behavior,
and it may decide that "localtime" is the most preferred spelling of
the active zone.  That's a very bad choice though, because it's
neither informative, nor portable, nor stable if someone changes
the system timezone setting.  Extend the preference logic added by
commit e3846a00c so that we will prefer any other zone file that
matches localtime's behavior over "localtime".

On the same logic, also discriminate against "posixrules", which
is another not-really-a-zone file that is often present in the
timezone directory.  (Since we install "posixrules" but not
"localtime", this change can affect the behavior of Postgres
with or without --with-system-tzdata.)

Note that this change doesn't prevent anyone from choosing these
pseudo-zones if they really want to (i.e., by setting TZ for initdb,
or modifying the timezone GUC later on).  It just prevents initdb
from preferring these zone names when there are multiple matches to
localtime's behavior.

Since we generally prefer to keep timezone-related behavior the
same in all branches, and since this is arguably a bug fix,
back-patch to all supported branches.

Discussion: https://postgr.es/m/CADT4RqCCnj6FKLisvT8tTPfTP4azPhhDFJqDF1JfBbOH5w4oyQ@mail.gmail.com
Discussion: https://postgr.es/m/27991.1560984458@sss.pgh.pa.us

4 years agoFix loss of fractional digits for large values in cash_numeric().
Tom Lane [Fri, 26 Jul 2019 15:59:00 +0000 (11:59 -0400)]
Fix loss of fractional digits for large values in cash_numeric().

Money values exceeding about 18 digits (depending on lc_monetary)
could be inaccurately converted to numeric, due to select_div_scale()
deciding it didn't need to compute any fractional digits.  Force
its hand by setting the dscale of one division input to equal the
number of fractional digits we need.

In passing, rearrange the logic to not do useless work in locales
where money values are considered integral.

Per bug #15925 from Slawomir Chodnicki.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/15925-da9953e2674bb5c8@postgresql.org

4 years agoFix LDAP test instability.
Thomas Munro [Thu, 25 Jul 2019 22:01:18 +0000 (10:01 +1200)]
Fix LDAP test instability.

After starting slapd, wait until it can accept a connection before
beginning the real test work.  This avoids occasional test failures.
Back-patch to 11, where the LDAP tests arrived.

Author: Thomas Munro
Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/20190719033013.GI1859%40paquier.xyz

4 years agoFix syntax error in commit 20e99cddd.
Tom Lane [Thu, 25 Jul 2019 18:42:02 +0000 (14:42 -0400)]
Fix syntax error in commit 20e99cddd.

Per buildfarm.

4 years agoFix failures to ignore \r when reading Windows-style newlines.
Tom Lane [Thu, 25 Jul 2019 16:10:55 +0000 (12:10 -0400)]
Fix failures to ignore \r when reading Windows-style newlines.

libpq failed to ignore Windows-style newlines in connection service files.
This normally wasn't a problem on Windows itself, because fgets() would
convert \r\n to just \n.  But if libpq were running inside a program that
changes the default fopen mode to binary, it would see the \r's and think
they were data.  In any case, it's project policy to ignore \r in text
files unconditionally, because people sometimes try to use files with
DOS-style newlines on Unix machines, where the C library won't hide that
from us.

Hence, adjust parseServiceFile() to ignore \r as well as \n at the end of
the line.  In HEAD, go a little further and make it ignore all trailing
whitespace, to match what it's always done with leading whitespace.

In HEAD, also run around and fix up everyplace where we have
newline-chomping code to make all those places look consistent and
uniformly drop \r.  It is not clear whether any of those changes are
fixing live bugs.  Most of the non-cosmetic changes are in places that
are reading popen output, and the jury is still out as to whether popen
on Windows can return \r\n.  (The Windows-specific code in pipe_read_line
seems to think so, but our lack of support for this elsewhere suggests
maybe it's not a problem in practice.)  Hence, I desisted from applying
those changes to back branches, except in run_ssl_passphrase_command()
which is new enough and little-tested enough that we'd probably not have
heard about any problems there.

Tom Lane and Michael Paquier, per bug #15827 from Jorge Gustavo Rocha.
Back-patch the parseServiceFile() change to all supported branches,
and the run_ssl_passphrase_command() change to v11 where that was added.

Discussion: https://postgr.es/m/15827-e6ba53a3a7ed543c@postgresql.org

4 years agoHonor MSVC WindowsSDKVersion if set
Andrew Dunstan [Thu, 25 Jul 2019 15:24:23 +0000 (11:24 -0400)]
Honor MSVC WindowsSDKVersion if set

Add a line to the project file setting the target SDK. Otherwise, in for
example VS2017, if the default but optional 8.1 SDK is not installed the
build will fail.

Patch from Peifeng Qiu, slightly edited by me.

Discussion: https://postgr.es/m/CABmtVJhw1boP_bd4=b3Qv5YnqEdL696NtHFi2ruiyQ6mFHkeQQ@mail.gmail.com

Backpatch to all live branches.

4 years agoFix contrib/sepgsql test policy to work with latest SELinux releases.
Tom Lane [Thu, 25 Jul 2019 15:02:43 +0000 (11:02 -0400)]
Fix contrib/sepgsql test policy to work with latest SELinux releases.

As of Fedora 30, it seems that the system-provided macros for setting
up user privileges in SELinux policies don't grant the ability to read
/etc/passwd, as they formerly did.  This restriction breaks psql
(which tries to use getpwuid() to obtain the user name it's running
under) and thereby the contrib/sepgsql regression test.  Add explicit
specifications that we need the right to read /etc/passwd.

Mike Palmiotto, per a report from me.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/23856.1563381159@sss.pgh.pa.us

4 years agoFix failure with pgperlcritic from the TAP test of synchronous replication
Michael Paquier [Wed, 24 Jul 2019 22:55:33 +0000 (07:55 +0900)]
Fix failure with pgperlcritic from the TAP test of synchronous replication

Oversight in 7d81bdc, which introduced a new routine in perl lacking a
return clause.  Per buildfarm member crake.

Backpatch down to 9.6 like its parent.

Reported-by: Andrew Dunstan
Discussion: https://postgr.es/m/16da29fa-d504-1380-7095-40de586dc038@2ndQuadrant.com
Backpatch-through: 9.6

4 years agoFix infelicities in describeOneTableDetails' partitioned-table handling.
Tom Lane [Wed, 24 Jul 2019 22:14:26 +0000 (18:14 -0400)]
Fix infelicities in describeOneTableDetails' partitioned-table handling.

describeOneTableDetails issued a partition-constraint-fetching query
for every table, even ones it knows perfectly well are not partitions.

To add insult to injury, it then proceeded to leak the empty PGresult
if the table wasn't a partition.  Doing that a lot of times might
amount to a meaningful leak, so this seems like a back-patchable bug.

Fix that, and also fix a related PGresult leak in the partition-parent
case (though that leak would occur only if we got no row, which is
unexpected).

Minor code beautification too, to make this code look more like the
pre-existing code around it.

Back-patch the whole change into v12.  However, the fact that we already
know whether the table is a partition dates only to commit 1af25ca0c;
back-patching the relevant changes from that is probably more churn
than is justified in released branches.  Hence, in v11 and v10, just
do the minimum to fix the PGresult leaks.

Noted while messing around with adjacent code for yesterday's \d
improvements.

4 years agoDon't assume expr is available in pgbench tests
Andrew Dunstan [Wed, 24 Jul 2019 15:41:39 +0000 (11:41 -0400)]
Don't assume expr is available in pgbench tests

Windows hosts do not normally come with expr, so instead of using that
to test the \setshell command, use echo instead, which is fairly
universally available.

Backpatch to release 11, where this came in.

Problem found by me, patch by Fabien Coelho.

4 years agoDoc: Clarify interactions of pg_receivewal with remote_apply
Michael Paquier [Wed, 24 Jul 2019 02:26:29 +0000 (11:26 +0900)]
Doc: Clarify interactions of pg_receivewal with remote_apply

Using pg_receivewal with synchronous_commit = remote_apply set in the
backend is incompatible if pg_receivewal is a synchronous standby as it
never applies WAL, so document this problem and solutions to it.

Backpatch to 9.6, where remote_apply has been added.

Author: Robert Haas, Jesper Pedersen
Reviewed-by: Laurenz Albe, Álvaro Herrera, Michael Paquier
Discussion: https://postgr.es/m/1427a2d3-1e51-9335-1931-4f8853d90d5e@redhat.com
Backpatch-through: 9.6

4 years agoImprove stability of TAP test for synchronous replication
Michael Paquier [Wed, 24 Jul 2019 01:54:26 +0000 (10:54 +0900)]
Improve stability of TAP test for synchronous replication

Slow buildfarm machines have run into issues with this TAP test caused
by a race condition related to the startup of a set of standbys, where
it is possible to finish with an unexpected order in the WAL sender
array of the primary.

This closes the race condition by making sure that any standby started
is registered into the WAL sender array of the primary before starting
the next one based on lookups of pg_stat_replication.

Backpatch down to 9.6 where the test has been introduced.

Author: Michael Paquier
Reviewed-by: Álvaro Herrera, Noah Misch
Discussion: https://postgr.es/m/20190617055145.GB18917@paquier.xyz
Backpatch-through: 9.6

4 years agoCheck that partitions are not in use when dropping constraints
Alvaro Herrera [Tue, 23 Jul 2019 21:22:15 +0000 (17:22 -0400)]
Check that partitions are not in use when dropping constraints

If the user creates a deferred constraint in a partition, and in a
transaction they cause the constraint's trigger execution to be deferred
until commit time *and* drop the constraint, then when commit time comes
the queued trigger will fail to run because the trigger object will have
been dropped.

This is explained because when a constraint gets dropped in a
partitioned table, the recursion to drop the ones in partitions is done
by the dependency mechanism, not by ALTER TABLE traversing the recursion
tree as in all other cases.  In the non-partitioned case, this problem
is avoided by checking that the table is not "in use" by alter-table;
other alter-table subcommands that recurse to partitions do that check
for each partition.  But the dependency mechanism doesn't have a way to
do that.  Fix the problem by applying the same check to all partitions
during ALTER TABLE's "prep" phase, which correctly raises the necessary
error.

Reported-by: Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>
Discussion: https://postgr.es/m/CAKcux6nZiO9-eEpr1ZD84bT1mBoVmeZkfont8iSpcmYrjhGWgA@mail.gmail.com

4 years agoMake pg_upgrade's test.sh less chatty.
Tom Lane [Mon, 22 Jul 2019 21:14:22 +0000 (17:14 -0400)]
Make pg_upgrade's test.sh less chatty.

Remove "set -x", and pass "-A trust" to initdb explicitly,
to suppress almost all of the noise this script used to emit
on stderr.

Back-patch of commit eb9812f27 into all active branches.

Discussion: https://postgr.es/m/21766.1558397960@sss.pgh.pa.us
Discussion: https://postgr.es/m/20190722193459.GA14241@alvherre.pgsql

4 years agoInstall dependencies to prevent dropping partition key columns.
Tom Lane [Mon, 22 Jul 2019 18:55:23 +0000 (14:55 -0400)]
Install dependencies to prevent dropping partition key columns.

The logic in ATExecDropColumn that rejects dropping partition key
columns is quite an inadequate defense, because it doesn't execute
in cases where a column needs to be dropped due to cascade from
something that only the column, not the whole partitioned table,
depends on.  That leaves us with a badly broken partitioned table;
even an attempt to load its relcache entry will fail.

We really need to have explicit pg_depend entries that show that the
column can't be dropped without dropping the whole table.  Hence,
add those entries.  In v12 and HEAD, bump catversion to ensure that
partitioned tables will have such entries.  We can't do that in
released branches of course, so in v10 and v11 this patch affords
protection only to partitioned tables created after the patch is
installed.  Given the lack of field complaints (this bug was found
by fuzz-testing not by end users), that's probably good enough.

In passing, fix ATExecDropColumn and ATPrepAlterColumnType
messages to be more specific about which partition key column
they're complaining about.

Per report from Manuel Rigger.  Back-patch to v10 where partitioned
tables were added.

Discussion: https://postgr.es/m/CA+u7OA4JKCPFrdrAbOs7XBiCyD61XJxeNav4LefkSmBLQ-Vobg@mail.gmail.com
Discussion: https://postgr.es/m/31920.1562526703@sss.pgh.pa.us

4 years agoDon't rely on estimates for amcheck Bloom filters.
Peter Geoghegan [Sat, 20 Jul 2019 18:11:52 +0000 (11:11 -0700)]
Don't rely on estimates for amcheck Bloom filters.

Solely relying on a relation's reltuples/relpages estimate to size the
Bloom filters used by amcheck verification makes verification less
effective when the estimates are very stale.  In extreme cases,
verification options that use Bloom filters internally could be totally
ineffective, without users receiving any clear indication that certain
types of corruption might easily be missed.

To fix, use RelationGetNumberOfBlocks() instead of relpages to size the
downlink block Bloom filter.  Use the same RelationGetNumberOfBlocks()
value to derive a minimum size for the heapallindexed Bloom filter,
rather than completely trusting reltuples.  Verification will still be
reasonably effective when the projected/estimated number of Bloom filter
elements is at least 1/5 of the final number of elements, which is
assured by the new sizing logic.

Reported-By: Alexander Korotkov
Discussion: https://postgr.es/m/CAH2-Wzk0ke2J42KrNYBKu0Xovjy-sU5ub7PWjgpbsKdAQcL4OA@mail.gmail.com
Backpatch: 11-, where downlink/heapallindexed verification were added.

4 years agoSilence compiler warning, hopefully.
Tom Lane [Fri, 19 Jul 2019 18:48:57 +0000 (14:48 -0400)]
Silence compiler warning, hopefully.

Absorb commit e5e04c962a5d12eebbf867ca25905b3ccc34cbe0 from upstream
IANA code, in hopes of silencing warnings from MSVC about negating
a bool value.

Discussion: https://postgr.es/m/20190719035347.GJ1859@paquier.xyz

4 years agoDoc: clarify when table rewrites happen with column addition and DEFAULT
Michael Paquier [Fri, 19 Jul 2019 02:43:11 +0000 (11:43 +0900)]
Doc: clarify when table rewrites happen with column addition and DEFAULT

16828d5 has improved ALTER TABLE so as a column addition does not
require a rewrite for a non-NULL default with constant expressions, but
one spot in the documentation did not get updated consistently.
The documentation also now clarifies the fact that this does not apply
if the expression is volatile, where a table rewrite is still required.

Reported-by: Daniel Westermann
Author: Ian Barwick
Reviewed-by: Michael Paquier, Daniel Westermann
Discussion: https://postgr.es/m/DB6PR0902MB2184C7D5645CF15D75EB7957D2CF0@DB6PR0902MB2184.eurprd09.prod.outlook.com
Backpatch-through: 11

4 years agoFix error in commit e6feef57.
Jeff Davis [Thu, 18 Jul 2019 23:45:03 +0000 (16:45 -0700)]
Fix error in commit e6feef57.

I was careless passing a datum directly to DATE_NOT_FINITE without
calling DatumGetDateADT() first.

Backpatch-through: 9.4

4 years agoFix daterange canonicalization for +/- infinity.
Jeff Davis [Thu, 18 Jul 2019 21:01:17 +0000 (14:01 -0700)]
Fix daterange canonicalization for +/- infinity.

The values 'infinity' and '-infinity' are a part of the DATE type
itself, so a bound of the date 'infinity' is not the same as an
unbounded/infinite range. However, it is still wrong to try to
canonicalize such values, because adding or subtracting one has no
effect. Fix by treating 'infinity' and '-infinity' the same as
unbounded ranges for the purposes of canonicalization (but not other
purposes).

Backpatch to all versions because it is inconsistent with the
documented behavior. Note that this could be an incompatibility for
applications relying on the behavior contrary to the documentation.

Author: Laurenz Albe
Reviewed-by: Thomas Munro
Discussion: https://postgr.es/m/77f24ea19ab802bc9bc60ddbb8977ee2d646aec1.camel%40cybertec.at
Backpatch-through: 9.4

4 years agoFix nbtree metapage cache upgrade bug.
Peter Geoghegan [Thu, 18 Jul 2019 20:22:53 +0000 (13:22 -0700)]
Fix nbtree metapage cache upgrade bug.

Commit 857f9c36cda, which taught nbtree VACUUM to avoid unnecessary
index scans, bumped the nbtree version number from 2 to 3, while adding
the ability for nbtree indexes to be upgraded on-the-fly.  Various
assertions that assumed that an nbtree index was always on version 2 had
to be changed to accept any supported version (version 2 or 3 on
Postgres 11).

However, a few assertions were missed in the initial commit, all of
which were in code paths that cache a local copy of the metapage
metadata, where the index had been expected to be on the current version
(no longer version 2) as a generic sanity check.  Rather than simply
update the assertions, follow-up commit 0a64b45152b intentionally made
the metapage caching code update the per-backend cached metadata version
without changing the on-disk version at the same time.  This could even
happen when the planner needed to determine the height of a B-Tree for
costing purposes.  The assertions only fail on Postgres v12 when
upgrading from v10, because they were adjusted to use the authoritative
shared memory metapage by v12's commit dd299df8.

To fix, remove the cache-only upgrade mechanism entirely, and update the
assertions themselves to accept any supported version (go back to using
the cached version in v12).  The fix is almost a full revert of commit
0a64b45152b on the v11 branch.

VACUUM only considers the authoritative metapage, and never bothers with
a locally cached version, whereas everywhere else isn't interested in
the metapage fields that were added by commit 857f9c36cda.  It seems
unlikely that this bug has affected any user on v11.

Reported-By: Christoph Berg
Bug: #15896
Discussion: https://postgr.es/m/15896-5b25e260fdb0b081%40postgresql.org
Backpatch: 11-, where VACUUM was taught to avoid unnecessary index scans.

4 years agoUpdate time zone data files to tzdata release 2019b.
Tom Lane [Wed, 17 Jul 2019 23:15:21 +0000 (19:15 -0400)]
Update time zone data files to tzdata release 2019b.

Brazil no longer observes DST.
Historical corrections for Palestine, Hong Kong, and Italy.

4 years agoSync our copy of the timezone library with IANA release tzcode2019b.
Tom Lane [Wed, 17 Jul 2019 22:26:23 +0000 (18:26 -0400)]
Sync our copy of the timezone library with IANA release tzcode2019b.

A large fraction of this diff is just due to upstream's somewhat
random decision to rename a bunch of internal variables and struct
fields.  However, there is an interesting new feature in zic:
it's grown a "-b slim" option that emits zone files without 32-bit
data and other backwards-compatibility hacks.  We should consider
whether we wish to enable that.

4 years agoFix thinko in construction of old_conpfeqop list.
Tom Lane [Tue, 16 Jul 2019 22:17:47 +0000 (18:17 -0400)]
Fix thinko in construction of old_conpfeqop list.

This should lappend the OIDs, not lcons them; the existing code produced
a list in reversed order.  This is harmless for single-key FKs or FKs
where all the key columns are of the same type, which probably explains
how it went unnoticed.  But if those conditions are not met,
ATAddForeignKeyConstraint would make the wrong decision about whether an
existing FK needs to be revalidated.  I think it would almost always err
in the safe direction by revalidating a constraint that didn't need it.
You could imagine scenarios where the pfeqop check was fooled by
swapping the types of two FK columns in one ALTER TABLE, but that case
would probably be rejected by other tests, so it might be impossible to
get to the worst-case scenario where an FK should be revalidated and
isn't.  (And even then, it's likely to be fine, unless there are weird
inconsistencies in the equality behavior of the replacement types.)
However, this is a performance bug at least.

Noted while poking around to see whether lcons calls could be converted
to lappend.

This bug is old, dating to commit cb3a7c2b9, so back-patch to all
supported branches.

4 years agodoc: mention pg_reload_conf() for reloading the config file
Bruce Momjian [Tue, 16 Jul 2019 00:57:24 +0000 (20:57 -0400)]
doc:  mention pg_reload_conf() for reloading the config file

Reported-by: Ian Barwick
Discussion: https://postgr.es/m/538950ec-b86a-1650-6078-beb7091c09c2@2ndquadrant.com

Backpatch-through: 9.4

4 years agoFix documentation for pgbench tpcb-like.
Thomas Munro [Sun, 14 Jul 2019 02:19:54 +0000 (14:19 +1200)]
Fix documentation for pgbench tpcb-like.

We choose a random value for delta, not balance.  Back-patch to 9.6 where
the mistake arrived.

Author: Fabien Coelho
Discussion: https://postgr.es/m/alpine.DEB.2.21.1904081752210.5867@lancre

4 years agoFix get_actual_variable_range() to cope with broken HOT chains.
Tom Lane [Fri, 12 Jul 2019 20:24:59 +0000 (16:24 -0400)]
Fix get_actual_variable_range() to cope with broken HOT chains.

Commit 3ca930fc3 modified get_actual_variable_range() to use a new
"SnapshotNonVacuumable" snapshot type for selecting tuples that it
would consider valid.  However, because that snapshot type can accept
recently-dead tuples, this caused a bug when using a recently-created
index: we might accept a recently-dead tuple that is an early member
of a broken HOT chain and does not actually match the index entry.
Then, the data extracted from the heap tuple would not necessarily be
an endpoint value of the column; it could even be NULL, leading to
get_actual_variable_range() itself reporting "found unexpected null
value in index".  Even without an error, this could lead to poor
plan choices due to an erroneous notion of the endpoint value.

We can improve matters by changing the code to use the index-only
scan technique (which didn't exist when get_actual_variable_range was
originally written).  If any of the tuples in a HOT chain are live
enough to satisfy SnapshotNonVacuumable, we take the data from the
index entry, ignoring what is in the heap.  This fixes the problem
without changing the live-vs-dead-tuple behavior from what was
intended by commit 3ca930fc3.

A side benefit is that for static tables we might not have to touch
the heap at all (when the extremal value is in an all-visible page).
In addition, we can save some overhead by not having to create a
complete ExecutorState, and we don't need to run FormIndexDatum,
avoiding more cycles as well as the possibility of failure for
indexes on expressions.  (I'm not sure that this code would ever
be used to determine the extreme value of an expression, in the
current state of the planner; but it's definitely possible that
lower-order columns of the selected index could be expressions.
So one could construct perhaps-artificial examples in which the
old code unexpectedly failed due to trying to compute an
expression's value for a now-dead row.)

Per report from Manuel Rigger.  Back-patch to v11 where commit
3ca930fc3 came in.

Discussion: https://postgr.es/m/CA+u7OA7W4NWEhCvftdV6_8bbm2vgypi5nuxfnSEJQqVKFSUoMg@mail.gmail.com

4 years agoFix RANGE partition pruning with multiple boolean partition keys
David Rowley [Fri, 12 Jul 2019 07:10:12 +0000 (19:10 +1200)]
Fix RANGE partition pruning with multiple boolean partition keys

match_clause_to_partition_key incorrectly would return
PARTCLAUSE_UNSUPPORTED if a bool qual could not be matched to the current
partition key.  This was a problem, as it causes the calling function to
discard the qual and not try to match it to any other partition key.  If
there was another partition key which did match this qual, then the qual
would not be checked again and we could fail to prune some partitions.

The worst this could do was to cause partitions not to be pruned when they
could have been, so there was no danger of incorrect query results here.

Fix this by changing match_boolean_partition_clause to have it return a
PartClauseMatchStatus rather than a boolean value.  This allows it to
communicate if the qual is unsupported or if it just does not match this
particular partition key, previously these two cases were treated the
same.  Now, if match_clause_to_partition_key is unable to match the qual
to any other qual type then we can simply return the value from the
match_boolean_partition_clause call so that the calling function properly
treats the qual as either unmatched or unsupported.

Reported-by: Rares Salcudean
Reviewed-by: Amit Langote
Backpatch-through: 11 where partition pruning was introduced
Discussion: https://postgr.es/m/CAHp_FN2xwEznH6oyS0hNTuUUZKp5PvegcVv=Co6nBXJ+mC7Y5w@mail.gmail.com

4 years agoMention limitation of unique in partitioned tables
Alvaro Herrera [Wed, 10 Jul 2019 12:58:41 +0000 (08:58 -0400)]
Mention limitation of unique in partitioned tables

Per gripe from Phil Bayer.

Authors: Amit Langote and others
Discussion: https://postgr.es/m/156236160709.1192.4498528196556144085@wrigleys.postgresql.org

4 years agoFix compile failure
Alvaro Herrera [Wed, 10 Jul 2019 13:01:28 +0000 (09:01 -0400)]
Fix compile failure

REL_11_STABLE's configure does not select C99 mode by default, so using
C99 block initializer broke the build for some compilers.  Revert to C89
in that branch.

Author: Michaël Paquier
Discussion: https://postgr.es/m/20190710070122.GE1031@paquier.xyz

4 years agoFix variable initialization when using buffering build with GiST
Michael Paquier [Wed, 10 Jul 2019 06:15:07 +0000 (15:15 +0900)]
Fix variable initialization when using buffering build with GiST

This can cause valgrind to complain, as the flag marking a buffer as a
temporary copy was not getting initialized.

While on it, fill in with zeros newly-created buffer pages.  This does
not matter when loading a block from a temporary file, but it makes the
push of an index tuple into a new buffer page safer.

This has been introduced by 1d27dcf, so backpatch all the way down to
9.4.

Author: Alexander Lakhin
Discussion: https://postgr.es/m/15899-0d24fb273b3dd90c@postgresql.org
Backpatch-through: 9.4

4 years agoPass QueryEnvironment down to EvalPlanQual's EState.
Thomas Munro [Tue, 9 Jul 2019 22:15:54 +0000 (10:15 +1200)]
Pass QueryEnvironment down to EvalPlanQual's EState.

Otherwise the executor can't see trigger transition tables during
EPQ evaluation.  Fixes bug #15900 and almost certainly also #15720.
Back-patch to 10, where trigger transition tables landed.

Author: Alex Aktsipetrov
Reviewed-by: Thomas Munro, Tom Lane
Discussion: https://postgr.es/m/15900-bc482754fe8d7415%40postgresql.org
Discussion: https://postgr.es/m/15720-38c2b29e5d720187%40postgresql.org

4 years agoPropagate trigger arguments to partitions
Alvaro Herrera [Tue, 9 Jul 2019 21:16:36 +0000 (17:16 -0400)]
Propagate trigger arguments to partitions

We were creating the cloned triggers with an empty list of arguments,
losing the ones that had been specified by the user when creating the
trigger in the partitioned table.  Repair.

This was forgotten in commit 86f575948c77.

Author: Patrick McHardy
Reviewed-by: Tomas Vondra
Discussion: https://postgr.es/m/20190709130027.amr2cavjvo7rdvac@access1.trash.net
Discussion: https://postgr.es/m/15752-123bc90287986de4@postgresql.org

4 years agoForce hash joins to be enabled in the hash join regression tests.
Thomas Munro [Tue, 9 Jul 2019 06:24:33 +0000 (18:24 +1200)]
Force hash joins to be enabled in the hash join regression tests.

Otherwise the regressplans.sh tests generate extremely slow nested
loop joins.  Back-patch to 11 where the hash join tests came in.

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/20190708055256.GB2709%40paquier.xyz

4 years agodoc: Clarify logical replication documentation
Peter Eisentraut [Mon, 8 Jul 2019 12:28:42 +0000 (14:28 +0200)]
doc: Clarify logical replication documentation

Document that the data types of replicated tables do not need to
match.  The documentation previously claimed that they had to match.

Author: Robert Treat <rob@xzilla.net>
Discussion: https://www.postgresql.org/message-id/flat/CAJSLCQ13==D8Ka2YLyctTm0Y+8MhGYcX_zj7fU0rqRzhcV++3w@mail.gmail.com

4 years agoEnsure plpgsql result tuples have the right composite type marking.
Tom Lane [Wed, 3 Jul 2019 22:08:53 +0000 (18:08 -0400)]
Ensure plpgsql result tuples have the right composite type marking.

A function that is declared to return a named composite type must
return tuple datums that are physically marked as having that type.
The plpgsql code path that allowed directly returning an expanded-record
datum forgot to check that, so that an expanded record marked as type
RECORDOID could be returned if it had a physically-compatible tupdesc.
This'd be harmless, I think, if the record value never escaped the
current session --- but it's possible for it to get stored into a table,
and then subsequent sessions can't interpret the anonymous record type.

Fix by flattening the record into a tuple datum and overwriting its
type/typmod fields, if its declared type doesn't match the function's
declared type.  (In principle it might be possible to just change the
expanded record's stored type ID info, but there are enough tricky
consequences that I didn't want to mess with that, especially not in
a back-patched bug fix.)

Per bug report from Steve Rogerson.  Back-patch to v11 where the bug
was introduced.

Discussion: https://postgr.es/m/cbaecae6-7b87-584e-45f6-4d047b92ca2a@yewtc.demon.co.uk

4 years agoDon't remove surplus columns from GROUP BY for inheritance parents
David Rowley [Wed, 3 Jul 2019 11:45:42 +0000 (23:45 +1200)]
Don't remove surplus columns from GROUP BY for inheritance parents

d4c3a156c added code to remove columns that were not part of a table's
PRIMARY KEY constraint from the GROUP BY clause when all the primary key
columns were present in the group by.  This is fine to do since we know
that there will only be one row per group coming from this relation.
However, the logic failed to consider inheritance parent relations.  These
can have child relations without a primary key, but even if they did, they
could duplicate one of the parent's rows or one from another child
relation.  In this case, those additional GROUP BY columns are required.

Fix this by disabling the optimization for inheritance parent tables.
In v11 and beyond, partitioned tables are fine since partitions cannot
overlap and before v11 partitioned tables could not have a primary key.

Reported-by: Manuel Rigger
Discussion: http://postgr.es/m/CA+u7OA7VLKf_vEr6kLF3MnWSA9LToJYncgpNX2tQ-oWzYCBQAw@mail.gmail.com
Backpatch-through: 9.6

4 years agoAdd support for Visual Studio 2019 in build scripts
Michael Paquier [Tue, 2 Jul 2019 23:57:39 +0000 (08:57 +0900)]
Add support for Visual Studio 2019 in build scripts

This adjusts the documentation and the scripts related to the versions
of Windows SDK supported.

Author: Haribabu Kommi
Reviewed-by: Andrew Dunstan, Juan José Santamaría Flecha, Michael
Paquier
Discussion: https://postgr.es/m/CAJrrPGcfqXhfPyMrny9apoDU7M1t59dzVAvoJ9AeAh5BJi+UzA@mail.gmail.com
Backpatch-through: 9.4

4 years agoFix tab completion of "SET variable TO|=" to not offer bogus completions.
Tom Lane [Tue, 2 Jul 2019 17:35:14 +0000 (13:35 -0400)]
Fix tab completion of "SET variable TO|=" to not offer bogus completions.

Don't think that the context "UPDATE tab SET var =" is a GUC-setting
command.

If we have "SET var =" but the "var" is not a known GUC variable,
don't offer any completions.  The most likely explanation is that
we've misparsed the context and it's not really a GUC-setting command.

Per gripe from Ken Tanzer.  Back-patch to 9.6.  The issue exists
further back, but before 9.6 the code looks very different and it
doesn't actually know whether the "var" name matches anything,
so I desisted from trying to fix it.

Discussion: https://postgr.es/m/CAD3a31XpXzrZA9TT3BqLSHghdTK+=cXjNCE+oL2Zn4+oWoc=qA@mail.gmail.com

4 years agoDon't read fields of a misaligned ExpandedObjectHeader or AnyArrayType.
Noah Misch [Mon, 1 Jul 2019 00:34:17 +0000 (17:34 -0700)]
Don't read fields of a misaligned ExpandedObjectHeader or AnyArrayType.

UBSan complains about this.  Instead, cast to a suitable type requiring
only 4-byte alignment.  DatumGetAnyArrayP() already assumes one can cast
between AnyArrayType and ArrayType, so this doesn't introduce a new
assumption.  Back-patch to 9.5, where AnyArrayType was introduced.

Reviewed by Tom Lane.

Discussion: https://postgr.es/m/20190629210334.GA1244217@rfd.leadboat.com

4 years agoRepair logic for reordering grouping sets optimization.
Andrew Gierth [Sun, 30 Jun 2019 22:49:23 +0000 (23:49 +0100)]
Repair logic for reordering grouping sets optimization.

The logic in reorder_grouping_sets to order grouping set elements to
match a pre-specified sort ordering was defective, resulting in
unnecessary sort nodes (though the query output would still be
correct). Repair, simplifying the code a little, and add a test.

Per report from Richard Guo, though I didn't use their patch. Original
bug seems to have been my fault.

Backpatch back to 9.5 where grouping sets were introduced.

Discussion: https://postgr.es/m/CAN_9JTzyjGcUjiBHxLsgqfk7PkdLGXiM=pwM+=ph2LsWw0WO1A@mail.gmail.com

4 years agoFix for dropped columns in a partitioned table's default partition
Alvaro Herrera [Fri, 28 Jun 2019 18:51:08 +0000 (14:51 -0400)]
Fix for dropped columns in a partitioned table's default partition

We forgot to map column numbers to/from the default partition for
various operations, leading to valid cases failing with spurious
errors, such as
ERROR:  attribute N of type some_partition has been dropped

It was also possible that the search for conflicting rows in the default
partition when attaching another partition would fail to detect some.
Secondarily, it was also possible that such a search should be skipped
(because the constraint was implied) but wasn't.

Fix all this by mapping column numbers when necessary.

Reported by: Daniel Wilches
Author: Amit Langote
Discussion: https://postgr.es/m/15873-8c61945d6b3ef87c@postgresql.org

4 years agoFix misleading comment in nodeIndexonlyscan.c.
Thomas Munro [Thu, 27 Jun 2019 23:11:26 +0000 (11:11 +1200)]
Fix misleading comment in nodeIndexonlyscan.c.

The stated reason for acquiring predicate locks on heap pages hasn't
existed since commit c01262a8, so fix the comment.  Perhaps in a later
release we'll also be able to change the code to use tuple locks.

Back-patch all the way.

Reviewed-by: Ashwin Agrawal
Discussion: https://postgr.es/m/CAEepm%3D2GK3FVdnt5V3d%2Bh9njWipCv_fNL%3DwjxyUhzsF%3D0PcbNg%40mail.gmail.com

4 years agoUpdate reference to sampling algorithm in analyze.c
Tomas Vondra [Thu, 27 Jun 2019 16:14:25 +0000 (18:14 +0200)]
Update reference to sampling algorithm in analyze.c

Commit 83e176ec1 moved row sampling functions from analyze.c to
utils/misc/sampling.c, but failed to update comment referring to
the sampling algorithm from Jeff Vitter's paper. Correct the
comment by pointing to utils/misc/sampling.c.

Author: Etsuro Fujita
Discussion: https://postgr.es/m/CAPmGK154gp%2BQd%3DcorQOv%2BPmbyVyZBjp_%2Bhb766UJeD1e_ie6XQ%40mail.gmail.com

4 years agoFix use-after-free introduced in 55ed3defc966
Alvaro Herrera [Thu, 27 Jun 2019 15:57:10 +0000 (11:57 -0400)]
Fix use-after-free introduced in 55ed3defc966

Evidenced by failure under RELCACHE_FORCE_RELEASE (buildfarm member
prion).

Author: Amit Langote
Discussion: https://postgr.es/m/CA+HiwqGV=k_Eh4jBiQw66ivvdG+EUkrEYeHTYL1SvDj_YOYV0g@mail.gmail.com

4 years agoFix partitioned index creation with foreign partitions
Alvaro Herrera [Wed, 26 Jun 2019 22:38:51 +0000 (18:38 -0400)]
Fix partitioned index creation with foreign partitions

When a partitioned tables contains foreign tables as partitions, it is
not possible to implement unique or primary key indexes -- but when
regular indexes are created, there is no reason to do anything other
than ignoring such partitions.  We were raising errors upon encountering
the foreign partitions, which is unfriendly and doesn't protect against
any actual problems.

Relax this restriction so that index creation is allowed on partitioned
tables containing foreign partitions, becoming a no-op on them.  (We may
later want to redefine this so that the FDW is told to create the
indexes on the foreign side.)  This applies to CREATE INDEX, as well as
ALTER TABLE / ATTACH PARTITION and CREATE TABLE / PARTITION OF.

Backpatch to 11, where indexes on partitioned tables were introduced.

Discussion: https://postgr.es/m/15724-d5a58fa9472eef4f@postgresql.org
Author: Álvaro Herrera
Reviewed-by: Amit Langote
4 years agoAdd support for OpenSSL 1.1.0 and newer versions in MSVC scripts
Michael Paquier [Wed, 26 Jun 2019 14:04:32 +0000 (23:04 +0900)]
Add support for OpenSSL 1.1.0 and newer versions in MSVC scripts

Up to now, the MSVC build scripts are able to support only one fixed
version of OpenSSL, and they lacked logic to detect the version of
OpenSSL a given compilation of Postgres is linking to (currently 1.0.2,
the latest LTS of upstream which will be EOL'd at the end of 2019).

This commit adds more logic to detect the version of OpenSSL used by a
build and makes use of it to add support for compilation with OpenSSL
1.1.0 which requires a new set of compilation flags to work properly.

The supported OpenSSL installers have changed their library layer with
various library renames with the upgrade to 1.1.0, making the logic a
bit more complicated.  The scripts are now able to adapt to the new
world order.

Reported-by: Sergey Pashkov
Author: Juan José Santamaría Flecha, Michael Paquier
Reviewed-by: Álvaro Herrera
Discussion: https://postgr.es/m/15789-8fc75dea3c5a17c8@postgresql.org
Backpatch-through: 9.4

4 years agoFollow the rule that regression-test-created roles are named "regress_xxx".
Tom Lane [Wed, 26 Jun 2019 03:06:17 +0000 (23:06 -0400)]
Follow the rule that regression-test-created roles are named "regress_xxx".

contrib/amcheck didn't get the memo either.

4 years agoFix thinkos in LookupFuncName() for function name lookups
Michael Paquier [Tue, 25 Jun 2019 02:15:38 +0000 (11:15 +0900)]
Fix thinkos in LookupFuncName() for function name lookups

This could trigger valgrind failures when doing ambiguous function name
lookups when no arguments are provided by the caller.  The problem has
been introduced in aefeb68, so backpatch to v10.  HEAD is fine thanks to
the refactoring done in bfb456c1.

Reported-by: Alexander Lakhin
Author: Alexander Lakhin, Michael Paquier
Discussion: https://postgr.es/m/3d068be5-f617-a5ee-99f6-458a407bfd65@gmail.com
Backpatch-through: 10

4 years agoDon't unset MAKEFLAGS in non-GNU Makefile.
Thomas Munro [Mon, 24 Jun 2019 21:29:53 +0000 (09:29 +1200)]
Don't unset MAKEFLAGS in non-GNU Makefile.

It's useful to be able to pass down options like -s and -j.

Back-patch to 9.5, like commit a76200de.

Discussion: https://postgr.es/m/CA%2BhUKG%2Be1M8-BbL%3DPqhTp6oO6XPO6%2Bs9WGQMLfbuZ%3DG9CtzyXg%40mail.gmail.com

4 years agoRemove misleading comment from pathnodes.h.
Thomas Munro [Mon, 24 Jun 2019 21:17:04 +0000 (09:17 +1200)]
Remove misleading comment from pathnodes.h.

As of commit e5253fdc, it is no longer true that the leader always
executes the subplan of a Gather Merge node.  Remove comment to that
effect.

Back-patch to 11.

Discussion: https://postgr.es/m/CA%2BhUKGJEaZJYezXAOutuiWT%2BfxCA44%2BoKtVPAND2ubLiigR%3D-w%40mail.gmail.com

4 years agoFurther fix ALTER COLUMN TYPE's handling of indexes and index constraints.
Tom Lane [Mon, 24 Jun 2019 20:43:05 +0000 (16:43 -0400)]
Further fix ALTER COLUMN TYPE's handling of indexes and index constraints.

This patch reverts all the code changes of commit e76de8861, which turns
out to have been seriously misguided.  We can't wait till later to compute
the definition string for an index; we must capture that before applying
the data type change for any column it depends on, else ruleutils.c will
deliverr wrong/misleading results.  (This fine point was documented
nowhere, of course.)

I'd also managed to forget that ATExecAlterColumnType executes once per
ALTER COLUMN TYPE clause, not once per statement; which resulted in the
code being basically completely broken for any case in which multiple ALTER
COLUMN TYPE clauses are applied to a table having non-constraint indexes
that must be rebuilt.  Through very bad luck, none of the existing test
cases nor the ones added by e76de8861 caught that, but of course it was
soon found in the field.

The previous patch also had an implicit assumption that if a constraint's
index had a dependency on a table column, so would the constraint --- but
that isn't actually true, so it didn't fix such cases.

Instead of trying to delete unneeded index dependencies later, do the
is-there-a-constraint lookup immediately on seeing an index dependency,
and switch to remembering the constraint if so.  In the unusual case of
multiple column dependencies for a constraint index, this will result in
duplicate constraint lookups, but that's not that horrible compared to all
the other work that happens here.  Besides, such cases did not work at all
before, so it's hard to argue that they're performance-critical for anyone.

Per bug #15865 from Keith Fiske.  As before, back-patch to all supported
branches.

Discussion: https://postgr.es/m/15865-17940eacc8f8b081@postgresql.org

4 years agoFix spinlock assembly code for MIPS so it works on MIPS r6.
Tom Lane [Sun, 23 Jun 2019 00:31:50 +0000 (20:31 -0400)]
Fix spinlock assembly code for MIPS so it works on MIPS r6.

Original MIPS-I processors didn't have the LL/SC instructions (nor any
other userland synchronization primitive).  If the build toolchain
targets that ISA variant by default, as an astonishingly large fraction
of MIPS platforms still do, the assembler won't take LL/SC without
coercion in the form of a ".set mips2" instruction.  But we issued that
unconditionally, making it an ISA downgrade for chips later than MIPS2.
That breaks things for the latest MIPS r6 ISA, which encodes these
instructions differently.  Adjust the code so we don't change ISA level
if it's >= 2.

Note that this patch doesn't change what happens on an actual MIPS-I
processor: either the kernel will emulate these instructions
transparently, or you'll get a SIGILL failure.  That tradeoff seemed
fine in 2002 when this code was added (cf 3cbe6b247), and it's even
more so today when MIPS-I is basically extinct.  But let's add a
comment about that.

YunQiang Su (with cosmetic adjustments by me).  Back-patch to all
supported branches.

Discussion: https://postgr.es/m/15844-8f62fe7e163939b3@postgresql.org

4 years agoConsolidate methods for translating a Perl path to a Windows path.
Noah Misch [Sat, 22 Jun 2019 03:34:23 +0000 (20:34 -0700)]
Consolidate methods for translating a Perl path to a Windows path.

This fixes some TAP suites when using msys Perl and a builddir located
in an msys mount point other than "/".  For example, builddir=/c/pg
exhibited the problem, since /c/pg falls in mount point "/c".
Back-patch to 9.6, where tests first started to perform such
translations.  In back branches, offer both new and old APIs.

Reviewed by Andrew Dunstan.

Discussion: https://postgr.es/m/20190610045838.GA238501@rfd.leadboat.com

4 years agoRemove obsolete comments about sempahores from proc.c.
Thomas Munro [Thu, 20 Jun 2019 22:57:07 +0000 (10:57 +1200)]
Remove obsolete comments about sempahores from proc.c.

Commit 6753333f switched from a semaphore-based wait to a latch-based
wait for ProcSleep()/ProcWakeup(), but left behind some stray references
to semaphores.

Back-patch to 9.5.

Reviewed-by: Daniel Gustafsson, Michael Paquier
Discussion: https://postgr.es/m/CA+hUKGLs5H6zhmgTijZ1OaJvC1sG0=AFXc1aHuce32tKiQrdEA@mail.gmail.com

4 years agoFix description of WAL record XLOG_BTREE_META_CLEANUP
Michael Paquier [Wed, 19 Jun 2019 02:02:28 +0000 (11:02 +0900)]
Fix description of WAL record XLOG_BTREE_META_CLEANUP

This record uses one metadata buffer and registers some data associated
to the buffer, but when parsing the record for its description a direct
access to the record data was done, but there is none.  This leads
usually to an incorrect description, but can also cause crashes like in
pg_waldump.  Instead, fix things so as the parsing uses the data
associated to the metadata block.

This is an oversight from 3d92796, so backpatch down to 11.

Author: Michael Paquier
Description: https://postgr.es/m/20190617013059.GA3153@paquier.xyz
Backpatch-through: 11

4 years agoAvoid spurious deadlocks when upgrading a tuple lock
Alvaro Herrera [Tue, 18 Jun 2019 22:23:16 +0000 (18:23 -0400)]
Avoid spurious deadlocks when upgrading a tuple lock

This puts back reverted commit de87a084c0a5, with some bug fixes.

When two (or more) transactions are waiting for transaction T1 to release a
tuple-level lock, and transaction T1 upgrades its lock to a higher level, a
spurious deadlock can be reported among the waiting transactions when T1
finishes.  The simplest example case seems to be:

T1: select id from job where name = 'a' for key share;
Y: select id from job where name = 'a' for update; -- starts waiting for T1
Z: select id from job where name = 'a' for key share;
T1: update job set name = 'b' where id = 1;
Z: update job set name = 'c' where id = 1; -- starts waiting for T1
T1: rollback;

At this point, transaction Y is rolled back on account of a deadlock: Y
holds the heavyweight tuple lock and is waiting for the Xmax to be released,
while Z holds part of the multixact and tries to acquire the heavyweight
lock (per protocol) and goes to sleep; once T1 releases its part of the
multixact, Z is awakened only to be put back to sleep on the heavyweight
lock that Y is holding while sleeping.  Kaboom.

This can be avoided by having Z skip the heavyweight lock acquisition.  As
far as I can see, the biggest downside is that if there are multiple Z
transactions, the order in which they resume after T1 finishes is not
guaranteed.

Backpatch to 9.6.  The patch applies cleanly on 9.5, but the new tests don't
work there (because isolationtester is not smart enough), so I'm not going
to risk it.

Author: Oleksii Kliukin
Discussion: https://postgr.es/m/B9C9D7CD-EB94-4635-91B6-E558ACEC0EC3@hintbits.com
Discussion: https://postgr.es/m/2815.1560521451@sss.pgh.pa.us

4 years agoPrevent Parallel Hash Join for JOIN_UNIQUE_INNER.
Thomas Munro [Tue, 18 Jun 2019 10:38:30 +0000 (22:38 +1200)]
Prevent Parallel Hash Join for JOIN_UNIQUE_INNER.

WHERE EXISTS (...) queries cannot be executed by Parallel Hash Join
with jointype JOIN_UNIQUE_INNER, because there is no way to make a
partial plan totally unique.  The consequence of allowing such plans
was duplicate results from some EXISTS queries.

Back-patch to 11.  Bug #15857.

Author: Thomas Munro
Reviewed-by: Tom Lane
Reported-by: Vladimir Kriukov
Discussion: https://postgr.es/m/15857-d1ba2a64bce0795e%40postgresql.org

4 years agoStamp 11.4. REL_11_4
Tom Lane [Mon, 17 Jun 2019 21:15:30 +0000 (17:15 -0400)]
Stamp 11.4.

4 years agoLast-minute updates for release notes.
Tom Lane [Mon, 17 Jun 2019 14:53:45 +0000 (10:53 -0400)]
Last-minute updates for release notes.

Security: CVE-2019-10164

4 years agoTranslation updates
Peter Eisentraut [Mon, 17 Jun 2019 13:04:41 +0000 (15:04 +0200)]
Translation updates

Source-Git-URL: https://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 599a4bccd28710a88972e1a0ef6961c9bad816fc

4 years agoFix buffer overflow when processing SCRAM final message in libpq
Michael Paquier [Mon, 17 Jun 2019 13:14:04 +0000 (22:14 +0900)]
Fix buffer overflow when processing SCRAM final message in libpq

When a client connects to a rogue server sending specifically-crafted
messages, this can suffice to execute arbitrary code as the operating
system account used by the client.

While on it, fix one error handling when decoding an incorrect salt
included in the first message received from server.

Author: Michael Paquier
Reviewed-by: Jonathan Katz, Heikki Linnakangas
Security: CVE-2019-10164
Backpatch-through: 10

4 years agoFix buffer overflow when parsing SCRAM verifiers in backend
Michael Paquier [Mon, 17 Jun 2019 12:48:25 +0000 (21:48 +0900)]
Fix buffer overflow when parsing SCRAM verifiers in backend

Any authenticated user can overflow a stack-based buffer by changing the
user's own password to a purpose-crafted value.  This often suffices to
execute arbitrary code as the PostgreSQL operating system account.

This fix is contributed by multiple folks, based on an initial analysis
from Tom Lane.  This issue has been introduced by 68e61ee, so it was
possible to make use of it at authentication time.  It became more
easily to trigger after ccae190 which has made the SCRAM parsing more
strict when changing a password, in the case where the client passes
down a verifier already hashed using SCRAM.  Back-patch to v10 where
SCRAM has been introduced.

Reported-by: Alexander Lakhin
Author: Jonathan Katz, Heikki Linnakangas, Michael Paquier
Security: CVE-2019-10164
Backpatch-through: 10

4 years agoRevert "Avoid spurious deadlocks when upgrading a tuple lock"
Alvaro Herrera [Mon, 17 Jun 2019 02:24:21 +0000 (22:24 -0400)]
Revert "Avoid spurious deadlocks when upgrading a tuple lock"

This reverts commits 3da73d6839dc and de87a084c0a5.

This code has some tricky corner cases that I'm not sure are correct and
not properly tested anyway, so I'm reverting the whole thing for next
week's releases (reintroducing the deadlock bug that we set to fix).
I'll try again afterwards.

Discussion: https://postgr.es/m/E1hbXKQ-0003g1-0C@gemulon.postgresql.org

4 years agoDoc: update 11.4 release notes through today.
Tom Lane [Sun, 16 Jun 2019 18:47:34 +0000 (14:47 -0400)]
Doc: update 11.4 release notes through today.

Also improve wording of some items (thanks to Noah Misch for suggestions).

4 years agoPrefer timezone name "UTC" over alternative spellings.
Andrew Gierth [Sat, 15 Jun 2019 17:15:23 +0000 (18:15 +0100)]
Prefer timezone name "UTC" over alternative spellings.

tzdb 2019a made "UCT" a link to the "UTC" zone rather than a separate
zone with its own abbreviation. Unfortunately, our code for choosing a
timezone in initdb has an arbitrary preference for names earlier in
the alphabet, and so it would choose the spelling "UCT" over "UTC"
when the system is running on a UTC zone.

Commit 23bd3cec6 was backpatched in order to address this issue, but
that code helps only when /etc/localtime exists as a symlink, and does
nothing to help on systems where /etc/localtime is a copy of a zone
file (as is the standard setup on FreeBSD and probably some other
platforms too) or when /etc/localtime is simply absent (giving UTC as
the default).

Accordingly, add a preference for the spelling "UTC", such that if
multiple zone names have equally good content matches, we prefer that
name before applying the existing arbitrary rules. Also add a slightly
lower preference for "Etc/UTC"; lower because that preserves the
previous behaviour of choosing the shorter name, but letting us still
choose "Etc/UTC" over "Etc/UCT" when both exist but "UTC" does
not (not common, but I've seen it happen).

Backpatch all the way, because the tzdb change that sparked this issue
is in those branches too.

4 years agoFirst-draft release notes for 11.4.
Tom Lane [Fri, 14 Jun 2019 20:56:49 +0000 (16:56 -0400)]
First-draft release notes for 11.4.

As usual, the release notes for other branches will be made by cutting
these down, but put them up for community review first.

4 years agoSilence compiler warning
Alvaro Herrera [Fri, 14 Jun 2019 15:33:40 +0000 (11:33 -0400)]
Silence compiler warning

Introduced in de87a084c0a5.

4 years agoAttempt to identify system timezone by reading /etc/localtime symlink.
Tom Lane [Fri, 14 Jun 2019 15:25:13 +0000 (11:25 -0400)]
Attempt to identify system timezone by reading /etc/localtime symlink.

On many modern platforms, /etc/localtime is a symlink to a file within the
IANA database.  Reading the symlink lets us find out the name of the system
timezone directly, without going through the brute-force search embodied in
scan_available_timezones().  This shortens the runtime of initdb by some
tens of ms, which is helpful for the buildfarm, and it also allows us to
reliably select the same zone name the system was actually configured for,
rather than possibly choosing one of IANA's many zone aliases.  (For
example, in a system configured for "Asia/Tokyo", the brute-force search
would not choose that name but its alias "Japan", on the grounds of the
latter string being shorter.  More surprisingly, "Navajo" is preferred
to either "America/Denver" or "US/Mountain", as seen in an old complaint
from Josh Berkus.)

If /etc/localtime doesn't exist, or isn't a symlink, or we can't make
sense of its contents, or the contents match a zone we know but that
zone doesn't match the observed behavior of localtime(), fall back to
the brute-force search.

Also, tweak initdb so that it prints the zone name it selected.

In passing, replace the last few references to the "Olson" database in
code comments with "IANA", as that's been our preferred term since
commit b2cbced9e.

Back-patch of commit 23bd3cec6.  The original intention was to not
back-patch, since this can result in cosmetic behavioral changes ---
for example, on my own workstation initdb now chooses "America/New_York",
where it used to prefer "US/Eastern" which is equivalent and shorter.
However, our hand has been more or less forced by tzdb update 2019a,
which made the "UCT" zone fully equivalent to "UTC".  Our old code
now prefers "UCT" on the grounds of it being alphabetically first,
and that's making nobody happy.  Choosing the alias indicated by
/etc/localtime is a more defensible behavior.  (Users who don't like
the results can always force the decision by setting the TZ environment
variable before running initdb.)

Patch by me, per a suggestion from Robert Haas; review by Michael Paquier

Discussion: https://postgr.es/m/7408.1525812528@sss.pgh.pa.us
Discussion: https://postgr.es/m/20190604085735.GD24018@msg.df7cb.de

4 years agoAvoid spurious deadlocks when upgrading a tuple lock
Alvaro Herrera [Thu, 13 Jun 2019 21:28:24 +0000 (17:28 -0400)]
Avoid spurious deadlocks when upgrading a tuple lock

When two (or more) transactions are waiting for transaction T1 to release a
tuple-level lock, and transaction T1 upgrades its lock to a higher level, a
spurious deadlock can be reported among the waiting transactions when T1
finishes.  The simplest example case seems to be:

T1: select id from job where name = 'a' for key share;
Y: select id from job where name = 'a' for update; -- starts waiting for X
Z: select id from job where name = 'a' for key share;
T1: update job set name = 'b' where id = 1;
Z: update job set name = 'c' where id = 1; -- starts waiting for X
T1: rollback;

At this point, transaction Y is rolled back on account of a deadlock: Y
holds the heavyweight tuple lock and is waiting for the Xmax to be released,
while Z holds part of the multixact and tries to acquire the heavyweight
lock (per protocol) and goes to sleep; once X releases its part of the
multixact, Z is awakened only to be put back to sleep on the heavyweight
lock that Y is holding while sleeping.  Kaboom.

This can be avoided by having Z skip the heavyweight lock acquisition.  As
far as I can see, the biggest downside is that if there are multiple Z
transactions, the order in which they resume after X finishes is not
guaranteed.

Backpatch to 9.6.  The patch applies cleanly on 9.5, but the new tests don't
work there (because isolationtester is not smart enough), so I'm not going
to risk it.

Author: Oleksii Kliukin
Discussion: https://postgr.es/m/B9C9D7CD-EB94-4635-91B6-E558ACEC0EC3@hintbits.com

4 years agoMark ReplicationSlotCtl as PGDLLIMPORT.
Tom Lane [Thu, 13 Jun 2019 14:53:17 +0000 (10:53 -0400)]
Mark ReplicationSlotCtl as PGDLLIMPORT.

Also MyReplicationSlot, in branches where it wasn't already.

This was discussed in the thread that resulted in c572599c6, but
for some reason nobody pulled the trigger.  Now that we have another
request for the same thing, we should just do it.

Craig Ringer

Discussion: https://postgr.es/m/CAMsr+YFTsq-86MnsNng=mPvjjh5EAbzfMK0ptJPvzyvpFARuRg@mail.gmail.com
Discussion: https://postgr.es/m/345138875.20190611151943@cybertec.at

4 years agopostgres_fdw: Account for triggers in non-direct remote UPDATE planning.
Etsuro Fujita [Thu, 13 Jun 2019 08:59:11 +0000 (17:59 +0900)]
postgres_fdw: Account for triggers in non-direct remote UPDATE planning.

Previously, in postgresPlanForeignModify, we planned an UPDATE operation
on a foreign table so that we transmit only columns that were explicitly
targets of the UPDATE, so as to avoid unnecessary data transmission, but
if there were BEFORE ROW UPDATE triggers on the foreign table, those
triggers might change values for non-target columns, in which case we
would miss sending changed values for those columns.  Prevent optimizing
away transmitting all columns if there are BEFORE ROW UPDATE triggers on
the foreign table.

This is an oversight in commit 7cbe57c34 which added triggers on foreign
tables, so apply the patch all the way back to 9.4 where that came in.

Author: Shohei Mochizuki
Reviewed-by: Amit Langote
Discussion: https://postgr.es/m/201905270152.x4R1q3qi014550@toshiba.co.jp

4 years agoDoc: improve description of allowed spellings for Boolean input.
Tom Lane [Thu, 13 Jun 2019 02:54:46 +0000 (22:54 -0400)]
Doc: improve description of allowed spellings for Boolean input.

datatype.sgml failed to explain that boolin() accepts any unique
prefix of the basic input strings.  Indeed it was actively misleading
because it called out a few minimal prefixes without mentioning that
there were more valid inputs.

I also felt that it wasn't doing anybody any favors by conflating
SQL key words, valid Boolean input, and string literals containing
valid Boolean input.  Rewrite in hopes of reducing the confusion.

Per bug #15836 from Yuming Wang, as diagnosed by David Johnston.
Back-patch to supported branches.

Discussion: https://postgr.es/m/15836-656fab055735f511@postgresql.org

4 years agoFix incorrect printing of queries with duplicated join names.
Tom Lane [Wed, 12 Jun 2019 23:42:38 +0000 (19:42 -0400)]
Fix incorrect printing of queries with duplicated join names.

Given a query in which multiple JOIN nodes used the same alias
(which'd necessarily be in different sub-SELECTs), ruleutils.c
would assign the JOIN nodes distinct aliases for clarity ...
but then it forgot to print the modified aliases when dumping
the JOIN nodes themselves.  This results in a dump/reload hazard
for views, because the emitted query is flat-out incorrect:
Vars will be printed with table names that have no referent.

This has been wrong for a long time, so back-patch to all supported
branches.

Philip Dubé

Discussion: https://postgr.es/m/CY4PR2101MB080246F2955FF58A6ED1FEAC98140@CY4PR2101MB0802.namprd21.prod.outlook.com

4 years agodoc: Fix grammatical error in partitioning docs
David Rowley [Wed, 12 Jun 2019 22:35:27 +0000 (10:35 +1200)]
doc: Fix grammatical error in partitioning docs

Reported-by: Amit Langote
Discussion: https://postgr.es/m/CA+HiwqGZFkKi0TkBGYpr2_5qrRAbHZoP47AP1BRLUOUkfQdy_A@mail.gmail.com
Backpatch-through: 10

4 years agoIn walreceiver, don't try to do ereport() in a signal handler.
Tom Lane [Wed, 12 Jun 2019 21:29:48 +0000 (17:29 -0400)]
In walreceiver, don't try to do ereport() in a signal handler.

This is quite unsafe, even for the case of ereport(FATAL) where we won't
return control to the interrupted code, and despite this code's use of
a flag to restrict the areas where we'd try to do it.  It's possible
for example that we interrupt malloc or free while that's holding a lock
that's meant to protect against cross-thread interference.  Then, any
attempt to do malloc or free within ereport() will result in a deadlock,
preventing the walreceiver process from exiting in response to SIGTERM.
We hypothesize that this explains some hard-to-reproduce failures seen
in the buildfarm.

Hence, get rid of the immediate-exit code in WalRcvShutdownHandler,
as well as the logic associated with WalRcvImmediateInterruptOK.
Instead, we need to take care that potentially-blocking operations
in the walreceiver's data transmission logic (libpqwalreceiver.c)
will respond reasonably promptly to the process's latch becoming
set and then call ProcessWalRcvInterrupts.  Much of the needed code
for that was already present in libpqwalreceiver.c.  I refactored
things a bit so that all the uses of PQgetResult use latch-aware
waiting, but didn't need to do much more.

These changes should be enough to ensure that libpqwalreceiver.c
will respond promptly to SIGTERM whenever it's waiting to receive
data.  In principle, it could block for a long time while waiting
to send data too, and this patch does nothing to guard against that.
I think that that hazard is mostly theoretical though: such blocking
should occur only if we fill the kernel's data transmission buffers,
and we don't generally send enough data to make that happen without
waiting for input.  If we find out that the hazard isn't just
theoretical, we could fix it by using PQsetnonblocking, but that
would require more ticklish changes than I care to make now.

Back-patch of commit a1a789eb5.  This problem goes all the way back
to the origins of walreceiver; but given the substantial reworking
the module received during the v10 cycle, it seems unsafe to assume
that our testing on HEAD validates this patch for pre-v10 branches.
And we'd need to back-patch some prerequisite patches (at least
597a87ccc and its followups, maybe other things), increasing the risk
of problems.  Given the dearth of field reports matching this problem,
it's not worth much risk.  Hence back-patch to v10 and v11 only.

Patch by me; thanks to Thomas Munro for review.

Discussion: https://postgr.es/m/20190416070119.GK2673@paquier.xyz

4 years agoFix ALTER COLUMN TYPE failure with a partial exclusion constraint.
Tom Lane [Wed, 12 Jun 2019 16:29:24 +0000 (12:29 -0400)]
Fix ALTER COLUMN TYPE failure with a partial exclusion constraint.

ATExecAlterColumnType failed to consider the possibility that an index
that needs to be rebuilt might be a child of a constraint that needs to be
rebuilt.  We missed this so far because usually a constraint index doesn't
have a direct dependency on its table, just on the constraint object.
But if there's a WHERE clause, then dependency analysis of the WHERE
clause results in direct dependencies on the column(s) mentioned in WHERE.
This led to trying to drop and rebuild both the constraint and its
underlying index.

In v11/HEAD, we successfully drop both the index and the constraint,
and then try to rebuild both, and of course the second rebuild hits a
duplicate-index-name problem.  Before v11, it fails with obscure messages
about a missing relation OID, due to trying to drop the index twice.

This is essentially the same kind of problem noted in commit
20bef2c31: the possible dependency linkages are broader than what
ATExecAlterColumnType was designed for.  It was probably OK when
written, but it's certainly been broken since the introduction of
partial exclusion constraints.  Fix by adding an explicit check
for whether any of the indexes-to-be-rebuilt belong to any of the
constraints-to-be-rebuilt, and ignoring any that do.

In passing, fix a latent bug introduced by commit 8b08f7d48: in
get_constraint_index() we must "continue" not "break" when rejecting
a relation of a wrong relkind.  This is harmless today because we don't
expect that code path to be taken anyway; but if there ever were any
relations to be ignored, the existing coding would have an extremely
undesirable dependency on the order of pg_depend entries.

Also adjust a couple of obsolete comments.

Per bug #15835 from Yaroslav Schekin.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/15835-32d9b7a76c06a7a9@postgresql.org

4 years agoFix handling of COMMENT for domain constraints
Michael Paquier [Wed, 12 Jun 2019 02:30:41 +0000 (11:30 +0900)]
Fix handling of COMMENT for domain constraints

For a non-superuser, changing a comment on a domain constraint was
leading to a cache lookup failure as the code tried to perform the
ownership lookup on the constraint OID itself, thinking that it was a
type, but this check needs to happen on the type the domain constraint
relies on.  As the type a domain constraint relies on can be guessed
directly based on the constraint OID, first fetch its type OID and
perform the ownership on it.

This is broken since 7eca575, which has split the handling of comments
for table constraints and domain constraints, so back-patch down to
9.5.

Reported-by: Clemens Ladisch
Author: Daniel Gustafsson, Michael Paquier
Reviewed-by: Álvaro Herrera
Discussion: https://postgr.es/m/15833-808e11904835d26f@postgresql.org
Backpatch-through: 9.5

4 years agodoc: Add best practises section to partitioning docs
David Rowley [Tue, 11 Jun 2019 20:09:11 +0000 (08:09 +1200)]
doc: Add best practises section to partitioning docs

A few questionable partitioning designs have been cropping up lately
around the mailing lists.  Generally, these cases have been partitioning
using too many partitions which have caused performance or OOM problems for
the users.

Since we have very little else to guide users into good design, here we
add a new section to the partitioning documentation with some best
practise guidelines for good design.

Reviewed-by: Justin Pryzby, Amit Langote, Alvaro Herrera
Discussion: https://postgr.es/m/CAKJS1f-2rx+E9mG3xrCVHupefMjAp1+tpczQa9SEOZWyU7fjEA@mail.gmail.com
Backpatch-through: 10