postgresql.git
4 years agoMinor fixes in COPY progress docs
Tomas Vondra [Thu, 7 Jan 2021 16:31:58 +0000 (17:31 +0100)]
Minor fixes in COPY progress docs

Author: Justin Pryzby
Discussion: https://postgr.es/m/CAFp7Qwr6_FmRM6pCO0x_a0mymOfX_Gg+FEKet4XaTGSW=LitKQ@mail.gmail.com

4 years agoAdd GUC to log long wait times on recovery conflicts.
Fujii Masao [Thu, 7 Jan 2021 15:47:03 +0000 (00:47 +0900)]
Add GUC to log long wait times on recovery conflicts.

This commit adds GUC log_recovery_conflict_waits that controls whether
a log message is produced when the startup process is waiting longer than
deadlock_timeout for recovery conflicts. This is useful in determining
if recovery conflicts prevent the recovery from applying WAL.

Note that currently a log message is produced only when recovery conflict
has not been resolved yet even after deadlock_timeout passes, i.e.,
only when the startup process is still waiting for recovery conflict
even after deadlock_timeout.

Author: Bertrand Drouvot, Masahiko Sawada
Reviewed-by: Alvaro Herrera, Kyotaro Horiguchi, Fujii Masao
Discussion: https://postgr.es/m/9a60178c-a853-1440-2cdc-c3af916cff59@amazon.com

4 years agoFix bogus link in test comments.
Tom Lane [Thu, 7 Jan 2021 03:09:00 +0000 (22:09 -0500)]
Fix bogus link in test comments.

I apparently copied-and-pasted the wrong link in commit ca8217c10.
Point it where it was meant to go.

4 years agoImprove commentary in timeout.c.
Tom Lane [Thu, 7 Jan 2021 03:02:35 +0000 (22:02 -0500)]
Improve commentary in timeout.c.

On re-reading I realized that I'd missed one race condition in the new
timeout code.  It's safe, but add a comment explaining it.

Discussion: https://postgr.es/m/CA+hUKG+o6pbuHBJSGnud=TadsuXySWA7CCcPgCt2QE9F6_4iHQ@mail.gmail.com

4 years agoFix allocation logic of cryptohash context data with OpenSSL
Michael Paquier [Thu, 7 Jan 2021 01:21:02 +0000 (10:21 +0900)]
Fix allocation logic of cryptohash context data with OpenSSL

The allocation of the cryptohash context data when building with OpenSSL
was happening in the memory context of the caller of
pg_cryptohash_create(), which could lead to issues with resowner cleanup
if cascading resources are cleaned up on an error.  Like other
facilities using resowners, move the base allocation to TopMemoryContext
to ensure a correct cleanup on failure.

The resulting code gets simpler with this commit as the context data is
now hold by a unique opaque pointer, so as there is only one single
allocation done in TopMemoryContext.

After discussion, also change the cryptohash subroutines to return an
error if the caller provides NULL for the context data to ease error
detection on OOM.

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

4 years agoAdd idle_session_timeout.
Tom Lane [Wed, 6 Jan 2021 23:28:42 +0000 (18:28 -0500)]
Add idle_session_timeout.

This GUC variable works much like idle_in_transaction_session_timeout,
in that it kills sessions that have waited too long for a new client
query.  But it applies when we're not in a transaction, rather than
when we are.

Li Japin, reviewed by David Johnston and Hayato Kuroda, some
fixes by me

Discussion: https://postgr.es/m/763A0689-F189-459E-946F-F0EC4458980B@hotmail.com

4 years agoImprove timeout.c's handling of repeated timeout set/cancel.
Tom Lane [Wed, 6 Jan 2021 23:23:03 +0000 (18:23 -0500)]
Improve timeout.c's handling of repeated timeout set/cancel.

A very common usage pattern is that we set a timeout that we don't
expect to reach, cancel it after a little bit, and later repeat.
With the original implementation of timeout.c, this results in one
setitimer() call per timeout set or cancel.  We can do a lot better
by being lazy about changing the timeout interrupt request, namely:
(1) never cancel the outstanding interrupt, even when we have no
active timeout events;
(2) if we need to set an interrupt, but there already is one pending
at or before the required time, leave it alone.  When the interrupt
happens, the signal handler will reschedule it at whatever time is
then needed.

For example, with a one-second setting for statement_timeout, this
method results in having to interact with the kernel only a little
more than once a second, no matter how many statements we execute
in between.  The mainline code might never call setitimer() at all
after the first time, while each time the signal handler fires,
it sees that the then-pending request is most of a second away,
and that's when it sets the next interrupt request for.  Each
mainline timeout-set request after that will observe that the time
it wants is past the pending interrupt request time, and do nothing.

This also works pretty well for cases where a few different timeout
lengths are in use, as long as none of them are very short.  But
that describes our usage well.

Idea and original  by Thomas Munro; I fixed a race condition
and improved the comments.

Discussion: https://postgr.es/m/CA+hUKG+o6pbuHBJSGnud=TadsuXySWA7CCcPgCt2QE9F6_4iHQ@mail.gmail.com

4 years agoReport progress of COPY commands
Tomas Vondra [Wed, 6 Jan 2021 20:46:26 +0000 (21:46 +0100)]
Report progress of COPY commands

This commit introduces a view pg_stat_progress_copy, reporting progress
of COPY commands.  This allows rough estimates how far a running COPY
progressed, with the caveat that the total number of bytes may not be
available in some cases (e.g. when the input comes from the client).

Author: Josef Šimánek
Reviewed-by: Fujii Masao, Bharath Rupireddy, Vignesh C, Matthias van de Meent
Discussion: https://postgr.es/m/CAFp7QwqMGEi4OyyaLEK9DR0+E+oK3UtA4bEjDVCa4bNkwUY2PQ@mail.gmail.com
Discussion: https://postgr.es/m/CAFp7Qwr6_FmRM6pCO0x_a0mymOfX_Gg+FEKet4XaTGSW=LitKQ@mail.gmail.com

4 years agoAdd a test module for the regular expression package.
Tom Lane [Wed, 6 Jan 2021 15:51:14 +0000 (10:51 -0500)]
Add a test module for the regular expression package.

This module provides a function test_regex() that is functionally
rather like regexp_matches(), but with additional debugging-oriented
options and additional output.  The debug options are somewhat obscure;
they are chosen to match the API of the test harness that Henry Spencer
wrote way-back-when for use in Tcl.  With this, we can import all the
test cases that Spencer wrote originally, even for regex functionality
that we don't currently expose in Postgres.  This seems necessary
because we can no longer rely on Tcl to act as upstream and verify
any fixes or improvements that we make.

In addition to Spencer's tests, I added a few for lookbehind
constraints (which we added in 2015, and Tcl still hasn't absorbed)
that are modeled on his tests for lookahead constraints.  After looking
at code coverage reports, I also threw in a couple of tests to more
fully exercise our "high colormap" logic.

According to my testing, this brings the check-world coverage
for src/backend/regex/ from 71.1% to 86.7% of lines.
(coverage.postgresql.org shows a slightly different number,
which I think is because it measures a non-assert build.)

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

4 years agoReplace CLOBBER_CACHE_ALWAYS with run-time GUC
Peter Eisentraut [Wed, 6 Jan 2021 09:15:19 +0000 (10:15 +0100)]
Replace CLOBBER_CACHE_ALWAYS with run-time GUC

Forced cache invalidation (CLOBBER_CACHE_ALWAYS) has been impractical
to use for testing in PostgreSQL because it's so slow and because it's
toggled on/off only at build time.  It is helpful when hunting bugs in
any code that uses the sycache/relcache because causes cache
invalidations to be injected whenever it would be possible for an
invalidation to occur, whether or not one was really pending.

Address this by providing run-time control over cache clobber
behaviour using the new debug_invalidate_system_caches_always GUC.
Support is not compiled in at all unless assertions are enabled or
CLOBBER_CACHE_ENABLED is explicitly defined at compile time.  It
defaults to 0 if compiled in, so it has negligible effect on assert
build performance by default.

When support is compiled in, test code can now set
debug_invalidate_system_caches_always=1 locally to a backend to test
specific queries, functions, extensions, etc.  Or tests can toggle it
globally for a specific test case while retaining normal performance
during test setup and teardown.

For backwards compatibility with existing test harnesses and scripts,
debug_invalidate_system_caches_always defaults to 1 if
CLOBBER_CACHE_ALWAYS is defined, and to 3 if CLOBBER_CACHE_RECURSIVE
is defined.

CLOBBER_CACHE_ENABLED is now visible in pg_config_manual.h, as is the
related RECOVER_RELATION_BUILD_MEMORY setting for the relcache.

Author: Craig Ringer <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CAMsr+YF=+ctXBZj3ywmvKNUjWpxmuTuUKuv-rgbHGX5i5pLstQ@mail.gmail.com

4 years agoDetect the deadlocks between backends and the startup process.
Fujii Masao [Wed, 6 Jan 2021 03:39:18 +0000 (12:39 +0900)]
Detect the deadlocks between backends and the startup process.

The deadlocks that the recovery conflict on lock is involved in can
happen between hot-standby backends and the startup process.
If a backend takes an access exclusive lock on the table and which
finally triggers the deadlock, that deadlock can be detected
as expected. On the other hand, previously, if the startup process
took an access exclusive lock and which finally triggered the deadlock,
that deadlock could not be detected and could remain even after
deadlock_timeout passed. This is a bug.

The cause of this bug was that the code for handling the recovery
conflict on lock didn't take care of deadlock case at all. It assumed
that deadlocks involving the startup process and backends were able
to be detected by the deadlock detector invoked within backends.
But this assumption was incorrect. The startup process also should
have invoked the deadlock detector if necessary.

To fix this bug, this commit makes the startup process invoke
the deadlock detector if deadlock_timeout is reached while handling
the recovery conflict on lock. Specifically, in that case, the startup
process requests all the backends holding the conflicting locks to
check themselves for deadlocks.

Back- to v9.6. v9.5 has also this bug, but per discussion we decided
not to back- the fix to v9.5. Because v9.5 doesn't have some
infrastructure codes (e.g., 37c54863cf) that this bug fix  depends on.
We can apply those codes for the back-, but since the next minor
version release is the final one for v9.5, it's risky to do that. If we
unexpectedly introduce new bug to v9.5 by the back-, there is no
chance to fix that. We determined that the back- to v9.5 would give
more risk than gain.

Author: Fujii Masao
Reviewed-by: Bertrand Drouvot, Masahiko Sawada, Kyotaro Horiguchi
Discussion: https://postgr.es/m/4041d6b6-cf24-a120-36fa-1294220f8243@oss.nttdata.com

4 years agoFix typos in decode.c and logical.c.
Amit Kapila [Wed, 6 Jan 2021 03:26:19 +0000 (08:56 +0530)]
Fix typos in decode.c and logical.c.

Per report by Ajin Cherian in email:
https://postgr.es/m/CAFPTHDYnRKDvzgDxoMn_CKqXA-D0MtrbyJvfvjBsO4G=UHDXkg@mail.gmail.com

4 years agodoc: Fix description about default behavior of recovery_target_timeline.
Fujii Masao [Wed, 6 Jan 2021 02:58:23 +0000 (11:58 +0900)]
doc: Fix description about default behavior of recovery_target_timeline.

The default value of recovery_target_timeline was changed in v12,
but the description about the default behavior of that was not updated.

Back- to v12 where the default behavior of recovery_target_timeline
was changed.

Author: Benoit Lobréau
Reviewed-by: Fujii Masao
Discussion: https://postgr.es/m/CAPE8EZ7c3aruEmM24GYkj8y8WmHKD1m9TtPtgCF0nQ3zw4LCkQ@mail.gmail.com

4 years agoPromote --data-checksums to the common set of options in initdb --help
Michael Paquier [Wed, 6 Jan 2021 01:52:26 +0000 (10:52 +0900)]
Promote --data-checksums to the common set of options in initdb --help

This was previously part of the section dedicated to less common
options, but it is an option commonly used these days.

Author: Michael Banck
Reviewed-by: Stephen Frost, Michael Paquier
Discussion: https://postgr.es/m/d7938aca4d4ea8e8c72c33bd75efe9f8218fe390[email protected]

4 years agoRevert unstable test cases from commit 7d80441d2.
Tom Lane [Wed, 6 Jan 2021 00:03:56 +0000 (19:03 -0500)]
Revert unstable test cases from commit 7d80441d2.

I momentarily forgot that the "owner" column wouldn't be stable
in the buildfarm.  Oh well, these tests weren't very valuable
anyway.

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

4 years agoAllow psql's \dt and \di to show TOAST tables and their indexes.
Tom Lane [Tue, 5 Jan 2021 23:41:50 +0000 (18:41 -0500)]
Allow psql's \dt and \di to show TOAST tables and their indexes.

Formerly, TOAST objects were unconditionally suppressed, but since
\d is able to print them it's not very clear why these variants
should not.  Instead, use the same rules as for system catalogs:
they can be seen if you write the 'S' modifier or a table name
pattern.  (In practice, since hardly anybody would keep pg_toast
in their search_path, it's really down to whether you use a pattern
that can match pg_toast.*.)

No docs change seems necessary because the docs already say that
this happens for "system objects"; we're just classifying TOAST
tables as being that.

Justin Pryzby, reviewed by Laurenz Albe

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

4 years agoIntroduce a new GUC_REPORT setting "in_hot_standby".
Tom Lane [Tue, 5 Jan 2021 21:18:01 +0000 (16:18 -0500)]
Introduce a new GUC_REPORT setting "in_hot_standby".

Aside from being queriable via SHOW, this value is sent to the client
immediately at session startup, and again later on if the server gets
promoted to primary during the session.  The immediate report will be
used in an upcoming  to avoid an extra round trip when trying to
connect to a primary server.

Haribabu Kommi, Greg Nancarrow, Tom Lane; reviewed at various times
by Laurenz Albe, Takayuki Tsunakawa, Peter Smith.

Discussion: https://postgr.es/m/CAF3+xM+8-ztOkaV9gHiJ3wfgENTq97QcjXQt+rbFQ6F7oNzt9A@mail.gmail.com

4 years agodoc: improve NLS instruction wording
Bruce Momjian [Tue, 5 Jan 2021 19:26:37 +0000 (14:26 -0500)]
doc:  improve NLS instruction wording

Reported-by: "Tang, Haiying"
Discussion: https://postgr.es/m/bbbccf7a3c2d436e85d45869d612fd6b@G08CNEXMBPEKD05.g08.fujitsu.local

Author: "Tang, Haiying"

Back-through: 9.5

4 years agoAdd an explicit cast to double when using fabs().
Dean Rasheed [Tue, 5 Jan 2021 11:52:42 +0000 (11:52 +0000)]
Add an explicit cast to double when using fabs().

Commit bc43b7c2c0 used fabs() directly on an int variable, which
apparently requires an explicit cast on some platforms.

Per buildfarm.

4 years agoFix numeric_power() when the exponent is INT_MIN.
Dean Rasheed [Tue, 5 Jan 2021 11:15:28 +0000 (11:15 +0000)]
Fix numeric_power() when the exponent is INT_MIN.

In power_var_int(), the computation of the number of significant
digits to use in the computation used log(Abs(exp)), which isn't safe
because Abs(exp) returns INT_MIN when exp is INT_MIN. Use fabs()
instead of Abs(), so that the exponent is cast to a double before the
absolute value is taken.

Back- to 9.6, where this was introduced (by 7d9a4737c2).

Discussion: https://postgr.es/m/CAEZATCVd6pMkz=BrZEgBKyqqJrt2xghr=fNc8+Z=5xC6cgWrWA@mail.gmail.com

4 years agoTest decoding of two-phase transactions during the build of a consistent snapshot.
Amit Kapila [Tue, 5 Jan 2021 09:35:22 +0000 (15:05 +0530)]
Test decoding of two-phase transactions during the build of a consistent snapshot.

Commit a271a1b50e added the capability to allow decoding at prepare time.
This adds an isolation testcase to test that decoding happens at commit
time when the consistent snapshot state is reached after prepare but
before commit prepared.

Author: Ajin Cherian
Reviewed-by: Amit Kapila
Discussion:
https://postgr.es/m/02DA5F5E-CECE-4D9C-8B4B-418077E2C010@postgrespro.ru
https://postgr.es/m/CAMGcDxeqEpWj3fTXwqhSwBdXd2RS9jzwWscO-XbeCfso6ts3+Q@mail.gmail.com

4 years agodoc: Document how to run regression tests with custom server settings
Peter Eisentraut [Tue, 5 Jan 2021 07:17:40 +0000 (08:17 +0100)]
doc: Document how to run regression tests with custom server settings

Author: Craig Ringer <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CAMsr+YF=+ctXBZj3ywmvKNUjWpxmuTuUKuv-rgbHGX5i5pLstQ@mail.gmail.com

4 years agoStandardize one aspect of rmgr desc output.
Peter Geoghegan [Tue, 5 Jan 2021 03:46:11 +0000 (19:46 -0800)]
Standardize one aspect of rmgr desc output.

Bring heap and hash rmgr desc output in line with nbtree and GiST desc
output by using the name latestRemovedXid for all fields that output the
contents of the latestRemovedXid field from the WAL record's C struct
(stop using local variants).

This seems like a clear improvement because latestRemovedXid is a symbol
name that already appears across many different source files, and so is
probably much more recognizable.

Discussion: https://postgr.es/m/CAH2-Wzkt_Rs4VqPSCk87nyjPAAEmWL8STU9zgET_83EF5YfrLw@mail.gmail.com

4 years agoFix typo in origin.c.
Amit Kapila [Tue, 5 Jan 2021 02:35:08 +0000 (08:05 +0530)]
Fix typo in origin.c.

Author: Peter Smith
Discussion: https://postgr.es/m/CAHut+PsReyuvww_Fn1NN_Vsv0wBP1bnzuhzRFr_2=y1nNZrG7w@mail.gmail.com

4 years agoFix typo in reorderbuffer.c.
Amit Kapila [Tue, 5 Jan 2021 02:26:40 +0000 (07:56 +0530)]
Fix typo in reorderbuffer.c.

Author: Zhijie Hou
Reviewed-by: Sawada Masahiko
Discussion: https://postgr.es/m/ba88bb58aaf14284abca16aec04bf279@G08CNEXMBPEKD05.g08.fujitsu.local

4 years agoReplace remaining uses of "whitelist".
Thomas Munro [Tue, 5 Jan 2021 01:00:16 +0000 (14:00 +1300)]
Replace remaining uses of "whitelist".

Instead describe the action that the list effects, or just use "list"
where the meaning is obvious from context.

Author: Dagfinn Ilmari Mannsåker <[email protected]>
Discussion: https://postgr.es/m/20200615182235.x7lch5n6kcjq4aue%40alap3.anarazel.de

4 years agopgindent: whitelist/blacklist -> additional/excluded.
Thomas Munro [Tue, 5 Jan 2021 00:27:06 +0000 (13:27 +1300)]
pgindent: whitelist/blacklist -> additional/excluded.

Author: Dagfinn Ilmari Mannsåker <[email protected]>
Discussion: https://postgr.es/m/20200615182235.x7lch5n6kcjq4aue%40alap3.anarazel.de

4 years agoRename "enum blacklist" to "uncommitted enums".
Thomas Munro [Mon, 4 Jan 2021 23:06:15 +0000 (12:06 +1300)]
Rename "enum blacklist" to "uncommitted enums".

We agreed to remove this terminology and use something more descriptive.

Discussion: https://postgr.es/m/20200615182235.x7lch5n6kcjq4aue%40alap3.anarazel.de

4 years agoFix integer-overflow corner cases in substring() functions.
Tom Lane [Mon, 4 Jan 2021 23:32:40 +0000 (18:32 -0500)]
Fix integer-overflow corner cases in substring() functions.

If the substring start index and length overflow when added together,
substring() misbehaved, either throwing a bogus "negative substring
length" error on a case that should succeed, or failing to complain that
a negative length is negative (and instead returning the whole string,
in most cases).  Unsurprisingly, the text, bytea, and bit variants of
the function all had this issue.  Rearrange the logic to ensure that
negative lengths are always rejected, and add an overflow check to
handle the other case.

Also install similar guards into detoast_attr_slice() (nee
heap_tuple_untoast_attr_slice()), since it's far from clear that
no other code paths leading to that function could pass it values
that would overflow.

 by myself and Pavel Stehule, per bug #16804 from Rafi Shamim.

Back- to v11.  While these bugs are old, the common/int.h
infrastructure for overflow-detecting arithmetic didn't exist before
commit 4d6ad3125, and it doesn't seem like these misbehaviors are bad
enough to justify developing a standalone fix for the older branches.

Discussion: https://postgr.es/m/16804-f4eeeb6c11ba71d4@postgresql.org

4 years agoRemove unused function s.
Thomas Munro [Mon, 4 Jan 2021 22:40:03 +0000 (11:40 +1300)]
Remove unused function s.

Cleanup for commit dee663f7.

Reported-by: Tomas Vondra <[email protected]>
Discussion: https://postgr.es/m/CA+hUKGLJ=84YT+NvhkEEDAuUtVHMfQ9i-N7k_o50JmQ6Rpj_OQ@mail.gmail.com

4 years agoRethink the "read/write parameter" mechanism in pl/pgsql.
Tom Lane [Mon, 4 Jan 2021 17:39:27 +0000 (12:39 -0500)]
Rethink the "read/write parameter" mechanism in pl/pgsql.

Performance issues with the preceding  to re-implement array
element assignment within pl/pgsql led me to realize that the read/write
parameter mechanism is misdesigned.  Instead of requiring the assignment
source expression to be such that *all* its references to the target
variable could be passed as R/W, we really want to identify *one*
reference to the target variable to be passed as R/W, allowing any other
ones to be passed read/only as they would be by default.  As long as the
R/W reference is a direct argument to the top-level (hence last to be
executed) function in the expression, there is no harm in R/O references
being passed to other lower parts of the expression.  Nor is there any
use-case for more than one argument of the top-level function being R/W.

Hence, rewrite that logic to identify one single Param that references
the target variable, and make only that Param pass a read/write
reference, not any other Params referencing the target variable.

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

4 years agoRemove PLPGSQL_DTYPE_ARRAYELEM datum type within pl/pgsql.
Tom Lane [Mon, 4 Jan 2021 17:14:37 +0000 (12:14 -0500)]
Remove PLPGSQL_DTYPE_ARRAYELEM datum type within pl/pgsql.

In the wake of the previous commit, we don't really need this anymore,
since array assignment is primarily handled by the core code.

The only way that that code could still be reached is that a GET
DIAGNOSTICS target variable could be an array element.  But that
doesn't seem like a particularly essential feature.  I'd added it
in commit 55caaaeba, but just because it was easy not because
anyone had actually asked for it.  Hence, revert that  and
then remove the now-unreachable stuff.  (If we really had to,
we could probably reimplement GET DIAGNOSTICS using the new
assignment machinery; but the cost/benefit ratio looks very poor,
and it'd likely be a bit slower.)

Note that PLPGSQL_DTYPE_RECFIELD remains.  It's possible that we
could get rid of that too, but maintaining the existing behaviors
for RECORD-type variables seems like it might be difficult.  Since
there's not any functional limitation in those code paths as there
was in the ARRAYELEM code, I've not pursued the idea.

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

4 years agoRe-implement pl/pgsql's expression and assignment parsing.
Tom Lane [Mon, 4 Jan 2021 16:52:00 +0000 (11:52 -0500)]
Re-implement pl/pgsql's expression and assignment parsing.

Invent new RawParseModes that allow the core grammar to handle
pl/pgsql expressions and assignments directly, and thereby get rid
of a lot of hackery in pl/pgsql's parser.  This moves a good deal
of knowledge about pl/pgsql into the core code: notably, we have to
invent a CoercionContext that matches pl/pgsql's (rather dubious)
historical behavior for assignment coercions.  That's getting away
from the original idea of pl/pgsql as an arm's-length extension of
the core, but really we crossed that bridge a long time ago.

The main advantage of doing this is that we can now use the core
parser to generate FieldStore and/or SubscriptingRef nodes to handle
assignments to pl/pgsql variables that are records or arrays.  That
fixes a number of cases that had never been implemented in pl/pgsql
assignment, such as nested records and array slicing, and it allows
pl/pgsql assignment to support the datatype-specific subscripting
behaviors introduced in commit c7aba7c14.

There are cosmetic benefits too: when a syntax error occurs in a
pl/pgsql expression, the error report no longer includes the confusing
"SELECT" keyword that used to get prefixed to the expression text.
Also, there seem to be some small speed gains.

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

4 years agoAdd the ability for the core grammar to have more than one parse target.
Tom Lane [Mon, 4 Jan 2021 16:03:22 +0000 (11:03 -0500)]
Add the ability for the core grammar to have more than one parse target.

This  essentially allows gram.y to implement a family of related
syntax trees, rather than necessarily always parsing a list of SQL
statements.  raw_parser() gains a new argument, enum RawParseMode,
to say what to do.  As proof of concept, add a mode that just parses
a TypeName without any other decoration, and use that to greatly
simplify typeStringToTypeName().

In addition, invent a new SPI entry point SPI_prepare_extended() to
allow SPI users (particularly plpgsql) to get at this new functionality.
In hopes of making this the last variant of SPI_prepare(), set up its
additional arguments as a struct rather than direct arguments, and
promise that future additions to the struct can default to zero.
SPI_prepare_cursor() and SPI_prepare_params() can perhaps go away at
some point.

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

4 years agoSimplify some comments in xml.c
Michael Paquier [Mon, 4 Jan 2021 10:47:58 +0000 (19:47 +0900)]
Simplify some comments in xml.c

Author: Justin Pryzby
Discussion: https://postgr.es/m/X/[email protected]

4 years agoAllow decoding at prepare time in ReorderBuffer.
Amit Kapila [Mon, 4 Jan 2021 03:04:50 +0000 (08:34 +0530)]
Allow decoding at prepare time in ReorderBuffer.

This  allows PREPARE-time decoding of two-phase transactions (if the
output plugin supports this capability), in which case the transactions
are replayed at PREPARE and then committed later when COMMIT PREPARED
arrives.

Now that we decode the changes before the commit, the concurrent aborts
may cause failures when the output plugin consults catalogs (both system
and user-defined).

We detect such failures with a special sqlerrcode
ERRCODE_TRANSACTION_ROLLBACK introduced by commit 7259736a6e and stop
decoding the remaining changes. Then we rollback the changes when rollback
prepared is encountered.

Author: Ajin Cherian and Amit Kapila based on previous work by Nikhil Sontakke and Stas Kelvich
Reviewed-by: Amit Kapila, Peter Smith, Sawada Masahiko, Arseny Sher, and Dilip Kumar
Tested-by: Takamichi Osumi
Discussion:
https://postgr.es/m/02DA5F5E-CECE-4D9C-8B4B-418077E2C010@postgrespro.ru
https://postgr.es/m/CAMGcDxeqEpWj3fTXwqhSwBdXd2RS9jzwWscO-XbeCfso6ts3+Q@mail.gmail.com

4 years agoUpdate copyright for 2021
Bruce Momjian [Sat, 2 Jan 2021 18:06:25 +0000 (13:06 -0500)]
Update copyright for 2021

Back-through: 9.5

4 years agoDoc: improve explanation of EXTRACT(EPOCH) for timestamp without tz.
Tom Lane [Fri, 1 Jan 2021 20:51:09 +0000 (15:51 -0500)]
Doc: improve explanation of EXTRACT(EPOCH) for timestamp without tz.

Try to be clearer about what computation is actually happening here.

Per bug #16797 from Dana Burd.

Discussion: https://postgr.es/m/16797-f264b0b980b53b8b@postgresql.org

4 years agoGet heap page max offset with buffer lock held.
Peter Geoghegan [Thu, 31 Dec 2020 01:21:42 +0000 (17:21 -0800)]
Get heap page max offset with buffer lock held.

On further reflection it seems better to call PageGetMaxOffsetNumber()
after acquiring a buffer lock on the page.  This shouldn't really
matter, but doing it this way is cleaner.

Follow-up to commit 42288174.

Back: 12-, just like commit 42288174

4 years agoFix index deletion latestRemovedXid bug.
Peter Geoghegan [Thu, 31 Dec 2020 00:29:05 +0000 (16:29 -0800)]
Fix index deletion latestRemovedXid bug.

The logic for determining the latest removed XID for the purposes of
generating recovery conflicts in REDO routines was subtly broken.  It
failed to follow links from HOT chains, and so failed to consider all
relevant heap tuple headers in some cases.

To fix, expand the loop that deals with LP_REDIRECT line pointers to
also deal with HOT chains.  The new version of the loop is loosely based
on a similar loop from heap_prune_chain().

The impact of this bug is probably quite limited, since the horizon code
necessarily deals with heap tuples that are pointed to by LP_DEAD-set
index tuples.  The process of setting LP_DEAD index tuples (e.g. within
the kill_prior_tuple mechanism) is highly correlated with opportunistic
pruning of pointed-to heap tuples.  Plus the question of generating a
recovery conflict usually comes up some time after index tuple LP_DEAD
bits were initially set, unlike heap pruning, where a latestRemovedXid
is generated at the point of the pruning operation (heap pruning has no
deferred "would-be page split" style processing that produces conflicts
lazily).

Only back to Postgres 12, the first version where this logic runs
during original execution (following commit 558a9165e08).  The index
latestRemovedXid mechanism has had the same bug since it first appeared
over 10 years ago (in commit a760893d), but backing to all
supported versions now seems like a bad idea on balance.  Running the
new improved code during recovery seems risky, especially given the lack
of complaints from the field.

Author: Peter Geoghegan <[email protected]>
Discussion: https://postgr.es/m/CAH2-Wz=Eib393+HHcERK_9MtgNS7Ew1HY=RDC_g6GL46zM5C6Q@mail.gmail.com
Back: 12-

4 years agoDoc: spell out comparison behaviors for the date/time types.
Tom Lane [Wed, 30 Dec 2020 22:48:43 +0000 (17:48 -0500)]
Doc: spell out comparison behaviors for the date/time types.

The behavior of cross-type comparisons among date/time data types was
not really explained anywhere.  You could probably infer it if you
recognized the applicability of comments elsewhere about datatype
conversions, but it seems worthy of explicit documentation.

Per bug #16797 from Dana Burd.

Discussion: https://postgr.es/m/16797-f264b0b980b53b8b@postgresql.org

4 years agoMore fixups for pg_upgrade cross-version tests.
Tom Lane [Wed, 30 Dec 2020 19:15:41 +0000 (14:15 -0500)]
More fixups for pg_upgrade cross-version tests.

Commit 7ca37fb04 removed regress_putenv from the regress.so library,
so reloading a SQL function dependent on that would not work.
Fix similarly to 52202bb39.

Per buildfarm.

4 years agoRefactor multirange_in()
Alexander Korotkov [Wed, 30 Dec 2020 18:11:31 +0000 (21:11 +0300)]
Refactor multirange_in()

This commit preserves the logic of multirange_in() but makes it more clear
what's going on.  Also, this commit fixes the compiler warning spotted by the
buildfarm.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/2246043.1609290699%40sss.pgh.pa.us

4 years agoUse setenv() in preference to putenv().
Tom Lane [Wed, 30 Dec 2020 17:55:59 +0000 (12:55 -0500)]
Use setenv() in preference to putenv().

Since at least 2001 we've used putenv() and avoided setenv(), on the
grounds that the latter was unportable and not in POSIX.  However,
POSIX added it that same year, and by now the situation has reversed:
setenv() is probably more portable than putenv(), since POSIX now
treats the latter as not being a core function.  And setenv() has
cleaner semantics too.  So, let's reverse that old policy.

This commit adds a simple src/port/ implementation of setenv() for
any stragglers (we have one in the buildfarm, but I'd not be surprised
if that code is never used in the field).  More importantly, extend
win32env.c to also support setenv().  Then, replace usages of putenv()
with setenv(), and get rid of some ad-hoc implementations of setenv()
wannabees.

Also, adjust our src/port/ implementation of unsetenv() to follow the
POSIX spec that it returns an error indicator, rather than returning
void as per the ancient BSD convention.  I don't feel a need to make
all the call sites check for errors, but the portability stub ought
to match real-world practice.

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

4 years agoFix selectivity estimation @> (anymultirange, anyrange) operator
Alexander Korotkov [Wed, 30 Dec 2020 17:19:15 +0000 (20:19 +0300)]
Fix selectivity estimation @> (anymultirange, anyrange) operator

Attempt to get selectivity estimation for @> (anymultirange, anyrange) operator
caused an error in buildfarm, because this operator was missed in switch()
of calc_hist_selectivity().  Fix that and also make regression tests reliably
check that selectivity estimation for (multi)ranges doesn't fall.  Previously,
whether we test selectivity estimation for (multi)ranges depended on
whether autovacuum managed to gather concurrently to the test.

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/X%2BwmgjRItuvHNBeV%40paquier.xyz

4 years agoFix up usage of krb_server_keyfile GUC parameter.
Tom Lane [Wed, 30 Dec 2020 16:38:42 +0000 (11:38 -0500)]
Fix up usage of krb_server_keyfile GUC parameter.

secure_open_gssapi() installed the krb_server_keyfile setting as
KRB5_KTNAME unconditionally, so long as it's not empty.  However,
pg_GSS_recvauth() only installed it if KRB5_KTNAME wasn't set already,
leading to a troubling inconsistency: in theory, clients could see
different sets of server principal names depending on whether they
use GSSAPI encryption.  Always using krb_server_keyfile seems like
the right thing, so make both places do that.  Also fix up
secure_open_gssapi()'s lack of a check for setenv() failure ---
it's unlikely, surely, but security-critical actions are no place
to be sloppy.

Also improve the associated documentation.

This  does nothing about secure_open_gssapi()'s use of setenv(),
and indeed causes pg_GSS_recvauth() to use it too.  That's nominally
against project portability rules, but since this code is only built
with --with-gssapi, I do not feel a need to do something about this
in the back branches.  A fix will be forthcoming for HEAD though.

Back- to v12 where GSSAPI encryption was introduced.  The
dubious behavior in pg_GSS_recvauth() goes back further, but it
didn't have anything to be inconsistent with, so let it be.

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

4 years agoSanitize IF NOT EXISTS in EXPLAIN for CTAS and matviews
Michael Paquier [Wed, 30 Dec 2020 12:23:24 +0000 (21:23 +0900)]
Sanitize IF NOT EXISTS in EXPLAIN for CTAS and matviews

IF NOT EXISTS was ignored when specified in an EXPLAIN query for CREATE
MATERIALIZED VIEW or CREATE TABLE AS.  Hence, if this clause was
specified, the caller would get a failure if the relation already
exists instead of a success with a NOTICE message.

This commit makes the behavior of IF NOT EXISTS in EXPLAIN consistent
with the non-EXPLAIN'd DDL queries, preventing a failure with IF NOT
EXISTS if the relation to-be-created already exists.  The skip is done
before the SELECT query used for the relation is planned or executed,
and a "dummy" plan is generated instead depending on the format used by
EXPLAIN.

Author: Bharath Rupireddy
Reviewed-by: Zhijie Hou, Michael Paquier
Discussion: https://postgr.es/m/CALj2ACVa3oJ9O_wcGd+FtHWZds04dEKcakxphGz5POVgD4wC7Q@mail.gmail.com

4 years agoExtend the output plugin API to allow decoding of prepared xacts.
Amit Kapila [Wed, 30 Dec 2020 10:47:26 +0000 (16:17 +0530)]
Extend the output plugin API to allow decoding of prepared xacts.

This adds six methods to the output plugin API, adding support for
 changes of two-phase transactions at prepare time.

* begin_prepare
* filter_prepare
* prepare
* commit_prepared
* rollback_prepared
* stream_prepare

Most of this is a simple extension of the existing methods, with the
semantic difference that the transaction is not yet committed and maybe
aborted later.

Until now two-phase transactions were translated into regular transactions
on the subscriber, and the GID was not forwarded to it. None of the
two-phase commands were communicated to the subscriber.

This  provides the infrastructure for logical decoding plugins to be
informed of two-phase commands Like PREPARE TRANSACTION, COMMIT PREPARED
and ROLLBACK PREPARED commands with the corresponding GID.

This also extends the 'test_decoding' plugin, implementing these new
methods.

This commit simply adds these new APIs and the upcoming  to "allow
the decoding at prepare time in ReorderBuffer" will use these APIs.

Author: Ajin Cherian and Amit Kapila based on previous work by Nikhil Sontakke and Stas Kelvich
Reviewed-by: Amit Kapila, Peter Smith, Sawada Masahiko, and Dilip Kumar
Discussion:
https://postgr.es/m/02DA5F5E-CECE-4D9C-8B4B-418077E2C010@postgrespro.ru
https://postgr.es/m/CAMGcDxeqEpWj3fTXwqhSwBdXd2RS9jzwWscO-XbeCfso6ts3+Q@mail.gmail.com

4 years agoIn pg_upgrade cross-version test, handle postfix operators.
Noah Misch [Wed, 30 Dec 2020 09:43:43 +0000 (01:43 -0800)]
In pg_upgrade cross-version test, handle postfix operators.

Commit 1ed6b895634ce0dc5fd4bd040e87252b32182cba eliminated support for
them, so drop them from regression databases before upgrading.  This is
necessary but not sufficient for testing v13 -> v14 upgrades.

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

4 years agoIn pg_upgrade cross-version test, handle lack of oldstyle_length().
Noah Misch [Wed, 30 Dec 2020 09:43:43 +0000 (01:43 -0800)]
In pg_upgrade cross-version test, handle lack of oldstyle_length().

This suffices for testing v12 -> v13; some other version pairs need more
changes.  Back- to v10, which removed the function.

4 years agoRemove references to libpq_srcdir in adminpack and old_snapshot
Michael Paquier [Wed, 30 Dec 2020 03:38:16 +0000 (12:38 +0900)]
Remove references to libpq_srcdir in adminpack and old_snapshot

Those two modules included references to libpq's source path, without
using anything from libpq.  Some copy-pastos done when each module was
created are likely at the origin of those useless references (aecf5ee
for old_snapshot, fe59e56 for adminpack).

Reviewed-by: Tom Lane, David Rowley
Discussion: https://postgr.es/m/[email protected]

4 years agoDoc: fix up PDF build warnings from over-width table columns.
Tom Lane [Wed, 30 Dec 2020 01:44:03 +0000 (20:44 -0500)]
Doc: fix up PDF build warnings from over-width table columns.

Addition of multirange info to tables 8.27 and 65.1 made them start
throwing "exceed the available area" warnings in PDF docs builds.

For 8.27, twiddling the existing column width hints was enough to
fix this.  For 65.1, I twiddled the widths a little, but to really
fix it I had to insert a space after each comma in the table, to
allow a line break to occur there.  (This seemed easier to read
and maintain than the alternative of inserting &zwsp; entities.)

Per buildfarm.

4 years agoSuppress log spam from multiple reports of SIGQUIT shutdown.
Tom Lane [Tue, 29 Dec 2020 23:02:38 +0000 (18:02 -0500)]
Suppress log spam from multiple reports of SIGQUIT shutdown.

When the postmaster sends SIGQUIT to its children, there's no real
need for all the children to log that fact; the postmaster already
made a log entry about it, so adding perhaps dozens or hundreds of
child-process log entries adds nothing of value.  So, let's introduce
a new ereport level to specify "WARNING, but never send to log" and
use that for these messages.

Such a change wouldn't have been desirable before commit 7e784d1dc,
because if someone manually SIGQUIT's a backend, we *do* want to log
that.  But now we can tell the difference between a signal that was
issued by the postmaster and one that was not with reasonable
certainty.

While we're here, also clear error_context_stack before ereport'ing,
to prevent error callbacks from being invoked in the signal-handler
context.  This should reduce the odds of getting hung up while trying
to notify the client.

Per a suggestion from Andres Freund.

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

4 years agoAdd support of multirange matching to the existing range GiST indexes
Alexander Korotkov [Tue, 29 Dec 2020 20:36:43 +0000 (23:36 +0300)]
Add support of multirange matching to the existing range GiST indexes

6df7a9698b has introduced a set of operators between ranges and multiranges.
Existing GiST indexes for ranges could easily support majority of them.
This commit adds support for new operators to the existing range GiST indexes.
New operators resides the same strategy numbers as existing ones.  Appropriate
check function is determined using the subtype.

Catversion is bumped.

4 years agoImprove the signature of internal multirange functions
Alexander Korotkov [Tue, 29 Dec 2020 20:35:38 +0000 (23:35 +0300)]
Improve the signature of internal multirange functions

There is a set of *_internal() functions exposed in
include/utils/multirangetypes.h.  This commit improves the signatures of these
functions in two ways.
 * Add const qualifies where applicable.
 * Replace multirange typecache argument with range typecache argument.
   Multirange typecache was used solely to find the range typecache.  At the
   same time, range typecache is easier for the caller to find.

4 years agoImplement operators for checking if the range contains a multirange
Alexander Korotkov [Tue, 29 Dec 2020 20:35:33 +0000 (23:35 +0300)]
Implement operators for checking if the range contains a multirange

We have operators for checking if the multirange contains a range but don't
have the opposite.  This commit improves completeness of the operator set by
adding two new operators: @> (anyrange,anymultirange) and
<@(anymultirange,anyrange).

Catversion is bumped.

4 years agoFix bugs in comparison functions for multirange_bsearch_match()
Alexander Korotkov [Tue, 29 Dec 2020 20:35:26 +0000 (23:35 +0300)]
Fix bugs in comparison functions for multirange_bsearch_match()

Two functions multirange_range_overlaps_bsearch_comparison() and
multirange_range_contains_bsearch_comparison() contain bugs of returning -1
instead of 1.  This commit fixes these bugs and adds corresponding regression
tests.

4 years agodoc: Improve description of min_dynamic_shared_memory
Michael Paquier [Tue, 29 Dec 2020 07:49:14 +0000 (16:49 +0900)]
doc: Improve description of min_dynamic_shared_memory

While on it, fix one oversight in 90fbf7c, that introduced a reference
to an incorrect value for the compression level of pg_dump.

Author: Justin Pryzby
Reviewed-by: Thomas Munro, Michael Paquier
Discussion: https://postgr.es/m/CA+hUKGJRTLWWPcQfjm_xaOk98M8aROK903X92O0x-4vLJPWrrA@mail.gmail.com

4 years agoImprove log messages related to pg_hba.conf not matching a connection.
Tom Lane [Mon, 28 Dec 2020 22:58:58 +0000 (17:58 -0500)]
Improve log messages related to pg_hba.conf not matching a connection.

Include details on whether GSS encryption has been activated;
since we added "hostgssenc" type HBA entries, that's relevant info.

Kyotaro Horiguchi and Tom Lane.  Back- to v12 where
GSS encryption was introduced.

Discussion: https://postgr.es/m/e5b0b6ed05764324a2f3fe7acfc766d5@smhi.se

4 years agoFix assorted issues in backend's GSSAPI encryption support.
Tom Lane [Mon, 28 Dec 2020 22:44:17 +0000 (17:44 -0500)]
Fix assorted issues in backend's GSSAPI encryption support.

Unrecoverable errors detected by GSSAPI encryption can't just be
reported with elog(ERROR) or elog(FATAL), because attempting to
send the error report to the client is likely to lead to infinite
recursion or loss of protocol sync.  Instead make this code do what
the SSL encryption code has long done, which is to just report any
such failure to the server log (with elevel COMMERROR), then pretend
we've lost the connection by returning errno = ECONNRESET.

Along the way, fix confusion about whether message translation is done
by pg_GSS_error() or its callers (the latter should do it), and make
the backend version of that function work more like the frontend
version.

Avoid allocating the port->gss struct until it's needed; we surely
don't need to allocate it in the postmaster.

Improve logging of "connection authorized" messages with GSS enabled.
(As part of this, I back-ed the code changes from dc11f31a1.)

Make BackendStatusShmemSize() account for the GSS-related space that
will be allocated by CreateSharedBackendStatus().  This omission
could possibly cause out-of-shared-memory problems with very high
max_connections settings.

Remove arbitrary, pointless restriction that only GSS authentication
can be used on a GSS-encrypted connection.

Improve documentation; notably, document the fact that libpq now
prefers GSS encryption over SSL encryption if both are possible.

Per report from Mikael Gustavsson.  Back- to v12 where
this code was introduced.

Discussion: https://postgr.es/m/e5b0b6ed05764324a2f3fe7acfc766d5@smhi.se

4 years agoFix bugs in libpq's GSSAPI encryption support.
Tom Lane [Mon, 28 Dec 2020 20:43:44 +0000 (15:43 -0500)]
Fix bugs in libpq's GSSAPI encryption support.

The critical issue fixed here is that if a GSSAPI-encrypted connection
is successfully made, pqsecure_open_gss() cleared conn->allow_ssl_try,
as an admittedly-hacky way of preventing us from then trying to tunnel
SSL encryption over the already-encrypted connection.  The problem
with that is that if we abandon the GSSAPI connection because of a
failure during authentication, we would not attempt SSL encryption
in the next try with the same server.  This can lead to unexpected
connection failure, or silently getting a non-encrypted connection
where an encrypted one is expected.

Fortunately, we'd only manage to make a GSSAPI-encrypted connection
if both client and server hold valid tickets in the same Kerberos
infrastructure, which is a relatively uncommon environment.
Nonetheless this is a very nasty bug with potential security
consequences.  To fix, don't reset the flag, instead adding a
check for conn->gssenc being already true when deciding whether
to try to initiate SSL.

While here, fix some lesser issues in libpq's GSSAPI code:

* Use the need_new_connection stanza when dropping an attempted
GSSAPI connection, instead of partially duplicating that code.
The consequences of this are pretty minor: AFAICS it could only
lead to auth_req_received or password_needed remaining set when
they shouldn't, which is not too harmful.

* Fix pg_GSS_error() to not repeat the "mprefix" it's given multiple
times, and to notice any failure return from gss_display_status().

* Avoid gratuitous dependency on NI_MAXHOST in
pg_GSS_load_servicename().

Per report from Mikael Gustavsson.  Back- to v12 where
this code was introduced.

Discussion: https://postgr.es/m/e5b0b6ed05764324a2f3fe7acfc766d5@smhi.se

4 years agoExpose the default for channel_binding in PQconndefaults().
Tom Lane [Mon, 28 Dec 2020 17:13:40 +0000 (12:13 -0500)]
Expose the default for channel_binding in PQconndefaults().

If there's a static default value for a connection option,
it should be shown in the PQconninfoOptions array.

Daniele Varrazzo

Discussion: https://postgr.es/m/CA+mi_8Zo8Rgn7p+6ZRY7QdDu+23ukT9AvoHNyPbgKACxwgGhZA@mail.gmail.com

4 years agoFurther fix thinko in plpgsql memory fix.
Tom Lane [Mon, 28 Dec 2020 16:55:23 +0000 (11:55 -0500)]
Further fix thinko in plpgsql memory  fix.

There's a second call of get_eval_mcontext() that should also be
get_stmt_mcontext().  This is actually dead code, since no
interesting allocations happen before switching back to the
original context, but we should keep it in sync with the other
call to forestall possible future bugs.

Discussion: https://postgr.es/m/f075f7be-c654-9aa8-3ffc-e9214622f02a@enterprisedb.com

4 years agoFix thinko in plpgsql memory fix.
Tom Lane [Mon, 28 Dec 2020 16:41:25 +0000 (11:41 -0500)]
Fix thinko in plpgsql memory  fix.

Commit a6b1f5365 intended to place the transient "target" list of
a CALL statement in the function's statement-lifespan context,
but I fat-fingered that and used get_eval_mcontext() instead of
get_stmt_mcontext().  The eval_mcontext belongs to the "simple
expression" infrastructure, which is destroyed at transaction end.
The net effect is that a CALL in a procedure to another procedure
that has OUT or INOUT parameters would fail if the called procedure
did a COMMIT.

Per report from Peter Eisentraut.  Back- to v11, like the
prior .

Discussion: https://postgr.es/m/f075f7be-c654-9aa8-3ffc-e9214622f02a@enterprisedb.com

4 years agoFix inconsistent code with shared invalidations of snapshots
Michael Paquier [Mon, 28 Dec 2020 13:16:49 +0000 (22:16 +0900)]
Fix inconsistent code with shared invalidations of snapshots

The code in charge of processing a single invalidation message has been
using since 568d413 the structure for relation mapping messages.  This
had fortunately no consequence as both locate the database ID at the
same location, but it could become a problem in the future if this area
of the code changes.

Author: Konstantin Knizhnik
Discussion: https://postgr.es/m/8044c223-4d3a-2cdb-42bf-29940840ce94@postgrespro.ru
Back-through: 9.5

4 years agopostgres_fdw: Fix connection .
Fujii Masao [Mon, 28 Dec 2020 10:56:13 +0000 (19:56 +0900)]
postgres_fdw: Fix connection .

In postgres_fdw, the cached connections to foreign servers will not be
closed until the local session exits if the user mappings or foreign servers
that those connections depend on are dropped. Those connections can be
.

To fix that connection  issue, after a change to a pg_foreign_server
or pg_user_mapping catalog entry, this commit makes postgres_fdw close
the connections depending on that entry immediately if current
transaction has not used those connections yet. Otherwise, mark those
connections as invalid and then close them at the end of current transaction,
since they cannot be closed in the midst of the transaction using them.
Closed connections will be remade at the next opportunity if necessary.

Back- to all supported branches.

Author: Bharath Rupireddy
Reviewed-by: Zhihong Yu, Zhijie Hou, Fujii Masao
Discussion: https://postgr.es/m/CALj2ACVNcGH_6qLY-4_tXz8JLvA+4yeBThRfxMz7Oxbk1aHcpQ@mail.gmail.com

4 years agoRevert "Add key management system" (978f869b99) & later commits
Bruce Momjian [Mon, 28 Dec 2020 02:37:42 +0000 (21:37 -0500)]
Revert "Add key management system" (978f869b99) & later commits

The  needs test cases, reorganization, and cfbot testing.
Technically reverts commits 5c31afc49d..e35b2bad1a (exclusive/inclusive)
and 08db7c63f3..ccbe34139b.

Reported-by: Tom Lane, Michael Paquier
Discussion: https://postgr.es/m/[email protected]

4 years agoSecond attempt to stabilize 05c02589.
Jeff Davis [Sun, 27 Dec 2020 20:09:00 +0000 (12:09 -0800)]
Second attempt to stabilize 05c02589.

Removing the EXPLAIN test to stabilize the buildfarm. The execution
test should still be effective to catch the bug even if the plan is
slightly different on different platforms.

4 years agoStabilize test introduced in 05c02589, per buildfarm.
Jeff Davis [Sun, 27 Dec 2020 17:47:23 +0000 (09:47 -0800)]
Stabilize test introduced in 05c02589, per buildfarm.

In passing, make the capitalization match the rest of the file.

Reported-by: Tom Lane
4 years agoFix bug #16784 in Disk-based Hash Aggregation.
Jeff Davis [Sun, 27 Dec 2020 01:25:30 +0000 (17:25 -0800)]
Fix bug #16784 in Disk-based Hash Aggregation.

Before processing tuples, agg_refill_hash_table() was setting all
pergroup pointers to NULL to signal to advance_aggregates() that it
should not attempt to advance groups that had spilled.

The problem was that it also set the pergroups for sorted grouping
sets to NULL, which caused rescanning to fail.

Instead, change agg_refill_hash_table() to only set the pergroups for
hashed grouping sets to NULL; and when compiling the expression, pass
doSort=false.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/16784-7ff169bf2c3d1588%40postgresql.org
Back-through: 13

4 years agoinitdb: document that -K requires an argument
Bruce Momjian [Sat, 26 Dec 2020 15:00:05 +0000 (10:00 -0500)]
initdb:  document that -K requires an argument

Reported-by: "Shinoda, Noriyoshi"
Discussion: https://postgr.es/m/TU4PR8401MB1152E92B4D44C81E496D6032EEDB0@TU4PR8401MB1152.NAMPRD84.PROD.OUTLOOK.COM

Author: "Shinoda, Noriyoshi"

Back-through: msater

4 years agoauth commands: list specific commands to install in Makefile
Bruce Momjian [Sat, 26 Dec 2020 14:25:05 +0000 (09:25 -0500)]
auth commands:  list specific commands to install in Makefile

Previously I used Makefile functions.

Back-through: master

4 years agopg_alterckey: remove TAP check rules from Makefile
Bruce Momjian [Sat, 26 Dec 2020 14:03:12 +0000 (09:03 -0500)]
pg_alterckey:  remove TAP check rules from Makefile

Reported-by: Pavel Stehule, Michael Paquier
Discussion: https://postgr.es/m/CAFj8pRBRNo4co5bqCx4BLx1ZZ45Z_T-opPxA+u7SLp7gAtBpNA@mail.gmail.com

Back-through: master

4 years agoAdd scripts for retrieving the cluster file encryption key
Bruce Momjian [Sat, 26 Dec 2020 06:19:09 +0000 (01:19 -0500)]
Add scripts for retrieving the cluster file encryption key

Scripts are passphrase, direct, AWS, and two Yubikey ones.

Back-through: master

4 years agodoc: fix SGML markup for pg_alterckey from commit 62afb42a7f
Bruce Momjian [Sat, 26 Dec 2020 06:10:24 +0000 (01:10 -0500)]
doc:  fix SGML markup for pg_alterckey from commit 62afb42a7f

Back-through: master

4 years agopg_alterckey: adjust doc build and Win32 sleep/open build fails
Bruce Momjian [Sat, 26 Dec 2020 03:47:16 +0000 (22:47 -0500)]
pg_alterckey: adjust doc build and Win32 sleep/open build fails

Fix for commit 62afb42a7f.

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

Back-through: master

4 years agoFix function call typo in frontend Win32 code, commit 978f869b99
Bruce Momjian [Sat, 26 Dec 2020 01:49:50 +0000 (20:49 -0500)]
Fix function call typo in frontend Win32 code, commit 978f869b99

Reported-by: buildfarm member walleye
Back-through: master

4 years agoAllow ssl_passphrase_command to prompt the terminal
Bruce Momjian [Sat, 26 Dec 2020 01:41:06 +0000 (20:41 -0500)]
Allow ssl_passphrase_command to prompt the terminal

Previously the command could not access the terminal for a passphrase.

Back-through: master

4 years agoAdd pg_alterckey utility to change the cluster key
Bruce Momjian [Sat, 26 Dec 2020 01:24:53 +0000 (20:24 -0500)]
Add pg_alterckey utility to change the cluster key

This can change the key that encrypts the data encryption keys used for
cluster file encryption.

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

Back-through: master

4 years agoremove missing reference to crypto test from 978f869b99
Bruce Momjian [Fri, 25 Dec 2020 20:13:16 +0000 (15:13 -0500)]
remove missing reference to crypto test from  978f869b99

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

Back-through: master

4 years agoReally fix the dummy implementations in cipher.c.
Tom Lane [Fri, 25 Dec 2020 19:44:17 +0000 (14:44 -0500)]
Really fix the dummy implementations in cipher.c.

945083b2f wasn't enough to silence compiler warnings.

4 years agofix no-return function call in cipher.c from commit 978f869b99
Bruce Momjian [Fri, 25 Dec 2020 19:40:46 +0000 (14:40 -0500)]
fix no-return function call in cipher.c from commit 978f869b99

Reported-by: buildfarm member sifaka
Back-through: master

4 years agofixes docs and missing initdb help option for commit 978f869b99
Bruce Momjian [Fri, 25 Dec 2020 19:00:12 +0000 (14:00 -0500)]
fixes docs and missing initdb help option for commit 978f869b99

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

Back-through: master

4 years agoInvalidate acl.c caches when pg_authid changes.
Noah Misch [Fri, 25 Dec 2020 18:41:59 +0000 (10:41 -0800)]
Invalidate acl.c caches when pg_authid changes.

This makes existing sessions reflect "ALTER ROLE ... [NO]INHERIT" as
quickly as they have been reflecting "GRANT role_name".  Back- to
9.5 (all supported versions).

Reviewed by Nathan Bossart.

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

4 years agoremove uint128 requirement from 978f869b99 (CFE)
Bruce Momjian [Fri, 25 Dec 2020 16:35:59 +0000 (11:35 -0500)]
remove uint128 requirement from  978f869b99 (CFE)

Used char[16] instead.

Reported-by: buildfarm member florican
Back-through: master

4 years agoFix return value and const declaration from commit 978f869b99
Bruce Momjian [Fri, 25 Dec 2020 16:00:32 +0000 (11:00 -0500)]
Fix return value and const declaration from commit 978f869b99

This fixes the non-OpenSSL compile case.

Reported-by: buildfarm member sifaka
Back-through: master

4 years agoAdd key management system
Bruce Momjian [Fri, 25 Dec 2020 15:19:44 +0000 (10:19 -0500)]
Add key management system

This adds a key management system that stores (currently) two data
encryption keys of length 128, 192, or 256 bits.  The data keys are
AES256 encrypted using a key encryption key, and validated via GCM
cipher mode.  A command to obtain the key encryption key must be
specified at initdb time, and will be run at every database server
start.  New parameters allow a file descriptor open to the terminal to
be passed.  pg_upgrade support has also been added.

Discussion: https://postgr.es/m/CA+fd4k7q5o6Nc_AaX6BcYM9yqTbC6_pnH-6nSD=54Zp6NBQTCQ@mail.gmail.com
Discussion: https://postgr.es/m/20201202213814[email protected]

Author: Masahiko Sawada, me, Stephen Frost

4 years agoAvoid time-of-day-dependent failure in log rotation test.
Tom Lane [Fri, 25 Dec 2020 02:37:46 +0000 (21:37 -0500)]
Avoid time-of-day-dependent failure in log rotation test.

Buildfarm members pogona and petalura have shown a failure when
pg_ctl/t/004_logrotate.pl starts just before local midnight.
The default rotate-at-midnight behavior occurs just before the
Perl script examines current_logfiles, so it figures that the
rotation it's already requested has occurred ... but in reality,
that rotation happens just after it looks, so the expected new
log data goes into a different file than the one it's examining.

In HEAD, src/test/kerberos/t/001_auth.pl has acquired similar code
that evidently has a related failure mode.  Besides being quite new,
few buildfarm critters run that test, so it's unsurprising that
we've not yet seen a failure there.

Fix both cases by setting log_rotation_age = 0 so that no time-based
rotation can occur.  Also absorb 004_logrotate.pl's decision to
set lc_messages = 'C' into the kerberos test, in hopes that it will
work in non-English prevailing locales.

Report: https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=pogona&dt=2020-12-24%2022%3A10%3A04
Report: https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=petalura&dt=2020-02-01%2022%3A20%3A04

4 years agorevert removal of hex_decode() from ecpg from commit c3826f831e
Bruce Momjian [Thu, 24 Dec 2020 23:21:37 +0000 (18:21 -0500)]
revert removal of hex_decode() from ecpg from commit c3826f831e

ecpglib on certain platforms can't handle the pg_log_fatal calls from
libraries.  This was reported by the buildfarm.  It needs a refactoring
and return value change if it is later removed.

Back-through: master

4 years agomove hex_decode() to /common so it can be called from frontend
Bruce Momjian [Thu, 24 Dec 2020 22:25:48 +0000 (17:25 -0500)]
move hex_decode() to /common so it can be called from frontend

This allows removal of a copy of hex_decode() from ecpg, and will be
used by the soon-to-be added pg_alterckey command.

Back-through: master

4 years agoFix race condition between shutdown and unstarted background workers.
Tom Lane [Thu, 24 Dec 2020 22:00:43 +0000 (17:00 -0500)]
Fix race condition between shutdown and unstarted background workers.

If a database shutdown (smart or fast) is commanded between the time
some process decides to request a new background worker and the time
that the postmaster can launch that worker, then nothing happens
because the postmaster won't launch any bgworkers once it's exited
PM_RUN state.  This is fine ... unless the requesting process is
waiting for that worker to finish (or even for it to start); in that
case the requestor is stuck, and only manual intervention will get us
to the point of being able to shut down.

To fix, cancel pending requests for workers when the postmaster sends
shutdown (SIGTERM) signals, and similarly cancel any new requests that
arrive after that point.  (We can optimize things slightly by only
doing the cancellation for workers that have waiters.)  To fit within
the existing bgworker APIs, the "cancel" is made to look like the
worker was started and immediately stopped, causing deregistration of
the bgworker entry.  Waiting processes would have to deal with
premature worker exit anyway, so this should introduce no bugs that
weren't there before.  We do have a side effect that registration
records for restartable bgworkers might disappear when theoretically
they should have remained in place; but since we're shutting down,
that shouldn't matter.

Back- to v10.  There might be value in putting this into 9.6
as well, but the management of bgworkers is a bit different there
(notably see 8ff518699) and I'm not convinced it's worth the effort
to validate the  for that branch.

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

4 years agoImprove client error messages for immediate-stop situations.
Tom Lane [Thu, 24 Dec 2020 17:58:32 +0000 (12:58 -0500)]
Improve client error messages for immediate-stop situations.

Up to now, if the DBA issued "pg_ctl stop -m immediate", the message
sent to clients was the same as for a crash-and-restart situation.
This is confusing, not least because the message claims that the
database will soon be up again, something we have no business
predicting.

Improve things so that we can generate distinct messages for the two
cases (and also recognize an ad-hoc SIGQUIT, should somebody try that).
To do that, add a field to pmsignal.c's shared memory data structure
that the postmaster sets just before broadcasting SIGQUIT to its
children.  No interlocking seems to be necessary; the intervening
signal-sending and signal-receipt should sufficiently serialize accesses
to the field.  Hence, this isn't any riskier than the existing usages
of pmsignal.c.

We might in future extend this idea to improve other
postmaster-to-children signal scenarios, although none of them
currently seem to be as badly overloaded as SIGQUIT.

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

4 years agoFix typos and grammar in docs and comments
Michael Paquier [Thu, 24 Dec 2020 08:05:49 +0000 (17:05 +0900)]
Fix typos and grammar in docs and comments

This fixes several areas of the documentation and some comments in
matters of style, grammar, or even format.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20201222041153[email protected]

4 years agodummy commit
Bruce Momjian [Wed, 25 Nov 2020 17:29:21 +0000 (12:29 -0500)]
dummy commit

4 years agoFix portability issues with parsing of recovery_target_xid
Michael Paquier [Wed, 23 Dec 2020 03:51:22 +0000 (12:51 +0900)]
Fix portability issues with parsing of recovery_target_xid

The parsing of this parameter has been using strtoul(), which is not
portable across platforms.  On most Unix platforms, unsigned long has a
size of 64 bits, while on Windows it is 32 bits.  It is common in
recovery scenarios to rely on the output of txid_current() or even the
newer pg_current_xact_id() to get a transaction ID for setting up
recovery_target_xid.  The value returned by those functions includes the
epoch in the computed result, which would cause strtoul() to fail where
unsigned long has a size of 32 bits once the epoch is incremented.

WAL records and 2PC data include only information about 32-bit XIDs and
it is not possible to have XIDs across more than one epoch, so
discarding the high bits from the transaction ID set has no impact on
recovery.  On the contrary, the use of strtoul() prevents a consistent
behavior across platforms depending on the size of unsigned long.

This commit changes the parsing of recovery_target_xid to use
pg_strtouint64() instead, available down to 9.6.  There is one TAP test
stressing recovery with recovery_target_xid, where a tweak based on
pg_reset{xlog,wal} is added to bump the XID epoch so as this change gets
tested, as per an idea from Alexander Lakhin.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/16780-107fd0c0385b1035@postgresql.org
Back-through: 9.6

4 years agoImprove autoprewarm's handling of early-shutdown scenarios.
Tom Lane [Tue, 22 Dec 2020 18:23:49 +0000 (13:23 -0500)]
Improve autoprewarm's handling of early-shutdown scenarios.

Bad things happen if the DBA issues "pg_ctl stop -m fast" before
autoprewarm finishes loading its list of blocks to prewarm.
The current worker process successfully terminates early, but
(if this wasn't the last database with blocks to prewarm) the
leader process will just try to launch another worker for the
next database.  Since the postmaster is now in PM_WAIT_BACKENDS
state, it ignores the launch request, and the leader just sits
until it's killed manually.

This is mostly the fault of our half-baked design for launching
background workers, but a proper fix for that is likely to be
too invasive to be back-able.  To ameliorate the situation,
fix apw_load_buffers() to check whether SIGTERM has arrived
just before trying to launch another worker.  That leaves us with
only a very narrow window in each worker launch where SIGTERM
could occur between the launch request and successful worker start.

Another issue is that if the leader process does manage to exit,
it unconditionally rewrites autoprewarm.blocks with only the
blocks currently in shared buffers, thus forgetting any blocks
that we hadn't reached yet while prewarming.  This seems quite
unhelpful, since the next database start will then not have the
expected prewarming benefit.  Fix it to not modify the file if
we shut down before the initial load attempt is complete.

Per bug #16785 from John Thompson.  Back- to v11 where
the autoprewarm code was introduced.

Discussion: https://postgr.es/m/16785-c0207d8c67fb5f25@postgresql.org

4 years agoIncrease timeout in 021_row_visibility.pl.
Tom Lane [Tue, 22 Dec 2020 16:10:12 +0000 (11:10 -0500)]
Increase timeout in 021_row_visibility.pl.

Commit 7b28913bc figured 30 seconds is long enough for anybody,
but in contexts like valgrind runs, it isn't necessarily.

4 years agoImprove find_em_expr_usable_for_sorting_rel comment
Tomas Vondra [Tue, 22 Dec 2020 01:00:39 +0000 (02:00 +0100)]
Improve find_em_expr_usable_for_sorting_rel comment

Clarify the relationship between find_em_expr_usable_for_sorting_rel and
prepare_sort_from_pathkeys, i.e. what restrictions need to be shared
between those two places.

Author: James Coleman
Reviewed-by: Tomas Vondra
Back-through: 13
Discussion: https://postgr.es/m/CAAaqYe8cK3g5CfLC4w7bs%3DhC0mSksZC%3DH5M8LSchj5e5OxpTAg%40mail.gmail.com

4 years agoDon't search for volatile expr in find_em_expr_usable_for_sorting_rel
Tomas Vondra [Mon, 21 Dec 2020 18:37:14 +0000 (19:37 +0100)]
Don't search for volatile expr in find_em_expr_usable_for_sorting_rel

While prepare_sort_from_pathkeys has to be concerned about matching up
a volatile expression to the proper tlist entry, we don't need to do
that in find_em_expr_usable_for_sorting_rel becausee such a sort will
have to be postponed anyway.

Author: James Coleman
Reviewed-by: Tomas Vondra
Back-through: 13
Discussion: https://postgr.es/m/CAAaqYe8cK3g5CfLC4w7bs%3DhC0mSksZC%3DH5M8LSchj5e5OxpTAg%40mail.gmail.com

4 years agoDisallow SRFs when considering sorts below Gather Merge
Tomas Vondra [Mon, 21 Dec 2020 17:58:32 +0000 (18:58 +0100)]
Disallow SRFs when considering sorts below Gather Merge

While we do allow SRFs in ORDER BY, scan/join processing should not
consider such cases - such sorts should only happen via final Sort atop
a ProjectSet. So make sure we don't try adding such sorts below Gather
Merge, just like we do for expressions that are volatile and/or not
parallel safe.

Back to PostgreSQL 13, where this code was introduced as part of
the Incremental Sort .

Author: James Coleman
Reviewed-by: Tomas Vondra
Back-through: 13
Discussion: https://postgr.es/m/CAAaqYe8cK3g5CfLC4w7bs=hC0mSksZC=H5M8LSchj5e5OxpTAg@mail.gmail.com
Discussion: https://postgr.es/m/295524.1606246314%40sss.pgh.pa.us