postgresql.git
4 years agoDoc: clarify that CREATE TABLE discards redundant unique constraints.
Tom Lane [Tue, 8 Dec 2020 18:09:48 +0000 (13:09 -0500)]
Doc: clarify that CREATE TABLE discards redundant unique constraints.

The SQL standard says that redundant unique constraints are disallowed,
but we long ago decided that throwing an error would be too
user-unfriendly, so we just drop redundant ones.  The docs weren't very
clear about that though, as this behavior was only explained for PRIMARY
KEY vs UNIQUE, not UNIQUE vs UNIQUE.

While here, I couldn't resist doing some copy-editing and markup-fixing
on the adjacent text about INCLUDE options.

Per bug #16767 from Matthias vd Meent.

Discussion: https://postgr.es/m/16767-1714a2056ca516d0@postgresql.org

4 years agoDoc: explain that the string types can't store \0 (ASCII NUL).
Tom Lane [Tue, 8 Dec 2020 17:06:19 +0000 (12:06 -0500)]
Doc: explain that the string types can't store \0 (ASCII NUL).

This restriction was mentioned in connection with string literals,
but it wasn't made clear that it's a general restriction not just
a syntactic limitation in query strings.

Per unsigned documentation comment.

Discussion: https://postgr.es/m/160720552914.710.16625261471128631268@wrigleys.postgresql.org

4 years agopgcrypto: Detect errors with EVP calls from OpenSSL
Michael Paquier [Tue, 8 Dec 2020 06:23:02 +0000 (15:23 +0900)]
pgcrypto: Detect errors with EVP calls from OpenSSL

The following routines are called within pgcrypto when handling digests
but there were no checks for failures:
- EVP_MD_CTX_size (can fail with -1 as of 3.0.0)
- EVP_MD_CTX_block_size (can fail with -1 as of 3.0.0)
- EVP_DigestInit_ex
- EVP_DigestUpdate
- EVP_DigestFinal_ex

A set of elog(ERROR) is added by this commit to detect such failures,
that should never happen except in the event of a processing failure
internal to OpenSSL.

Note that it would be possible to use ERR_reason_error_string() to get
more context about such errors, but these refer mainly to the internals
of OpenSSL, so it is not really obvious how useful that would be.  This
is left out for simplicity.

Per report from Coverity.  Thanks to Tom Lane for the discussion.

Backpatch-through: 9.5

4 years agoFix more race conditions in the newly-added pg_rewind test.
Heikki Linnakangas [Mon, 7 Dec 2020 12:44:34 +0000 (14:44 +0200)]
Fix more race conditions in the newly-added pg_rewind test.

pg_rewind looks at the control file to check what timeline a server is on.
But promotion doesn't immediately write a checkpoint, it merely writes
an end-of-recovery WAL record. If pg_rewind runs immediately after
promotion, before the checkpoint has completed, it will think think that
the server is still on the earlier timeline. We ran into this issue a long
time ago already, see commit 484a848a73f.

It's a bit bogus that pg_rewind doesn't determine the timeline correctly
until the end-of-recovery checkpoint has completed. We probably should
fix that. But for now work around it by waiting for the checkpoint
to complete before running pg_rewind, like we did in commit 484a848a73f.

In the passing, tidy up the new test a little bit. Rerder the INSERTs so
that the comments make more sense, remove a spurious CHECKPOINT call after
pg_rewind has already run, and add --debug option, so that if this fails
again, we'll have more data.

Per buildfarm failure at https://buildfarm.postgresql.org/cgi-bin/show_stage_log.pl?nm=rorqual&dt=2020-12-06%2018%3A32%3A19&stg=pg_rewind-check.
Backpatch to all supported versions.

Discussion: https://www.postgresql.org/message-id/1713707e-e318-761c-d287-5b6a4aa807e8@iki.fi

4 years agoFix race conditions in newly-added test.
Heikki Linnakangas [Fri, 4 Dec 2020 16:20:18 +0000 (18:20 +0200)]
Fix race conditions in newly-added test.

Buildfarm has been failing sporadically on the new test.  I was able to
reproduce this by adding a random 0-10 s delay in the walreceiver, just
before it connects to the primary. There's a race condition where node_3
is promoted before it has fully caught up with node_1, leading to diverged
timelines. When node_1 is later reconfigured as standby following node_3,
it fails to catch up:

LOG:  primary server contains no more WAL on requested timeline 1
LOG:  new timeline 2 forked off current database system timeline 1 before current recovery point 0/30000A0

That's the situation where you'd need to use pg_rewind, but in this case
it happens already when we are just setting up the actual pg_rewind
scenario we want to test, so change the test so that it waits until
node_3 is connected and fully caught up before promoting it, so that you
get a clean, controlled failover.

Also rewrite some of the comments, for clarity. The existing comments
detailed what each step in the test did, but didn't give a good overview
of the situation the steps were trying to create.

For reasons I don't understand, the test setup had to be written slightly
differently in 9.6 and 9.5 than in later versions. The 9.5/9.6 version
needed node 1 to be reinitialized from backup, whereas in later versions
it could be shut down and reconfigured to be a standby. But even 9.5 should
support "clean switchover", where primary makes sure that pending WAL is
replicated to standby on shutdown. It would be nice to figure out what's
going on there, but that's independent of pg_rewind and the scenario that
this test tests.

Discussion: https://www.postgresql.org/message-id/b0a3b95b-82d2-6089-6892-40570f8c5e60%40iki.fi

4 years agodocs: list single-letter options first in command-line summary
Bruce Momjian [Thu, 3 Dec 2020 15:28:58 +0000 (10:28 -0500)]
docs:  list single-letter options first in command-line summary

In a few places, the long-version options were listed before the
single-letter ones in the command summary of a few commands.  This
didn't match other commands, and didn't match the option ordering later
in the same reference page.

Backpatch-through: 9.5

4 years agoFix pg_rewind bugs when rewinding a standby server.
Heikki Linnakangas [Thu, 3 Dec 2020 13:57:48 +0000 (15:57 +0200)]
Fix pg_rewind bugs when rewinding a standby server.

If the target is a standby server, its WAL doesn't end at the last
checkpoint record, but at minRecoveryPoint. We must scan all the
WAL from the last common checkpoint all the way up to minRecoveryPoint
for modified pages, and also consider that portion when determining
whether the server needs rewinding.

Backpatch to all supported versions.

Author: Ian Barwick and me
Discussion: https://www.postgresql.org/message-id/CABvVfJU-LDWvoz4-Yow3Ay5LZYTuPD7eSjjE4kGyNZpXC6FrVQ%40mail.gmail.com

4 years agoEnsure that expandTableLikeClause() re-examines the same table.
Tom Lane [Tue, 1 Dec 2020 19:02:28 +0000 (14:02 -0500)]
Ensure that expandTableLikeClause() re-examines the same table.

As it stood, expandTableLikeClause() re-did the same relation_openrv
call that transformTableLikeClause() had done.  However there are
scenarios where this would not find the same table as expected.
We hold lock on the LIKE source table, so it can't be renamed or
dropped, but another table could appear before it in the search path.
This explains the odd behavior reported in bug #16758 when cloning a
table as a temp table of the same name.  This case worked as expected
before commit 502898192 introduced the need to open the source table
twice, so we should fix it.

To make really sure we get the same table, let's re-open it by OID not
name.  That requires adding an OID field to struct TableLikeClause,
which is a little nervous-making from an ABI standpoint, but as long
as it's at the end I don't think there's any serious risk.

Per bug #16758 from Marc Boeren.  Like the previous patch,
back-patch to all supported branches.

Discussion: https://postgr.es/m/16758-840e84a6cfab276d@postgresql.org

4 years agoFree disk space for dropped relations on commit.
Thomas Munro [Tue, 1 Dec 2020 00:46:27 +0000 (13:46 +1300)]
Free disk space for dropped relations on commit.

When committing a transaction that dropped a relation, we previously
truncated only the first segment file to free up disk space (the one
that won't be unlinked until the next checkpoint).

Truncate higher numbered segments too, even though we unlink them on
commit.  This frees the disk space immediately, even if other backends
have open file descriptors and might take a long time to get around to
handling shared invalidation events and closing them.  Also extend the
same behavior to the first segment, in recovery.

Back-patch to all supported releases.

Bug: #16663
Reported-by: Denis Patron <[email protected]>
Reviewed-by: Pavel Borisov <[email protected]>
Reviewed-by: Neil Chen <[email protected]>
Reviewed-by: David Zhang <[email protected]>
Discussion: https://postgr.es/m/16663-fe97ccf9932fc800%40postgresql.org

4 years agoDocument concurrent indexes waiting on each other
Alvaro Herrera [Mon, 30 Nov 2020 21:24:55 +0000 (18:24 -0300)]
Document concurrent indexes waiting on each other

Because regular CREATE INDEX commands are independent, and there's no
logical data dependency, it's not immediately obvious that transactions
held by concurrent index builds on one table will block the second phase
of concurrent index creation on an unrelated table, so document this
caveat.

Backpatch this all the way back.  In branch master, mention that only
some indexes are involved.

Author: James Coleman <[email protected]>
Reviewed-by: David Johnston <[email protected]>
Discussion: https://postgr.es/m/CAAaqYe994=PUrn8CJZ4UEo_S-FfRr_3ogERyhtdgHAb2WG_Ufg@mail.gmail.com

4 years agoFix miscomputation of direct_lateral_relids for join relations.
Tom Lane [Mon, 30 Nov 2020 17:22:43 +0000 (12:22 -0500)]
Fix miscomputation of direct_lateral_relids for join relations.

If a PlaceHolderVar is to be evaluated at a join relation, but
its value is only needed there and not at higher levels, we neglected
to update the joinrel's direct_lateral_relids to include the PHV's
source rel.  This causes problems because join_is_legal() then won't
allow joining the joinrel to the PHV's source rel at all, leading
to "failed to build any N-way joins" planner failures.

Per report from Andreas Seltenreich.  Back-patch to 9.5
where the problem originated.

Discussion: https://postgr.es/m/[email protected]

4 years agoFix recently-introduced breakage in psql's \connect command.
Tom Lane [Sun, 29 Nov 2020 20:22:04 +0000 (15:22 -0500)]
Fix recently-introduced breakage in psql's \connect command.

Through my misreading of what the existing code actually did,
commits 85c54287a et al. broke psql's behavior for the case where
"\c connstring" provides a password in the connstring.  We should
use that password in such a case, but as of 85c54287a we ignored it
(and instead, prompted for a password).

Commit 94929f1cf fixed that in HEAD, but since I thought it was
cleaning up a longstanding misbehavior and not one I'd just created,
I didn't back-patch it.

Hence, back-patch the portions of 94929f1cf having to do with
password management.  In addition to fixing the introduced bug,
this means that "\c -reuse-previous=on connstring" will allow
re-use of an existing connection's password if the connstring
doesn't change user/host/port.  That didn't happen before, but
it seems like a bug fix, and anyway I'm loath to have significant
differences in this code across versions.

Also fix an error with the same root cause about whether or not to
override a connstring's setting of client_encoding.  As of 85c54287a
we always did so; restore the previous behavior of overriding only
when stdin/stdout are a terminal and there's no environment setting
of PGCLIENTENCODING.  (I find that definition a bit surprising, but
right now doesn't seem like the time to revisit it.)

Per bug #16746 from Krzysztof Gradek.  As with the previous patch,
back-patch to all supported branches.

Discussion: https://postgr.es/m/16746-44b30e2edf4335d4@postgresql.org

4 years agoDoc: clarify behavior of PQconnectdbParams().
Tom Lane [Sun, 29 Nov 2020 18:58:30 +0000 (13:58 -0500)]
Doc: clarify behavior of PQconnectdbParams().

The documentation omitted the critical tidbit that a keyword-array entry
is simply ignored if its corresponding value-array entry is NULL or an
empty string; it will *not* override any previously-obtained value for
the parameter.  (See conninfo_array_parse().)  I'd supposed that would
force the setting back to default, which is what led me into bug #16746;
but it doesn't.

While here, I couldn't resist the temptation to do some copy-editing,
both in the description of PQconnectdbParams() and in the section
about connection URI syntax.

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

4 years agoFix a recently-introduced race condition in LISTEN/NOTIFY handling.
Tom Lane [Sat, 28 Nov 2020 19:03:40 +0000 (14:03 -0500)]
Fix a recently-introduced race condition in LISTEN/NOTIFY handling.

Commit 566372b3d fixed some race conditions involving concurrent
SimpleLruTruncate calls, but it introduced new ones in async.c.
A newly-listening backend could attempt to read Notify SLRU pages that
were in process of being truncated, possibly causing an error.  Also,
the QUEUE_TAIL pointer could become set to a value that's not equal to
the queue position of any backend.  While that's fairly harmless in
v13 and up (thanks to commit 51004c717), in older branches it resulted
in near-permanent disabling of the queue truncation logic, so that
continued use of NOTIFY led to queue-fill warnings and eventual
inability to send any more notifies.  (A server restart is enough to
make that go away, but it's still pretty unpleasant.)

The core of the problem is confusion about whether QUEUE_TAIL
represents the "logical" tail of the queue (i.e., the oldest
still-interesting data) or the "physical" tail (the oldest data we've
not yet truncated away).  To fix, split that into two variables.
QUEUE_TAIL regains its definition as the logical tail, and we
introduce a new variable to track the oldest un-truncated page.

Per report from Mikael Gustavsson.  Like the previous patch,
back-patch to all supported branches.

Discussion: https://postgr.es/m/1b8561412e8a4f038d7a491c8b922788@smhi.se

4 years agodoc: Fix typos
Peter Eisentraut [Wed, 25 Nov 2020 08:49:00 +0000 (09:49 +0100)]
doc: Fix typos

Author: Justin Pryzby <[email protected]>
Discussion: https://www.postgresql.org/message-id/20201121194105[email protected]

4 years agoProperly check index mark/restore in ExecSupportsMarkRestore.
Andrew Gierth [Tue, 24 Nov 2020 20:58:32 +0000 (20:58 +0000)]
Properly check index mark/restore in ExecSupportsMarkRestore.

Previously this code assumed that all IndexScan nodes supported
mark/restore, which is not true since it depends on optional index AM
support functions. This could lead to errors about missing support
functions in rare edge cases of mergejoins with no sort keys, where an
unordered non-btree index scan was placed on the inner path without a
protecting Materialize node. (Normally, the fact that merge join
requires ordered input would avoid this error.)

Backpatch all the way since this bug is ancient.

Per report from Eugen Konkov on irc.

Discussion: https://postgr.es/m/[email protected]

4 years agoSkip allocating hash table in EXPLAIN-only mode.
Heikki Linnakangas [Fri, 20 Nov 2020 12:41:14 +0000 (14:41 +0200)]
Skip allocating hash table in EXPLAIN-only mode.

This is a backpatch of commit 2cccb627f1, backpatched due to popular
demand. Backpatch to all supported versions.

Author: Alexey Bashtanov
Discussion: https://www.postgresql.org/message-id/36823f65-050d-ae24-aa4d-a37726998240%40imap.cc

4 years agoOn macOS, use -isysroot in link steps as well as compile steps.
Tom Lane [Fri, 20 Nov 2020 05:58:26 +0000 (00:58 -0500)]
On macOS, use -isysroot in link steps as well as compile steps.

We previously put the -isysroot switch only into CPPFLAGS, theorizing
that it was only needed to find the right copies of include files.
However, it seems that we also need to use it while linking programs,
to find the right stub ".tbd" files for libraries.  We got away
without that up to now, but apparently that was mostly luck.  It may
also be that failures are only observed when the Xcode version is
noticeably out of sync with the host macOS version; the case that's
prompting action right now is that builds fail when using latest Xcode
(12.2) on macOS Catalina, even though it's fine on Big Sur.

Hence, add -isysroot to LDFLAGS as well.  (It seems that the more
common practice is to put it in CFLAGS, whence it'd be included at
both compile and link steps.  However, we can't mess with CFLAGS in
the platform template file without confusing configure's logic for
choosing default CFLAGS.)

Back-patch of 49407dc32 into all supported branches.

Report and patch by James Hilliard (some cosmetic mods by me)

Discussion: https://postgr.es/m/20201120003314[email protected]

4 years agoFurther fixes for CREATE TABLE LIKE: cope with self-referential FKs.
Tom Lane [Thu, 19 Nov 2020 20:03:17 +0000 (15:03 -0500)]
Further fixes for CREATE TABLE LIKE: cope with self-referential FKs.

Commit 502898192 was too careless about the order of execution of the
additional ALTER TABLE operations generated by expandTableLikeClause.
It just stuck them all at the end, which seems okay for most purposes.
But it falls down in the case where LIKE is importing a primary key
or unique index and the outer CREATE TABLE includes a FOREIGN KEY
constraint that needs to depend on that index.  Weird as that is,
it used to work, so we ought to keep it working.

To fix, make parse_utilcmd.c insert LIKE clauses between index-creation
and FK-creation commands in the transformed list of commands, and change
utility.c so that the commands generated by expandTableLikeClause are
executed immediately not at the end.  One could imagine scenarios where
this wouldn't work either; but currently expandTableLikeClause only
makes column default expressions, CHECK constraints, and indexes, and
this ordering seems fine for those.

Per bug #16730 from Sofoklis Papasofokli.  Like the previous patch,
back-patch to all supported branches.

Discussion: https://postgr.es/m/16730-b902f7e6e0276b30@postgresql.org

4 years agoDon't Insert() a VFD entry until it's fully built.
Tom Lane [Tue, 17 Nov 2020 01:32:35 +0000 (20:32 -0500)]
Don't Insert() a VFD entry until it's fully built.

Otherwise, if FDDEBUG is enabled, the debugging output fails because
it tries to read the fileName, which isn't set up yet (and should in
fact always be NULL).

AFAICT, this has been wrong since Berkeley.  Before 96bf88d52,
it would accidentally fail to crash on platforms where snprintf()
is forgiving about being passed a NULL pointer for %s; but the
file name intended to be included in the debug output wouldn't
ever have shown up.

Report and fix by Greg Nancarrow.  Although this is only visibly
broken in custom-made builds, it still seems worth back-patching
to all supported branches, as the FDDEBUG code is pretty useless
as it stands.

Discussion: https://postgr.es/m/CAJcOf-cUDgm9qYtC_B6XrC6MktMPNRby2p61EtSGZKnfotMArw@mail.gmail.com

4 years agodoc: update bgwriter description
Bruce Momjian [Mon, 16 Nov 2020 18:13:43 +0000 (13:13 -0500)]
doc:  update bgwriter description

This clarifies exactly what the bgwriter does, which should help with
tuning.

Reported-by: Chris Wilson
Discussion: https://postgr.es/m/160399562040.7809.7335281028960123489@wrigleys.postgresql.org

Backpatch-through: 9.5

4 years agodoc: clarify how to find pg_type_d.h in the install tree
Bruce Momjian [Mon, 16 Nov 2020 17:36:16 +0000 (12:36 -0500)]
doc:  clarify how to find pg_type_d.h in the install tree

Followup to patch 152ed04799.

Reported-by: Alvaro Herrera
Discussion: https://postgr.es/m/20201112202900[email protected]

Backpatch-through: 9.5

4 years agodoc: adjust expression index analyze working some more
Bruce Momjian [Mon, 16 Nov 2020 16:14:53 +0000 (11:14 -0500)]
doc:  adjust expression index analyze working some more

This applies the fix bcbd771332 to skipped branches.

Reported-by: Erik Rijkers
Discussion: https://postgr.es/m/e92b3fba98a0c0f7afc0a2a37e765954@xs4all.nl

Backpatch-through: 9.5-11

4 years agodoc: improve wording of the need for analyze of exp. indexes
Bruce Momjian [Mon, 16 Nov 2020 15:26:16 +0000 (10:26 -0500)]
doc:  improve wording of the need for analyze of exp. indexes

This is a followup commit on 3370207986.

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20201112211143[email protected]

Backpatch-through: 9.5

4 years agodoc: clarify where to find pg_type_d.h (PG 11+) and pg_type.h
Bruce Momjian [Thu, 12 Nov 2020 20:13:01 +0000 (15:13 -0500)]
doc:  clarify where to find pg_type_d.h (PG 11+) and pg_type.h

These files are in compiled directories and install directories.

Reported-by: [email protected]
Discussion: https://postgr.es/m/160379609706.24746.7506163279454026608@wrigleys.postgresql.org

Backpatch-through: 9.5

4 years agodocs: mention that expression indexes need analyze
Bruce Momjian [Thu, 12 Nov 2020 20:00:43 +0000 (15:00 -0500)]
docs: mention that expression indexes need analyze

Expression indexes can't benefit from pre-computed statistics on
columns.

Reported-by: Nikolay Samokhvalov
Discussion: https://postgr.es/m/CANNMO++5rw9RDA=p40iMVbMNPaW6O=S0AFzTU=KpYHRpCd1voA@mail.gmail.com

Author: Nikolay Samokhvalov, modified

Backpatch-through: 9.5

4 years agodoc: wire protocol data type for history file content is bytea
Bruce Momjian [Thu, 12 Nov 2020 19:33:28 +0000 (14:33 -0500)]
doc:  wire protocol data type for history file content is bytea

Document that though the history file content is marked as bytea, it is
the same a text, and neither is btyea-escaped or encoding converted.

Reported-by: Brar Piening
Discussion: https://postgr.es/m/6a1b9cd9-17e3-df67-be55-86102af6bdf5@gmx.de

Backpatch-through: 13 - 9.5 (not master)

4 years agopg_trgm: fix crash in 2-item picksplit
Andrew Gierth [Thu, 12 Nov 2020 14:34:37 +0000 (14:34 +0000)]
pg_trgm: fix crash in 2-item picksplit

Whether from size overflow in gistSplit or from secondary splits,
picksplit is (rarely) called with exactly two items to split.

Formerly, due to special-case handling of the last item, this would
lead to access to an uninitialized cache entry; prior to PG 13 this
might have been harmless or at worst led to an incorrect union datum,
but in 13 onwards it can cause a backend crash from using an
uninitialized pointer.

Repair by removing the special case, which was deemed not to have been
appropriate anyway. Backpatch all the way, because this bug has
existed since pg_trgm was added.

Per report on IRC from user "ftzdomino". Analysis and testing by me,
patch from Alexander Korotkov.

Discussion: https://postgr.es/m/[email protected]

4 years agoFix and simplify some usages of TimestampDifference().
Tom Lane [Wed, 11 Nov 2020 03:51:19 +0000 (22:51 -0500)]
Fix and simplify some usages of TimestampDifference().

Introduce TimestampDifferenceMilliseconds() to simplify callers
that would rather have the difference in milliseconds, instead of
the select()-oriented seconds-and-microseconds format.  This gets
rid of at least one integer division per call, and it eliminates
some apparently-easy-to-mess-up arithmetic.

Two of these call sites were in fact wrong:

* pg_prewarm's autoprewarm_main() forgot to multiply the seconds
by 1000, thus ending up with a delay 1000X shorter than intended.
That doesn't quite make it a busy-wait, but close.

* postgres_fdw's pgfdw_get_cleanup_result() thought it needed to compute
microseconds not milliseconds, thus ending up with a delay 1000X longer
than intended.  Somebody along the way had noticed this problem but
misdiagnosed the cause, and imposed an ad-hoc 60-second limit rather
than fixing the units.  This was relatively harmless in context, because
we don't care that much about exactly how long this delay is; still,
it's wrong.

There are a few more callers of TimestampDifference() that don't
have a direct need for seconds-and-microseconds, but can't use
TimestampDifferenceMilliseconds() either because they do need
microsecond precision or because they might possibly deal with
intervals long enough to overflow 32-bit milliseconds.  It might be
worth inventing another API to improve that, but that seems outside
the scope of this patch; so those callers are untouched here.

Given the fact that we are fixing some bugs, and the likelihood
that future patches might want to back-patch code that uses this
new API, back-patch to all supported branches.

Alexey Kondratov and Tom Lane

Discussion: https://postgr.es/m/3b1c053a21c07c1ed5e00be3b2b855ef@postgrespro.ru

4 years agodoc: fix spelling "connction" to "connection"
Bruce Momjian [Wed, 11 Nov 2020 00:18:35 +0000 (19:18 -0500)]
doc: fix spelling "connction" to "connection"

Was wrong in commit 1a9388bd0f.

Reported-by: Tom Lane, Justin Pryzby
Discussion: https://postgr.es/m/20201102063333[email protected]

Backpatch-through: 9.5

4 years agoWork around cross-version-upgrade issues created by commit 9e38c2bb5.
Tom Lane [Tue, 10 Nov 2020 23:32:36 +0000 (18:32 -0500)]
Work around cross-version-upgrade issues created by commit 9e38c2bb5.

Summarily changing the STYPE of regression-test aggregates that
depend on array_append or array_cat is an issue for the buildfarm's
cross-version-upgrade tests, because those aggregates (as defined
in the back branches) now won't load into HEAD.  Although this seems
like only a minimal risk for genuine user-defined aggregates, we
need to do something for the buildfarm.  Hence, adjust the aggregate
definitions, in both HEAD and the back branches.

Discussion: https://postgr.es/m/1401824.1604537031@sss.pgh.pa.us
Discussion: https://postgr.es/m/[email protected]

4 years agoStamp 9.5.24. REL9_5_24
Tom Lane [Mon, 9 Nov 2020 22:34:09 +0000 (17:34 -0500)]
Stamp 9.5.24.

4 years agoLast-minute updates for release notes.
Tom Lane [Mon, 9 Nov 2020 18:02:14 +0000 (13:02 -0500)]
Last-minute updates for release notes.

Security: CVE-2020-25694, CVE-2020-25695, CVE-2020-25696

4 years agoDoc: clarify data type behavior of COALESCE and NULLIF.
Tom Lane [Mon, 9 Nov 2020 17:02:24 +0000 (12:02 -0500)]
Doc: clarify data type behavior of COALESCE and NULLIF.

After studying the code, NULLIF is a lot more subtle than you might
have guessed.

Discussion: https://postgr.es/m/160486028730.25500.15740897403028593550@wrigleys.postgresql.org

4 years agoIgnore attempts to \gset into specially treated variables.
Noah Misch [Mon, 9 Nov 2020 15:32:09 +0000 (07:32 -0800)]
Ignore attempts to \gset into specially treated variables.

If an interactive psql session used \gset when querying a compromised
server, the attacker could execute arbitrary code as the operating
system account running psql.  Using a prefix not found among specially
treated variables, e.g. every lowercase string, precluded the attack.
Fix by issuing a warning and setting no variable for the column in
question.  Users wanting the old behavior can use a prefix and then a
meta-command like "\set HISTSIZE :prefix_HISTSIZE".  Back-patch to 9.5
(all supported versions).

Reviewed by Robert Haas.  Reported by Nick Cleaton.

Security: CVE-2020-25696

4 years agoIn security-restricted operations, block enqueue of at-commit user code.
Noah Misch [Mon, 9 Nov 2020 15:32:09 +0000 (07:32 -0800)]
In security-restricted operations, block enqueue of at-commit user code.

Specifically, this blocks DECLARE ... WITH HOLD and firing of deferred
triggers within index expressions and materialized view queries.  An
attacker having permission to create non-temp objects in at least one
schema could execute arbitrary SQL functions under the identity of the
bootstrap superuser.  One can work around the vulnerability by disabling
autovacuum and not manually running ANALYZE, CLUSTER, REINDEX, CREATE
INDEX, VACUUM FULL, or REFRESH MATERIALIZED VIEW.  (Don't restore from
pg_dump, since it runs some of those commands.)  Plain VACUUM (without
FULL) is safe, and all commands are fine when a trusted user owns the
target object.  Performance may degrade quickly under this workaround,
however.  Back-patch to 9.5 (all supported versions).

Reviewed by Robert Haas.  Reported by Etienne Stalmans.

Security: CVE-2020-25695

4 years agoTranslation updates
Peter Eisentraut [Mon, 9 Nov 2020 11:50:59 +0000 (12:50 +0100)]
Translation updates

Source-Git-URL: https://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 8740d75e31771525e9bb55e71bfd343faae253b4

4 years agoRelease notes for 13.1, 12.5, 11.10, 10.15, 9.6.20, 9.5.24.
Tom Lane [Sun, 8 Nov 2020 20:16:12 +0000 (15:16 -0500)]
Release notes for 13.1, 12.5, 11.10, 10.15, 9.6.20, 9.5.24.

4 years agoFix redundant error messages in client tools
Peter Eisentraut [Sat, 7 Nov 2020 21:15:52 +0000 (22:15 +0100)]
Fix redundant error messages in client tools

A few client tools duplicate error messages already provided by libpq.

Discussion: https://www.postgresql.org/message-id/flat/3e937641-88a1-e697-612e-99bba4b8e5e4%40enterprisedb.com

4 years agoProperly detoast data in brin_form_tuple
Tomas Vondra [Fri, 6 Nov 2020 23:41:52 +0000 (00:41 +0100)]
Properly detoast data in brin_form_tuple

brin_form_tuple failed to consider the values may be toasted, inserting
the toast pointer into the index. This may easily result in index
corruption, as the toast data may be deleted and cleaned up by vacuum.
The cleanup however does not care about indexes, leaving invalid toast
pointers behind, which triggers errors like this:

  ERROR:  missing chunk number 0 for toast value 16433 in pg_toast_16426

A less severe consequence are inconsistent failures due to the index row
being too large, depending on whether brin_form_tuple operated on plain
or toasted version of the row. For example

    CREATE TABLE t (val TEXT);
    INSERT INTO t VALUES ('... long value ...')
    CREATE INDEX idx ON t USING brin (val);

would likely succeed, as the row would likely include toast pointer.
Switching the order of INSERT and CREATE INDEX would likely fail:

    ERROR:  index row size 8712 exceeds maximum 8152 for index "idx"

because this happens before the row values are toasted.

The bug exists since PostgreSQL 9.5 where BRIN indexes were introduced.
So backpatch all the way back.

Author: Tomas Vondra
Reviewed-by: Alvaro Herrera
Backpatch-through: 9.5
Discussion: https://postgr.es/m/20201001184133.oq5uq75sb45pu3aw@development
Discussion: https://postgr.es/m/20201104010544.zexj52mlldagzowv%40development

4 years agoRevert "Accept relations of any kind in LOCK TABLE".
Tom Lane [Fri, 6 Nov 2020 21:17:57 +0000 (16:17 -0500)]
Revert "Accept relations of any kind in LOCK TABLE".

Revert 59ab4ac32, as well as the followup fix 33862cb9c, in all
branches.  We need to think a bit harder about what the behavior
of LOCK TABLE on views should be, and there's no time for that
before next week's releases.  We'll take another crack at this
later.

Discussion: https://postgr.es/m/16703-e348f58aab3cf6cc@postgresql.org

4 years agoRevert "pg_dump: Lock all relations, not just plain tables".
Tom Lane [Fri, 6 Nov 2020 20:48:21 +0000 (15:48 -0500)]
Revert "pg_dump: Lock all relations, not just plain tables".

Revert 403a3d91c, as well as the followup fix 7f4235032, in all
branches.  We need to think a bit harder about what the behavior
of LOCK TABLE on views should be, and there's no time for that
before next week's releases.  We'll take another crack at this
later.

Discussion: https://postgr.es/m/16703-e348f58aab3cf6cc@postgresql.org

4 years agoDoc: undo mistaken adjustment to LOCK TABLE docs in back branches.
Tom Lane [Fri, 6 Nov 2020 17:14:55 +0000 (12:14 -0500)]
Doc: undo mistaken adjustment to LOCK TABLE docs in back branches.

Commits 59ab4ac32 et al mistakenly copied-and-pasted some text about
how LOCK on a view recurses to referenced tables into pre-v11 branches,
which in fact don't do that.  Undo that, and instead state clearly
that they don't.  (I also chose to add a note that this behavior
changed in v11.  We usually don't back-patch such statements, but
since it's easy to add the warning now, might as well.)

Noted while considering followup fixes for bug #16703.

Discussion: https://postgr.es/m/16703-e348f58aab3cf6cc@postgresql.org

4 years agoAllow users with BYPASSRLS to alter their own passwords.
Tom Lane [Tue, 3 Nov 2020 20:41:32 +0000 (15:41 -0500)]
Allow users with BYPASSRLS to alter their own passwords.

The intention in commit 491c029db was to require superuserness to
change the BYPASSRLS property, but the actual effect of the coding
in AlterRole() was to require superuserness to change anything at all
about a BYPASSRLS role.  Other properties of a BYPASSRLS role should
be changeable under the same rules as for a normal role, though.

Fix that, and also take care of some documentation omissions related
to BYPASSRLS and REPLICATION role properties.

Tom Lane and Stephen Frost, per bug report from Wolfgang Walther.
Back-patch to all supported branches.

Discussion: https://postgr.es/m/a5548a9f-89ee-3167-129d-162b5985fcf8@technowledgy.de

4 years agoAvoid null pointer dereference if error result lacks SQLSTATE.
Tom Lane [Sun, 1 Nov 2020 16:26:16 +0000 (11:26 -0500)]
Avoid null pointer dereference if error result lacks SQLSTATE.

Although error results received from the backend should always have
a SQLSTATE field, ones generated by libpq won't, making this code
vulnerable to a crash after, say, untimely loss of connection.
Noted by Coverity.

Oversight in commit 403a3d91c.  Back-patch to 9.5, as that was.

4 years agoUse mode "r" for popen() in psql's evaluate_backtick().
Tom Lane [Wed, 28 Oct 2020 18:35:53 +0000 (14:35 -0400)]
Use mode "r" for popen() in psql's evaluate_backtick().

In almost all other places, we use plain "r" or "w" mode in popen()
calls (the exceptions being for COPY data).  This one has been
overlooked (possibly because it's buried in a ".l" flex file?),
but it's using PG_BINARY_R.

Kensuke Okamura complained in bug #16688 that we fail to strip \r
when stripping the trailing newline from a backtick result string.
That's true enough, but we'd also fail to convert embedded \r\n
cleanly, which also seems undesirable.  Fixing the popen() mode
seems like the best way to deal with this.

It's been like this for a long time, so back-patch to all supported
branches.

Discussion: https://postgr.es/m/16688-c649c7b69cd7e6f8@postgresql.org

4 years agoFix use-after-free bug with event triggers and ALTER TABLE.
Tom Lane [Tue, 27 Oct 2020 19:37:13 +0000 (15:37 -0400)]
Fix use-after-free bug with event triggers and ALTER TABLE.

EventTriggerAlterTableEnd neglected to make sure that it built its
output list in the right context.  In simple cases this was masked
because the function is called in PortalContext which will be
sufficiently long-lived anyway; but that doesn't make it not a bug.
Commit ced138e8c fixed this in HEAD and v13, but mistakenly chose
not to back-patch further.  Back-patch the same code change all
the way (I didn't bother with the test case though, as it would
prove nothing in pre-v13 branches).

Per report from Arseny Sher.
Original fix by Jehan-Guillaume de Rorthais.

Discussion: https://postgr.es/m/877drcyprb.fsf@ars-thinkpad
Discussion: https://postgr.es/m/20200902193715.6e0269d4@firost

4 years agoMakefile comment: remove reference to tools/thread/thread_test
Bruce Momjian [Tue, 27 Oct 2020 18:00:38 +0000 (14:00 -0400)]
Makefile comment:  remove reference to tools/thread/thread_test

You can't compile thread_test alone anymore, and the location moved too.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/1062278.1603819969@sss.pgh.pa.us

Backpatch-through: 9.5

4 years agopg_dump: Lock all relations, not just plain tables
Alvaro Herrera [Tue, 27 Oct 2020 17:31:37 +0000 (14:31 -0300)]
pg_dump: Lock all relations, not just plain tables

Now that LOCK TABLE can take any relation type, acquire lock on all
relations that are to be dumped.  This prevents schema changes or
deadlock errors that could cause a dump to fail after expending much
effort.  The server is tested to have the capability and the feature
disabled if it doesn't, so that a patched pg_dump doesn't fail when
connecting to an unpatched server.

Backpatch to 9.5.

Author: Álvaro Herrera <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Reported-by: Wells Oliver <[email protected]>
Discussion: https://postgr.es/m/20201021200659[email protected]

4 years agoAccept relations of any kind in LOCK TABLE
Alvaro Herrera [Tue, 27 Oct 2020 16:49:19 +0000 (13:49 -0300)]
Accept relations of any kind in LOCK TABLE

The restriction that only tables and views can be locked by LOCK TABLE
is quite arbitrary, since the underlying mechanism can lock any relation
type.  Drop the restriction so that programs such as pg_dump can lock
all relations they're interested in, preventing schema changes that
could cause a dump to fail after expending much effort.

Backpatch to 9.5.

Author: Álvaro Herrera <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Reported-by: Wells Oliver <[email protected]>
Discussion: https://postgr.es/m/20201021200659[email protected]

4 years agodocs: remove reference to src/tools/thread
Bruce Momjian [Tue, 27 Oct 2020 16:43:11 +0000 (12:43 -0400)]
docs:  remove reference to src/tools/thread

This directory and the ability to build the thread test independently
were removed in commit 8a2121185b.

Reported-by: [email protected]
Discussion: https://postgr.es/m/160379609706.24746.7506163279454026608@wrigleys.postgresql.org

Backpatch-through: 9.5

4 years agodoc: simplify wording of function error affects
Bruce Momjian [Tue, 27 Oct 2020 02:38:11 +0000 (22:38 -0400)]
doc:  simplify wording of function error affects

Reported-by: [email protected]
Discussion: https://postgr.es/m/160324449781.693.8298142858847611071@wrigleys.postgresql.org

Backpatch-through: 9.5

4 years agoFix ancient bug in ecpg's pthread_once() emulation for Windows.
Tom Lane [Sat, 24 Oct 2020 17:12:08 +0000 (13:12 -0400)]
Fix ancient bug in ecpg's pthread_once() emulation for Windows.

We must not set the "done" flag until after we've executed the
initialization function.  Otherwise, other threads can fall through
the initial unlocked test before initialization is really complete.

This has been seen to cause rare failures of ecpg's thread/descriptor
test, and it could presumably cause other sorts of misbehavior in
threaded ECPG-using applications, since ecpglib relies on
pthread_once() in several places.

Diagnosis and patch by me, based on investigation by Alexander Lakhin.
Back-patch to all supported branches (the bug dates to 2007).

Discussion: https://postgr.es/m/16685-d6cd241872c101d3@postgresql.org

4 years agoUpdate time zone data files to tzdata release 2020d.
Tom Lane [Fri, 23 Oct 2020 01:23:47 +0000 (21:23 -0400)]
Update time zone data files to tzdata release 2020d.

DST law changes in Palestine, with a whopping 120 hours' notice.
Also some historical corrections for Palestine.

4 years agoSync our copy of the timezone library with IANA release tzcode2020d.
Tom Lane [Fri, 23 Oct 2020 01:15:22 +0000 (21:15 -0400)]
Sync our copy of the timezone library with IANA release tzcode2020d.

There's no functional change at all here, but I'm curious to see
whether this change successfully shuts up Coverity's warning about
a useless strcmp(), which appeared with the previous update.

Discussion: http://mm.icann.org/pipermail/tz/2020-October/029370.html

4 years agoFix connection string handling in psql's \connect command.
Tom Lane [Wed, 21 Oct 2020 20:18:41 +0000 (16:18 -0400)]
Fix connection string handling in psql's \connect command.

psql's \connect claims to be able to re-use previous connection
parameters, but in fact it only re-uses the database name, user name,
host name (and possibly hostaddr, depending on version), and port.
This is problematic for assorted use cases.  Notably, pg_dump[all]
emits "\connect databasename" commands which we would like to have
re-use all other parameters.  If such a script is loaded in a psql run
that initially had "-d connstring" with some non-default parameters,
those other parameters would be lost, potentially causing connection
failure.  (Thus, this is the same kind of bug addressed in commits
a45bc8a4f and 8e5793ab6, although the details are much different.)

To fix, redesign do_connect() so that it pulls out all properties
of the old PGconn using PQconninfo(), and then replaces individual
properties in that array.  In the case where we don't wish to re-use
anything, get libpq's default settings using PQconndefaults() and
replace entries in that, so that we don't need different code paths
for the two cases.

This does result in an additional behavioral change for cases where
the original connection parameters allowed multiple hosts, say
"psql -h host1,host2", and the \connect request allows re-use of the
host setting.  Because the previous coding relied on PQhost(), it
would only permit reconnection to the same host originally selected.
Although one can think of scenarios where that's a good thing, there
are others where it is not.  Moreover, that behavior doesn't seem to
meet the principle of least surprise, nor was it documented; nor is
it even clear it was intended, since that coding long pre-dates the
addition of multi-host support to libpq.  Hence, this patch is content
to drop it and re-use the host list as given.

Per Peter Eisentraut's comments on bug #16604.  Back-patch to all
supported branches.

Discussion: https://postgr.es/m/16604-933f4b8791227b15@postgresql.org

4 years agoAvoid invalid alloc size error in shm_mq
Peter Eisentraut [Mon, 19 Oct 2020 06:52:25 +0000 (08:52 +0200)]
Avoid invalid alloc size error in shm_mq

In shm_mq_receive(), a huge payload could trigger an unjustified
"invalid memory alloc request size" error due to the way the buffer
size is increased.

Add error checks (documenting the upper limit) and avoid the error by
limiting the allocation size to MaxAllocSize.

Author: Markus Wanner <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/3bb363e7-ac04-0ac4-9fe8-db1148755bfa%402ndquadrant.com

4 years agoFix connection string handling in src/bin/scripts/ programs.
Tom Lane [Mon, 19 Oct 2020 23:03:47 +0000 (19:03 -0400)]
Fix connection string handling in src/bin/scripts/ programs.

When told to process all databases, clusterdb, reindexdb, and vacuumdb
would reconnect by replacing their --maintenance-db parameter with the
name of the target database.  If that parameter is a connstring (which
has been allowed for a long time, though we failed to document that
before this patch), we'd lose any other options it might specify, for
example SSL or GSS parameters, possibly resulting in failure to connect.
Thus, this is the same bug as commit a45bc8a4f fixed in pg_dump and
pg_restore.  We can fix it in the same way, by using libpq's rules for
handling multiple "dbname" parameters to add the target database name
separately.  I chose to apply the same refactoring approach as in that
patch, with a struct to handle the command line parameters that need to
be passed through to connectDatabase.  (Maybe someday we can unify the
very similar functions here and in pg_dump/pg_restore.)

Per Peter Eisentraut's comments on bug #16604.  Back-patch to all
supported branches.

Discussion: https://postgr.es/m/16604-933f4b8791227b15@postgresql.org

4 years agoMisc documentation fixes.
Heikki Linnakangas [Mon, 19 Oct 2020 16:28:54 +0000 (19:28 +0300)]
Misc documentation fixes.

- Misc grammar and punctuation fixes.

- Stylistic cleanup: use spaces between function arguments and JSON fields
  in examples. For example "foo(a,b)" -> "foo(a, b)". Add semicolon after
  last END in a few PL/pgSQL examples that were missing them.

- Make sentence that talked about "..." and ".." operators more clear,
  by avoiding to end the sentence with "..". That makes it look the same
  as "..."

- Fix syntax description for HAVING: HAVING conditions cannot be repeated

Patch by Justin Pryzby, per Yaroslav Schekin's report. Backpatch to all
supported versions, to the extent that the patch applies easily.

Discussion: https://www.postgresql.org/message-id/20201005191922.GE17626%40telsasoft.com

4 years agoIn libpq for Windows, call WSAStartup once and WSACleanup not at all.
Tom Lane [Mon, 19 Oct 2020 15:23:52 +0000 (11:23 -0400)]
In libpq for Windows, call WSAStartup once and WSACleanup not at all.

The Windows documentation insists that every WSAStartup call should
have a matching WSACleanup call.  However, if that ever had actual
relevance, it wasn't in this century.  Every remotely-modern Windows
kernel is capable of cleaning up when a process exits without doing
that, and must be so to avoid resource leaks in case of a process
crash.  Moreover, Postgres backends have done WSAStartup without
WSACleanup since commit 4cdf51e64 in 2004, and we've never seen any
indication of a problem with that.

libpq's habit of doing WSAStartup during connection start and
WSACleanup during shutdown is also rather inefficient, since a
series of non-overlapping connection requests leads to repeated,
quite expensive DLL unload/reload cycles.  We document a workaround
for that (having the application call WSAStartup for itself), but
that's just a kluge.  It's also worth noting that it's far from
uncommon for applications to exit without doing PQfinish, and
we've not heard reports of trouble from that either.

However, the real reason for acting on this is that recent
experiments by Alexander Lakhin show that calling WSACleanup
during PQfinish is triggering the symptom we occasionally see
that a process using libpq fails to emit expected stdio output.

Therefore, let's change libpq so that it calls WSAStartup only
once per process, during the first connection attempt, and never
calls WSACleanup at all.

While at it, get rid of the only other WSACleanup call in our code
tree, in pg_dump/parallel.c; that presumably is equally useless.

Back-patch of HEAD commit 7d00a6b2d.

Discussion: https://postgr.es/m/ac976d8c-03df-d6b8-025c-15a2de8d9af1@postgrespro.ru

4 years agoRelax some asserts in merge join costing code
David Rowley [Mon, 19 Oct 2020 11:01:44 +0000 (00:01 +1300)]
Relax some asserts in merge join costing code

In the planner, it was possible, given an extreme enough case containing a
large number of joins for the number of estimated rows to become infinite.
This could cause problems in initial_cost_mergejoin() where we perform
some calculations based on those row estimates.

A problem case, presented by Onder Kalaci showed an Assert failure from
an Assert checking outerstartsel <= outerendsel.  In his test case this
was effectively NaN <= Inf, which is false.  The NaN outerstartsel came
from multiplying the infinite outer_path_rows by 0.0.

In master, this problem was fixed by a90c950fc, however, that fix was too
invasive for the backbranches.  Here we just relax the Asserts to allow
them to pass.  The worst that appears to happen from this is that we show
NaN cost values and infinite row estimates in EXPLAIN.  add_path() would
have had a hard time doing anything useful with such costs, but that does
not really matter as if the row estimates were even close to accurate,
such plan would not complete this side of the heat death of the universe.

Reported-by: Onder Kalaci
Backpatch: 9.5 to 13
Discussion: https://postgr.es/m/DM6PR21MB1211FF360183BCA901B27F04D80B0@DM6PR21MB1211.namprd21.prod.outlook.com

4 years agoFix potential memory leak in pgcrypto
Michael Paquier [Mon, 19 Oct 2020 00:38:18 +0000 (09:38 +0900)]
Fix potential memory leak in pgcrypto

When allocating a EVP context, it would have been possible to leak some
memory allocated directly by OpenSSL, that PostgreSQL lost track of if
the initialization of the context allocated failed.  The cleanup can be
done with EVP_MD_CTX_destroy().

Note that EVP APIs exist since OpenSSL 0.9.7 and we have in the tree
equivalent implementations for older versions since ce9b75d (code
removed with 9b7cd59a as of 10~).  However, in 9.5 and 9.6, the existing
code makes use of EVP_MD_CTX_destroy() and EVP_MD_CTX_create() without
an equivalent implementation when building the tree with OpenSSL 0.9.6
or older, meaning that this code is in reality broken with such versions
since it got introduced in e2838c5.  As we have heard no complains about
that, it does not seem worth bothering with in 9.5 and 9.6, so I have
left that out for simplicity.

Author: Michael Paquier
Discussion: https://postgr.es/m/20201015072212[email protected]
Backpatch-through: 9.5

4 years agoDoc: caution against misuse of 'now' and related datetime literals.
Tom Lane [Sat, 17 Oct 2020 20:02:47 +0000 (16:02 -0400)]
Doc: caution against misuse of 'now' and related datetime literals.

Section 8.5.1.4, which defines these literals, made only a vague
reference to the fact that they might be evaluated too soon to be
safe in non-interactive contexts.  Provide a more explicit caution
against misuse.  Also, generalize the wording in the related tip in
section 9.9.4: while it clearly described this problem, it implied
(or really, stated outright) that the problem only applies to table
DEFAULT clauses.

Per gripe from Tijs van Dam.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/c2LuRv9BiRT3bqIo5mMQiVraEXey_25B4vUn0kDqVqilwOEu_iVF1tbtvLnyQK7yDG3PFaz_GxLLPil2SDkj1MCObNRVaac-7j1dVdFERk8=@thalex.com

4 years agoUpdate time zone data files to tzdata release 2020c.
Tom Lane [Sat, 17 Oct 2020 01:53:33 +0000 (21:53 -0400)]
Update time zone data files to tzdata release 2020c.

DST law changes in Morocco, Canadian Yukon, Fiji, Macquarie Island,
Casey Station (Antarctica).  Historical corrections for France,
Hungary, Monaco.

4 years agoSync our copy of the timezone library with IANA release tzcode2020c.
Tom Lane [Sat, 17 Oct 2020 01:40:16 +0000 (21:40 -0400)]
Sync our copy of the timezone library with IANA release tzcode2020c.

This changes zic's default output format from "-b fat" to "-b slim".
We were already using "slim" in v13/HEAD, so those branches drop
the explicit -b switch in the Makefiles.  Instead, add an explicit
"-b fat" in v12 and before, so that we don't change the output file
format in those branches.  (This is perhaps excessively conservative,
but we decided not to do so in a12079109, and I'll stick with that.)

Other non-cosmetic changes are to drop support for zic's long-obsolete
"-y" switch, and to ensure that strftime() does not change errno
unless it fails.

As usual with tzcode changes, back-patch to all supported branches.

4 years agoAdd missing error check in pgcrypto/crypt-md5.c.
Tom Lane [Fri, 16 Oct 2020 15:59:13 +0000 (11:59 -0400)]
Add missing error check in pgcrypto/crypt-md5.c.

In theory, the second px_find_digest call in px_crypt_md5 could fail
even though the first one succeeded, since resource allocation is
required.  Don't skip testing for a failure.  (If one did happen,
the likely result would be a crash rather than clean recovery from
an OOM failure.)

The code's been like this all along, so back-patch to all supported
branches.

Daniel Gustafsson

Discussion: https://postgr.es/m/AA8D6FE9-4AB2-41B4-98CB-AE64BA668C03@yesql.se

4 years agopg_upgrade: remove C99 compiler req. from commit 3c0471b5fd
Bruce Momjian [Fri, 16 Oct 2020 00:37:19 +0000 (20:37 -0400)]
pg_upgrade:  remove C99 compiler req. from commit 3c0471b5fd

This commit required support for inline variable definition, which is
not a requirement.

RELEASE NOTE AUTHOR:  the author of commit 3c0471b5fd
(pg_upgrade/tablespaces) was Justin Pryzby, not me.

Reported-by: Andres Freund
Discussion: https://postgr.es/m/20201016001959[email protected]

Backpatch-through: 9.5

4 years agopg_upgrade: generate check error for left-over new tablespace
Bruce Momjian [Thu, 15 Oct 2020 23:33:36 +0000 (19:33 -0400)]
pg_upgrade:  generate check error for left-over new tablespace

Previously, if pg_upgrade failed, and the user recreated the cluster but
did not remove the new cluster tablespace directory, a later pg_upgrade
would fail since the new tablespace directory would already exists.
This adds error reporting for this during check.

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20200925005531[email protected]

Backpatch-through: 9.5

4 years agoFix memory leak when guc.c decides a setting can't be applied now.
Tom Lane [Mon, 12 Oct 2020 17:31:24 +0000 (13:31 -0400)]
Fix memory leak when guc.c decides a setting can't be applied now.

The prohibitValueChange code paths in set_config_option(), which
are executed whenever we re-read a PGC_POSTMASTER variable from
postgresql.conf, neglected to free anything before exiting.  Thus
we'd leak the proposed new value of a PGC_STRING variable, as noted
by BoChen in bug #16666.  For all variable types, if the check hook
creates an "extra" chunk, we'd also leak that.

These are malloc not palloc chunks, so there is no mechanism for
recovering the leaks before process exit.  Fortunately, the values
are typically not very large, meaning you'd have to go through an
awful lot of SIGHUP configuration-reload cycles to make the leakage
amount to anything.  Still, for a long-lived postmaster process it
could potentially be a problem.

Oversight in commit 2594cf0e8.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/16666-2c41a4eec61b03e1@postgresql.org

4 years agoFix optimization hazard in gram.y's makeOrderedSetArgs(), redux.
Tom Lane [Wed, 7 Oct 2020 22:41:39 +0000 (18:41 -0400)]
Fix optimization hazard in gram.y's makeOrderedSetArgs(), redux.

It appears that commit cf63c641c, which intended to prevent
misoptimization of the result-building step in makeOrderedSetArgs,
didn't go far enough: buildfarm member hornet's version of xlc
is now optimizing back to the old, broken behavior in which
list_length(directargs) is fetched only after list_concat() has
changed that value.  I'm not entirely convinced whether that's
an undeniable compiler bug or whether it can be justified by a
sufficiently aggressive interpretation of C sequence points.
So let's just change the code to make it harder to misinterpret.

Back-patch to all supported versions, just in case.

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

4 years agoRethink recent fix for pg_dump's handling of extension config tables.
Tom Lane [Wed, 7 Oct 2020 16:50:55 +0000 (12:50 -0400)]
Rethink recent fix for pg_dump's handling of extension config tables.

Commit 3eb3d3e78 was a few bricks shy of a load: while it correctly
set the table's "interesting" flag when deciding to dump the data of
an extension config table, it was not correct to clear that flag
if we concluded we shouldn't dump the data.  This led to the crash
reported in bug #16655, because in fact we'll traverse dumpTableSchema
anyway for all extension tables (to see if they have user-added
seclabels or RLS policies).

The right thing to do is to force "interesting" true in makeTableDataInfo,
and otherwise leave the flag alone.  (Doing it there is more future-proof
in case additional calls are added, and it also avoids setting the flag
unnecessarily if that function decides the table is non-dumpable.)

This investigation also showed that while only the --inserts code path
had an obvious failure in the case considered by 3eb3d3e78, the COPY
code path also has a problem with not having loaded table subsidiary
data.  That causes fmtCopyColumnList to silently return an empty string
instead of the correct column list.  That accidentally mostly works,
which perhaps is why we didn't notice this before.  It would only fail
if the restore column order is different from the dump column order,
which only happens in weird inheritance cases, so it's not surprising
nobody had hit the case with an extension config table.  Nonetheless,
it's a bug, and it goes a long way back, not just to v12 where the
--inserts code path started to have a problem with this.

In hopes of catching such cases a bit sooner in future, add some
Asserts that "interesting" has been set in both dumpTableData and
dumpTableSchema.  Adjust the test case added by 3eb3d3e78 so that it
checks the COPY rather than INSERT form of that bug, allowing it to
detect the longer-standing symptom.

Per bug #16655 from Cameron Daniel.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/16655-5c92d6b3a9438137@postgresql.org
Discussion: https://postgr.es/m/18048b44-3414-b983-8c7c-9165b177900d@2ndQuadrant.com

4 years agopg_upgrade: remove pre-8.4 code and >= 8.4 check
Bruce Momjian [Tue, 6 Oct 2020 18:31:21 +0000 (14:31 -0400)]
pg_upgrade:  remove pre-8.4 code and >= 8.4 check

We only support upgrading from >= 8.4 so no need for this code or tests.

Reported-by: Magnus Hagander
Discussion: https://postgr.es/m/CABUevEx-D0PNVe00tkeQRGennZQwDtBJn=493MJt-x6sppbUxA@mail.gmail.com

Backpatch-through: 9.5

4 years agopg_upgrade; change major version comparisons to use <=, not <
Bruce Momjian [Tue, 6 Oct 2020 16:12:09 +0000 (12:12 -0400)]
pg_upgrade;  change major version comparisons to use <=, not <

This makes checking for older major versions more consistent.

Backpatch-through: 9.5

4 years agodoc: show functions returning record types and use of ROWS FROM
Bruce Momjian [Mon, 5 Oct 2020 20:27:33 +0000 (16:27 -0400)]
doc:  show functions returning record types and use of ROWS FROM

Previously it was unclear exactly how ROWS FROM behaved and how to cast
the data types of columns returned by FROM functions.  Also document
that only non-OUT record functions can have their columns cast to data
types.

Reported-by: [email protected]
Discussion: https://postgr.es/m/158638264419.662.2482095087061084020@wrigleys.postgresql.org

Backpatch-through: 9.5

4 years agoFix two latent(?) bugs in equivclass.c.
Tom Lane [Mon, 5 Oct 2020 17:15:40 +0000 (13:15 -0400)]
Fix two latent(?) bugs in equivclass.c.

get_eclass_for_sort_expr() computes expr_relids and nullable_relids
early on, even though they won't be needed unless we make a new
EquivalenceClass, which we often don't.  Aside from the probably-minor
inefficiency, there's a memory management problem: these bitmapsets will
be built in the caller's context, leading to dangling pointers if that
is shorter-lived than root->planner_cxt.  This would be a live bug if
get_eclass_for_sort_expr() could be called with create_it = true during
GEQO join planning.  So far as I can find, the core code never does
that, but it's hard to be sure that no extensions do, especially since
the comments make it clear that that's supposed to be a supported case.
Fix by not computing these values until we've switched into planner_cxt
to build the new EquivalenceClass.

generate_join_implied_equalities() uses inner_rel->relids to look up
relevant eclasses, but it ought to be using nominal_inner_relids.
This is presently harmless because a child RelOptInfo will always have
exactly the same eclass_indexes as its topmost parent; but that might
not be true forever, and anyway it makes the code confusing.

The first of these is old (introduced by me in f3b3b8d5b), so back-patch
to all supported branches.  The second only dates to v13, but we might
as well back-patch it to keep the code looking similar across branches.

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

4 years agodoc: libpq connection options can override command-line flags
Bruce Momjian [Sat, 3 Oct 2020 02:19:30 +0000 (22:19 -0400)]
doc:  libpq connection options can override command-line flags

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/16486-b9c93d71c02c4907@postgresql.org

Backpatch-through: 9.5

4 years agodoc: clarify the use of ssh port forwarding
Bruce Momjian [Sat, 3 Oct 2020 01:39:33 +0000 (21:39 -0400)]
doc:  clarify the use of ssh port forwarding

Reported-by: [email protected]
Discussion: https://postgr.es/m/159854511172.24991.4373145230066586863@wrigleys.postgresql.org

Backpatch-through: 9.5

4 years agoFix handling of BC years in to_date/to_timestamp.
Tom Lane [Wed, 30 Sep 2020 19:40:23 +0000 (15:40 -0400)]
Fix handling of BC years in to_date/to_timestamp.

Previously, a conversion such as
to_date('-44-02-01','YYYY-MM-DD')
would result in '0045-02-01 BC', as the code attempted to interpret
the negative year as BC, but failed to apply the correction needed
for our internal handling of BC years.  Fix the off-by-one problem.

Also, arrange for the combination of a negative year and an
explicit "BC" marker to cancel out and produce AD.  This is how
the negative-century case works, so it seems sane to do likewise.

Continue to read "year 0000" as 1 BC.  Oracle would throw an error,
but we've accepted that case for a long time so I'm hesitant to
change it in a back-patch.

Per bug #16419 from Saeed Hubaishan.  Back-patch to all supported
branches.

Dar Alathar-Yemen and Tom Lane

Discussion: https://postgr.es/m/16419-d8d9db0a7553f01b@postgresql.org

4 years agoArchive timeline history files in standby if archive_mode is set to "always".
Fujii Masao [Tue, 29 Sep 2020 07:21:46 +0000 (16:21 +0900)]
Archive timeline history files in standby if archive_mode is set to "always".

Previously the standby server didn't archive timeline history files
streamed from the primary even when archive_mode is set to "always",
while it archives the streamed WAL files. This could cause the PITR to
fail because there was no required timeline history file in the archive.
The cause of this issue was that walreceiver didn't mark those files as
ready for archiving.

This commit makes walreceiver mark those streamed timeline history
files as ready for archiving if archive_mode=always. Then the archiver
process archives the marked timeline history files.

Back-patch to all supported versions.

Reported-by: Grigory Smolkin
Author: Grigory Smolkin, Fujii Masao
Reviewed-by: David Zhang, Anastasia Lubennikova
Discussion: https://postgr.es/m/54b059d4-2b48-13a4-6f43-95a087c92367@postgrespro.ru

4 years agoRevise RelationBuildRowSecurity() to avoid memory leaks.
Tom Lane [Sat, 26 Sep 2020 20:04:06 +0000 (16:04 -0400)]
Revise RelationBuildRowSecurity() to avoid memory leaks.

This function leaked some memory while loading qual clauses for
an RLS policy.  While ordinarily negligible, that could build up
in some repeated-reload cases, as reported by Konstantin Knizhnik.
We can improve matters by borrowing the coding long used in
RelationBuildRuleLock: build stringToNode's result directly in
the target context, and remember to explicitly pfree the
input string.

This patch by no means completely guarantees zero leaks within
this function, since we have no real guarantee that the catalog-
reading subroutines it calls don't leak anything.  However,
practical tests suggest that this is enough to resolve the issue.
In any case, any remaining leaks are similar to those risked by
RelationBuildRuleLock and other relcache-loading subroutines.
If we need to fix them, we should adopt a more global approach
such as that used by the RECOVER_RELATION_BUILD_MEMORY hack.

While here, let's remove the need for an expensive PG_TRY block by
using MemoryContextSetParent to reparent an initially-short-lived
context for the RLS data.

Back-patch to all supported branches.

Discussion: https://postgr.es/m/21356c12-8917-8249-b35f-1c447231922b@postgrespro.ru

4 years agoFix handling of -d "connection string" in pg_dump/pg_restore.
Tom Lane [Thu, 24 Sep 2020 22:19:39 +0000 (18:19 -0400)]
Fix handling of -d "connection string" in pg_dump/pg_restore.

Parallel pg_dump failed if its -d parameter was a connection string
containing any essential information other than host, port, or username.
The same was true for pg_restore with --create.

The reason is that these scenarios failed to preserve the connection
string from the command line; the code felt free to replace that with
just the database name when reconnecting from a pg_dump parallel worker
or after creating the target database.  By chance, parallel pg_restore
did not suffer this defect, as long as you didn't say --create.

In practice it seems that the error would be obvious only if the
connstring included essential, non-default SSL or GSS parameters.
This may explain why it took us so long to notice.  (It also makes
it very difficult to craft a regression test case illustrating the
problem, since the test would fail in builds without those options.)

Fix by refactoring so that ConnectDatabase always receives all the
relevant options directly from the command line, rather than
reconstructed values.  Inject a different database name, when necessary,
by relying on libpq's rules for handling multiple "dbname" parameters.

While here, let's get rid of the essentially duplicate _connectDB
function, as well as some obsolete nearby cruft.

Per bug #16604 from Zsolt Ero.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/16604-933f4b8791227b15@postgresql.org

4 years agoFix missing fsync of SLRU directories.
Thomas Munro [Wed, 23 Sep 2020 21:26:09 +0000 (09:26 +1200)]
Fix missing fsync of SLRU directories.

Harmonize behavior by moving reponsibility for fsyncing directories down
into slru.c.  In 10 and later, only the multixact directories were
missed (see commit 1b02be21), and in older branches all SLRUs were
missed.

Back-patch to all supported releases.

Reviewed-by: Andres Freund <[email protected]>
Reviewed-by: Michael Paquier <[email protected]>
Discussion: https://postgr.es/m/CA%2BhUKGLtsTUOScnNoSMZ-2ZLv%2BwGh01J6kAo_DM8mTRq1sKdSQ%40mail.gmail.com

4 years agoAvoid possible dangling-pointer access in tsearch_readline_callback.
Tom Lane [Wed, 23 Sep 2020 15:36:13 +0000 (11:36 -0400)]
Avoid possible dangling-pointer access in tsearch_readline_callback.

tsearch_readline() saves the string pointer it returns to the caller
for possible use in the associated error context callback.  However,
the caller will usually pfree that string sometime before it next
calls tsearch_readline(), so that there is a window where an ereport
will try to print an already-freed string.

The built-in users of tsearch_readline() happen to all do that pfree
at the bottoms of their loops, so that the window is effectively
empty for them.  However, this is not documented as a requirement,
and contrib/dict_xsyn doesn't do it like that, so it seems likely
that third-party dictionaries might have live bugs here.

The practical consequences of this seem pretty limited in any case,
since production builds wouldn't clobber the freed string immediately,
besides which you'd not expect syntax errors in dictionary files
being used in production.  Still, it's clearly a bug waiting to bite
somebody.

Fix by pstrdup'ing the string to be saved for the error callback,
and then pfree'ing it next time through.  It's been like this for
a long time, so back-patch to all supported branches.

Discussion: https://postgr.es/m/48A4FA71-524E-41B9-953A-FD04EF36E2E7@yesql.se

4 years agoUse factorial rather than numeric_fac in create_operator.sql.
Tom Lane [Fri, 18 Sep 2020 22:03:44 +0000 (18:03 -0400)]
Use factorial rather than numeric_fac in create_operator.sql.

These two SQL functions are aliases for the same C function, so this
change has no semantic effect.  However, because we dropped the
numeric_fac alias in HEAD (commit 76f412ab3), operator definitions
based on that one don't port forward, causing problems for cross-version
upgrade tests based on the regression database.

Patch all active back branches to dodge the problem.

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

4 years agoFix race in test of pg_switch_wal().
Noah Misch [Mon, 14 Sep 2020 06:13:44 +0000 (23:13 -0700)]
Fix race in test of pg_switch_wal().

The test failed when something added WAL between pg_switch_wal() and
pg_current_wal_lsn(), seen on buildfarm members hornet and sungazer.
Fix v10, v9.6 and v9.5 by making this code mirror its v13+ counterpart.
v12 and v11 lack a counterpart.

4 years agoUse the properly transformed RangeVar for expandTableLikeClause().
Tom Lane [Sun, 13 Sep 2020 16:51:21 +0000 (12:51 -0400)]
Use the properly transformed RangeVar for expandTableLikeClause().

transformCreateStmt() adjusts the transformed statement's RangeVar
to specify the target schema explicitly, for the express reason
of making sure that auxiliary statements derived by parse
transformation operate on the right table.  But the refactoring
I did in commit 502898192 got this wrong and passed the untransformed
RangeVar to expandTableLikeClause().  This could lead to assertion
failures or weird misbehavior if the wrong table was accessed.

Per report from Alexander Lakhin.  Like the previous patch, back-patch
to all supported branches.

Discussion: https://postgr.es/m/05051f9d-b32b-cb35-6735-0e9f2ab86b5f@gmail.com

4 years agoUse _exit(2) for SIGQUIT during ProcessStartupPacket, too.
Tom Lane [Thu, 10 Sep 2020 16:06:26 +0000 (12:06 -0400)]
Use _exit(2) for SIGQUIT during ProcessStartupPacket, too.

Bring the signal handling for startup-packet collection into line
with the policy established in commits bedadc732 and 8e19a8264,
namely don't risk running atexit callbacks when handling SIGQUIT.

Ideally, we'd not do so for SIGTERM or timeout interrupts either,
but that change seems a bit too risky for the back branches.
For now, just improve the comments in this area to describe the risk.

Also relocate where BackendInitialize re-disables these interrupts,
to minimize the code span where they're active.  This doesn't buy
a whole lot of safety, but it can't hurt.

In passing, rename startup_die() to remove confusion about whether
it is for the startup process.

Like the previous commits, back-patch to all supported branches.

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

4 years agoFix title in reference section
Magnus Hagander [Thu, 10 Sep 2020 12:15:26 +0000 (14:15 +0200)]
Fix title in reference section

Reported-by: Robert Kahlert
Author: Daniel Gustafsson

4 years agoMake archiver's SIGQUIT handler exit via _exit().
Tom Lane [Wed, 9 Sep 2020 19:32:34 +0000 (15:32 -0400)]
Make archiver's SIGQUIT handler exit via _exit().

Commit 8e19a8264 changed the SIGQUIT handlers of almost all server
processes not to run atexit callbacks.  The archiver process was
skipped, perhaps because it's not connected to shared memory; but
it's just as true here that running atexit callbacks in a signal
handler is unsafe.  So let's make it work like the rest.

In HEAD and v13, we can use the common SignalHandlerForCrashExit
handler.  Before that, just tweak pgarch_exit to use _exit(2)
explicitly.

Like the previous commit, back-patch to all supported branches.

Kyotaro Horiguchi, back-patching by me

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

4 years agoUse return instead of exit() in configure
Peter Eisentraut [Tue, 8 Sep 2020 08:09:56 +0000 (10:09 +0200)]
Use return instead of exit() in configure

Using exit() requires stdlib.h, which is not included.  Use return
instead.  Also add return type for main().

Reviewed-by: Heikki Linnakangas <[email protected]>
Reviewed-by: Thomas Munro <[email protected]>
Backpatched because Apple macOS 10.16/11 (Big Sur) compiler makes
calling undeclared functions an error, so these configure tests would
fail.

Reported-by: Thomas Gilligan <[email protected]>
Reported-by: Jesse Zhang <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/09A4B554-82B1-4536-B191-2461342EE0BB%40icloud.com

4 years agoFix misleading error message about inconsistent moving-aggregate types.
Tom Lane [Sun, 6 Sep 2020 16:55:13 +0000 (12:55 -0400)]
Fix misleading error message about inconsistent moving-aggregate types.

We reported the wrong types when complaining that an aggregate's
moving-aggregate implementation is inconsistent with its regular
implementation.

This was wrong since the feature was introduced, so back-patch
to all supported branches.

Jeff Janes

Discussion: https://postgr.es/m/CAMkU=1x808LH=LPhZp9mNSP0Xd1xDqEd+XeGcvEe48dfE6xV=A@mail.gmail.com

4 years agoRemove useless lstat() call in pg_rewind.
Tom Lane [Sun, 6 Sep 2020 15:50:41 +0000 (11:50 -0400)]
Remove useless lstat() call in pg_rewind.

This is duplicative of an lstat that was just done by the calling
function (traverse_datadir), besides which we weren't really doing
anything with the results.  There's not much point in checking to
see if someone removed the file since the previous lstat, since the
FILE_ACTION_REMOVE code would have to deal with missing-file cases
anyway.  Moreover, the "exists = false" assignment was a dead store;
nothing was done with that value later.

A syscall saved is a syscall earned, so back-patch to 9.5
where this code was introduced.

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

4 years agoC comment: correct use of 64-"byte" cache line size
Bruce Momjian [Fri, 4 Sep 2020 17:27:52 +0000 (13:27 -0400)]
C comment:  correct use of 64-"byte" cache line size

Reported-by: Kelly Min
Discussion: https://postgr.es/m/CAPSbxatOiQO90LYpSC3+svAU9-sHgDfEP4oFhcEUt_X=DqFA9g@mail.gmail.com

Backpatch-through: 9.5

4 years agoAvoid lockup of a parallel worker when reporting a long error message.
Tom Lane [Thu, 3 Sep 2020 20:52:09 +0000 (16:52 -0400)]
Avoid lockup of a parallel worker when reporting a long error message.

Because sigsetjmp() will restore the initial state with signals blocked,
the code path in bgworker.c for reporting an error and exiting would
execute that way.  Usually this is fairly harmless; but if a parallel
worker had an error message exceeding the shared-memory communication
buffer size (16K) it would lock up, because it would wait for a
resume-sending signal from its parallel leader which it would never
detect.

To fix, just unblock signals at the appropriate point.

This can be shown to fail back to 9.6.  The lack of parallel query
infrastructure makes it difficult to provide a simple test case for
9.5; but I'm pretty sure the issue exists in some form there as well,
so apply the code change there too.

Vignesh C, reviewed by Bharath Rupireddy, Robert Haas, and myself

Discussion: https://postgr.es/m/CALDaNm1d1hHPZUg3xU4XjtWBOLCrA+-2cJcLpw-cePZ=GgDVfA@mail.gmail.com

4 years agodoc: clarify that max_wal_size is "during" checkpoints
Bruce Momjian [Tue, 1 Sep 2020 21:00:09 +0000 (17:00 -0400)]
doc:  clarify that max_wal_size is "during" checkpoints

Previous wording was "between".

Reported-by: Pavel Luzanov
Discussion: https://postgr.es/m/26906a54-d7cb-2f8e-eed7-e31660024694@postgrespro.ru

Backpatch-through: 9.5

4 years agoTeach libpq to handle arbitrary-length lines in .pgpass files.
Tom Lane [Tue, 1 Sep 2020 17:14:44 +0000 (13:14 -0400)]
Teach libpq to handle arbitrary-length lines in .pgpass files.

Historically there's been a hard-wired assumption here that no line of
a .pgpass file could be as long as NAMEDATALEN*5 bytes.  That's a bit
shaky to start off with, because (a) there's no reason to suppose that
host names fit in NAMEDATALEN, and (b) this figure fails to allow for
backslash escape characters.  However, it fails completely if someone
wants to use a very long password, and we're now hearing reports of
people wanting to use "security tokens" that can run up to several
hundred bytes.  Another angle is that the file is specified to allow
comment lines, but there's no reason to assume that long comment lines
aren't possible.

Rather than guessing at what might be a more suitable limit, let's
replace the fixed-size buffer with an expansible PQExpBuffer.  That
adds one malloc/free cycle to the typical use-case, but that's surely
pretty cheap relative to the I/O this code has to do.

Also, add TAP test cases to exercise this code, because there was no
test coverage before.

This reverts most of commit 2eb3bc588, as there's no longer a need for
a warning message about overlength .pgpass lines.  (I kept the explicit
check for comment lines, though.)

In HEAD and v13, this also fixes an oversight in 74a308cf5: there's not
much point in explicit_bzero'ing the line buffer if we only do so in two
of the three exit paths.

Back-patch to all supported branches, except that the test case only
goes back to v10 where src/test/authentication/ was added.

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

4 years agodoc: add commas after 'i.e.' and 'e.g.'
Bruce Momjian [Mon, 31 Aug 2020 22:33:36 +0000 (18:33 -0400)]
doc: add commas after 'i.e.' and 'e.g.'

This follows the American format,
https://jakubmarian.com/comma-after-i-e-and-e-g/. There is no intention
of requiring this format for future text, but making existing text
consistent every few years makes sense.

Discussion: https://postgr.es/m/20200825183619[email protected]

Backpatch-through: 9.5

4 years agoC comment: remove mention of use of t_hoff WAL structure member
Bruce Momjian [Mon, 31 Aug 2020 21:51:31 +0000 (17:51 -0400)]
C comment:  remove mention of use of t_hoff WAL structure member

Reported-by: Antonin Houska
Discussion: https://postgr.es/m/21643.1595353537@antos

Backpatch-through: 9.5

4 years agopg_upgrade doc: mention saving postgresql.conf.auto files
Bruce Momjian [Mon, 31 Aug 2020 21:36:22 +0000 (17:36 -0400)]
pg_upgrade doc:  mention saving postgresql.conf.auto files

Also mention files included by postgresql.conf.

Reported-by: Álvaro Herrera
Discussion: https://postgr.es/m/08AD4526-75AB-457B-B2DD-099663F28040@yesql.se

Backpatch-through: 9.5

4 years agodocs: in mapping SQL to C data types, timestamp isn't a pointer
Bruce Momjian [Mon, 31 Aug 2020 21:05:53 +0000 (17:05 -0400)]
docs:  in mapping SQL to C data types, timestamp isn't a pointer

It is an int64.

Reported-by: [email protected]
Discussion: https://postgr.es/m/159845038271.24995.15682121015698255155@wrigleys.postgresql.org

Backpatch-through: 9.5