postgresql.git
5 months agoIf a C23 compiler is detected, try asking for C17. REL_11_STABLE github/REL_11_STABLE
Thomas Munro [Wed, 27 Nov 2024 02:43:18 +0000 (15:43 +1300)]
If a C23 compiler is detected, try asking for C17.

Branches before 16 can't be compiled with a C23 compiler (see
deprecation warnings silenced by commit f9a56e72, and non-back-patchable
changes made in 16 by commit 1c27d16e).  Test __STDC_VERSION__, and if
it's above C17 then try appending -std=gnu17.  The test is done with the
user's CFLAGS, so an acceptable language version can also be configured
manually that way.

This is done in branches 15 and older, back to 9.2, per policy of
keeping them buildable with modern tools.

Discussion: https://postgr.es/m/87o72eo9iu.fsf%40gentoo.org

5 months agoAssume that <stdbool.h> conforms to the C standard.
Thomas Munro [Mon, 25 Nov 2024 00:11:28 +0000 (13:11 +1300)]
Assume that <stdbool.h> conforms to the C standard.

Previously we checked "for <stdbool.h> that conforms to C99" using
autoconf's AC_HEADER_STDBOOL macro.  We've required C99 since PostgreSQL
12, so the test was redundant, and under C23 it was broken: autoconf
2.69's implementation doesn't understand C23's new empty header (the
macros it's looking for went away, replaced by language keywords).
Later autoconf versions fixed that, but let's just remove the
anachronistic test.

HAVE_STDBOOL_H and HAVE__BOOL will no longer be defined, but they
weren't directly tested in core or likely extensions (except in 11, see
below).  PG_USE_STDBOOL (or USE_STDBOOL in 11 and 12) is still defined
when sizeof(bool) is 1, which should be true on all modern systems.
Otherwise we define our own bool type and values of size 1, which would
fail to compile under C23 as revealed by the broken test.  (We'll
probably clean that dead code up in master, but here we want a minimal
back-patchable change.)

This came to our attention when GCC 15 recently started using using C23
by default and failed to compile the replacement code, as reported by
Sam James and build farm animal alligator.

Back-patch to all supported releases, and then two older versions that
also know about <stdbool.h>, per the recently-out-of-support policy[1].
12 requires C99 so it's much like the supported releases, but 11 only
assumes C89 so it now uses AC_CHECK_HEADERS instead of the overly picky
AC_HEADER_STDBOOL.  (I could find no discussion of which historical
systems had <stdbool.h> but failed the conformance test; if they ever
existed, they surely aren't relevant to that policy's goals.)

[1] https://wiki.postgresql.org/wiki/Committing_checklist#Policies

Reported-by: Sam James <sam@gentoo.org>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org> (master version)
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us> (approach)
Discussion: https://www.postgresql.org/message-id/flat/87o72eo9iu.fsf%40gentoo.org

10 months agoRemove redundant perl version checks
Andrew Dunstan [Wed, 26 Jun 2024 11:01:47 +0000 (07:01 -0400)]
Remove redundant perl version checks

Commit 4c1532763a removed some redundant uses of 'use 5.008001;' in perl
scripts, including in plperl's plc_perlboot.pl. Because it made other
changes it wasn't backpatched. However, now this is causing a failure on
back branches when built with bleeding edge perl. Therefore, backpatch
just that part of it which removed those uses, from 15 all the way down
to 9.2, which is the earliest version currently built in the buildfarm.

per report from Alexander Lakhin

Discussion: https://postgr.es/m/4cc2ee93-e03c-8e13-61ed-412e7e6ff19d@gmail.com

17 months agoStamp 11.22. REL_11_22
Tom Lane [Mon, 6 Nov 2023 22:13:58 +0000 (17:13 -0500)]
Stamp 11.22.

17 months agoLast-minute updates for release notes.
Tom Lane [Mon, 6 Nov 2023 18:26:33 +0000 (13:26 -0500)]
Last-minute updates for release notes.

Security: CVE-2023-5868, CVE-2023-5869, CVE-2023-5870

17 months agoDetect integer overflow while computing new array dimensions.
Tom Lane [Mon, 6 Nov 2023 15:56:43 +0000 (10:56 -0500)]
Detect integer overflow while computing new array dimensions.

array_set_element() and related functions allow an array to be
enlarged by assigning to subscripts outside the current array bounds.
While these places were careful to check that the new bounds are
allowable, they neglected to consider the risk of integer overflow
in computing the new bounds.  In edge cases, we could compute new
bounds that are invalid but get past the subsequent checks,
allowing bad things to happen.  Memory stomps that are potentially
exploitable for arbitrary code execution are possible, and so is
disclosure of server memory.

To fix, perform the hazardous computations using overflow-detecting
arithmetic routines, which fortunately exist in all still-supported
branches.

The test cases added for this generate (after patching) errors that
mention the value of MaxArraySize, which is platform-dependent.
Rather than introduce multiple expected-files, use psql's VERBOSITY
parameter to suppress the printing of the message text.  v11 psql
lacks that parameter, so omit the tests in that branch.

Our thanks to Pedro Gallegos for reporting this problem.

Security: CVE-2023-5869

17 months agoCompute aggregate argument types correctly in transformAggregateCall().
Tom Lane [Mon, 6 Nov 2023 15:38:00 +0000 (10:38 -0500)]
Compute aggregate argument types correctly in transformAggregateCall().

transformAggregateCall() captures the datatypes of the aggregate's
arguments immediately to construct the Aggref.aggargtypes list.
This seems reasonable because the arguments have already been
transformed --- but there is an edge case where they haven't been.
Specifically, if we have an unknown-type literal in an ANY argument
position, nothing will have been done with it earlier.  But if we
also have DISTINCT, then addTargetToGroupList() converts the literal
to "text" type, resulting in the aggargtypes list not matching the
actual runtime type of the argument.  The end result is that the
aggregate tries to interpret a "text" value as being of type
"unknown", that is a zero-terminated C string.  If the text value
contains no zero bytes, this could result in disclosure of server
memory following the text literal value.

To fix, move the collection of the aggargtypes list to the end
of transformAggregateCall(), after DISTINCT has been handled.
This requires slightly more code, but not a great deal.

Our thanks to Jingzhou Fu for reporting this problem.

Security: CVE-2023-5868

17 months agoSet GUC "is_superuser" in all processes that set AuthenticatedUserId.
Noah Misch [Mon, 6 Nov 2023 14:14:13 +0000 (06:14 -0800)]
Set GUC "is_superuser" in all processes that set AuthenticatedUserId.

It was always false in single-user mode, in autovacuum workers, and in
background workers.  This had no specifically-identified security
consequences, but non-core code or future work might make it
security-relevant.  Back-patch to v11 (all supported versions).

Jelte Fennema-Nio.  Reported by Jelte Fennema-Nio.

17 months agoBan role pg_signal_backend from more superuser backend types.
Noah Misch [Mon, 6 Nov 2023 14:14:13 +0000 (06:14 -0800)]
Ban role pg_signal_backend from more superuser backend types.

Documentation says it cannot signal "a backend owned by a superuser".
On the contrary, it could signal background workers, including the
logical replication launcher.  It could signal autovacuum workers and
the autovacuum launcher.  Block all that.  Signaling autovacuum workers
and those two launchers doesn't stall progress beyond what one could
achieve other ways.  If a cluster uses a non-core extension with a
background worker that does not auto-restart, this could create a denial
of service with respect to that background worker.  A background worker
with bugs in its code for responding to terminations or cancellations
could experience those bugs at a time the pg_signal_backend member
chooses.  Back-patch to v11 (all supported versions).

Reviewed by Jelte Fennema-Nio.  Reported by Hemanth Sandrana and
Mahendrakar Srinivasarao.

Security: CVE-2023-5870

17 months agoTranslation updates
Peter Eisentraut [Mon, 6 Nov 2023 12:29:04 +0000 (13:29 +0100)]
Translation updates

Source-Git-URL: https://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 8174b9117de39641851e8c8f8f8cd300487a6f70

17 months agoRelease notes for 16.1, 15.5, 14.10, 13.13, 12.17, 11.22.
Tom Lane [Sun, 5 Nov 2023 18:14:07 +0000 (13:14 -0500)]
Release notes for 16.1, 15.5, 14.10, 13.13, 12.17, 11.22.

17 months agodoc: \copy can get data values \. and end-of-input confused
Bruce Momjian [Fri, 3 Nov 2023 17:57:58 +0000 (13:57 -0400)]
doc: \copy can get data values \. and end-of-input confused

Reported-by: Svante Richter
Discussion: https://postgr.es/m/fcd57e4-8f23-4c3e-a5db-2571d09208e2@beta.fastmail.com

Backpatch-through: 11

17 months agodoc: CREATE DATABASE doesn't copy db-level perms. from template
Bruce Momjian [Fri, 3 Nov 2023 17:39:50 +0000 (13:39 -0400)]
doc: CREATE DATABASE doesn't copy db-level perms. from template

Reported-by: david@kapitaltrading.com
Discussion: https://postgr.es/m/166007719137.995877.13951579839074751714@wrigleys.postgresql.org

Backpatch-through: 11

17 months agoDoc: update CREATE RULE ref page's hoary discussion of views.
Tom Lane [Fri, 3 Nov 2023 15:48:23 +0000 (11:48 -0400)]
Doc: update CREATE RULE ref page's hoary discussion of views.

This text left one with the impression that an ON SELECT rule could
be attached to a plain table, which has not been true since commit
264c06820 (meaning the text was already misleading when written,
evidently by me in 96bd67f61).  However, it didn't get really bad
until b23cd185f removed the convert-a-table-to-a-view logic, which
had made it possible for scripts that thought they were attaching
ON SELECTs to tables to still work.

Rewrite into a form that makes it clear that an ON SELECT rule
is better regarded as an implementation detail of a view.
Pre-v16, point out that adding ON SELECT to a table actually
converts it to a view.

Per bug #18178 from Joshua Uyehara.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18178-05534d7064044d2d@postgresql.org

17 months agodoc: ALTER DEFAULT PRIVILEGES does not affect inherited roles
Bruce Momjian [Fri, 3 Nov 2023 13:51:52 +0000 (09:51 -0400)]
doc:  ALTER DEFAULT PRIVILEGES does not affect inherited roles

Reported-by: Jordi Gutiérrez Hermoso
Discussion: https://postgr.es/m/72652d72e1816bfc3c05d40f9e0e0373d07823c8.camel@octave.org

Co-authored-by: Laurenz Albe
Backpatch-through: 11

17 months agoBe more wary about NULL values for GUC string variables.
Tom Lane [Thu, 2 Nov 2023 15:47:33 +0000 (11:47 -0400)]
Be more wary about NULL values for GUC string variables.

get_explain_guc_options() crashed if a string GUC marked GUC_EXPLAIN
has a NULL boot_val.  Nosing around found a couple of other places
that seemed insufficiently cautious about NULL string values, although
those are likely unreachable in practice.  Add some commentary
defining the expectations for NULL values of string variables,
in hopes of forestalling future additions of more such bugs.

Xing Guo, Aleksander Alekseev, Tom Lane

Discussion: https://postgr.es/m/CACpMh+AyDx5YUpPaAgzVwC1d8zfOL4JoD-uyFDnNSa1z0EsDQQ@mail.gmail.com

17 months agodoc: Replace reference to ERRCODE_RAISE_EXCEPTION by "raise_exception"
Michael Paquier [Wed, 1 Nov 2023 22:33:02 +0000 (07:33 +0900)]
doc: Replace reference to ERRCODE_RAISE_EXCEPTION by "raise_exception"

This part of the documentation refers to exceptions as handled by
PL/pgSQL, and using the internal error code is confusing.

Per thinko in 66bde49d96a9.

Reported-by: Euler Taveira, Bruce Momjian
Discussion: https://postgr.es/m/ZUEUnLevXyW7DlCs@momjian.us
Backpatch-through: 11

18 months agodoc: improve ALTER SYSTEM description of value list quoting
Bruce Momjian [Tue, 31 Oct 2023 14:21:31 +0000 (10:21 -0400)]
doc: improve ALTER SYSTEM description of value list quoting

Reported-by: splarv@ya.ru
Discussion: https://postgr.es/m/167105927893.1897.13227723035830709578@wrigleys.postgresql.org

Backpatch-through: 11

18 months agodoc: 1-byte varlena headers can be used for user PLAIN storage
Bruce Momjian [Tue, 31 Oct 2023 13:10:34 +0000 (09:10 -0400)]
doc:  1-byte varlena headers can be used for user PLAIN storage

This also updates some C comments.

Reported-by: suchithjn22@gmail.com
Discussion: https://postgr.es/m/167336599095.2667301.15497893107226841625@wrigleys.postgresql.org

Author: Laurenz Albe (doc patch)

Backpatch-through: 11

18 months agoDiagnose !indisvalid in more SQL functions.
Noah Misch [Mon, 30 Oct 2023 21:46:05 +0000 (14:46 -0700)]
Diagnose !indisvalid in more SQL functions.

pgstatindex failed with ERRCODE_DATA_CORRUPTED, of the "can't-happen"
class XX.  The other functions succeeded on an empty index; they might
have malfunctioned if the failed index build left torn I/O or other
complex state.  Report an ERROR in statistics functions pgstatindex,
pgstatginindex, pgstathashindex, and pgstattuple.  Report DEBUG1 and
skip all index I/O in maintenance functions brin_desummarize_range,
brin_summarize_new_values, brin_summarize_range, and
gin_clean_pending_list.  Back-patch to v11 (all supported versions).

Discussion: https://postgr.es/m/20231001195309.a3@google.com

18 months agoamcheck: Distinguish interrupted page deletion from corruption.
Noah Misch [Mon, 30 Oct 2023 21:46:05 +0000 (14:46 -0700)]
amcheck: Distinguish interrupted page deletion from corruption.

This prevents false-positive reports about "the first child of leftmost
target page is not leftmost of its level", "block %u is not leftmost"
and "left link/right link pair".  They appeared if amcheck ran before
VACUUM cleaned things, after a cluster exited recovery between the
first-stage and second-stage WAL records of a deletion.  Back-patch to
v11 (all supported versions).

Reviewed by Peter Geoghegan.

Discussion: https://postgr.es/m/20231005025232.c7.nmisch@google.com

18 months agobtree_gin: Fix calculation of leftmost interval value.
Dean Rasheed [Sun, 29 Oct 2023 11:14:32 +0000 (11:14 +0000)]
btree_gin: Fix calculation of leftmost interval value.

Formerly, the value computed by leftmostvalue_interval() was a long
way short of the minimum possible interval value.  As a result, an
index scan on a GIN index on an interval column with < or <= operators
would miss large negative interval values.

Fix by setting all fields of the leftmost interval to their minimum
values, ensuring that the result is less than any other possible
interval.  Since this only affects index searches, no index rebuild is
necessary.

Back-patch to all supported branches.

Dean Rasheed, reviewed by Heikki Linnakangas.

Discussion: https://postgr.es/m/CAEZATCV80%2BgOfF8ehNUUfaKBZgZMDfCfL-g1HhWGb6kC3rpDfw%40mail.gmail.com

18 months agoFix intra-query memory leak when a SRF returns zero rows.
Tom Lane [Sat, 28 Oct 2023 18:04:43 +0000 (14:04 -0400)]
Fix intra-query memory leak when a SRF returns zero rows.

When looping around after finding that the set-returning function
returned zero rows for the current input tuple, ExecProjectSet
neglected to reset either of the two memory contexts it's
responsible for cleaning out.  Typically this wouldn't cause much
problem, because once the SRF does return at least one row, the
contexts would get reset on the next call.  However, if the SRF
returns no rows for many input tuples in succession, quite a lot
of memory could be transiently consumed.

To fix, make sure we reset both contexts while looping around.

Per bug #18172 from Sergei Kornilov.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18172-9b8c5fc1d676ded3@postgresql.org

18 months agoRemove PHOT from our default timezone abbreviations list.
Tom Lane [Sat, 28 Oct 2023 15:54:40 +0000 (11:54 -0400)]
Remove PHOT from our default timezone abbreviations list.

Debian recently decided to split out a bunch of "obsolete" timezone
names into a new tzdata-legacy package, which isn't installed by
default.  One of these zone names is Pacific/Enderbury, and that
breaks our regression tests (on --with-system-tzdata builds)
because our default timezone abbreviations list defines PHOT as
Pacific/Enderbury.

Pacific/Enderbury got renamed to Pacific/Kanton in tzdata 2021b,
so that in distros that still have this entry it's just a symlink
to Pacific/Kanton anyway.  So one answer would be to redefine PHOT
as Pacific/Kanton.  However, then things would fail if the
installed tzdata predates 2021b, which is recent enough that that
seems like a real problem.

Instead, let's just remove PHOT from the default list.  That seems
likely to affect nobody in the real world, because (a) it was an
abbreviation that the tzdb crew made up in the first place, with
no evidence of real-world usage, and (b) the total human population
of the Phoenix Islands is less than two dozen persons, per Wikipedia.
If anyone does use this zone abbreviation they can easily put it back
via a custom abbreviations file.

We'll keep PHOT in the Pacific.txt reference file, but change it
to Pacific/Kanton there, as that definition seems more likely to
be useful to future readers of that file.

Per report from Victor Wagner.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/20231027152049.4b5c8044@wagner.wagner.home

18 months agoDoc: remove misleading info about ecpg's CONNECT/DISCONNECT DEFAULT.
Tom Lane [Wed, 25 Oct 2023 21:34:47 +0000 (17:34 -0400)]
Doc: remove misleading info about ecpg's CONNECT/DISCONNECT DEFAULT.

As far as I can see, ecpg has no notion of a "default" open
connection.  You can do "CONNECT TO DEFAULT" but that just specifies
letting libpq use all its default connection parameters --- the
resulting connection is not special subsequently.  In particular,
SET CONNECTION = DEFAULT and DISCONNECT DEFAULT simply act on a
connection named DEFAULT, if you've made one; they do not have
special lookup rules.  But the documentation of these commands
makes it look like they do.

Simplest fix, I think, is just to remove the paras suggesting that
DEFAULT is special here.

Also, SET CONNECTION *does* have one special lookup rule, which
is that it recognizes CURRENT as an alias for the currently selected
connection.  SET CONNECTION = CURRENT is a no-op, so it's pretty
useless, but nonetheless it does something different from selecting
a connection by name; so we'd better document it.

Per report from Sylvain Frandaz.  Back-patch to all supported
versions.

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

18 months agodoc: Fix link to catalog table
Daniel Gustafsson [Wed, 25 Oct 2023 09:33:24 +0000 (11:33 +0200)]
doc: Fix link to catalog table

The link to pg_type was accidentally linking to pg_authid instead.
Backpatch to 12 and 11.

Author: Maxim Yablokov <m.yablokov@postgrespro.ru>
Discussion: https://postgr.es/m/3289f0ff-0925-46c9-b126-7e4ab6831dad@postgrespro.ru
Backpatch-through: 11, 12

18 months agodoc: Fix some typos and grammar
Michael Paquier [Wed, 25 Oct 2023 00:41:17 +0000 (09:41 +0900)]
doc: Fix some typos and grammar

Author: Ekaterina Kiryanova, Elena Indrupskaya, Oleg Sibiryakov, Maxim
Yablokov
Discussion: https://postgr.es/m/7aad518b-3e6d-47f3-9184-b1d69cb412e7@postgrespro.ru
Backpatch-through: 11

18 months agoLog LLVM library version in configure output.
Thomas Munro [Sun, 22 Oct 2023 01:17:00 +0000 (14:17 +1300)]
Log LLVM library version in configure output.

When scanning build farm results, it's useful to be able to see which
version is in use.  For the Meson build system, this information was
already displayed.

Back-patch to all supported branches.

Discussion: https://postgr.es/m/4022690.1697852728%40sss.pgh.pa.us

18 months agoDodge a compiler bug affecting timetz_zone/timetz_izone.
Tom Lane [Fri, 20 Oct 2023 17:40:15 +0000 (13:40 -0400)]
Dodge a compiler bug affecting timetz_zone/timetz_izone.

This avoids a compiler bug occurring in AIX's xlc, even in pretty
late-model revisions.  Buildfarm testing has now confirmed that
only 64-bit xlc is affected.  Although we are contemplating
dropping support for xlc in v17, it's still supported in the
back branches, so we need this fix.

Back-patch of code changes from HEAD commit 19fa97731.
(The test cases were already back-patched, in 4a427b82c et al.)

Discussion: https://postgr.es/m/CA+hUKGK=DOC+hE-62FKfZy=Ybt5uLkrg3zCZD-jFykM-iPn8yw@mail.gmail.com

18 months agoDoc: update CREATE OPERATOR's statement about => as an operator.
Tom Lane [Fri, 20 Oct 2023 17:01:02 +0000 (13:01 -0400)]
Doc: update CREATE OPERATOR's statement about => as an operator.

This doco said that use of => as an operator "is deprecated".
It's been fully disallowed since 865f14a2d back in 9.5, but
evidently that commit missed updating this statement.
Do so now.

18 months agowindows: msvc: Define STDIN/OUT/ERR_FILENO.
Nathan Bossart [Tue, 17 Oct 2023 21:11:18 +0000 (16:11 -0500)]
windows: msvc: Define STDIN/OUT/ERR_FILENO.

This commit (c290e79cf0) was originally back-patched to v15.
Commit 97550c0711 added a new use of STDERR_FILENO, and it was
back-patched all the way to v11, thus breaking MSVC builds for v11
through v14.  Since STDERR_FILENO is now needed on older versions,
let's back-patch c290e79cf0 down to v11, too.

Here follows the original commit message describing the change:

Because they are not available we've used _fileno(stdin) in some places, but
that doesn't reliably work, because stdin might be closed. This is the
prerequisite of the subsequent commit, fixing a failure introduced in
76e38b37a5.

Author: Andres Freund <andres@anarazel.de>
Reported-By: Sandeep Thakkar <sandeep.thakkar@enterprisedb.com>
Message-Id: 20220520164558.ozb7lm6unakqzezi@alap3.anarazel.de (on pgsql-packagers)
Discussion: https://postgr.es/m/20231017164517.GA613565%40nathanxps13
Backpatch-through: 11

18 months agoBack-patch test cases for timetz_zone/timetz_izone.
Tom Lane [Tue, 17 Oct 2023 17:55:45 +0000 (13:55 -0400)]
Back-patch test cases for timetz_zone/timetz_izone.

Per code coverage reports, we had zero regression test coverage
of these functions.  That came back to bite us, as apparently
that's allowed us to miss discovering misbehavior of this code
with AIX's xlc compiler.  Install relevant portions of the
test cases added in 97957fdba2f047203019fa97731.

(Assuming the expected outcome that the xlc problem does appear
in back branches, a code fix will follow.)

Discussion: https://postgr.es/m/CA+hUKGK=DOC+hE-62FKfZy=Ybt5uLkrg3zCZD-jFykM-iPn8yw@mail.gmail.com

18 months agoAvoid calling proc_exit() in processes forked by system().
Nathan Bossart [Tue, 17 Oct 2023 15:42:28 +0000 (10:42 -0500)]
Avoid calling proc_exit() in processes forked by system().

The SIGTERM handler for the startup process immediately calls
proc_exit() for the duration of the restore_command, i.e., a call
to system().  This system() call forks a new process to execute the
shell command, and this child process inherits the parent's signal
handlers.  If both the parent and child processes receive SIGTERM,
both will attempt to call proc_exit().  This can end badly.  For
example, both processes will try to remove themselves from the
PGPROC shared array.

To fix this problem, this commit adds a check in
StartupProcShutdownHandler() to see whether MyProcPid == getpid().
If they match, this is the parent process, and we can proc_exit()
like before.  If they do not match, this is a child process, and we
just emit a message to STDERR (in a signal safe manner) and
_exit(), thereby skipping any problematic exit callbacks.

This commit also adds checks in proc_exit(), ProcKill(), and
AuxiliaryProcKill() that verify they are not being called within
such child processes.

Suggested-by: Andres Freund
Reviewed-by: Thomas Munro, Andres Freund
Discussion: https://postgr.es/m/Y9nGDSgIm83FHcad%40paquier.xyz
Discussion: https://postgr.es/m/20230223231503.GA743455%40nathanxps13
Backpatch-through: 11

18 months agoEnsure we have a snapshot while dropping ON COMMIT DROP temp tables.
Tom Lane [Mon, 16 Oct 2023 18:06:12 +0000 (14:06 -0400)]
Ensure we have a snapshot while dropping ON COMMIT DROP temp tables.

Dropping a temp table could entail TOAST table access to clean out
toasted catalog entries, such as large pg_constraint.conbin strings
for complex CHECK constraints.  If we did that via ON COMMIT DROP,
we triggered the assertion in init_toast_snapshot(), because
there was no provision for setting up a snapshot for the drop
actions.  Fix that.

(I assume here that the adjacent truncation actions for ON COMMIT
DELETE ROWS don't have a similar problem: it doesn't seem like
nontransactional truncations would need to touch any toasted fields.
If that proves wrong, we could refactor a bit to have the same
snapshot acquisition cover that too.)

The test case added here does not fail before v15, because that
assertion was added in 277692220 which was not back-patched.
However, the race condition the assertion warns of surely
exists further back, so back-patch to all supported branches.

Per report from Richard Guo.

Discussion: https://postgr.es/m/CAMbWs4-x26=_QxxgdJyNbiCDzvtr2WV5ZDso_v-CukKEe6cBZw@mail.gmail.com

18 months agoAcquire ControlFileLock in relevant SQL functions.
Thomas Munro [Sun, 15 Oct 2023 21:43:47 +0000 (10:43 +1300)]
Acquire ControlFileLock in relevant SQL functions.

Commit dc7d70ea added functions that read the control file, but didn't
acquire ControlFileLock.  With unlucky timing, file systems that have
weak interlocking like ext4 and ntfs could expose partially overwritten
contents, and the checksum would fail.

Back-patch to all supported releases.

Reviewed-by: David Steele <david@pgmasters.net>
Reviewed-by: Anton A. Melnikov <aamelnikov@inbox.ru>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/20221123014224.xisi44byq3cf5psi%40awork3.anarazel.de

18 months agoFix runtime partition pruning for HASH partitioned tables
David Rowley [Thu, 12 Oct 2023 12:15:12 +0000 (01:15 +1300)]
Fix runtime partition pruning for HASH partitioned tables

This could only affect HASH partitioned tables with at least 2 partition
key columns.

If partition pruning was delayed until execution and the query contained
an IS NULL qual on one of the partitioned keys, and some subsequent
partitioned key was being compared to a non-Const, then this could result
in a crash due to the incorrect keyno being used to calculate the
stateidx for the expression evaluation code.

Here we fix this by properly skipping partitioned keys which have a
nullkey set.  Effectively, this must be the same as what's going on
inside perform_pruning_base_step().

Sergei Glukhov also provided a patch, but that's not what's being used
here.

Reported-by: Sergei Glukhov
Reviewed-by: tender wang, Sergei Glukhov
Discussion: https://postgr.es/m/d05b26fa-af54-27e1-f693-6c31590802fa@postgrespro.ru
Backpatch-through: 11, where runtime partition pruning was added.

18 months agoDoc: fix grammatical errors for enable_partitionwise_aggregate
David Rowley [Thu, 12 Oct 2023 08:17:49 +0000 (21:17 +1300)]
Doc: fix grammatical errors for enable_partitionwise_aggregate

Author: Andrew Atkinson
Reviewed-by: Ashutosh Bapat
Discussion: https://postgr.es/m/CAG6XLEnC%3DEgq0YHRic2kWWDs4xwQnQ_kBA6qhhzAq1-pO_9Tfw%40mail.gmail.com
Backpatch-through: 11, where enable_partitionwise_aggregate was added

18 months agoFix incorrect step generation in HASH partition pruning
David Rowley [Thu, 12 Oct 2023 06:53:50 +0000 (19:53 +1300)]
Fix incorrect step generation in HASH partition pruning

get_steps_using_prefix_recurse() incorrectly assumed that it could stop
recursive processing of the 'prefix' list when cur_keyno was one before
the step_lastkeyno.  Since hash partition pruning can prune using IS
NULL quals, and these IS NULL quals are not present in the 'prefix'
list, then that logic could cause more levels of recursion than what is
needed and lead to there being no more items in the 'prefix' list to
process.  This would manifest itself as a crash in some code that
expected the 'start' ListCell not to be NULL.

Here we adjust the logic so that instead of stopping recursion at 1 key
before the step_lastkeyno, we just look at the llast(prefix) item and
ensure we only recursively process up until just before whichever the last
key is.  This effectively allows keys to be missing in the 'prefix' list.

This change does mean that step_lastkeyno is no longer needed, so we
remove that from the static functions.  I also spent quite some time
reading this code and testing it to try to convince myself that there
are no other issues.  That resulted in the irresistible temptation of
rewriting some comments, many of which were just not true or inconcise.

Reported-by: Sergei Glukhov
Reviewed-by: Sergei Glukhov, tender wang
Discussion: https://postgr.es/m/2f09ce72-315e-2a33-589a-8519ada8df61@postgrespro.ru
Backpatch-through: 11, where partition pruning was introduced.

18 months agodoc: clarify that SSPI and GSSAPI are interchangeable
Bruce Momjian [Tue, 10 Oct 2023 20:51:08 +0000 (16:51 -0400)]
doc:  clarify that SSPI and GSSAPI are interchangeable

Reported-by: tpo_deb@sourcepole.ch
Discussion: https://postgr.es/m/167846222574.1803490.15815104179136215862@wrigleys.postgresql.org

Backpatch-through: 11

18 months agodoc: foreign servers with pushdown need matching collation
Bruce Momjian [Tue, 10 Oct 2023 20:04:56 +0000 (16:04 -0400)]
doc:  foreign servers with pushdown need matching collation

Reported-by: Pete Storer
Discussion: https://postgr.es/m/BL0PR05MB66283C57D72E321591AE4EB1F3CE9@BL0PR05MB6628.namprd05.prod.outlook.com

Backpatch-through: 11

18 months agodoc: add SSL configuration section reference
Bruce Momjian [Tue, 10 Oct 2023 19:54:28 +0000 (15:54 -0400)]
doc:  add SSL configuration section reference

Reported-by: Steve Atkins
Discussion: https://postgr.es/m/B82E80DD-1452-4175-B19C-564FE46705BA@blighty.com

Backpatch-through: 11

18 months agodoc: document the need to analyze partitioned tables
Bruce Momjian [Tue, 10 Oct 2023 19:14:18 +0000 (15:14 -0400)]
doc:  document the need to analyze partitioned tables

Autovacuum does not do it.

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20210913035409.GA10647@telsasoft.com

Backpatch-through: 11

18 months agoFix bug in GenericXLogFinish().
Jeff Davis [Tue, 10 Oct 2023 18:01:13 +0000 (11:01 -0700)]
Fix bug in GenericXLogFinish().

Mark the buffers dirty before writing WAL.

Discussion: https://postgr.es/m/25104133-7df8-cae3-b9a2-1c0aaa1c094a@iki.fi
Reviewed-by: Heikki Linnakangas
Backpatch-through: 11

18 months agoDoc: use CURRENT_USER not USER in plpgsql trigger examples.
Tom Lane [Mon, 9 Oct 2023 15:29:21 +0000 (11:29 -0400)]
Doc: use CURRENT_USER not USER in plpgsql trigger examples.

While these two built-in functions do exactly the same thing,
CURRENT_USER seems preferable to use in documentation examples.
It's easier to look up if the reader is unsure what it is.
Also, this puts these examples in sync with an adjacent example
that already used CURRENT_USER.

Per question from Kirk Parker.

Discussion: https://postgr.es/m/CANwZ8rmN_Eb0h0hoMRS8Feftaik0z89PxVsKg+cP+PctuOq=Qg@mail.gmail.com

18 months agoFix omission of column-level privileges in selective pg_restore.
Tom Lane [Mon, 2 Oct 2023 17:27:51 +0000 (13:27 -0400)]
Fix omission of column-level privileges in selective pg_restore.

In a selective restore, ACLs for a table should be dumped if the
table is selected to be dumped.  However, if the table has both
table-level and column-level ACLs, only the table-level ACL was
restored.  This happened because _tocEntryRequired assumed that
an ACL could have only one dependency (the one on its table),
and punted if there was more than one.  But since commit ea9125304,
column-level ACLs also depend on the table-level ACL if any, to
ensure correct ordering in parallel restores.  To fix, adjust the
logic in _tocEntryRequired to ignore dependencies on ACLs.

I extended a test case in 002_pg_dump.pl so that it purports to
test for this; but in fact the test passes even without the fix.
That's because this bug only manifests during a selective restore,
while the scenarios 002_pg_dump.pl tests include only selective dumps.
Perhaps somebody would like to extend the script so that it can test
scenarios including selective restore, but I'm not touching that.

Euler Taveira and Tom Lane, per report from Kong Man.
Back-patch to all supported branches.

Discussion: https://postgr.es/m/DM4PR11MB73976902DBBA10B1D652F9498B06A@DM4PR11MB7397.namprd11.prod.outlook.com

19 months agoFix datalen calculation in tsvectorrecv().
Tom Lane [Sun, 1 Oct 2023 17:16:47 +0000 (13:16 -0400)]
Fix datalen calculation in tsvectorrecv().

After receiving position data for a lexeme, tsvectorrecv()
advanced its "datalen" value by (npos+1)*sizeof(WordEntry)
where the correct calculation is (npos+1)*sizeof(WordEntryPos).
This accidentally failed to render the constructed tsvector
invalid, but it did result in leaving some wasted space
approximately equal to the space consumed by the position data.
That could have several bad effects:

* Disk space is wasted if the received tsvector is stored into a
  table as-is.

* A legal tsvector could get rejected with "maximum total lexeme
  length exceeded" if the extra space pushes it over the MAXSTRPOS
  limit.

* In edge cases, the finished tsvector could be assigned a length
  larger than the allocated size of its palloc chunk, conceivably
  leading to SIGSEGV when the tsvector gets copied somewhere else.
  The odds of a field failure of this sort seem low, though valgrind
  testing could probably have found this.

While we're here, let's express the calculation as
"sizeof(uint16) + npos * sizeof(WordEntryPos)" to avoid the type
pun implicit in the "npos + 1" formulation.  It's not wrong
given that WordEntryPos had better be 2 bytes to avoid padding
problems, but it seems clearer this way.

Report and patch by Denis Erokhin.  Back-patch to all supported
versions.

Discussion: https://postgr.es/m/009801d9f2d9$f29730c0$d7c59240$@datagile.ru

19 months agoRemove environment sensitivity in pl/tcl regression test.
Tom Lane [Sat, 30 Sep 2023 00:20:57 +0000 (20:20 -0400)]
Remove environment sensitivity in pl/tcl regression test.

Add "-gmt 1" to our test invocations of the Tcl "clock" command,
so that they do not consult the timezone environment.  While it
doesn't really matter which timezone is used here, it does
matter that the command not fall over entirely.  We've now
discovered that at least on FreeBSD, "clock scan" will fail if
/etc/localtime is missing.  It seems worth making the test
insensitive to that.

Per Tomas Vondras' buildfarm animal dikkop.  Thanks to
Thomas Munro for the diagnosis.

Discussion: https://postgr.es/m/316d304a-1dcd-cea1-3d6c-27f794727a06@enterprisedb.com

19 months agoSuppress macOS warnings about duplicate libraries in link commands.
Tom Lane [Fri, 29 Sep 2023 18:07:30 +0000 (14:07 -0400)]
Suppress macOS warnings about duplicate libraries in link commands.

As of Xcode 15 (macOS Sonoma), the linker complains about duplicate
references to the same library.  We see warnings about libpgport and
libpgcommon being duplicated in many client executables.  This is a
consequence of the hack introduced in commit 6b7ef076b to list
libpgport before libpq while not removing it from $(LIBS).
(Commit 8396447cd later applied the same rule to libpgcommon.)

The concern in 6b7ef076b was to ensure that the client executable
wouldn't unintentionally depend on pgport functions from libpq.
That concern is obsolete on any platform for which we can do symbol
export control, because if we can then the pgport functions in libpq
won't be exposed anyway.  Hence, we can fix this problem by just
removing libpgport and libpgcommon from $(libpq_pgport), and letting
clients depend on the occurrences in $(LIBS).

In the back branches, do that only on macOS (which we know has
symbol export control).  In HEAD, let's be more aggressive and
remove the extra libraries everywhere.  The only still-supported
platforms that lack export control are MinGW/Cygwin, and it
doesn't seem worth sweating over ABI stability details for those
(or if somebody does care, it'd probably be possible to perform
symbol export control for those too).  As well as being simpler,
this might give some microscopic improvement in build time.

The meson build system is not changed here, as it doesn't have
this particular disease, though it does have some related issues
that we'll fix separately.

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

19 months agoDoc: improve description of dump/restore's --clean and --if-exists.
Tom Lane [Fri, 29 Sep 2023 17:13:54 +0000 (13:13 -0400)]
Doc: improve description of dump/restore's --clean and --if-exists.

Try to make these option descriptions a little clearer for novices.
Per gripe from Attila Gulyás.

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

19 months agodoc: Change statistics function xref to the right target
Daniel Gustafsson [Fri, 29 Sep 2023 13:55:37 +0000 (15:55 +0200)]
doc: Change statistics function xref to the right target

Commit 7d3b7011b added a link to the statistics functions, which at the
time were anchored under the section for statistics views.  aebe989477a
added a separate section for statistics functions, but the link was not
updated to point to the new anchor.  Fix by changing the xref.

Backpatch to all supported branches.

Author: Peter Smith <peter.b.smith@fujitsu.com>
Discussion: https://postgr.es/m/CAHut+Ptr0jKzNNtWnssLq+3jNhbyaBseqf6NPrWHk08mQFRoTg@mail.gmail.com
Backpatch-through: 11

19 months agoFix btmarkpos/btrestrpos array key wraparound bug.
Peter Geoghegan [Thu, 28 Sep 2023 23:29:22 +0000 (16:29 -0700)]
Fix btmarkpos/btrestrpos array key wraparound bug.

nbtree's mark/restore processing failed to correctly handle an edge case
involving array key advancement and related search-type scan key state.
Scans with ScalarArrayScalarArrayOpExpr quals requiring mark/restore
processing (for a merge join) could incorrectly conclude that an
affected array/scan key must not have advanced during the time between
marking and restoring the scan's position.

As a result of all this, array key handling within btrestrpos could skip
a required call to _bt_preprocess_keys().  This confusion allowed later
primitive index scans to overlook tuples matching the true current array
keys.  The scan's search-type scan keys would still have spurious values
corresponding to the final array element(s) -- not values matching the
first/now-current array element(s).

To fix, remember that "array key wraparound" has taken place during the
ongoing btrescan in a flag variable stored in the scan's state, and use
that information at the point where btrestrpos decides if another call
to _bt_preprocess_keys is required.

Oversight in commit 70bc5833, which taught nbtree to handle array keys
during mark/restore processing, but missed this subtlety.  That commit
was itself a bug fix for an issue in commit 9e8da0f7, which taught
nbtree to handle ScalarArrayOpExpr quals natively.

Author: Peter Geoghegan <pg@bowt.ie>
Discussion: https://postgr.es/m/CAH2-WzkgP3DDRJxw6DgjCxo-cu-DKrvjEv_ArkP2ctBJatDCYg@mail.gmail.com
Backpatch: 11- (all supported branches).

19 months agoFix checking of index expressions in CompareIndexInfo().
Tom Lane [Thu, 28 Sep 2023 18:05:26 +0000 (14:05 -0400)]
Fix checking of index expressions in CompareIndexInfo().

This code was sloppy about comparison of index columns that
are expressions.  It didn't reliably reject cases where one
index has an expression where the other has a plain column,
and it could index off the start of the attmap array, leading
to a Valgrind complaint (though an actual crash seems unlikely).

I'm not sure that the expression-vs-column sloppiness leads
to any visible problem in practice, because the subsequent
comparison of the two expression lists would reject cases
where the indexes have different numbers of expressions
overall.  Maybe we could falsely match indexes having the
same expressions in different column positions, but it'd
require unlucky contents of the word before the attmap array.
It's not too surprising that no problem has been reported
from the field.  Nonetheless, this code is clearly wrong.

Per bug #18135 from Alexander Lakhin.  Back-patch to all
supported branches.

Discussion: https://postgr.es/m/18135-532f4a755e71e4d2@postgresql.org

19 months agoStop using "-multiply_defined suppress" on macOS.
Tom Lane [Wed, 27 Sep 2023 01:06:21 +0000 (21:06 -0400)]
Stop using "-multiply_defined suppress" on macOS.

We started to use this linker switch in commit 9df308697 of
2004-07-13, which was in the OS X 10.3 era.  Apparently it's been a
no-op since around OS X 10.9.  Apple's most recent toolchain version
actively complains about it, so it's time to get rid of it.

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

19 months agodoc: clarify the effect of concurrent work_mem allocations
Bruce Momjian [Tue, 26 Sep 2023 23:44:21 +0000 (19:44 -0400)]
doc: clarify the effect of concurrent work_mem allocations

Reported-by: Sami Imseih
Discussion: https://postgr.es/m/66590882-F48C-4A25-83E3-73792CF8C51F@amazon.com

Backpatch-through: 11

19 months agodoc: clarify handling of time zones with "time with time zone"
Bruce Momjian [Tue, 26 Sep 2023 23:23:58 +0000 (19:23 -0400)]
doc:  clarify handling of time zones with "time with time zone"

Reported-by: davecramer@postgres.rocks
Discussion: https://postgr.es/m/168451942371.714.9173574930845904336@wrigleys.postgresql.org

Backpatch-through: 11

19 months agodoc: clarify the behavior of unopenable listen_addresses
Bruce Momjian [Tue, 26 Sep 2023 23:02:17 +0000 (19:02 -0400)]
doc:  clarify the behavior of unopenable listen_addresses

Reported-by: Gurjeet Singh
Discussion: https://postgr.es/m/CABwTF4WYPD9ov-kcSq1+J+ZJ5wYDQLXquY6Lu2cvb-Y7pTpSGA@mail.gmail.com

Backpatch-through: 11

19 months agodoc: pg_upgrade, clarify standby servers must remain running
Bruce Momjian [Tue, 26 Sep 2023 22:54:10 +0000 (18:54 -0400)]
doc: pg_upgrade, clarify standby servers must remain running

Also mention that mismatching primary/standby LSNs should never
happen.

Reported-by: Nikolay Samokhvalov
Discussion: https://postgr.es/m/CAM527d8heqkjG5VrvjU3Xjsqxg41ufUyabD9QZccdAxnpbRH-Q@mail.gmail.com

Backpatch-through: 11

19 months agodoc: mention GROUP BY columns can reference target col numbers
Bruce Momjian [Tue, 26 Sep 2023 21:31:05 +0000 (17:31 -0400)]
doc:  mention GROUP BY columns can reference target col numbers

Reported-by: hape <postgres-hape@gmx.de>
Discussion: https://postgr.es/m/168871536004.379168.9352636188330923805@wrigleys.postgresql.org

Backpatch-through: 11

19 months agodoc: Tell about "vcregress taptest" for regression tests on Windows
Michael Paquier [Mon, 25 Sep 2023 23:16:49 +0000 (08:16 +0900)]
doc: Tell about "vcregress taptest" for regression tests on Windows

There was no mention of this command in the documentation, and it is
useful to run the TAP tests of a target source directory.

Author: Yugo Nagata
Discussion: https://postgr.es/m/20230925153204.926d685d347ee1c8f527090c@sraoss.co.jp
Backpatch-through: 11

19 months agopg_dump: tests: Correct test condition for invalid databases
Andres Freund [Mon, 25 Sep 2023 18:50:02 +0000 (11:50 -0700)]
pg_dump: tests: Correct test condition for invalid databases

For some reason I used not_like = { pg_dumpall_dbprivs => 1, } in the test
condition of one of the tests added in in c66a7d75e65. That doesn't make sense
for two reasons: 1) not_like isn't a valid test condition 2) the database
should not be dumped in any of the tests.  Due to 1), the test achieved its
goal, but clearly the formulation is confusing.  Instead use like => {}, with
a comment explaining why.

Reported-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/3ddf79f2-8b7b-a093-11d2-5c739bc64f86@eisentraut.org
Backpatch: 11-, like c66a7d75e65

19 months agoCollect dependency information for parsed CallStmts.
Tom Lane [Mon, 25 Sep 2023 18:41:57 +0000 (14:41 -0400)]
Collect dependency information for parsed CallStmts.

Parse analysis of a CallStmt will inject mutable information,
for instance the OID of the called procedure, so that subsequent
DDL may create a need to re-parse the CALL.  We failed to detect
this for CALLs in plpgsql routines, because no dependency information
was collected when putting a CallStmt into the plan cache.  That
could lead to misbehavior or strange errors such as "cache lookup
failed".

Before commit ee895a655, the issue would only manifest for CALLs
appearing in atomic contexts, because we re-planned non-atomic
CALLs every time through anyway.

It is now apparent that extract_query_dependencies() probably
needs a special case for every utility statement type for which
stmt_requires_parse_analysis() returns true.  I wanted to add
something like Assert(!stmt_requires_parse_analysis(...)) when
falling out of extract_query_dependencies_walker without doing
anything, but there are API issues as well as a more fundamental
point: stmt_requires_parse_analysis is supposed to be applied to
raw parser output, so it'd be cheating to assume it will give the
correct answer for post-parse-analysis trees.  I contented myself
with adding a comment.

Per bug #18131 from Christian Stork.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18131-576854e79c5cd264@postgresql.org

19 months agoLimit to_tsvector_byid's initial array allocation to something sane.
Tom Lane [Mon, 25 Sep 2023 15:50:28 +0000 (11:50 -0400)]
Limit to_tsvector_byid's initial array allocation to something sane.

The initial estimate of the number of distinct ParsedWords is just
that: an estimate.  Don't let it exceed what palloc is willing to
allocate.  If in fact we need more entries, we'll eventually fail
trying to enlarge the array.  But if we don't, this allows success on
inputs that currently draw "invalid memory alloc request size".

Per bug #18080 from Uwe Binder.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/18080-d5c5e58fef8c99b7@postgresql.org

19 months agoDoc: copy-edit the introductory para for the pg_class catalog.
Tom Lane [Fri, 22 Sep 2023 18:52:36 +0000 (14:52 -0400)]
Doc: copy-edit the introductory para for the pg_class catalog.

The previous wording had a faint archaic whiff to it, and more
importantly used "catalogs" as a verb, which while cutely
self-referential seems likely to provoke confusion in this
particular context.  Also consistently use "kind" not "type" to
refer to the different kinds of relations distinguished by relkind.

Per gripe from Martin Nash.  Back-patch to supported versions.

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

19 months agoUpdate comment about set_join_pathlist_hook().
Etsuro Fujita [Thu, 21 Sep 2023 10:45:11 +0000 (19:45 +0900)]
Update comment about set_join_pathlist_hook().

The comment introduced by commit e7cb7ee14 was a bit too terse, which
could lead to extensions doing different things within the hook function
than we intend to allow.  Extend the comment to explain what they can do
within the hook function.

Back-patch to all supported branches.

In passing, I rephrased a nearby comment that I recently added to the
back branches.

Reviewed by David Rowley and Andrei Lepikhov.

Discussion: https://postgr.es/m/CAPmGK15SBPA1nr3Aqsdm%2BYyS-ay0Ayo2BRYQ8_A2To9eLqwopQ%40mail.gmail.com

19 months agoFix GiST README's explanation of the NSN cross-check.
Heikki Linnakangas [Tue, 19 Sep 2023 08:53:51 +0000 (11:53 +0300)]
Fix GiST README's explanation of the NSN cross-check.

The text got the condition backwards, it's "NSN > LSN", not "NSN < LSN".
While we're at it, expand it a little for clarity.

Reviewed-by: Daniel Gustafsson
Discussion: https://www.postgresql.org/message-id/4cb46e18-e688-524a-0f73-b1f03ed5d6ee@iki.fi

19 months agoFix assertion failure with PL/Python exceptions
Michael Paquier [Mon, 18 Sep 2023 23:31:31 +0000 (08:31 +0900)]
Fix assertion failure with PL/Python exceptions

PLy_elog() was not able to handle correctly cases where a SPI called
failed, which would fill in a DETAIL string able to trigger an
assertion.  We may want to improve this infrastructure so as it is able
to provide any extra detail information provided by an error stack, but
this is left as a future improvement as it could impact existing error
stacks and any applications that depend on them.  For now, the assertion
is removed and a regression test is added to cover the case of a failure
with a detail string.

This problem exists since 2bd78eb8d51c, so backpatch all the way down
with tweaks to the regression tests output added where required.

Author: Alexander Lakhin
Discussion: https://postgr.es/m/18070-ab9c171cbf4ebb0f@postgresql.org
Backpatch-through: 11

19 months agoDon't crash if cursor_to_xmlschema is used on a non-data-returning Portal.
Tom Lane [Mon, 18 Sep 2023 18:27:47 +0000 (14:27 -0400)]
Don't crash if cursor_to_xmlschema is used on a non-data-returning Portal.

cursor_to_xmlschema() assumed that any Portal must have a tupDesc,
which is not so.  Add a defensive check.

It's plausible that this mistake occurred because of the rather
poorly chosen name of the lookup function SPI_cursor_find(),
which in such cases is returning something that isn't very much
like a cursor.  Add some documentation to try to forestall future
errors of the same ilk.

Report and patch by Boyu Yang (docs changes by me).  Back-patch
to all supported branches.

Discussion: https://postgr.es/m/dd343010-c637-434c-a8cb-418f53bda3b8.yangboyu.yby@alibaba-inc.com

19 months agoTrack nesting depth correctly when drilling down into RECORD Vars.
Tom Lane [Fri, 15 Sep 2023 21:01:26 +0000 (17:01 -0400)]
Track nesting depth correctly when drilling down into RECORD Vars.

expandRecordVariable() failed to adjust the parse nesting structure
correctly when recursing to inspect an outer-level Var.  This could
result in assertion failures or core dumps in corner cases.

Likewise, get_name_for_var_field() failed to adjust the deparse
namespace stack correctly when recursing to inspect an outer-level
Var.  In this case the likely result was a "bogus varno" error
while deparsing a view.

Per bug #18077 from Jingzhou Fu.  Back-patch to all supported
branches.

Richard Guo, with some adjustments by me

Discussion: https://postgr.es/m/18077-b9db97c6e0ab45d8@postgresql.org

19 months agoFix get_expr_result_type() to find field names for RECORD Consts.
Tom Lane [Fri, 15 Sep 2023 20:39:27 +0000 (16:39 -0400)]
Fix get_expr_result_type() to find field names for RECORD Consts.

This is a back-patch of commit d57534740 ("Fix EXPLAIN of SEARCH
BREADTH FIRST with a constant initial value") into pre-v14 branches.
At the time I'd thought it was not needed in branches that lack the
SEARCH/CYCLE feature, but that was just a failure of imagination.
It's possible to demonstrate "record type has not been registered"
failures in older branches too, during deparsing of views that contain
references to fields of composite constants.

Back-patch only the code changes, as the test cases added by d57534740
all require SEARCH/CYCLE syntax.  A suitable test case will be added
in the upcoming fix for bug #18077.

Discussion: https://postgr.es/m/17644-3bd1f3036d6d7a16@postgresql.org
Discussion: https://postgr.es/m/3607145.1694803130@sss.pgh.pa.us

19 months agoAllow extracting fields from a ROW() expression in more cases.
Tom Lane [Fri, 15 Sep 2023 20:20:08 +0000 (16:20 -0400)]
Allow extracting fields from a ROW() expression in more cases.

Teach get_expr_result_type() to manufacture a tuple descriptor directly
from a RowExpr node.  If the RowExpr has type RECORD, this is the only
way to get a tupdesc for its result, since even if the rowtype has been
blessed, we don't have its typmod available at this point.  (If the
RowExpr has some named composite type, we continue to let the existing
code handle it, since the RowExpr might well not have the correct column
names embedded in it.)

This fixes assorted corner cases illustrated by the added regression
tests.

This is a back-patch of the v13-era commit 8b7a0f1d1 into previous
branches.  At the time I'd judged it not important enough to back-patch,
but the upcoming fix for bug #18077 includes a test case that depends
on this working correctly; and 8b7a0f1d1 has now aged long enough to
have good confidence that it won't break anything.

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

19 months agoRevert "Improve error message on snapshot import in snapmgr.c"
Michael Paquier [Thu, 14 Sep 2023 07:00:47 +0000 (16:00 +0900)]
Revert "Improve error message on snapshot import in snapmgr.c"

This reverts commit a0d87bcd9b57, following a remark from Andres Frend
that the new error can be triggered with an incorrect SET TRANSACTION
SNAPSHOT command without being really helpful for the user as it uses
the internal file name.

Discussion: https://postgr.es/m/20230914020724.hlks7vunitvtbbz4@awork3.anarazel.de
Backpatch-through: 11

19 months agoImprove error message on snapshot import in snapmgr.c
Michael Paquier [Thu, 14 Sep 2023 01:30:37 +0000 (10:30 +0900)]
Improve error message on snapshot import in snapmgr.c

When a snapshot file fails to be read in ImportSnapshot(), it would
issue an ERROR as "invalid snapshot identifier" when opening a stream
for it in read-only mode.  This error message is reworded to be the same
as all the other messages used in this case on failure, which is useful
when debugging this area.

Thinko introduced by bb446b689b66 where snapshot imports have been
added.  A backpatch down to 11 is done as this can improve any work
related to snapshot imports in older branches.

Author: Bharath Rupireddy
Reviewed-by: Daniel Gustafsson
Discussion: https://postgr.es/m/CALj2ACWmr=3KdxDkm8h7Zn1XxBoF6hdzq8WQyMn2y1OL5RYFrg@mail.gmail.com
Backpatch-through: 11

19 months agoFix exception safety bug in typcache.c.
Thomas Munro [Wed, 13 Sep 2023 02:32:24 +0000 (14:32 +1200)]
Fix exception safety bug in typcache.c.

If an out-of-memory error was thrown at an unfortunate time,
ensure_record_cache_typmod_slot_exists() could leak memory and leave
behind a global state that produced an infinite loop on the next call.

Fix by merging RecordCacheArray and RecordIdentifierArray into a single
array.  With only one allocation or re-allocation, there is no
intermediate state.

Back-patch to all supported releases.

Reported-by: "James Pang (chaolpan)" <chaolpan@cisco.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/PH0PR11MB519113E738814BDDA702EDADD6EFA%40PH0PR11MB5191.namprd11.prod.outlook.com

19 months agoFix uninitialized access to InitialRunningXacts during decoding after ERROR.
Amit Kapila [Tue, 12 Sep 2023 04:06:56 +0000 (09:36 +0530)]
Fix uninitialized access to InitialRunningXacts during decoding after ERROR.

The transactions and subtransactions array that was allocated under
snapshot builder memory context and recorded during decoding was not
cleared in case of errors. This can result in an assertion failure if we
attempt to retry logical decoding within the same session. To address this
issue, we register a callback function under the snapshot builder memory
context to clear the recorded transactions and subtransactions array along
with the context.

This problem doesn't exist in PG16 and HEAD as instead of using
InitialRunningXacts, we added the list of transaction IDs and
sub-transaction IDs, that have modified catalogs and are running during
snapshot serialization, to the serialized snapshot (see commit 7f13ac8123).

Author: Hou Zhijie
Reviewed-by: Amit Kapila
Backpatch-through: 11
Discussion: http://postgr.es/m/18055-ab3beed9f4b7b7d6@postgresql.org

19 months agodoc: remove mention of backslash doubling in strings
Bruce Momjian [Fri, 8 Sep 2023 21:25:14 +0000 (17:25 -0400)]
doc:  remove mention of backslash doubling in strings

Reported-by: Laurenz Albe
Discussion: https://postgr.es/m/0b03f91a875fb44182f5bed9e1d404ed6d138066.camel@cybertec.at

Author: Laurenz Albe

Backpatch-through: 11

19 months agopg_basebackup: Generate valid temporary slot names under PQbackendPID()
Michael Paquier [Thu, 7 Sep 2023 05:12:36 +0000 (14:12 +0900)]
pg_basebackup: Generate valid temporary slot names under PQbackendPID()

pgbouncer can cause PQbackendPID() to return negative values due to it
filling be_pid with random bytes (even these days pid_max can only be
set up to 2^22 on 64b machines on Linux, for example, so this cannot
happen with normal PID numbers).  When this happens, pg_basebackup may
generate a temporary slot name that may not be accepted by the parser,
leading to spurious failures, like:
pg_basebackup: error: could not send replication command
ERROR:  replication slot name "pg_basebackup_-1201966863" contains
invalid character

This commit fixes that problem by formatting the result from
PQbackendPID() as an unsigned integer when creating the temporary
replication slot name, so as the invalid character is gone and the
command can be parsed.

Author: Jelte Fennema
Reviewed-by: Daniel Gustafsson, Nishant Sharma
Discussion: https://postgr.es/m/CAGECzQQOGvYfp8ziF4fWQ_o8s2K7ppaoWBQnTmdakn3s-4Z=5g@mail.gmail.com
Backpatch-through: 11

19 months agodoc: mention that to_char() values are rounded
Bruce Momjian [Wed, 6 Sep 2023 20:52:24 +0000 (16:52 -0400)]
doc:  mention that to_char() values are rounded

Reported-by: barsikdacat@gmail.com
Diagnosed-by: Laurenz Albe
Discussion: https://postgr.es/m/168991536429.626.9957835774751337210@wrigleys.postgresql.org

Author: Laurenz Albe

Backpatch-through: 11

19 months agodoc: mention libpq regression tests
Bruce Momjian [Tue, 5 Sep 2023 17:05:27 +0000 (13:05 -0400)]
doc: mention libpq regression tests

Reported-by: Ryo Matsumura
Discussion: https://postgr.es/m/TYCPR01MB11316B3FB56EE54D70BF0CEF6E8E4A@TYCPR01MB11316.jpnprd01.prod.outlook.com

Backpatch-through: 11

19 months agoFix out-of-bound read in gtsvector_picksplit()
Michael Paquier [Mon, 4 Sep 2023 05:55:58 +0000 (14:55 +0900)]
Fix out-of-bound read in gtsvector_picksplit()

This could lead to an imprecise choice when splitting an index page of a
GiST index on a tsvector, deciding which entries should remain on the
old page and which entries should move to a new page.

This is wrong since tsearch2 has been moved into core with commit
140d4ebcb46e, so backpatch all the way down.  This error has been
spotted by valgrind.

Author: Alexander Lakhin
Discussion: https://postgr.es/m/17950-6c80a8d2b94ec695@postgresql.org
Backpatch-through: 11

20 months agopostgres_fdw: Fix test for parameterized foreign scan.
Etsuro Fujita [Wed, 30 Aug 2023 08:15:10 +0000 (17:15 +0900)]
postgres_fdw: Fix test for parameterized foreign scan.

Commit e4106b252 should have updated this test, but did not; back-patch
to all supported branches.

Reviewed by Richard Guo.

Discussion: http://postgr.es/m/CAPmGK15nR0NXLSCKQAcqbZbTzrzd5MozowWnTnGfPkayndF43Q%40mail.gmail.com

20 months agoSilence compiler warning in release 11 and 12 branches
Andrew Dunstan [Sun, 27 Aug 2023 11:01:26 +0000 (07:01 -0400)]
Silence compiler warning in release 11 and 12 branches

The offending code is not present in later branches.

Discussion: https://postgr.es/m/ba2150c1-8485-6597-fafe-4fcd39e49c28@dunslane.net

20 months agoInclude header file inadvertently missed in commit 2d13dab048
Andrew Dunstan [Thu, 24 Aug 2023 20:14:26 +0000 (16:14 -0400)]
Include header file inadvertently missed in commit 2d13dab048

per gripe from Tom Lane.

20 months agoAvoid unnecessary plancache revalidation of utility statements.
Tom Lane [Thu, 24 Aug 2023 16:02:40 +0000 (12:02 -0400)]
Avoid unnecessary plancache revalidation of utility statements.

Revalidation of a plancache entry (after a cache invalidation event)
requires acquiring a snapshot.  Normally that is harmless, but not
if the cached statement is one that needs to run without acquiring a
snapshot.  We were already aware of that for TransactionStmts,
but for some reason hadn't extrapolated to the other statements that
PlannedStmtRequiresSnapshot() knows mustn't set a snapshot.  This can
lead to unexpected failures of commands such as SET TRANSACTION
ISOLATION LEVEL.  We can fix it in the same way, by excluding those
command types from revalidation.

However, we can do even better than that: there is no need to
revalidate for any statement type for which parse analysis, rewrite,
and plan steps do nothing interesting, which is nearly all utility
commands.  To mechanize this, invent a parser function
stmt_requires_parse_analysis() that tells whether parse analysis does
anything beyond wrapping a CMD_UTILITY Query around the raw parse
tree.  If that's what it does, then rewrite and plan will just
skip the Query, so that it is not possible for the same raw parse
tree to produce a different plan tree after cache invalidation.

stmt_requires_parse_analysis() is basically equivalent to the
existing function analyze_requires_snapshot(), except that for
obscure reasons that function omits ReturnStmt and CallStmt.
It is unclear whether those were oversights or intentional.
I have not been able to demonstrate a bug from not acquiring a
snapshot while analyzing these commands, but at best it seems mighty
fragile.  It seems safer to acquire a snapshot for parse analysis of
these commands too, which allows making stmt_requires_parse_analysis
and analyze_requires_snapshot equivalent.

In passing this fixes a second bug, which is that ResetPlanCache
would exclude ReturnStmts and CallStmts from revalidation.
That's surely *not* safe, since they contain parsable expressions.

Per bug #18059 from Pavel Kulakov.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18059-79c692f036b25346@postgresql.org

20 months agoCache by-reference missing values in a long lived context
Andrew Dunstan [Tue, 22 Aug 2023 15:57:08 +0000 (11:57 -0400)]
Cache by-reference missing values in a long lived context

Attribute missing values might be needed past the lifetime of the tuple
descriptors from which they are extracted. To avoid possibly using
pointers for by-reference values which might thus be left dangling, we
cache a datumCopy'd version of the datum in the TopMemoryContext. Since
we first search for the value this only needs to be done once per
session for any such value.

Original complaint from Tom Lane, idea for mitigation by Andrew Dunstan,
tweaked by Tom Lane.

Backpatch to version 11 where missing values were introduced.

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

20 months agodoc: Replace list of drivers and PLs with wiki link
Daniel Gustafsson [Wed, 23 Aug 2023 12:13:07 +0000 (14:13 +0200)]
doc: Replace list of drivers and PLs with wiki link

The list of external language drivers and procedural languages was
never complete or exhaustive, and rather than attempting to manage
it the content has migrated to the wiki.  This replaces the tables
altogether with links to the wiki as we regularly get requests for
adding various projects,  which we reject without any clear policy
for why or how the content should be managed.

The threads linked to below are the most recent discussions about
this, the archives contain many more.

Backpatch to all supported branches since the list on the wiki
applies to all branches.

Author: Jonathan Katz <jkatz@postgresql.org>
Discussion: https://postgr.es/m/169165415312.635.10247434927885764880@wrigleys.postgresql.org
Discussion: https://postgr.es/m/169177958824.635.11087800083040275266@wrigleys.postgresql.org
Backpatch-through: v11

20 months agoRemove test from commit fa2e874946.
Jeff Davis [Thu, 10 Aug 2023 17:16:59 +0000 (10:16 -0700)]
Remove test from commit fa2e874946.

The fix itself is fine, but the test revealed other problems related
to parallel query that are not easily fixable. Remove the test for
now to fix the buildfarm.

Discussion: https://postgr.es/m/88825.1691665432@sss.pgh.pa.us
Backpatch-through: 11

20 months agoRecalculate search_path after ALTER ROLE.
Jeff Davis [Mon, 7 Aug 2023 22:09:11 +0000 (15:09 -0700)]
Recalculate search_path after ALTER ROLE.

Renaming a role can affect the meaning of the special string $user, so
must cause search_path to be recalculated.

Discussion: https://postgr.es/m/186761d32c0255debbdf50b6310b581b9c973e6c.camel@j-davis.com
Reviewed-by: Nathan Bossart, Michael Paquier
Backpatch-through: 11

20 months agoStamp 11.21. REL_11_21
Tom Lane [Mon, 7 Aug 2023 20:15:30 +0000 (16:15 -0400)]
Stamp 11.21.

20 months agoLast-minute updates for release notes.
Tom Lane [Mon, 7 Aug 2023 16:50:15 +0000 (12:50 -0400)]
Last-minute updates for release notes.

Security: CVE-2023-39417, CVE-2023-39418

20 months agoReject substituting extension schemas or owners matching ["$'\].
Noah Misch [Mon, 7 Aug 2023 13:05:56 +0000 (06:05 -0700)]
Reject substituting extension schemas or owners matching ["$'\].

Substituting such values in extension scripts facilitated SQL injection
when @extowner@, @extschema@, or @extschema:...@ appeared inside a
quoting construct (dollar quoting, '', or "").  No bundled extension was
vulnerable.  Vulnerable uses do appear in a documentation example and in
non-bundled extensions.  Hence, the attack prerequisite was an
administrator having installed files of a vulnerable, trusted,
non-bundled extension.  Subject to that prerequisite, this enabled an
attacker having database-level CREATE privilege to execute arbitrary
code as the bootstrap superuser.  By blocking this attack in the core
server, there's no need to modify individual extensions.  Back-patch to
v11 (all supported versions).

Reported by Micah Gate, Valerie Woolard, Tim Carey-Smith, and Christoph
Berg.

Security: CVE-2023-39417

20 months agoTranslation updates
Peter Eisentraut [Mon, 7 Aug 2023 10:38:17 +0000 (12:38 +0200)]
Translation updates

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

20 months agoRelease notes for 15.4, 14.9, 13.12, 12.16, 11.21.
Tom Lane [Sat, 5 Aug 2023 20:47:05 +0000 (16:47 -0400)]
Release notes for 15.4, 14.9, 13.12, 12.16, 11.21.

20 months agoDoc: update documentation for creating custom scan paths.
Etsuro Fujita [Thu, 3 Aug 2023 08:45:09 +0000 (17:45 +0900)]
Doc: update documentation for creating custom scan paths.

Commit f49842d1e added a new callback for custom scan paths, but missed
updating the documentation.

Back-patch to all supported branches.

Discussion: https://postgr.es/m/CAPmGK15ODkN%2B%3DhkBCufj1HBW0x5OTb65Xuy7ryXchMdiCMpx_g%40mail.gmail.com

20 months agoUpdate comments on CustomPath struct.
Etsuro Fujita [Thu, 3 Aug 2023 08:15:09 +0000 (17:15 +0900)]
Update comments on CustomPath struct.

Commit e7cb7ee14 allowed custom scan providers to create CustomPath
paths for join relations as well, but missed updating the comments.

Back-patch to all supported branches.

Discussion: https://postgr.es/m/CAPmGK15ODkN%2B%3DhkBCufj1HBW0x5OTb65Xuy7ryXchMdiCMpx_g%40mail.gmail.com

21 months agoDisallow replacing joins with scans in problematic cases.
Etsuro Fujita [Fri, 28 Jul 2023 06:45:09 +0000 (15:45 +0900)]
Disallow replacing joins with scans in problematic cases.

Commit e7cb7ee14, which introduced the infrastructure for FDWs and
custom scan providers to replace joins with scans, failed to add support
handling of pseudoconstant quals assigned to replaced joins in
createplan.c, leading to an incorrect plan without a gating Result node
when postgres_fdw replaced a join with such a qual.

To fix, we could add the support by 1) modifying the ForeignPath and
CustomPath structs to store the list of RestrictInfo nodes to apply to
the join, as in JoinPaths, if they represent foreign and custom scans
replacing a join with a scan, and by 2) modifying create_scan_plan() in
createplan.c to use that list in that case, instead of the
baserestrictinfo list, to get pseudoconstant quals assigned to the join;
but #1 would cause an ABI break.  So fix by modifying the infrastructure
to just disallow replacing joins with such quals.

Back-patch to all supported branches.

Reported by Nishant Sharma.  Patch by me, reviewed by Nishant Sharma and
Richard Guo.

Discussion: https://postgr.es/m/CADrsxdbcN1vejBaf8a%2BQhrZY5PXL-04mCd4GDu6qm6FigDZd6Q%40mail.gmail.com

21 months agoRaise fixed token-length limit in hba.c.
Tom Lane [Thu, 27 Jul 2023 16:07:48 +0000 (12:07 -0400)]
Raise fixed token-length limit in hba.c.

Historically, hba.c limited tokens in the authentication configuration
files (pg_hba.conf and pg_ident.conf) to less than 256 bytes.  We have
seen a few reports of this limit causing problems; notably, for
moderately-complex LDAP configurations.  Increase the limit to 10240
bytes as a low-risk stop-gap solution.

In v13 and earlier, this also requires raising MAX_LINE, the limit
on overall line length.  I'm hesitant to make this code consume
too much stack space, so I only raised that to 20480 bytes.

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

21 months agoDoc: improve description of IN and row-constructor comparisons.
Tom Lane [Wed, 19 Jul 2023 15:00:34 +0000 (11:00 -0400)]
Doc: improve description of IN and row-constructor comparisons.

IN and NOT IN work fine on records and arrays, so just say that
they accept "expressions" not "scalar expressions".  I think that
that phrasing was meant to say that they don't work on set-returning
expressions, but that's not the common meaning of "scalar".

Revise the description of row-constructor comparisons to make it
perhaps a bit less confusing.  (This partially reverts some
dubious wording changes made by commit f56651519.)

Per gripe from Ilya Nenashev.  Back-patch to supported branches.
In HEAD and v16, also drop a NOTE about pre-8.2 behavior, which
is hopefully no longer of interest to anybody.

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

21 months agoDoc: fix out-of-date example of SPI usage.
Tom Lane [Tue, 18 Jul 2023 15:59:39 +0000 (11:59 -0400)]
Doc: fix out-of-date example of SPI usage.

The "count" argument of SPI_exec() only limits execution when
the query is actually returning rows.  This was not the case
before PG 9.0, so this example was correct when written; but
we missed updating it in commit 2ddc600f8.  Extend the example
to show the behavior both with and without RETURNING.

While here, improve the commentary and markup for the rest
of the example.

David G. Johnston and Tom Lane, per report from Curt Kolovson.
Back-patch to all supported branches.

Discussion: https://postgr.es/m/CANhYJV6HWtgz_qjx_APfK0PAgLUzY-2vjLuj7i_o=TZF1LAQew@mail.gmail.com

21 months agoFix indentation in twophase.c
Michael Paquier [Tue, 18 Jul 2023 05:04:54 +0000 (14:04 +0900)]
Fix indentation in twophase.c

This has been missed in cb0cca1, noticed before buildfarm member koel
has been able to complain while poking at a different patch.  Like the
other commit, backpatch all the way down to limit the odds of merge
conflicts.

Backpatch-through: 11

21 months agoFix recovery of 2PC transaction during crash recovery
Michael Paquier [Tue, 18 Jul 2023 04:44:35 +0000 (13:44 +0900)]
Fix recovery of 2PC transaction during crash recovery

A crash in the middle of a checkpoint with some two-phase state data
already flushed to disk by this checkpoint could cause a follow-up crash
recovery to recover twice the same transaction, once from what has been
found in pg_twophase/ at the beginning of recovery and a second time
when replaying its corresponding record.

This would lead to FATAL failures in the startup process during
recovery, where the same transaction would have a state recovered twice
instead of once:
LOG:  recovering prepared transaction 731 from shared memory
LOG:  recovering prepared transaction 731 from shared memory
FATAL:  lock ExclusiveLock on object 731/0/0 is already held

This issue is fixed by skipping the addition of any 2PC state coming
from a record whose equivalent 2PC state file has already been loaded in
TwoPhaseState at the beginning of recovery by restoreTwoPhaseData(),
which is OK as long as the system has not reached a consistent state.

The timing to get a messed up recovery processing is very racy, and
would very unlikely happen.  The thread that has reported the issue has
demonstrated the bug using injection points to force a PANIC in the
middle of a checkpoint.

Issue introduced in 728bd99, so backpatch all the way down.

Reported-by: "suyu.cmj" <mengjuan.cmj@alibaba-inc.com>
Author: "suyu.cmj" <mengjuan.cmj@alibaba-inc.com>
Author: Michael Paquier
Discussion: https://postgr.es/m/109e6994-b971-48cb-84f6-829646f18b4c.mengjuan.cmj@alibaba-inc.com
Backpatch-through: 11