postgresql.git
5 months agoAdd nbtree amgettuple return item function.
Peter Geoghegan [Wed, 13 Nov 2024 14:50:57 +0000 (09:50 -0500)]
Add nbtree amgettuple return item function.

This makes it easier to add precondition assertions.  We now assert that
the last call to _bt_readpage succeeded, and that the current item index
is within the bounds of the currPos items array.

Author: Peter Geoghegan <[email protected]>
Reviewed-By: Masahiro Ikeda <[email protected]>
Discussion: https://postgr.es/m/CAH2-WznFkEs9K1PtNruti5JjawY-dwj+gkaEh_k1ZE+1xLLGkA@mail.gmail.com

5 months agoFix pg_upgrade's cross-version tests when old < 18
Álvaro Herrera [Wed, 13 Nov 2024 10:06:44 +0000 (11:06 +0100)]
Fix pg_upgrade's cross-version tests when old < 18

Because in the 18 cycle we turned checksums on by default with commit
04bec894a04c, and pg_upgrade fails if the setting doesn't match in old
and new clusters, the built-in cross-version pg_upgrade test is failing
if the old version is older than 18.  Fix the script so that it creates
the old cluster with checksums enabled (-k) in cross-version scenarios.

This went unnoticed because the buildfarm doesn't use the same test code
for cross-version testing.

Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/202411071838[email protected]

5 months agoconfigure.ac: Remove useless AC_SUBST
Peter Eisentraut [Wed, 13 Nov 2024 09:29:31 +0000 (10:29 +0100)]
configure.ac: Remove useless AC_SUBST

No longer used since commit 805e431a386.

5 months agodoc: Update pg_constraint.conexclop docs for WITHOUT OVERLAPS
Peter Eisentraut [Wed, 13 Nov 2024 08:05:02 +0000 (09:05 +0100)]
doc: Update pg_constraint.conexclop docs for WITHOUT OVERLAPS

Fixup for commit fc0438b4e80.

Author: Paul A. Jungwirth <[email protected]>
Discussion: https://www.postgresql.org/message-id/57ea0668-5205-426e-b934-efc89f2186c2@illuminatedcomputing.com

5 months agodoc: Add PERIOD to ALTER TABLE reference docs
Peter Eisentraut [Wed, 13 Nov 2024 07:53:08 +0000 (08:53 +0100)]
doc: Add PERIOD to ALTER TABLE reference docs

Commit 89f908a6d0a documented foreign keys with PERIOD in the CREATE
TABLE docs, but not in ALTER TABLE.  This commit adds the new syntax
to the ALTER TABLE docs.

Author: Paul A. Jungwirth <[email protected]>
Discussion: https://www.postgresql.org/message-id/57ea0668-5205-426e-b934-efc89f2186c2@illuminatedcomputing.com

5 months agodoc: Small improvement in CREATE TABLE / PERIOD documentation
Peter Eisentraut [Wed, 13 Nov 2024 07:51:23 +0000 (08:51 +0100)]
doc: Small improvement in CREATE TABLE / PERIOD documentation

Use placeholders that are more consistent and match the description
better.  Fixup for commit 89f908a6d0a.

5 months agodoc: Add WITHOUT OVERLAPS to ALTER TABLE reference docs
Peter Eisentraut [Wed, 13 Nov 2024 07:42:34 +0000 (08:42 +0100)]
doc: Add WITHOUT OVERLAPS to ALTER TABLE reference docs

Commit fc0438b4e80 documented WITHOUT OVERLAPS in the CREATE TABLE
docs, but not in ALTER TABLE.  This commit adds the new syntax to the
ALTER TABLE docs.

Author: Paul A. Jungwirth <[email protected]>
Discussion: https://www.postgresql.org/message-id/57ea0668-5205-426e-b934-efc89f2186c2@illuminatedcomputing.com

5 months agoFix comment in injection_point.c
Michael Paquier [Wed, 13 Nov 2024 04:58:09 +0000 (13:58 +0900)]
Fix comment in injection_point.c

InjectionPointEntry->name was described as a hash key, which was fine
when introduced in d86d20f0ba79, but it is not now.

Oversight in 86db52a5062a, that has changed the way injection points are
stored in shared memory from a hash table to an array.

Backpatch-through: 17

5 months agoFix obsolete nbtree page reuse FSM comment.
Peter Geoghegan [Wed, 13 Nov 2024 03:09:00 +0000 (22:09 -0500)]
Fix obsolete nbtree page reuse FSM comment.

Oversight in commit d088ba5a.

5 months agoCount contrib/bloom index scans in pgstat view.
Peter Geoghegan [Wed, 13 Nov 2024 01:57:45 +0000 (20:57 -0500)]
Count contrib/bloom index scans in pgstat view.

Maintain the pg_stat_user_indexes.idx_scan pgstat counter during
contrib/Bloom index scans.

Oversight in commit 9ee014fc, which added the Bloom index contrib
module.

Author: Masahiro Ikeda <[email protected]>
Reviewed-By: Peter Geoghegan <[email protected]>
Discussion: https://postgr.es/m/c48839d881388ee401a01807c686004d@oss.nttdata.com
Backpatch: 13- (all supported branches).

5 months agoAdd missing word in comment
Amit Langote [Tue, 12 Nov 2024 06:56:51 +0000 (15:56 +0900)]
Add missing word in comment

Discussion: https://postgr.es/m/CA+HiwqFgdp8=0_gi+DU0fPWZbg7qY3KZ_c1Wj1DEvzXC4BCnMQ@mail.gmail.com

5 months agoSilence compilers about extractNotNullColumn()
Álvaro Herrera [Tue, 12 Nov 2024 10:35:43 +0000 (11:35 +0100)]
Silence compilers about extractNotNullColumn()

Multiple buildfarm animals warn that a newly added Assert() is
impossible to fail; remove it to avoid the noise.  While at it, use
direct assignment to obtain the value we need, avoiding an unnecessary
memcpy().

(I decided to remove the "pfree" call for the detoasted short-datum;
because this is only used for DDL, it's not problematic to leak such a
small allocation.)

Noted by Tom Lane about 14e87ffa5c54.

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

5 months agopg_freespacemap: Use SQL-standard function bodies
Michael Paquier [Tue, 12 Nov 2024 08:28:03 +0000 (17:28 +0900)]
pg_freespacemap: Use SQL-standard function bodies

72a5b1fc8804 was the piece missing for the conversion of this module.
pg_freespace is bumped to 1.3, with its function pg_freespace(regclass)
converted to this new style.

There are other modules in the tree that need a similar treatment; these
will be handled later.

Author: Tom Lane
Reviewed-by: Ronan Dunklau
Discussion: https://postgr.es/m/3395418.1618352794@sss.pgh.pa.us

5 months agoFix arrays comparison in CompareOpclassOptions()
Alexander Korotkov [Mon, 11 Nov 2024 23:44:20 +0000 (01:44 +0200)]
Fix arrays comparison in CompareOpclassOptions()

The current code calls array_eq() and does not provide FmgrInfo.  This commit
provides initialization of FmgrInfo and uses C collation as the safe option
for text comparison because we don't know anything about the semantics of
opclass options.

Backpatch to 13, where opclass options were introduced.

Reported-by: Nicolas Maus
Discussion: https://postgr.es/m/18692-72ea398df3ec6712%40postgresql.org
Backpatch-through: 13

5 months agoParallel workers use AuthenticatedUserId for connection privilege checks.
Tom Lane [Mon, 11 Nov 2024 22:05:53 +0000 (17:05 -0500)]
Parallel workers use AuthenticatedUserId for connection privilege checks.

Commit 5a2fed911 had an unexpected side-effect: the parallel worker
launched for the new test case would fail if it couldn't use a
superuser-reserved connection slot.  The reason that test failed
while all our pre-existing ones worked is that the connection
privilege tests in InitPostgres had been based on the superuserness
of the leader's AuthenticatedUserId, but after the rearrangements
of 5a2fed911 we were testing the superuserness of CurrentUserId,
which the new test case deliberately made to be a non-superuser.

This all seems very accidental and probably not the behavior we really
want, but a security patch is no time to be redesigning things.
Pending some discussion about desirable semantics, hack it so that
InitPostgres continues to pay attention to the superuserness of
AuthenticatedUserId when starting a parallel worker.

Nathan Bossart and Tom Lane, per buildfarm member sawshark.

Security: CVE-2024-10978

5 months agoFix cross-version upgrade tests.
Tom Lane [Mon, 11 Nov 2024 18:57:21 +0000 (13:57 -0500)]
Fix cross-version upgrade tests.

TestUpgradeXversion knows how to make the main regression database's
references to pg_regress.so be version-independent.  But it doesn't
do that for plperl's database, so that the C function added by
commit b7e3a52a8 is causing cross-version upgrade test failures.
Path of least resistance is to just drop the function at the end
of the new test.

In <= v14, also take the opportunity to clean up the generated
test files.

Security: CVE-2024-10979

5 months agoAvoid bizarre meson behavior with backslashes in command arguments.
Tom Lane [Mon, 11 Nov 2024 17:20:08 +0000 (12:20 -0500)]
Avoid bizarre meson behavior with backslashes in command arguments.

meson makes the backslashes in text2macro.pl's --strip argument
into forward slashes, effectively disabling comment stripping.
That hasn't caused us issues before, but it breaks the test case
for b7e3a52a8.  We don't really need the pattern to be adjustable,
so just hard-wire it into the script instead.

Context: https://github.com/mesonbuild/meson/issues/1564
Security: CVE-2024-10979

5 months agoFix improper interactions between session_authorization and role.
Tom Lane [Mon, 11 Nov 2024 15:29:54 +0000 (10:29 -0500)]
Fix improper interactions between session_authorization and role.

The SQL spec mandates that SET SESSION AUTHORIZATION implies
SET ROLE NONE.  We tried to implement that within the lowest-level
functions that manipulate these settings, but that was a bad idea.
In particular, guc.c assumes that it doesn't matter in what order
it applies GUC variable updates, but that was not the case for these
two variables.  This problem, compounded by some hackish attempts to
work around it, led to some security-grade issues:

* Rolling back a transaction that had done SET SESSION AUTHORIZATION
would revert to SET ROLE NONE, even if that had not been the previous
state, so that the effective user ID might now be different from what
it had been.

* The same for SET SESSION AUTHORIZATION in a function SET clause.

* If a parallel worker inspected current_setting('role'), it saw
"none" even when it should see something else.

Also, although the parallel worker startup code intended to cope
with the current role's pg_authid row having disappeared, its
implementation of that was incomplete so it would still fail.

Fix by fully separating the miscinit.c functions that assign
session_authorization from those that assign role.  To implement the
spec's requirement, teach set_config_option itself to perform "SET
ROLE NONE" when it sets session_authorization.  (This is undoubtedly
ugly, but the alternatives seem worse.  In particular, there's no way
to do it within assign_session_authorization without incompatible
changes in the API for GUC assign hooks.)  Also, improve
ParallelWorkerMain to directly set all the relevant user-ID variables
instead of relying on some of them to get set indirectly.  That
allows us to survive not finding the pg_authid row during worker
startup.

In v16 and earlier, this includes back-patching 9987a7bf3 which
fixed a violation of GUC coding rules: SetSessionAuthorization
is not an appropriate place to be throwing errors from.

Security: CVE-2024-10978

5 months agoEnsure cached plans are correctly marked as dependent on role.
Nathan Bossart [Mon, 11 Nov 2024 15:00:00 +0000 (09:00 -0600)]
Ensure cached plans are correctly marked as dependent on role.

If a CTE, subquery, sublink, security invoker view, or coercion
projection references a table with row-level security policies, we
neglected to mark the plan as potentially dependent on which role
is executing it.  This could lead to later executions in the same
session returning or hiding rows that should have been hidden or
returned instead.

Reported-by: Wolfgang Walther
Reviewed-by: Noah Misch
Security: CVE-2024-10976
Backpatch-through: 12

5 months agoBlock environment variable mutations from trusted PL/Perl.
Noah Misch [Mon, 11 Nov 2024 14:23:43 +0000 (06:23 -0800)]
Block environment variable mutations from trusted PL/Perl.

Many process environment variables (e.g. PATH), bypass the containment
expected of a trusted PL.  Hence, trusted PLs must not offer features
that achieve setenv().  Otherwise, an attacker having USAGE privilege on
the language often can achieve arbitrary code execution, even if the
attacker lacks a database server operating system user.

To fix PL/Perl, replace trusted PL/Perl %ENV with a tied hash that just
replaces each modification attempt with a warning.  Sites that reach
these warnings should evaluate the application-specific implications of
proceeding without the environment modification:

  Can the application reasonably proceed without the modification?

    If no, switch to plperlu or another approach.

    If yes, the application should change the code to stop attempting
    environment modifications.  If that's too difficult, add "untie
    %main::ENV" in any code executed before the warning.  For example,
    one might add it to the start of the affected function or even to
    the plperl.on_plperl_init setting.

In passing, link to Perl's guidance about the Perl features behind the
security posture of PL/Perl.

Back-patch to v12 (all supported versions).

Andrew Dunstan and Noah Misch

Security: CVE-2024-10979

5 months agoDoc: Add links to clarify the max_replication_slots.
Amit Kapila [Mon, 11 Nov 2024 09:54:40 +0000 (15:24 +0530)]
Doc: Add links to clarify the max_replication_slots.

The GUC max_replication_slots has a different meaning for sending servers
and subscribers. Add cross-links in each section for easy reference.

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

5 months agoAdd two attributes to pg_stat_database for parallel workers activity
Michael Paquier [Mon, 11 Nov 2024 01:40:48 +0000 (10:40 +0900)]
Add two attributes to pg_stat_database for parallel workers activity

Two attributes are added to pg_stat_database:
* parallel_workers_to_launch, counting the total number of parallel
workers that were planned to be launched.
* parallel_workers_launched, counting the total number of parallel
workers actually launched.

The ratio of both fields can provide hints that there are not enough
slots available when launching parallel workers, also useful when
pg_stat_statements is not deployed on an instance (i.e. cf54a2c00254).

This commit relies on de3a2ea3b264, that has added two fields to EState,
that get incremented when executing Gather or GatherMerge nodes.

A test is added in select_parallel, where parallel workers are spawned.

Bump catalog version.

Author: Benoit Lobréau
Discussion: https://postgr.es/m/783bc7f7-659a-42fa-99dd-ee0565644e25@dalibo.com

5 months agolibpq: Bail out during SSL/GSS negotiation errors
Michael Paquier [Mon, 11 Nov 2024 01:19:52 +0000 (10:19 +0900)]
libpq: Bail out during SSL/GSS negotiation errors

This commit changes libpq so that errors reported by the backend during
the protocol negotiation for SSL and GSS are discarded by the client, as
these may include bytes that could be consumed by the client and write
arbitrary bytes to a client's terminal.

A failure with the SSL negotiation now leads to an error immediately
reported, without a retry on any other methods allowed, like a fallback
to a plaintext connection.

A failure with GSS discards the error message received, and we allow a
fallback as it may be possible that the error is caused by a connection
attempt with a pre-11 server, GSS encryption having been introduced in
v12.  This was a problem only with v17 and newer versions; older
versions discard the error message already in this case, assuming a
failure caused by a lack of support for GSS encryption.

Author: Jacob Champion
Reviewed-by: Peter Eisentraut, Heikki Linnakangas, Michael Paquier
Security: CVE-2024-10977
Backpatch-through: 12

5 months agopg_stat_statements: Avoid some locking during PGSS entry scans
Michael Paquier [Mon, 11 Nov 2024 00:02:30 +0000 (09:02 +0900)]
pg_stat_statements: Avoid some locking during PGSS entry scans

A single PGSS entry's spinlock is used to be able to modify "counters"
without holding pgss->lock exclusively, as mentioned at the top of
pg_stat_statements.c and within pgssEntry.

Within a single pgssEntry, stats_since and minmax_stats_since are never
modified without holding pgss->lock exclusively, so there is no need to
hold an entry's spinlock when reading stats_since and
minmax_stats_since, as done when scanning all the PGSS entries for
function calls of pg_stat_statements().

This also restores the consistency between the code and the comments
about the entry's spinlock usage.  This change is a performance
improvement (it can be argued that this is a logic bug), so there is no
need for a backpatch.  This saves two instructions from being read while
holding an entry's spinlock.

Author: Karina Litskevich
Reviewed-by: Michael Paquier, wenhui qiu
Discussion: https://postgr.es/m/CACiT8ibhCmzbcOxM0v4pRLH3abk-95LPkt7_uC2JMP+miPjxsg@mail.gmail.com

5 months agojit: Remove obsolete LLVM version guard.
Thomas Munro [Sun, 10 Nov 2024 22:46:37 +0000 (11:46 +1300)]
jit: Remove obsolete LLVM version guard.

Commit 9044fc1d needed a version guard when back-patched, but it is
redundant in master as of commit 972c2cd2, and I accidentally left it
in there.

5 months agoFix sign-compare warnings in pg_iovec.h.
Nathan Bossart [Fri, 8 Nov 2024 22:11:08 +0000 (16:11 -0600)]
Fix sign-compare warnings in pg_iovec.h.

The code in question (pg_preadv() and pg_pwritev()) has been around
for a while, but commit 15c9ac3629 moved it to a header file.  If
third-party code that includes this header file is built with
-Wsign-compare on a system without preadv() or pwritev(), warnings
ensue.  This commit fixes said warnings by casting the result of
pg_pread()/pg_pwrite() to size_t, which should be safe because we
will have already checked for a negative value.

Author: Wolfgang Walther
Discussion: https://postgr.es/m/16989737-1aa8-48fd-8dfe-b7ada06509ab%40technowledgy.de
Backpatch-through: 17

5 months agoAssert consistency of currPage that ended scan.
Peter Geoghegan [Fri, 8 Nov 2024 21:34:41 +0000 (16:34 -0500)]
Assert consistency of currPage that ended scan.

When _bt_readnextpage is called with our nbtree parallel scan already
seized (i.e. when it is directly called by _bt_first), we never expect a
prior call to _bt_readpage for lastcurrblkno to already indicate that
the scan should end -- the _bt_first caller's blkno must always be read.
After all, the "prior" _bt_readpage call (the call for lastcurrblkno)
probably took place in some other backend (and it might not even have
finished by the time our backend reaches _bt_first/_bt_readnextpage).

Add a documenting assertion to the path where _bt_readnextpage ends the
parallel scan based on information about lastcurrblkno from so->currPos.
Assert that the most recent _bt_readpage call that set so->currPos is in
fact lastcurrblkno's _bt_readpage call.

Follow-up to bugfix commit b5ee4e52.

5 months agoMove check for USE_AVX512_POPCNT_WITH_RUNTIME_CHECK.
Nathan Bossart [Fri, 8 Nov 2024 20:25:28 +0000 (14:25 -0600)]
Move check for USE_AVX512_POPCNT_WITH_RUNTIME_CHECK.

Unlike TRY_POPCNT_FAST, which is defined in pg_bitutils.h, this
macro is defined in c.h (via pg_config.h), so we can check for it
earlier and avoid some unnecessary #includes on systems that lack
AVX-512 support.

Oversight in commit f78667bd91.

Discussion: https://postgr.es/m/Zy5K5Qmlb3Z4dsd4%40nathan

5 months agoImprove fix for not entering parallel mode when holding interrupts.
Tom Lane [Fri, 8 Nov 2024 18:42:01 +0000 (13:42 -0500)]
Improve fix for not entering parallel mode when holding interrupts.

Commit ac04aa84a put the shutoff for this into the planner, which is
not ideal because it doesn't prevent us from re-using a previously
made parallel plan.  Revert the planner change and instead put the
shutoff into InitializeParallelDSM, modeling it on the existing code
there for recovering from failure to allocate a DSM segment.

However, that code path is mostly untested, and testing a bit harder
showed there's at least one bug: ExecHashJoinReInitializeDSM is not
prepared for us to have skipped doing parallel DSM setup.  I also
thought the Assert in ReinitializeParallelWorkers is pretty
ill-advised, and replaced it with a silent Min() operation.

The existing test case added by ac04aa84a serves fine to test this
version of the fix, so no change needed there.

Patch by me, but thanks to Noah Misch for the core idea that we
could shut off worker creation when !INTERRUPTS_CAN_BE_PROCESSED.
Back-patch to v12, as ac04aa84a was.

Discussion: https://postgr.es/m/CAC-SaSzHUKT=vZJ8MPxYdC_URPfax+yoA1hKTcF4ROz_Q6z0_Q@mail.gmail.com

5 months agoAvoid nbtree parallel scan currPos confusion.
Peter Geoghegan [Fri, 8 Nov 2024 18:10:10 +0000 (13:10 -0500)]
Avoid nbtree parallel scan currPos confusion.

Commit 1bd4bc85, which refactored nbtree sibling link traversal, made
_bt_parallel_seize reset the scan's currPos so that things were
consistent with the state of a serial backend moving between pages.
This overlooked the fact that _bt_readnextpage relied on the existing
currPos state to decide when to end the scan -- even though it came from
before the scan was seized.  As a result of all this, parallel nbtree
scans could needlessly behave like full index scans.

To fix, teach _bt_readnextpage to explicitly allow the use of an already
read page's so->currPos when deciding whether to end the scan -- even
during parallel index scans (allow it consistently now).  This requires
moving _bt_readnextpage's seizure of the scan to earlier in its loop.
That way _bt_readnextpage either deals with the true so->currPos state,
or an initialized-by-_bt_parallel_seize currPos state set from when the
scan was seized.  Now _bt_steppage (the most important _bt_readnextpage
caller) takes the same uniform approach to setting up its call using
details taken from so->currPos -- regardless of whether the scan happens
to be parallel or serial.

The new loop structure in _bt_readnextpage is prone to getting confused
by P_NONE blknos set when the rightmost or leftmost page was reached.
We could avoid that by adding an explicit check, but that would be ugly.
Avoid this problem by teaching _bt_parallel_seize to end the parallel
scan instead of returning a P_NONE next block/blkno.  Doing things this
way was arguably a missed opportunity for commit 1bd4bc85.  It allows us
to remove a similar "blkno == P_NONE" check from _bt_first.

Oversight in commit 1bd4bc85, which refactored sibling link traversal
(as part of optimizing nbtree backward scan locking).

Author: Peter Geoghegan <[email protected]>
Reported-By: Masahiro Ikeda <[email protected]>
Diagnosed-By: Masahiro Ikeda <[email protected]>
Reviewed-By: Masahiro Ikeda <[email protected]>
Discussion: https://postgr.es/m/f8efb9c0f8d1a71b44fd7f8e42e49c25@oss.nttdata.com

5 months agoAdd pg_constraint rows for not-null constraints
Álvaro Herrera [Fri, 8 Nov 2024 12:28:48 +0000 (13:28 +0100)]
Add pg_constraint rows for not-null constraints

We now create contype='n' pg_constraint rows for not-null constraints on
user tables.  Only one such constraint is allowed for a column.

We propagate these constraints to other tables during operations such as
adding inheritance relationships, creating and attaching partitions and
creating tables LIKE other tables.  These related constraints mostly
follow the well-known rules of conislocal and coninhcount that we have
for CHECK constraints, with some adaptations: for example, as opposed to
CHECK constraints, we don't match not-null ones by name when descending
a hierarchy to alter or remove it, instead matching by the name of the
column that they apply to.  This means we don't require the constraint
names to be identical across a hierarchy.

The inheritance status of these constraints can be controlled: now we
can be sure that if a parent table has one, then all children will have
it as well.  They can optionally be marked NO INHERIT, and then children
are free not to have one.  (There's currently no support for altering a
NO INHERIT constraint into inheriting down the hierarchy, but that's a
desirable future feature.)

This also opens the door for having these constraints be marked NOT
VALID, as well as allowing UNIQUE+NOT NULL to be used for functional
dependency determination, as envisioned by commit e49ae8d3bc58.  It's
likely possible to allow DEFERRABLE constraints as followup work, as
well.

psql shows these constraints in \d+, though we may want to reconsider if
this turns out to be too noisy.  Earlier versions of this patch hid
constraints that were on the same columns of the primary key, but I'm
not sure that that's very useful.  If clutter is a problem, we might be
better off inventing a new \d++ command and not showing the constraints
in \d+.

For now, we omit these constraints on system catalog columns, because
they're unlikely to achieve anything.

The main difference to the previous attempt at this (b0e96f311985) is
that we now require that such a constraint always exists when a primary
key is in the column; we didn't require this previously which had a
number of unpalatable consequences.  With this requirement, the code is
easier to reason about.  For example:

- We no longer have "throwaway constraints" during pg_dump.  We needed
  those for the case where a table had a PK without a not-null
  underneath, to prevent a slow scan of the data during restore of the
  PK creation, which was particularly problematic for pg_upgrade.

- We no longer have to cope with attnotnull being set spuriously in
  case a primary key is dropped indirectly (e.g., via DROP COLUMN).

Some bits of code in this patch were authored by Jian He.

Author: Álvaro Herrera <[email protected]>
Author: Bernd Helmle <[email protected]>
Reviewed-by: 何建 (jian he) <[email protected]>
Reviewed-by: 王刚 (Tender Wang) <[email protected]>
Reviewed-by: Justin Pryzby <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: Dean Rasheed <[email protected]>
Discussion: https://postgr.es/m/202408310358[email protected]

5 months agoDisallow partitionwise join when collations don't match
Amit Langote [Fri, 8 Nov 2024 07:27:24 +0000 (16:27 +0900)]
Disallow partitionwise join when collations don't match

If the collation of any join key column doesn’t match the collation of
the corresponding partition key, partitionwise joins can yield incorrect
results. For example, rows that would match under the join key collation
might be located in different partitions due to the partitioning
collation. In such cases, a partitionwise join would yield different
results from a non-partitionwise join, so disallow it in such cases.

Reported-by: Tender Wang <[email protected]>
Author: Jian He <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Reviewed-by: Junwang Zhao <[email protected]>
Discussion: https://postgr.es/m/CAHewXNno_HKiQ6PqyLYfuqDtwp7KKHZiH1J7Pqyz0nr+PS2Dwg@mail.gmail.com
Backpatch-through: 12

5 months agoDisallow partitionwise grouping when collations don't match
Amit Langote [Fri, 8 Nov 2024 07:07:22 +0000 (16:07 +0900)]
Disallow partitionwise grouping when collations don't match

If the collation of any grouping column doesn’t match the collation of
the corresponding partition key, partitionwise grouping can yield
incorrect results. For example, rows that would be grouped under the
grouping collation may end up in different partitions under the
partitioning collation. In such cases, full partitionwise grouping
would produce results that differ from those without partitionwise
grouping, so disallowed that.

Partial partitionwise aggregation is still allowed, as the Finalize
step reconciles partition-level aggregates with grouping requirements
across all partitions, ensuring that the final output remains
consistent.

This commit also fixes group_by_has_partkey() by ensuring the
RelabelType node is stripped from grouping expressions when matching
them to partition key expressions to avoid false mismatches.

Bug: #18568
Reported-by: Webbo Han <[email protected]>
Author: Webbo Han <1105066510@qq.com>
Reviewed-by: Tender Wang <[email protected]>
Reviewed-by: Aleksander Alekseev <[email protected]>
Reviewed-by: Jian He <[email protected]>
Discussion: https://postgr.es/m/18568-2a9afb6b9f7e6ed3@postgresql.org
Discussion: https://postgr.es/m/[email protected]
Discussion: https://postgr.es/m/CAHewXNno_HKiQ6PqyLYfuqDtwp7KKHZiH1J7Pqyz0nr+PS2Dwg@mail.gmail.com
Backpatch-through: 12

5 months agoFix inconsistent RestrictInfo serial numbers
Richard Guo [Fri, 8 Nov 2024 02:21:11 +0000 (11:21 +0900)]
Fix inconsistent RestrictInfo serial numbers

When we generate multiple clones of the same qual condition to cope
with outer join identity 3, we need to ensure that all the clones get
the same serial number.  To achieve this, we reset the
root->last_rinfo_serial counter each time we produce RestrictInfo(s)
from the qual list (see deconstruct_distribute_oj_quals).  This
approach works only if we ensure that we are not changing the qual
list in any way that'd affect the number of RestrictInfos built from
it.

However, with b262ad440, an IS NULL qual on a NOT NULL column might
result in an additional constant-FALSE RestrictInfo.  And different
versions of the same qual clause can lead to different conclusions
about whether it can be reduced to constant-FALSE.  This would affect
the number of RestrictInfos built from the qual list for different
versions, causing inconsistent RestrictInfo serial numbers across
multiple clones of the same qual.  This inconsistency can confuse
users of these serial numbers, such as rebuild_joinclause_attr_needed,
and lead to planner errors such as "ERROR:  variable not found in
subplan target lists".

To fix, reset the root->last_rinfo_serial counter after generating the
additional constant-FALSE RestrictInfo.

Back-patch to v17 where the issue crept in.  In v17, I failed to make
a test case that would expose this bug, so no test case for v17.

Author: Richard Guo
Discussion: https://postgr.es/m/CAMbWs4-B6kafn+LmPuh-TYFwFyEm-vVj3Qqv7Yo-69CEv14rRg@mail.gmail.com

5 months agoFix __attribute__((target(...))) usage.
Nathan Bossart [Thu, 7 Nov 2024 21:27:32 +0000 (15:27 -0600)]
Fix __attribute__((target(...))) usage.

The commonly supported way to specify multiple target options is to
surround the entire list with quotes and to use a comma (with no
extra spaces) as the delimiter.

Oversight in commit f78667bd91.

Discussion: https://postgr.es/m/Zy0jya8nF8CPpv3B%40nathan

5 months agoUse __attribute__((target(...))) for AVX-512 support.
Nathan Bossart [Thu, 7 Nov 2024 19:58:43 +0000 (13:58 -0600)]
Use __attribute__((target(...))) for AVX-512 support.

Presently, we check for compiler support for the required
intrinsics both with and without extra compiler flags (e.g.,
-mxsave), and then depending on the results of those checks, we
pick which files to compile with which flags.  This is tedious and
complicated, and it results in unsustainable coding patterns such
as separate files for each portion of code may need to be built
with different compiler flags.

This commit introduces support for __attribute__((target(...))) and
uses it for the AVX-512 code.  This simplifies both the
configure-time checks and the build scripts, and it allows us to
place the functions that use the intrinsics in files that we
otherwise do not want to build with special CPU instructions.  We
are careful to avoid using __attribute__((target(...))) on
compilers that do not understand it, but we still perform the
configure-time checks in case the compiler allows using the
intrinsics without it (e.g., MSVC).

A similar change could likely be made for some of the CRC-32C code,
but that is left as a future exercise.

Suggested-by: Andres Freund
Reviewed-by: Raghuveer Devulapalli, Andres Freund
Discussion: https://postgr.es/m/20240731205254.vfpap7uxwmebqeaf%40awork3.anarazel.de

5 months agodoc: Reword ALTER TABLE ATTACH restriction on NO INHERIT constraints
Álvaro Herrera [Thu, 7 Nov 2024 13:06:24 +0000 (14:06 +0100)]
doc: Reword ALTER TABLE ATTACH restriction on NO INHERIT constraints

The previous wording is easy to read incorrectly; this change makes it
simpler, less ambiguous, and less prominent.

Backpatch to all live branches.

Reviewed-by: Amit Langote <[email protected]>
Discussion: https://postgr.es/m/202411051201[email protected]

5 months agoClarify a foreign key error message
Peter Eisentraut [Thu, 7 Nov 2024 10:13:06 +0000 (11:13 +0100)]
Clarify a foreign key error message

Clarify the message about type mismatch in foreign key definition to
indicate which column the referencing and which is the referenced one.

Reported-by: Jian He <[email protected]>
Discussion: https://www.postgresql.org/message-id/CACJufxEL82ao-aXOa=d_-Xip0bix-qdSyNc9fcWxOdkEZFko8w@mail.gmail.com

5 months agoRemove an obsolete comment in gistinsert()
Michael Paquier [Thu, 7 Nov 2024 06:13:50 +0000 (15:13 +0900)]
Remove an obsolete comment in gistinsert()

This is inconsistent since 1f7ef548ec2e where the definition of
gistFormTuple() has changed.

Author: Tender Wang
Reviewed-by: Aleksander Alekseev
Discussion: https://postgr.es/m/CAHewXNkjU95_HdioDVU=5yBq_Xt=GfBv=Od-0oKtiA006pWW7Q@mail.gmail.com

5 months agoReplicate generated columns when 'publish_generated_columns' is set.
Amit Kapila [Thu, 7 Nov 2024 03:28:49 +0000 (08:58 +0530)]
Replicate generated columns when 'publish_generated_columns' is set.

This patch builds on the work done in commit 745217a051 by enabling the
replication of generated columns alongside regular column changes through
a new publication parameter: publish_generated_columns.

Example usage:
CREATE PUBLICATION pub1 FOR TABLE tab_gencol WITH (publish_generated_columns = true);

The column list takes precedence. If the generated columns are specified
in the column list, they will be replicated even if
'publish_generated_columns' is set to false. Conversely, if generated
columns are not included in the column list (assuming the user specifies a
column list), they will not be replicated even if
'publish_generated_columns' is true.

Author: Vignesh C, Shubham Khanna
Reviewed-by: Peter Smith, Amit Kapila, Hayato Kuroda, Shlok Kyal, Ajin Cherian, Hou Zhijie, Masahiko Sawada
Discussion: https://postgr.es/m/B80D17B2-2C8E-4C7D-87F2-E5B4BE3C069E@gmail.com

5 months agoImprove handling of empty query results in BackgroundPsql::query()
Michael Paquier [Thu, 7 Nov 2024 03:11:27 +0000 (12:11 +0900)]
Improve handling of empty query results in BackgroundPsql::query()

A newline is not added at the end of an empty query result, causing the
banner of the hardcoded \echo to not be discarded.  This would reflect
on scripts that expect an empty result by showing the "QUERY_SEPARATOR"
in the output returned back to the caller, which was confusing.

This commit changes BackgroundPsql::query() so as empty results are able
to work correctly, making the first newline before the banner optional,
bringing more flexibility.

Note that this change affects 037_invalid_database.pl, where three
queries generated an empty result, with the script relying on the data
from the hardcoded banner to exist in the expected output.  These
queries are changed to use query_safe(), leading to a simpler script.

The author has also proposed a test in a different patch where empty
results would exist when using BackgroundPsql.

Author: Jacob Champion
Reviewed-by: Andrew Dunstan, Michael Paquier
Discussion: https://postgr.es/m/CAOYmi+=60deN20WDyCoHCiecgivJxr=98s7s7-C8SkXwrCfHXg@mail.gmail.com

5 months agoFind invalid databases during upgrade check stage
Daniel Gustafsson [Wed, 6 Nov 2024 14:40:52 +0000 (15:40 +0100)]
Find invalid databases during upgrade check stage

Before continuing with the check start by checking that all databases
allow connections to avoid a hard fail without proper error reporting.

Inspired by a larger patch by Thomas Krennwallner.

Discussion: https://postgr.es/m/f9315bf0-e03e-4490-9f0d-5b6f7a6d9908@postsubmeta.net

5 months agoRemove unused variable
Daniel Gustafsson [Wed, 6 Nov 2024 14:11:14 +0000 (15:11 +0100)]
Remove unused variable

The low variable has not been used since it was added in d168b666823
and can be safely removed.  The variable is present in the Sedgewick
paper "Analysis of Shellsort and Related Algorithms" as a parameter
to the shellsort function, but our implementation does not use it.
Remove to improve readability of the code.

Author: Koki Nakamura <[email protected]>
Discussion: https://postgr.es/m/8aeb7b3eda53ca4c65fbacf8f43628fb@oss.nttdata.com

5 months agodoc: Remove event trigger firing matrix
Peter Eisentraut [Wed, 6 Nov 2024 12:42:27 +0000 (13:42 +0100)]
doc: Remove event trigger firing matrix

This is difficult to maintain accurately, and it was probably already
somewhat incorrect, especially in the sql_drop and table_rewrite
categories.

The prior section already documented which DDL commands are *not*
supported (which was also slightly outdated), so let's expand that a
bit and just rely on that instead of listing out each command in full
detail.

Reviewed-by: Daniel Gustafsson <[email protected]>
Reviewed-by: Michael Paquier <[email protected]>
Reviewed-by: Jian He <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CACJufxE_UAuxcM08BW5oVsg34v0cFWoEt8yBa5xSAoKLmL6LTQ%40mail.gmail.com

5 months agoMonkey-patch LLVM code to fix ARM relocation bug.
Thomas Munro [Wed, 6 Nov 2024 09:04:44 +0000 (22:04 +1300)]
Monkey-patch LLVM code to fix ARM relocation bug.

Supply a new memory manager for RuntimeDyld, to avoid crashes in
generated code caused by memory placement that can overflow a 32 bit
data type.  This is a drop-in replacement for the
llvm::SectionMemoryManager class in the LLVM library, with Michael
Smith's proposed fix from
https://www.github.com/llvm/llvm-project/pull/71968.

We hereby slurp it into our own source tree, after moving into a new
namespace llvm::backport and making some minor adjustments so that it
can be compiled with older LLVM versions as far back as 12.  It's harder
to make it work on even older LLVM versions, but it doesn't seem likely
that people are really using them so that is not investigated for now.

The problem could also be addressed by switching to JITLink instead of
RuntimeDyld, and that is the LLVM project's recommended solution as
the latter is about to be deprecated.  We'll have to do that soon enough
anyway, and then when the LLVM version support window advances far
enough in a few years we'll be able to delete this code.  Unfortunately
that wouldn't be enough for PostgreSQL today: in most relevant versions
of LLVM, JITLink is missing or incomplete.

Several other projects have already back-ported this fix into their fork
of LLVM, which is a vote of confidence despite the lack of commit into
LLVM as of today.  We don't have our own copy of LLVM so we can't do
exactly what they've done; instead we have a copy of the whole patched
class so we can pass an instance of it to RuntimeDyld.

The LLVM project hasn't chosen to commit the fix yet, and even if it
did, it wouldn't be back-ported into the releases of LLVM that most of
our users care about, so there is not much point in waiting any longer
for that.  If they make further changes and commit it to LLVM 19 or 20,
we'll still need this for older versions, but we may want to
resynchronize our copy and update some comments.

The changes that we've had to make to our copy can be seen by diffing
our SectionMemoryManager.{h,cpp} files against the ones in the tree of
the pull request.  Per the LLVM project's license requirements, a copy
is in SectionMemoryManager.LICENSE.

This should fix the spate of crash reports we've been receiving lately
from users on large memory ARM systems.

Back-patch to all supported releases.

Co-authored-by: Thomas Munro <[email protected]>
Co-authored-by: Anthonin Bonnefoy <[email protected]>
Reviewed-by: Anthonin Bonnefoy <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]> (license aspects)
Reported-by: Anthonin Bonnefoy <[email protected]>
Discussion: https://postgr.es/m/CAO6_Xqr63qj%3DSx7HY6ZiiQ6R_JbX%2B-p6sTPwDYwTWZjUmjsYBg%40mail.gmail.com

5 months agoRemove unused #include's from bin .c files
Peter Eisentraut [Wed, 6 Nov 2024 10:06:58 +0000 (11:06 +0100)]
Remove unused #include's from bin .c files

as determined by IWYU

Similar to commit dbbca2cf299, but for bin and some related files.

Discussion: https://www.postgresql.org/message-id/flat/0df1d5b1-8ca8-4f84-93be-121081bde049%40eisentraut.org

5 months agoExtend Cluster.pm's background_psql() to be able to start asynchronously
Michael Paquier [Wed, 6 Nov 2024 06:31:14 +0000 (15:31 +0900)]
Extend Cluster.pm's background_psql() to be able to start asynchronously

This commit extends the constructor routine of BackgroundPsql.pm with a
new "wait" parameter.  If set to 0, the routine returns without waiting
for psql to start, ready to consume input.

background_psql() in Cluster.pm gains the same "wait" parameter.  The
default behavior is still to wait for psql to start.  It becomes now
possible to not wait, giving to TAP scripts the possibility to perform
actions between a BackgroundPsql startup and its wait_connect() call.

Author: Jacob Champion
Discussion: https://postgr.es/m/CAOYmi+=60deN20WDyCoHCiecgivJxr=98s7s7-C8SkXwrCfHXg@mail.gmail.com

5 months agoFix hypothetical bug in ExprState building for hashing
David Rowley [Tue, 5 Nov 2024 20:16:00 +0000 (09:16 +1300)]
Fix hypothetical bug in ExprState building for hashing

adf97c156 gave ExprStates the ability to hash expressions and return a
single hash value.  That commit supports seeding the hash value with an
initial value to have that blended into the final hash value.

Here we fix a hypothetical bug where if there are zero expressions to
hash, the initial value is stored in the wrong location.  The existing
code stored the initial value in an intermediate location expecting that
when the expressions were hashed that those steps would store the final
hash value in the ExprState.resvalue field.  However, that wouldn't happen
when there are zero expressions to hash.  The correct thing to do instead
is to have a special case for zero expressions and when we hit that case,
store the initial value directly in the ExprState.resvalue.  The reason
that this is a hypothetical bug is that no code currently calls
ExecBuildHash32Expr passing a non-zero initial value.

Discussion: https://postgr.es/m/CAApHDvpMAL_zxbMRr1LOex3O7Y7R7ZN2i8iUFLQhqQiJMAg3qw@mail.gmail.com

5 months agoAdd a Git .mailmap file
Daniel Gustafsson [Tue, 5 Nov 2024 12:56:02 +0000 (13:56 +0100)]
Add a Git .mailmap file

This adds a Git .mailmap to unify spellings of committer names.

Discussion: https://postgr.es/m/76773029-A7AD-4BAF-AFC2-E511D26E866D@yesql.se

5 months agoSilence meson warning about PG_TEST_EXTRA in src/Makefile.global.in
Heikki Linnakangas [Tue, 5 Nov 2024 10:25:25 +0000 (12:25 +0200)]
Silence meson warning about PG_TEST_EXTRA in src/Makefile.global.in

Commit 99b937a44f introduced this warning when you run "meson setup":

    Configuring Makefile.global using configuration
    ../src/meson.build:31: WARNING: The variable(s) 'PG_TEST_EXTRA' in the input file 'src/Makefile.global.in' are not present in the given configuration data.

To fix, add PG_TEST_EXTRA to the list of variables that are not needed
in the makefiles generated by meson. In meson builds, the makefiles
are only used for PGXS, not for building or testing the server itself.

Reported-by: Peter Eisentraut
Discussion: https://www.postgresql.org/message-id/5c380997-e270-425a-9542-e4ef36a285de@eisentraut.org

5 months agoClear padding of PgStat_HashKey when handling pgstats entries
Michael Paquier [Tue, 5 Nov 2024 00:39:43 +0000 (09:39 +0900)]
Clear padding of PgStat_HashKey when handling pgstats entries

PgStat_HashKey is currently initialized in a way that could result in
random data if the structure has any padding bytes.  The structure
has no padding bytes currently, fortunately, but it could become a
problem should the structure change at some point in the future.

The code is changed to use some memset(0) so as any padding would be
handled properly, as it would be surprising to see random failures in
the pgstats entry lookups.  PgStat_HashKey is a structure internal to
pgstats, and an ABI change could be possible in the scope of a bug fix,
so backpatch down to 15 where this has been introduced.

Author: Bertrand Drouvot
Reviewed-by: Jelte Fennema-Nio, Michael Paquier
Discussion: https://postgr.es/m/[email protected]
Backpatch-through: 15

5 months agoUse portable diff options in pg_bsd_indent's regression test.
Tom Lane [Mon, 4 Nov 2024 23:08:48 +0000 (18:08 -0500)]
Use portable diff options in pg_bsd_indent's regression test.

We had been using "diff -upd", which evidently works for most people,
but Solaris's diff doesn't like it.  (We'd not noticed because the
Solaris buildfarm animals weren't running this test until they were
upgraded to the latest buildfarm client script.)  Change to "diff -U3"
which is what pg_regress has used for ages.

Per buildfarm (and off-list discussion with Noah Misch).

Back-patch to v16 where this test was added.  In v16,
also back-patch the relevant part of 628c1d1f2 so that
the test script looks about the same in all branches.

5 months agoRevert pg_wal_replay_wait() stored procedure
Alexander Korotkov [Mon, 4 Nov 2024 20:43:08 +0000 (22:43 +0200)]
Revert pg_wal_replay_wait() stored procedure

This commit reverts 3c5db1d6b0, and subsequent improvements and fixes
including 8036d73ae3867d396ccd3ac3ec580c0868d7ae7085b98b8d5a,
2520226c95014f9f34d2e658038772e1555645d75035172e4a6cfebfe88b,
73da6b8d1b, and e546989a26.

The reason for reverting is a set of remaining issues.  Most notably, the
stored procedure appears to need more effort than the utility statement
to turn the backend into a "snapshot-less" state.  This makes an approach
to use stored procedures questionable.

Catversion is bumped.

Discussion: https://postgr.es/m/Zyhj2anOPRKtb0xW%40paquier.xyz

5 months agodoc: use more accurate URL for bug reporting
Bruce Momjian [Mon, 4 Nov 2024 20:07:38 +0000 (15:07 -0500)]
doc:  use more accurate URL for bug reporting

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

Backpatch-through: master

5 months agopg_basebackup, pg_receivewal: fix failure to find password in ~/.pgpass.
Tom Lane [Mon, 4 Nov 2024 19:36:04 +0000 (14:36 -0500)]
pg_basebackup, pg_receivewal: fix failure to find password in ~/.pgpass.

Sloppy refactoring in commit cca97ce6a caused these programs
to pass dbname = NULL to libpq if there was no "--dbname" switch
on the command line, where before "replication" would be passed.
This didn't break things completely, because the source server doesn't
care about the dbname specified for a physical replication connection.
However, it did cause libpq to fail to match a ~/.pgpass entry that
has "replication" in the dbname field.  Restore the previous behavior
of passing "replication".

Also, closer inspection shows that if you do specify a dbname
in the connection string, that is what will be matched to ~/.pgpass,
not "replication".  This was the pre-existing behavior so we should
not change it, but the SGML docs were pretty misleading about it.
Improve that.

Per bug #18685 from Toshi Harada.  Back-patch to v17 where the
error crept in.

Discussion: https://postgr.es/m/18685-fee2dd142b9688f1@postgresql.org
Discussion: https://postgr.es/m/2702546.1730740456@sss.pgh.pa.us

5 months agodoc: remove check of SVG files, since they are derived
Bruce Momjian [Mon, 4 Nov 2024 19:10:11 +0000 (14:10 -0500)]
doc:  remove check of SVG files, since they are derived

revert of change from commit 641a5b7a144

Reported-by: Peter Eisentraut
Discussion: https://postgr.es/m/2c5dd601-b245-4092-9c27-6d1ad51609df@eisentraut.org

Backpatch-through: master

5 months agopg_dump: provide a stable sort order for rules.
Tom Lane [Mon, 4 Nov 2024 18:30:30 +0000 (13:30 -0500)]
pg_dump: provide a stable sort order for rules.

Previously, we sorted rules by schema name and then rule name;
if that wasn't unique, we sorted by rule OID.  This can be
problematic for comparing dumps from databases with different
histories, especially since certain rule names like "_RETURN"
are very common.  Let's make the sort key schema name, rule name,
table name, which should be unique.  (This is the same behavior
we've long used for triggers and RLS policies.)

Andreas Karlsson

Discussion: https://postgr.es/m/b4e468d8-0cd6-42e6-ac8a-1d6afa6e0cf1@proxel.se

5 months agoFix typo in comment of gistdoinsert().
Masahiko Sawada [Mon, 4 Nov 2024 18:21:59 +0000 (10:21 -0800)]
Fix typo in comment of gistdoinsert().

Author: Tender Wang
Reviewed-by: Masahiko Sawada
Discussion: https://postgr.es/m/CAHewXN%3D3sH2sNw4nC3QGCEVw1Lftmw9m5y1Xje0bXK6ApDrsPQ%40mail.gmail.com

5 months agoFix obsolete _bt_first comments.
Peter Geoghegan [Mon, 4 Nov 2024 17:43:54 +0000 (12:43 -0500)]
Fix obsolete _bt_first comments.

_bt_first doesn't necessarily hold onto a buffer pin on success exit.
Fix header comments that claimed that we'll always hold onto a pin.

Oversight in commit 2ed5b87f96.

5 months agodocs: Consistently use <optional> to indicate optional parameters
Heikki Linnakangas [Mon, 4 Nov 2024 16:28:40 +0000 (18:28 +0200)]
docs: Consistently use <optional> to indicate optional parameters

Some functions were using square brackets instead, replace them all
with <optional>.

Author: Dagfinn Ilmari Mannsåker <[email protected]>
Reviewed-by: jian he <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CACJufxFfUbSph5UUSsZbL4SitbuPuW%[email protected]

5 months agonbtree: Remove useless 'strat' local variable.
Peter Geoghegan [Mon, 4 Nov 2024 16:04:30 +0000 (11:04 -0500)]
nbtree: Remove useless 'strat' local variable.

Remove a local variable that was used to avoid overwriting strat_total
with the = operator strategy when a >= operator strategy key was already
included in the initial positioning/insertion scan keys by _bt_first
(for backwards scans it would have to be a <= key that was included).
_bt_first's strat_total local variable now simply tracks the operator
strategy of the final scan key that was included in the scan's insertion
scan key (barring the case where the !used_all_subkeys row compare path
adjusts strat_total in its own way).

_bt_first already treated >= keys (or <= keys) as = keys for initial
positioning purposes.  There is no good reason to remember that that was
what happened; no later _bt_first step cares about the distinction.
Note, in particular, that the insertion scan key's 'nextkey' and
'backward' fields will be initialized the same way regardless.

Author: Peter Geoghegan <[email protected]>
Reviewed-By: Tomas Vondra <[email protected]>
Discussion: https://postgr.es/m/CAH2-Wz=PKR6rB7qbx+Vnd7eqeB5VTcrW=iJvAsTsKbdG+kW_UA@mail.gmail.com

5 months agoSplit ProcSleep function into JoinWaitQueue and ProcSleep
Heikki Linnakangas [Mon, 4 Nov 2024 15:59:24 +0000 (17:59 +0200)]
Split ProcSleep function into JoinWaitQueue and ProcSleep

Split ProcSleep into two functions: JoinWaitQueue and ProcSleep.
JoinWaitQueue is called while holding the partition lock, and inserts
the current process to the wait queue, while ProcSleep() does the
actual sleeping. ProcSleep() is now called without holding the
partition lock, and it no longer re-acquires the partition lock before
returning. That makes the wakeup a little cheaper. Once upon a time,
re-acquiring the partition lock was needed to prevent a signal handler
from longjmping out at a bad time, but these days our signal handlers
just set flags, and longjmping can only happen at points where we
explicitly run CHECK_FOR_INTERRUPTS().

If JoinWaitQueue detects an "early deadlock" before even joining the
wait queue, it returns without changing the shared lock entry, leaving
the cleanup of the shared lock entry to the caller. This makes the
handling of an early deadlock the same as the dontWait=true case.

One small user-visible side-effect of this refactoring is that we now
only set the 'ps' title to say "waiting" when we actually enter the
sleep, not when the lock is skipped because dontWait=true, or when a
deadlock is detected early before entering the sleep.

This eliminates the 'lockAwaited' global variable in proc.c, which was
largely redundant with 'awaitedLock' in lock.c

Note: Updating the local lock table is now the caller's responsibility.
JoinWaitQueue and ProcSleep are now only responsible for modifying the
shared state. Seems a little nicer that way.

Based on Thomas Munro's earlier patch and observation that ProcSleep
doesn't really need to re-acquire the partition lock.

Reviewed-by: Maxim Orlov
Discussion: https://www.postgresql.org/message-id/7c2090cd-a72a-4e34-afaa-6dd2ef31440e@iki.fi

5 months agopg_combinebackup: Error if incremental file exists in full backup.
Robert Haas [Mon, 4 Nov 2024 15:11:05 +0000 (10:11 -0500)]
pg_combinebackup: Error if incremental file exists in full backup.

Suppose that you run a command like "pg_combinebackup b1 b2 -o output",
but both b1 and b2 contain an INCREMENTAL.$something file in a directory
that is expected to contain relation files. This is an error, but the
previous code would not detect the problem and instead write a garbage
full file named $something to the output directory. This commit adds
code to detect the error and a test case to verify the behavior.

It's difficult to imagine that this will ever happen unless someone
is intentionally trying to break incremental backup, but per discussion,
let's consider that the lack of adequate sanity checking in this area is
a bug and back-patch to v17, where incremental backup was introduced.

Patch by me, reviewed by Bertrand Drouvot and Amul Sul.

Discussion: http://postgr.es/m/CA+TgmoaD7dBYPqe7kMtO0dyto7rd0rUh7joh=JPUSaFszKY6Pg@mail.gmail.com

5 months agopg_combinebackup: When reconstructing, avoid double slash in filename.
Robert Haas [Mon, 4 Nov 2024 14:55:02 +0000 (09:55 -0500)]
pg_combinebackup: When reconstructing, avoid double slash in filename.

This function is always called with a relative_path that ends in a
slash, so there's no need to insert a second one. So, don't. Instead,
add an assertion to verify that nothing gets broken in the future, and
adjust the comments.

While this is not a critical bug, the duplicate slash is visible in
error messages, which could create confusion, so back-patch to v17.
This is also better in that it keeps the code consistent across
branches.

Patch by me, reviewed by Bertrand Drouvot and Amul Sul.

Discussion: http://postgr.es/m/CA+TgmoaD7dBYPqe7kMtO0dyto7rd0rUh7joh=JPUSaFszKY6Pg@mail.gmail.com

5 months agodoc: fix typo in mvcc clarification in commit 2fa255ce9b9
Bruce Momjian [Mon, 4 Nov 2024 14:24:36 +0000 (09:24 -0500)]
doc:  fix typo in mvcc clarification in commit 2fa255ce9b9

Reported-by: Erik Rijkers (private email)
Backpatch-through: master

5 months agoMove TRACE calls into WaitOnLock()
Heikki Linnakangas [Mon, 4 Nov 2024 14:21:01 +0000 (16:21 +0200)]
Move TRACE calls into WaitOnLock()

LockAcquire is a long and complex function. Pushing more stuff to its
subroutines makes it a little more manageable.

Reviewed-by: Maxim Orlov
Discussion: https://www.postgresql.org/message-id/7c2090cd-a72a-4e34-afaa-6dd2ef31440e@iki.fi

5 months agoSet MyProc->heldLocks in ProcSleep
Heikki Linnakangas [Mon, 4 Nov 2024 14:20:57 +0000 (16:20 +0200)]
Set MyProc->heldLocks in ProcSleep

Previously, ProcSleep()'s caller was responsible for setting
MyProc->heldLocks, and we had comments to remind about that.  But it
seems simpler to make ProcSleep() itself responsible for it.
ProcSleep() already set the other info about the lock its waiting for
(waitLock, waitProcLock and waitLockMode), so it is natural for it to
set heldLocks too.

Reviewed-by: Maxim Orlov
Discussion: https://www.postgresql.org/message-id/7c2090cd-a72a-4e34-afaa-6dd2ef31440e@iki.fi

5 months agoClarify nbtree parallel scan _bt_endpoint contract.
Peter Geoghegan [Mon, 4 Nov 2024 14:05:59 +0000 (09:05 -0500)]
Clarify nbtree parallel scan _bt_endpoint contract.

_bt_endpoint is a helper function for _bt_first that's called whenever
no useful insertion scan key can be used, and we need to lock and read
either the leftmost or rightmost leaf page in the index.  Simplify and
document its preconditions, relieving its _bt_first caller from having
to end the parallel scan when it returns false.

Also stop unnecessarily invalidating the current scan position in nearby
code in both _bt_first and _bt_endpoint.  This seems to have been
copy-pasted from _bt_readnextpage, where invalidating the scan's current
position really is necessary.

Follow-up to the refactoring work in commit 1bd4bc85.

5 months agoFix comment in LockReleaseAll() on when locallock->nLock can be zero
Heikki Linnakangas [Mon, 4 Nov 2024 13:31:46 +0000 (15:31 +0200)]
Fix comment in LockReleaseAll() on when locallock->nLock can be zero

We reach this case also e.g. when a deadlock is detected, not only
when we run out of memory.

Reviewed-by: Maxim Orlov
Discussion: https://www.postgresql.org/message-id/7c2090cd-a72a-4e34-afaa-6dd2ef31440e@iki.fi

5 months agoAdd PG_TEST_EXTRA configure option to the Make builds
Heikki Linnakangas [Mon, 4 Nov 2024 12:09:38 +0000 (14:09 +0200)]
Add PG_TEST_EXTRA configure option to the Make builds

The Meson builds have PG_TEST_EXTRA as a configure-time variable,
which was not available in the Make builds. To ensure both build
systems are in sync, PG_TEST_EXTRA is now added as a configure-time
variable. It can be set like this:

    ./configure PG_TEST_EXTRA="kerberos, ssl, ..."

Note that to preserve the old behavior, this configure-time variable
is overridden by the PG_TEST_EXTRA environment variable when you run
the tests.

Author: Jacob Champion
Reviewed by: Ashutosh Bapat, Nazir Bilal Yavuz

5 months agoMake PG_TEST_EXTRA env var override the "meson setup" option
Heikki Linnakangas [Mon, 4 Nov 2024 12:09:25 +0000 (14:09 +0200)]
Make PG_TEST_EXTRA env var override the "meson setup" option

"meson test" used to ignore the PG_TEST_EXTRA environment variable,
which meant that in order to run additional tests, you had to run
"meson setup -DPG_TEST_EXTRA=...". That's somewhat expensive, and not
consistent with autoconf builds. Allow PG_TEST_EXTRA environment
variable to override the setup-time option at run time, so that you
can do "PG_TEST_EXTRA=... meson test".

To implement this, the configuration time value is passed as an extra
"--pg-test-extra" argument to testwrap instead of adding it to the
test environment. If the environment variable is set at the time of
running test, testwrap uses the value from the environment variable
and ignores the --pg-test-extra option.

Now that "meson test" obeys the environment variable, we can remove it
from the "meson setup" steps in the CI script. It will now be picked
up from the environment variable like with "make check".

Author: Nazir Bilal Yavuzk, Ashutosh Bapat
Reviewed-by: Ashutosh Bapat with inputs from Tom Lane and Andrew Dunstan
5 months agoDoc: Update the behavior of generated columns in Logical Replication.
Amit Kapila [Mon, 4 Nov 2024 04:09:30 +0000 (09:39 +0530)]
Doc: Update the behavior of generated columns in Logical Replication.

Commit 745217a051 misses updating the new behavior of generated columns in
logical replication at a few places.

Reported-by: Peter Smith, Ajin Cherian
Author: Vignesh C
Discussion: https://postgr.es/m/CALDaNm2JOO7szz9+uaQbjmgZOfzbM_9tAQdFF8H5BjkQeaJs0A@mail.gmail.com
Discussion: https://postgr.es/m/B80D17B2-2C8E-4C7D-87F2-E5B4BE3C069E@gmail.com

5 months agoAdd missing newlines at the end of two SQL files
Michael Paquier [Sun, 3 Nov 2024 10:42:51 +0000 (19:42 +0900)]
Add missing newlines at the end of two SQL files

arrays.sql was already missing it before 49d6c7d8daba, and I have just
noticed it thanks to this commit.  The second one in test_slru has been
introduced by 768a9fd5535f.

5 months agoSuppress new "may be used uninitialized" warning.
Noah Misch [Sun, 3 Nov 2024 02:42:52 +0000 (19:42 -0700)]
Suppress new "may be used uninitialized" warning.

Buildfarm member mamba fails to deduce that the function never uses this
variable without initializing it.  Back-patch to v12, like commit
b412f402d1e020c5dac94f3bf4a005db69519b99.

5 months agoFix inplace update buffer self-deadlock.
Noah Misch [Sat, 2 Nov 2024 16:04:56 +0000 (09:04 -0700)]
Fix inplace update buffer self-deadlock.

A CacheInvalidateHeapTuple* callee might call
CatalogCacheInitializeCache(), which needs a relcache entry.  Acquiring
a valid relcache entry might scan pg_class.  Hence, to prevent
undetected LWLock self-deadlock, CacheInvalidateHeapTuple* callers must
not hold BUFFER_LOCK_EXCLUSIVE on buffers of pg_class.  Move the
CacheInvalidateHeapTupleInplace() before the BUFFER_LOCK_EXCLUSIVE.  No
back-patch, since I've reverted commit
243e9b40f1b2dd09d6e5bf91ebf6e822a2cd3704 from non-master branches.

Reported by Alexander Lakhin.  Reviewed by Alexander Lakhin.

Discussion: https://postgr.es/m/10ec0bc3-5933-1189-6bb8-5dec4114558e@gmail.com

5 months agoMove I/O before the index_update_stats() buffer lock region.
Noah Misch [Sat, 2 Nov 2024 16:04:55 +0000 (09:04 -0700)]
Move I/O before the index_update_stats() buffer lock region.

Commit a07e03fd8fa7daf4d1356f7cb501ffe784ea6257 enlarged the work done
here under the pg_class heap buffer lock.  Two preexisting actions are
best done before holding that lock.  Both RelationGetNumberOfBlocks()
and visibilitymap_count() do I/O, and the latter might exclusive-lock a
visibility map buffer.  Moving these reduces contention and risk of
undetected LWLock deadlock.  Back-patch to v12, like that commit.

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

5 months agodoc: clarify text around MVCC example query
Bruce Momjian [Fri, 1 Nov 2024 20:38:16 +0000 (16:38 -0400)]
doc:   clarify text around MVCC example query

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

Backpatch-through: master

5 months agodoc: remove useless MERGE example
Bruce Momjian [Fri, 1 Nov 2024 20:20:27 +0000 (16:20 -0400)]
doc:  remove useless MERGE example

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

Backpatch-through: master

5 months agodoc: improve tablespace example query and link to helper funcs.
Bruce Momjian [Fri, 1 Nov 2024 19:54:16 +0000 (15:54 -0400)]
doc:  improve tablespace example query and link to helper funcs.

Reported-by: Agustín
Discussion: https://postgr.es/m/172609721070.1128084.6724666076293146476@wrigleys.postgresql.org

Backpatch-through: master

5 months agodoc: fix ALTER DOMAIN domain_constraint to spell out options
Bruce Momjian [Fri, 1 Nov 2024 17:54:28 +0000 (13:54 -0400)]
doc:  fix ALTER DOMAIN domain_constraint to spell out options

It used to refer to CREATE DOMAIN, but CREATE DOMAIN allows NULL, while
ALTER DOMAIN does not.

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

Backpatch-through: 12

5 months agodoc: explain how the home directory is found on Unix-like syst.
Bruce Momjian [Fri, 1 Nov 2024 17:32:21 +0000 (13:32 -0400)]
doc:  explain how the home directory is found on Unix-like syst.

Done for libpq, postgres-fdw, and psql.

Reported-by: [email protected]
Discussion: https://postgr.es/m/CAKFQuwZ-T-zsVM7gApS9-XU9vGxC7Oa-UyRQPVcJFagNU=AjOw@mail.gmail.com

Backpatch-through: master

5 months agodoc: Add link to listen_addresses as cause of connection failure
Bruce Momjian [Fri, 1 Nov 2024 17:14:46 +0000 (13:14 -0400)]
doc: Add link to listen_addresses as cause of connection failure

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

Backpatch-through: master

5 months agoUpdate contrib/sepgsql regression tests for commit 89e51abcb.
Tom Lane [Fri, 1 Nov 2024 16:49:43 +0000 (12:49 -0400)]
Update contrib/sepgsql regression tests for commit 89e51abcb.

Oversight revealed by buildfarm.

5 months agodoc: improve build for non-Latin1 characters
Bruce Momjian [Fri, 1 Nov 2024 16:46:51 +0000 (12:46 -0400)]
doc:  improve build for non-Latin1 characters

Add README.non-ASCII to explain non-ASCII doc behavior; some text moved
from release.sgml.

Change UTF8 SGML characters to use HTML entities.

Remove unnecessary UTF8 spaces.

Add SVG file check for check-nbsp target.

Add dummy 'pdf' Makefile target.

Reported-by: Yugo Nagata
Discussion: https://postgr.es/m/20241011114122.c90f8a871462da36f2e2afeb@sraoss.co.jp

Backpatch-through: master

5 months agoClarify nbtree array preprocessing comment.
Peter Geoghegan [Fri, 1 Nov 2024 15:43:24 +0000 (11:43 -0400)]
Clarify nbtree array preprocessing comment.

Oversight in commit 5bf748b8.

5 months agodoc: remove mention of ActiveState for Perl and Tcl on Windows
Bruce Momjian [Fri, 1 Nov 2024 15:30:54 +0000 (11:30 -0400)]
doc:  remove mention of ActiveState for Perl and Tcl on Windows

Replace with Strawberry Perl and Magicsplat Tcl.

Reported-by: Yasir Hussain
Discussion: https://postgr.es/m/CAA9OW9fAAM_WDYYpAquqF6j1hmfRMzHPsFkRfP5E6oSfkF=dMA@mail.gmail.com

Backpatch-through: 12

5 months agoRename two functions that wake up other processes
Heikki Linnakangas [Fri, 1 Nov 2024 11:47:24 +0000 (13:47 +0200)]
Rename two functions that wake up other processes

Instead of talking about setting latches, which is a pretty low-level
mechanism, emphasize that they wake up other processes.

This is in preparation for replacing Latches with a new abstraction.
That's still work in progress, but this seems a little tidier anyway,
so let's get this refactoring out of the way already.

Discussion: https://www.postgresql.org/message-id/391abe21-413e-4d91-a650-b663af49500c%40iki.fi

5 months agoUse ProcNumbers instead of direct Latch pointers to address other procs
Heikki Linnakangas [Fri, 1 Nov 2024 11:47:20 +0000 (13:47 +0200)]
Use ProcNumbers instead of direct Latch pointers to address other procs

This is in preparation for replacing Latches with a new abstraction.
That's still work in progress, but this seems a little tidier anyway,
so let's get this refactoring out of the way already.

Discussion: https://www.postgresql.org/message-id/391abe21-413e-4d91-a650-b663af49500c%40iki.fi

5 months agoRemove use of pg_memory_is_all_zeros() in bufpage.c
Michael Paquier [Fri, 1 Nov 2024 08:05:36 +0000 (17:05 +0900)]
Remove use of pg_memory_is_all_zeros() in bufpage.c

After a closer lookup, this makes the all-zero check of the page more
expensive, so let's remove the new function call in bufpage.c.  The
maths of the check were also incorrect, checking that the page was full
of zeros only for the first 1kB.

This brings back the code to the state it was at 49d6c7d8daba.

Per discussion with David Rowley and Bertrand Drouvot.

Discussion: https://postgr.es/m/CAApHDvrXzPAr3FxoBuB7b3D-okNoNA2jxLun1rW8Yw5wkbqusw@mail.gmail.com

5 months agoAdd pg_memory_is_all_zeros() in memutils.h
Michael Paquier [Fri, 1 Nov 2024 02:35:46 +0000 (11:35 +0900)]
Add pg_memory_is_all_zeros() in memutils.h

This new function tests if a memory region starting at a given location
for a defined length is made only of zeroes.  This unifies in a single
path the all-zero checks that were happening in a couple of places of
the backend code:
- For pgstats entries of relation, checkpointer and bgwriter, where
some "all_zeroes" variables were previously used with memcpy().
- For all-zero buffer pages in PageIsVerifiedExtended().

This new function uses the same forward scan as the check for all-zero
buffer pages, applying it to the three pgstats paths mentioned above.

Author: Bertrand Drouvot
Reviewed-by: Peter Eisentraut, Heikki Linnakangas, Peter Smith
Discussion: https://postgr.es/m/[email protected]

5 months agoAdd SQL function array_reverse()
Michael Paquier [Fri, 1 Nov 2024 01:32:19 +0000 (10:32 +0900)]
Add SQL function array_reverse()

This function takes in input an array, and reverses the position of all
its elements.  This operation only affects the first dimension of the
array, like array_shuffle().

The implementation structure is inspired by array_shuffle(), with a
subroutine called array_reverse_n() that may come in handy in the
future, should more functions able to reverse portions of arrays be
introduced.

Bump catalog version.

Author: Aleksander Alekseev
Reviewed-by: Ashutosh Bapat, Tom Lane, Vladlen Popolitov
Discussion: https://postgr.es/m/CAJ7c6TMpeO_ke+QGOaAx9xdJuxa7r=49-anMh3G5476e3CX1CA@mail.gmail.com

6 months agoMake all ereport() calls within gram.y provide error locations.
Tom Lane [Thu, 31 Oct 2024 20:09:22 +0000 (16:09 -0400)]
Make all ereport() calls within gram.y provide error locations.

This patch responds to a comment that I (tgl) made in the
discussion leading up to 774171c4f, that really all errors
occurring during raw parsing should provide error cursors.
Syntax errors reported by Bison will have one, and most of
the handwritten ereport's in gram.y already provide one,
but there were a few stragglers.

(It is not claimed that this handles every failure reachable
during raw parsing --- out-of-memory is an obvious exception.
But this makes a good start on cases that are likely to occur.)

While we're at it, clean up the reported positions for errors
associated with LIMIT/OFFSET clauses.  Previously we were
relying on applying exprLocation() to the contained expressions,
but that leads to slightly odd cursor placement, e.g.

regression=# (select * from foo limit 10) limit 10;
ERROR:  multiple LIMIT clauses not allowed
LINE 1: (select * from foo limit 10) limit 10;
                                           ^

We can afford to keep a little more state in the transient
SelectLimit structs in order to make that better.

Jian He and Tom Lane (extracted from a larger patch by Jian,
with some additional work by me)

Discussion: https://postgr.es/m/CACJufxEmONE3P2En=jopZy1m=cCCUs65M4+1o52MW5og9oaUPA@mail.gmail.com

6 months agoAdd a parse location field to struct FunctionParameter.
Tom Lane [Thu, 31 Oct 2024 19:53:58 +0000 (15:53 -0400)]
Add a parse location field to struct FunctionParameter.

This allows an error cursor to be supplied for a bunch of
bad-function-definition errors that previously lacked one,
or that cheated a bit by pointing at the contained type name
when the error isn't really about that.

Bump catversion from an abundance of caution --- I don't think
this node type can actually appear in stored views/rules, but
better safe than sorry.

Jian He and Tom Lane (extracted from a larger patch by Jian,
with some additional work by me)

Discussion: https://postgr.es/m/CACJufxEmONE3P2En=jopZy1m=cCCUs65M4+1o52MW5og9oaUPA@mail.gmail.com

6 months agoFix refreshing physical relfilenumber on shared index
Heikki Linnakangas [Thu, 31 Oct 2024 16:24:48 +0000 (18:24 +0200)]
Fix refreshing physical relfilenumber on shared index

Buildfarm member 'prion', which is configured with
-DRELCACHE_FORCE_RELEASE -DCATCACHE_FORCE_RELEASE, failed with errors
like this:

    ERROR:  could not read blocks 0..0 in file "global/2672": read only 0 of 8192 bytes

while running a parallel test group that includes VACUUM FULL on some
catalog tables among other things. I was not able to reproduce that
just by running the tests with -DRELCACHE_FORCE_RELEASE
-DCATCACHE_FORCE_RELEASE, even though 'prion' hit it on first run
after commit 2b9b8ebbf8, so there might be something else that makes
it more susceptible to the race. However, I was able to reproduce it
by adding another test to the same test group that runs "vacuum full
pg_database" repeatedly.

The problem is that RelationReloadIndexInfo() no longer calls
RelationInitPhysicalAddr() on a nailed, shared index, when an
invalidation happens early during backend startup, before the critical
relcaches have been built. Before commit 2b9b8ebbf8, that was done by
RelationReloadNailed(), but it went missing from that path. Add it
back as an explicit step.

Broken by commit 2b9b8ebbf8, which refactored these functions.

Discussion: https://www.postgresql.org/message-id/db876575-8f5b-4193-a538-df7e1f92d47a%40iki.fi

6 months agoRemove duplicate words in comments
Daniel Gustafsson [Thu, 31 Oct 2024 10:38:03 +0000 (11:38 +0100)]
Remove duplicate words in comments

A few comments contained duplicate "the" in sentences, fix by removing
one occurrence.

Author: Vignesh C <[email protected]>
Discussion: https://postgr.es/m/CALDaNm2aEEiPwGJmPdzBxROVvs8n75yCjKz4K1f1B2TdWpzxTA@mail.gmail.com

6 months agoSplit RelationClearRelation into three different functions
Heikki Linnakangas [Thu, 31 Oct 2024 08:09:40 +0000 (10:09 +0200)]
Split RelationClearRelation into three different functions

The old RelationClearRelation function did different things depending
on the arguments and circumstances. It could:

a) remove the relation completely from relcache (rebuild == false),
b) mark the entry as invalid (rebuild == true, but not in xact), or
c) rebuild the entry (rebuild == true).

Different callers used it for different purposes, and often assumed a
particular behavior, which was confusing. Split it into three
different functions, one for each of the above actions (one of them,
RelationInvalidateRelation, was already added in commit e6cd857726).
Move the responsibility of choosing the action and calling the right
function to the callers.

Reviewed-by: jian he <[email protected]>
Discussion: https://www.postgresql.org/message-id/9c9e8908-7b3e-4ce7-85a8-00c0e165a3d6%40iki.fi

6 months agoSimplify call to rebuild relcache entry for indexes
Heikki Linnakangas [Thu, 31 Oct 2024 08:02:58 +0000 (10:02 +0200)]
Simplify call to rebuild relcache entry for indexes

RelationClearRelation(rebuild == true) calls RelationReloadIndexInfo()
for indexes. We can rely on that in RelationIdGetRelation(), instead
of calling RelationReloadIndexInfo() directly. That simplifies the
code a little.

In the passing, add a comment in RelationBuildLocalRelation()
explaining why it doesn't call RelationInitIndexAccessInfo(). It's
because at index creation, it's called before the pg_index row has
been created. That's also the reason that RelationClearRelation()
still needs a special case to go through the full-blown rebuild if the
index support information in the relcache entry hasn't been populated
yet.

Reviewed-by: jian he <[email protected]>
Discussion: https://www.postgresql.org/message-id/9c9e8908-7b3e-4ce7-85a8-00c0e165a3d6%40iki.fi

6 months agoRemove unused field from SubPlanState struct
David Rowley [Thu, 31 Oct 2024 00:44:15 +0000 (13:44 +1300)]
Remove unused field from SubPlanState struct

bf6c614a2 did some conversion work to use ExprState instead of manually
calling equality functions to check if one set of values is not distinct
from another set.  That patch removed many of the fields that became
redundant as a result of that change, but it forgot to remove
SubPlanState.tab_eq_funcs.  Fix that.

In passing, fix the header comment for TupleHashEntryData to correctly
spell the field name it's talking about.

Author: Rafia Sabih <[email protected]>
Reviewed-by: Andrei Lepikhov <[email protected]>
Discussion: https://postgr.es/m/CA+FpmFeycdombFzrjZw7Rmc29CVm4OOzCWwu=dVBQ6q=PX8SvQ@mail.gmail.com
Discussion: https://postgr.es/m/CAApHDvrWR2jYVhec=COyF2g2BE_ns91NDsCHAMFiXbyhEujKdQ@mail.gmail.com

6 months agoinjection_points: Improve comment about disabled isolation permutation
Michael Paquier [Wed, 30 Oct 2024 23:28:20 +0000 (08:28 +0900)]
injection_points: Improve comment about disabled isolation permutation

9f00edc22888 has disabled a permutation due to failures in the CI for
FreeBSD environments, but this is a matter of timing.  Let's document
properly why this type of permutation is a bad idea if relying on a wait
done in a SQL function, so as this can be avoided when implementing new
tests (this spec is also a template).

Reviewed-by: Bertrand Drouvot
Discussion: https://postgr.es/m/[email protected]

6 months agonbtree: assert no scheduled primscan between pages.
Peter Geoghegan [Wed, 30 Oct 2024 19:53:26 +0000 (15:53 -0400)]
nbtree: assert no scheduled primscan between pages.

Follow-up to bugfix commit 763d65ae.  Technically this new assertion is
redundant with the assertion recently added to _bt_readpage by that same
commit, but it seems like a good idea to have both.

The new assertion makes it clear that we expect to call _bt_readnextpage
when there's another primitive index scan scheduled, though only when
needed as the final step of ending the current primitive scan.