postgresql.git
6 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.

6 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

6 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

6 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

6 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

6 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]

6 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.

6 months agoClarify nbtree array exhaustion comments.
Peter Geoghegan [Wed, 30 Oct 2024 17:43:49 +0000 (13:43 -0400)]
Clarify nbtree array exhaustion comments.

Strictly speaking, we only need to make sure to leave the scan's array
keys in their final positions (final for the current scan direction) to
handle SAOP array exhaustion because btgettuple might only return a
subset of the items for the final page (final for the current scan
direction), before the scan changes direction.  While it's typical for
so->currPos to be invalidated shortly after the scan's arrays are first
exhausted, and while so->currPos invalidation does obviate the need to
leave the scan's arrays in any particular state, we can't rely on any of
that actually happening when handling array exhaustion.  Adjust comments
to make all of that a lot clearer.

Oversight in commit 5bf748b8, which enhanced nbtree ScalarArrayOp
execution.

6 months agoOptimize sifting down in binaryheap.
Nathan Bossart [Wed, 30 Oct 2024 16:28:34 +0000 (11:28 -0500)]
Optimize sifting down in binaryheap.

Presently, each iteration of the loop in sift_down() will perform
3 comparisons if both children are larger than the parent node (2
for comparing each child to the parent node, and a third to compare
the children to each other).  By first comparing the children to
each other and then comparing the larger child to the parent node,
we can accomplish the same thing with just 2 comparisons (while
also not affecting the number of comparisons in any other case).

Author: ChangAo Chen
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/tencent_0142D8DA90940B9930BCC08348BBD6D0BB07%40qq.com

6 months agoStabilize jsonb_path_query test case.
Tom Lane [Wed, 30 Oct 2024 15:42:28 +0000 (11:42 -0400)]
Stabilize jsonb_path_query test case.

An operation like '12:34:56'::time_tz takes the UTC offset from
the prevailing time zone, which means that the results change
across DST transitions.  One of the test cases added in ed055d249
failed to consider this.

Per report from Bernhard Wiedemann.  Back-patch to v17, as the
test case was.

Discussion: https://postgr.es/m/ba8e1bc0-8a99-45b7-8397-3f2e94415e03@suse.de

6 months agoFix bug in nbtree array primitive scan scheduling.
Peter Geoghegan [Wed, 30 Oct 2024 14:57:19 +0000 (10:57 -0400)]
Fix bug in nbtree array primitive scan scheduling.

A bug in nbtree's handling of primitive index scan scheduling could lead
to wrong answers when a scrollable cursor was used with an index scan
that had a SAOP index qual.  Wrong answers were only possible when the
scan direction changed after a primitive scan was scheduled, but before
_bt_next was asked to fetch the next tuple in line (i.e. for things to
break, _bt_next had to be denied the opportunity to step off the page in
the same direction as the one used when the primscan was scheduled).
Furthermore, the issue only occurred when the page in question happened
to be the first page to be visited by the entire top-level scan; the
issue hinged upon the cursor backing up to the absolute beginning of the
key space that it returns tuples from (fetching in the opposite scan
direction across a "primitive scan boundary" always worked correctly).

To fix, make _bt_next unset the "needs primitive index scan" flag when
it detects that the current scan direction is not the one that was used
by _bt_readpage back when the primitive scan in question was scheduled.
This fixes the cases that are known to be faulty, and also seems like a
good idea on general robustness grounds.

Affected scrollable cursor cases now avoid a spurious primitive index
scan when they fetch backwards to the absolute start of the key space to
be visited by their cursor.  Fetching backwards now only returns those
tuples at the start of the scan, as expected.  It'll also be okay to
once again fetch forwards from the start at that point, since the scan
will be left in a state that's exactly consistent with the state it was
in before any tuples were ever fetched, as expected.

Oversight in commit 5bf748b8, which enhanced nbtree ScalarArrayOp
execution.

Author: Peter Geoghegan <[email protected]>
Discussion: https://postgr.es/m/CAH2-Wznv49bFsE2jkt4GuZ0tU2C91dEST=50egzjY2FeOcHL4Q@mail.gmail.com
Backpatch: 17-, where commit 5bf748b8 first appears.

6 months agoFix some more bugs in foreign keys connecting partitioned tables
Álvaro Herrera [Wed, 30 Oct 2024 09:54:03 +0000 (10:54 +0100)]
Fix some more bugs in foreign keys connecting partitioned tables

* In DetachPartitionFinalize() we were applying a tuple conversion map
  to tuples that didn't need one, which can lead to erratic behavior if
  a partitioned table has a partition with a different column order, as
  reported by Alexander Lakhin. This was introduced by 53af9491a043.
  Don't do that.  Also, modify a recently added test case to exercise
  this.

* The same function as well as CloneFkReferenced() were acquiring
  AccessShareLock on a partition, only to have CreateTrigger() later
  acquire ShareRowExclusiveLock on it.  This can lead to deadlock by
  lock escalation, unnecessarily.  Avoid that by acquiring the stronger
  lock to begin with.  This probably dates back to branch 12, but I have
  never seen a report of this being a problem in the field.

* Innocuous but wasteful: also introduced by 53af9491a043, we were
  reading a pg_constraint tuple from syscache that we don't need, as
  reported by Tender Wang.  Don't.

Backpatch to 15.

Discussion: https://postgr.es/m/461e9c26-2076-8224-e119-84998b6a784e@gmail.com

6 months agomeson: Add missing dependency to unicode test programs
Peter Eisentraut [Wed, 30 Oct 2024 07:30:00 +0000 (08:30 +0100)]
meson: Add missing dependency to unicode test programs

The test programs in src/common/unicode/ (case_test, category_test,
norm_test), don't build with meson if the nls option is enabled,
because a libintl dependency is missing.  Fix that.  (The makefiles
are ok.)

Reviewed-by: Aleksander Alekseev <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/52db1d2b-4b96-473e-b323-a4b16a950fba%40eisentraut.org

6 months agoReplicate generated columns when specified in the column list.
Amit Kapila [Wed, 30 Oct 2024 07:06:26 +0000 (12:36 +0530)]
Replicate generated columns when specified in the column list.

This commit allows logical replication to publish and replicate generated
columns when explicitly listed in the column list. We also ensured that
the generated columns were copied during the initial tablesync when they
were published.

We will allow to replicate generated columns even when they are not
specified in the column list (via a new publication option) in a separate
commit.

The motivation of this work is to allow replication for cases where the
client doesn't have generated columns. For example, the case where one is
trying to replicate data from Postgres to the non-Postgres database.

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

6 months agoAdd missing CommandCounterIncrement() in stats import functions.
Jeff Davis [Tue, 29 Oct 2024 17:14:23 +0000 (10:14 -0700)]
Add missing CommandCounterIncrement() in stats import functions.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/98b2fcf0-f701-369e-d63d-6be9739ce17c@gmail.com

6 months agoUnpin buffer before inplace update waits for an XID to end.
Noah Misch [Tue, 29 Oct 2024 16:39:55 +0000 (09:39 -0700)]
Unpin buffer before inplace update waits for an XID to end.

Commit a07e03fd8fa7daf4d1356f7cb501ffe784ea6257 changed inplace updates
to wait for heap_update() commands like GRANT TABLE and GRANT DATABASE.
By keeping the pin during that wait, a sequence of autovacuum workers
and an uncommitted GRANT starved one foreground LockBufferForCleanup()
for six minutes, on buildfarm member sarus.  Prevent, at the cost of a
bit of complexity.  Back-patch to v12, like the earlier commit.  That
commit and heap_inplace_lock() have not yet appeared in any release.

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

6 months agoUpdate time zone data files to tzdata release 2024b.
Tom Lane [Tue, 29 Oct 2024 15:49:38 +0000 (11:49 -0400)]
Update time zone data files to tzdata release 2024b.

Historical corrections for Mexico, Mongolia, and Portugal.
Notably, Asia/Choibalsan is now an alias for Asia/Ulaanbaatar
rather than being a separate zone, mainly because the differences
between those zones were found to be based on untrustworthy data.

6 months agoReduce variable scope and possibly useless palloc
David Rowley [Tue, 29 Oct 2024 12:38:42 +0000 (01:38 +1300)]
Reduce variable scope and possibly useless palloc

Move the CreateStmt down to the branch that it's used in, thus
preventing the makeNode() call in cases where the CreateStmt isn't used.

Author: Ranier Vilela <[email protected]>
Discussion: https://postgr.es/m/CAEudQAq=06YPWPhS+yyTbCwv5JLKRz8rm3dWx6JR5Uj_d_fQDA@mail.gmail.com

6 months agoDoc: add detail about EXPLAIN's "Disabled" property
David Rowley [Tue, 29 Oct 2024 10:28:12 +0000 (23:28 +1300)]
Doc: add detail about EXPLAIN's "Disabled" property

c01743aa4 and later 161320b4b adjusted the EXPLAIN output to show which
plan nodes were chosen despite being disabled by the various enable*
GUCs.  Prior to e22253467, the disabledness of a node was only evident by
a large startup cost penalty.  Since we now explicitly tag disabled nodes
with a boolean property in EXPLAIN, let's add some documentation to
provide some details about why and when disabled nodes can appear in the
plan.

Author: Laurenz Albe, David Rowley
Discussion: https://postgr.es/m/883729e429267214753d5e438c82c73a58c3db5d[email protected]

6 months agoAdd missing FATAL => 'all' to a use warnings in Perl
Peter Eisentraut [Tue, 29 Oct 2024 09:26:17 +0000 (10:26 +0100)]
Add missing FATAL => 'all' to a use warnings in Perl

Author: Anton Voloshin <[email protected]>
Discussion: https://www.postgresql.org/message-id/aa8a55d5-554a-4027-a491-1b0ca7c85f7a@postgrespro.ru

6 months agodoc: Add better description for rewrite functions in event triggers
Michael Paquier [Tue, 29 Oct 2024 06:35:01 +0000 (15:35 +0900)]
doc: Add better description for rewrite functions in event triggers

There are two functions that can be used in event triggers to get more
details about a rewrite happening on a relation.  Both had a limited
documentation:
- pg_event_trigger_table_rewrite_reason() and
pg_event_trigger_table_rewrite_oid() were not mentioned in the main
event trigger section in the paragraph dedicated to the event
table_rewrite.
- pg_event_trigger_table_rewrite_reason() returns an integer which is a
bitmap of the reasons why a rewrite happens.  There was no explanation
about the meaning of these values, forcing the reader to look at the
code to find out that these are defined in event_trigger.h.

While on it, let's add a comment in event_trigger.h where the
AT_REWRITE_* are defined, telling to update the documentation when
these values are changed.

Backpatch down to 13 as a consequence of 1ad23335f36b, where this area
of the documentation has been heavily reworked.

Author: Greg Sabino Mullane
Discussion: https://postgr.es/m/CAKAnmmL+Z6j-C8dAx1tVrnBmZJu+BSoc68WSg3sR+CVNjBCqbw@mail.gmail.com
Backpatch-through: 13

6 months agoDoc: clarify enable_indexscan=off also disabled Index Only Scans
David Rowley [Tue, 29 Oct 2024 03:24:10 +0000 (16:24 +1300)]
Doc: clarify enable_indexscan=off also disabled Index Only Scans

Disabling enable_indexscan has always also disabled Index Only Scans.
Here we make that more clear in the documentation in an attempt to
prevent future complaints complaining about this expected behavior.

Reported-by: Melanie Plageman
Author: David G. Johnston, David Rowley
Backpatch-through: 12, oldest supported version
Discussion: https://postgr.es/m/CAAKRu_atV=kovgpaLREyG68PB5+ncKvJ2UNoeRetEgyC3Yb5Sw@mail.gmail.com

6 months agoFix dependency of partitioned table and table AM with CREATE TABLE .. USING
Michael Paquier [Mon, 28 Oct 2024 23:41:33 +0000 (08:41 +0900)]
Fix dependency of partitioned table and table AM with CREATE TABLE .. USING

A pg_depend entry between a partitioned table and its table access
method was missing when using CREATE TABLE .. USING with an unpinned
access method.  DROP ACCESS METHOD could be used, while it should be
blocked if CASCADE is not specified, even if there was a partitioned
table that depends on the table access method.  pg_class.relam would
then hold an orphaned OID value still pointing to the AM dropped.

The problem is fixed by adding a dependency between the partitioned
table and its table access method if set when the relation is created.
A test checking the contents of pg_depend in this case is added.

Issue introduced in 374c7a229042, that has added support for CREATE
TABLE .. USING for partitioned tables.

Reviewed-by: Alexander Lakhin
Discussion: https://postgr.es/m/18674-1ef01eceec278fab@postgresql.org
Backpatch-through: 17

6 months agoEnsure we have a snapshot when updating pg_index in index_drop().
Nathan Bossart [Mon, 28 Oct 2024 21:44:31 +0000 (16:44 -0500)]
Ensure we have a snapshot when updating pg_index in index_drop().

I assumed that all index_drop() callers set an active snapshot
beforehand, but that is evidently not true.  One counterexample is
autovacuum, which doesn't set an active snapshot when cleaning up
orphan temp indexes.  To fix, unconditionally push an active
snapshot before updating pg_index in index_drop().

Oversight in commit b52adbad46.

Reported-by: Masahiko Sawada
Reviewed-by: Stepan Neretin, Masahiko Sawada
Discussion: https://postgr.es/m/CAD21AoBgF9etQrXbN9or_YHsmBRJHHNUEkhHp9rGK9CyQv5aTQ%40mail.gmail.com

6 months agoUnify src/common/'s definitions of MaxAllocSize.
Tom Lane [Mon, 28 Oct 2024 18:39:01 +0000 (14:39 -0400)]
Unify src/common/'s definitions of MaxAllocSize.

As threatened in the previous patch, define MaxAllocSize in
src/include/common/fe_memutils.h rather than having several
copies of it in different src/common/*.c files.  This also
provides an opportunity to document it better.

While this would probably be safe to back-patch, I'll refrain
(for now anyway).

6 months agoGuard against enormously long input in pg_saslprep().
Tom Lane [Mon, 28 Oct 2024 18:33:55 +0000 (14:33 -0400)]
Guard against enormously long input in pg_saslprep().

Coverity complained that pg_saslprep() could suffer integer overflow,
leading to under-allocation of the output buffer, if the input string
exceeds SIZE_MAX/4.  This hazard seems largely hypothetical, but it's
easy enough to defend against, so let's do so.

This patch creates a third place in src/common/ where we are locally
defining MaxAllocSize so that we can test against that in the same way
in backend and frontend compiles.  That seems like about two places
too many, so the next patch will move that into common/fe_memutils.h.
I'm hesitant to do that in back branches however.

Back-patch to v14.  The code looks similar in older branches, but
before commit 67a472d71 there was a separate test on the input string
length that prevented this hazard.

Per Coverity report.

6 months agoStrip Windows newlines from extension script files manually.
Tom Lane [Mon, 28 Oct 2024 17:07:29 +0000 (13:07 -0400)]
Strip Windows newlines from extension script files manually.

Revert commit 924e03917 in favor of adding code to convert \r\n to \n
explicitly, on Windows only.  The idea of letting text mode do the
work fails for a couple of reasons:

* Per Microsoft documentation, text mode also causes control-Z to be
interpreted as end-of-file.  While it may be unlikely that extension
scripts contain control-Z, we've historically allowed it, and breaking
the case doesn't seem wise.

* Apparently, on some Windows configurations, "r" mode is interpreted
as binary not text mode.  We could force it with "rt" but that would
be inconsistent with our code elsewhere, and it would still require
Windows-specific coding.

Thanks to Alexander Lakhin for investigation.

Discussion: https://postgr.es/m/79284195-4993-7b00-f6df-8db28ca60fa3@gmail.com

6 months agoFix WAL_DEBUG build
Peter Eisentraut [Mon, 28 Oct 2024 16:44:18 +0000 (17:44 +0100)]
Fix WAL_DEBUG build

broken by commit e18512c000e

Reported-by: Peter Geoghegan <[email protected]>
6 months agonbtree: Minor sibling link traversal tweaks.
Peter Geoghegan [Mon, 28 Oct 2024 16:22:52 +0000 (12:22 -0400)]
nbtree: Minor sibling link traversal tweaks.

Tweak some code comments for clarity, and relocate some local variable
declarations to the scope where they're actually used.

Follow-up to recent commit 1bd4bc85.

6 months agoFix overflow in bsearch_arg() with more than INT_MAX elements
Heikki Linnakangas [Mon, 28 Oct 2024 12:07:38 +0000 (14:07 +0200)]
Fix overflow in bsearch_arg() with more than INT_MAX elements

This was introduced in commit bfa2cee784, which replaced the old
bsearch_cmp() function we had in extended_stats.c with the current
implementation. The original discussion or commit message of
bfa2cee784 didn't mention where the new implementation came from, but
based on some googling, I'm guessing *BSD or libiberty, all of which
share this same code, with or without this fix.

Author: Ranier Vilela
Reviewed-by: Nathan Bossart
Backpatch-through: 14
Discussion: https://www.postgresql.org/message-id/CAEudQAp34o_8u6sGSVraLwuMv9F7T9hyHpePXHmRaxR2Aboi%2Bw%40mail.gmail.com

6 months agoRestore missing line to copyright notice
Heikki Linnakangas [Mon, 28 Oct 2024 11:08:43 +0000 (13:08 +0200)]
Restore missing line to copyright notice

Commit 12c9423832 in May 2003 accidentally removed the last line of
the copyright notice in getopt.c. Put it back.

6 months agoRemove unused #include's from contrib, pl, test .c files
Peter Eisentraut [Mon, 28 Oct 2024 07:02:17 +0000 (08:02 +0100)]
Remove unused #include's from contrib, pl, test .c files

as determined by IWYU

Similar to commit dbbca2cf299, but for contrib, pl, and src/test/.

Reviewed-by: Alvaro Herrera <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/0df1d5b1-8ca8-4f84-93be-121081bde049%40eisentraut.org

6 months agoChange the default value of the streaming option to 'parallel'.
Amit Kapila [Mon, 28 Oct 2024 03:12:05 +0000 (08:42 +0530)]
Change the default value of the streaming option to 'parallel'.

Previously the default value of streaming option for a subscription was
'off'. The parallel option indicates that the changes in large
transactions (greater than logical_decoding_work_mem) are to be applied
directly via one of the parallel apply workers, if available.

The parallel mode was introduced in 16, but we refrain from enabling it by
default to avoid seeing any unpleasant behavior in the existing
applications. However we haven't found any such report yet, so this is a
good time to enable it by default.

Reported-by: Vignesh C
Author: Hayato Kuroda, Masahiko Sawada, Peter Smith, Amit Kapila
Discussion: https://postgr.es/m/CALDaNm1=MedhW23NuoePJTmonwsMSp80ddsw+sEJs0GUMC_kqQ@mail.gmail.com

6 months agoSet query ID for inner queries of CREATE TABLE AS and DECLARE
Michael Paquier [Mon, 28 Oct 2024 00:03:20 +0000 (09:03 +0900)]
Set query ID for inner queries of CREATE TABLE AS and DECLARE

Some utility statements contain queries that can be planned and
executed: CREATE TABLE AS and DECLARE CURSOR.  This commit adds query ID
computation for the inner queries executed by these two utility
commands, with and without EXPLAIN.  This change leads to four new
callers of JumbleQuery() and post_parse_analyze_hook() so as extensions
can decide what to do with this new data.

Previously, extensions relying on the query ID, like pg_stat_statements,
were not able to track these nested queries as the query_id was 0.

For pg_stat_statements, this commit leads to additions under !toplevel
when pg_stat_statements.track is set to "all", as shown in its
regression tests.  The output of EXPLAIN for these two utilities gains a
"Query Identifier" if compute_query_id is enabled.

Author: Anthonin Bonnefoy
Reviewed-by: Michael Paquier, Jian He
Discussion: https://postgr.es/m/CAO6_XqqM6S9bQ2qd=75W+yKATwoazxSNhv5sjW06fjGAtHbTUA@mail.gmail.com

6 months agoFix obsolete nbtree split buffer comment.
Peter Geoghegan [Sun, 27 Oct 2024 14:38:24 +0000 (10:38 -0400)]
Fix obsolete nbtree split buffer comment.

Oversight in commit d088ba5a.

6 months agoRemove unused #include's from backend .c files
Peter Eisentraut [Sun, 27 Oct 2024 07:18:25 +0000 (08:18 +0100)]
Remove unused #include's from backend .c files

as determined by IWYU

These are mostly issues that are new since commit dbbca2cf299.

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

6 months agoRefactor the code to create a pg_locale_t into new function.
Jeff Davis [Fri, 25 Oct 2024 23:31:08 +0000 (16:31 -0700)]
Refactor the code to create a pg_locale_t into new function.

Reviewed-by: Andreas Karlsson
Discussion: https://postgr.es/m/59da7ee4-5e1a-4727-b464-a603c6ed84cd@proxel.se

6 months agoRead extension script files in text not binary mode.
Tom Lane [Fri, 25 Oct 2024 16:19:58 +0000 (12:19 -0400)]
Read extension script files in text not binary mode.

This change affects only Windows, where it should cause DOS-style
newlines (\r\n) to be converted to plain \n during script loading.
This eliminates one potential discrepancy in the behavior of
extension script files between Windows and non-Windows.  While
there's a small chance that this might cause undesirable behavior
changes for some extensions, it can also be argued that this may
remove behavioral surprises for others.  An example is that in
the buildfarm, we are getting different results for the tests
added by commit 774171c4f depending on whether our git tree has
been checked out with Unix or DOS newlines.

The choice to use binary mode goes all the way back to our invention
of extensions in commit d9572c4e3.  However, I suspect it was not
thought through carefully but was just a side-effect of the ready
availability of an almost-suitable function read_binary_file().
On balance, changing to text mode seems like a better answer than
other ways in which we might fix the inconsistent test results.

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

6 months agoMake table_scan_bitmap_next_block() async-friendly
Melanie Plageman [Fri, 25 Oct 2024 14:11:58 +0000 (10:11 -0400)]
Make table_scan_bitmap_next_block() async-friendly

Move all responsibility for indicating a block is exhuasted into
table_scan_bitmap_next_tuple() and advance the main iterator in
heap-specific code. This flow control makes more sense and is a step
toward using the read stream API for bitmap heap scans.

Previously, table_scan_bitmap_next_block() returned false to indicate
table_scan_bitmap_next_tuple() should not be called for the tuples on
the page. This happened both when 1) there were no visible tuples on the
page and 2) when the block returned by the iterator was past the end of
the table. BitmapHeapNext() (generic bitmap table scan code) handled the
case when the bitmap was exhausted.

It makes more sense for table_scan_bitmap_next_tuple() to return false
when there are no visible tuples on the page and
table_scan_bitmap_next_block() to return false when the bitmap is
exhausted or there are no more blocks in the table.

As part of this new design, TBMIterateResults are no longer used as a
flow control mechanism in BitmapHeapNext(), so we removed
table_scan_bitmap_next_tuple's TBMIterateResult parameter.

Note that the prefetch iterator is still saved in the
BitmapHeapScanState node and advanced in generic bitmap table scan code.
This is because 1) it was not necessary to change the prefetch iterator
location to change the flow control in BitmapHeapNext() 2) modifying
prefetch iterator management requires several more steps better split
over multiple commits and 3) the prefetch iterator will be removed once
the read stream API is used.

Author: Melanie Plageman
Reviewed-by: Tomas Vondra, Andres Freund, Heikki Linnakangas, Mark Dilger
Discussion: https://postgr.es/m/063e4eb4-32d9-439e-a0b1-75565a9835a8%40iki.fi

6 months agoMove EXPLAIN counter increment to heapam_scan_bitmap_next_block
Melanie Plageman [Fri, 25 Oct 2024 14:11:46 +0000 (10:11 -0400)]
Move EXPLAIN counter increment to heapam_scan_bitmap_next_block

Increment the lossy and exact page counters for EXPLAIN of bitmap heap
scans in heapam_scan_bitmap_next_block(). Note that other table AMs will
need to do this as well

Pushing the counters into heapam_scan_bitmap_next_block() is required to
be able to use the read stream API for bitmap heap scans. The bitmap
iterator must be advanced from inside the read stream callback, so
TBMIterateResults cannot be used as a flow control mechanism in
BitmapHeapNext().

Author: Melanie Plageman
Reviewed-by: Tomas Vondra, Heikki Linnakangas
Discussion: https://postgr.es/m/063e4eb4-32d9-439e-a0b1-75565a9835a8%40iki.fi

6 months agoWAL-log inplace update before revealing it to other sessions.
Noah Misch [Fri, 25 Oct 2024 13:51:03 +0000 (06:51 -0700)]
WAL-log inplace update before revealing it to other sessions.

A buffer lock won't stop a reader having already checked tuple
visibility.  If a vac_update_datfrozenid() and then a crash happened
during inplace update of a relfrozenxid value, datfrozenxid could
overtake relfrozenxid.  That could lead to "could not access status of
transaction" errors.  Back-patch to v12 (all supported versions).  In
v14 and earlier, this also back-patches the assertion removal from
commit 7fcf2faf9c7dd473208fd6d5565f88d7f733782b.

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

6 months agoFor inplace update, send nontransactional invalidations.
Noah Misch [Fri, 25 Oct 2024 13:51:02 +0000 (06:51 -0700)]
For inplace update, send nontransactional invalidations.

The inplace update survives ROLLBACK.  The inval didn't, so another
backend's DDL could then update the row without incorporating the
inplace update.  In the test this fixes, a mix of CREATE INDEX and ALTER
TABLE resulted in a table with an index, yet relhasindex=f.  That is a
source of index corruption.  Back-patch to v12 (all supported versions).
The back branch versions don't change WAL, because those branches just
added end-of-recovery SIResetAll().  All branches change the ABI of
extern function PrepareToInvalidateCacheTuple().  No PGXN extension
calls that, and there's no apparent use case in extensions.

Reviewed by Nitin Motiani and (in earlier versions) Andres Freund.

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

6 months agodoc: Fix typo in pg_restore_*_stats function documentation
Daniel Gustafsson [Fri, 25 Oct 2024 12:00:13 +0000 (14:00 +0200)]
doc: Fix typo in pg_restore_*_stats function documentation

Fix accidental typo from d32d146399, s/intepretation/interpretation/

6 months agoFix concurrrently in typcache_rel_type_cache.sql
Alexander Korotkov [Fri, 25 Oct 2024 10:07:07 +0000 (13:07 +0300)]
Fix concurrrently in typcache_rel_type_cache.sql

All injection points there must be local.  Otherwise it affects parallel
tests.

Reported-by: Andres Freund
Discussion: https://postgr.es/m/b3ybc66l6lhmtzj2n7ypumz5yjz7njc46sddsqshdtstgj74ah%40qgtn6nzokj6a

6 months agoDoc: Add a caution in alter publication.
Amit Kapila [Fri, 25 Oct 2024 08:49:05 +0000 (14:19 +0530)]
Doc: Add a caution in alter publication.

Clarify that altering the 'publish_via_partition_root' option can lead to
data loss or duplication when a partition root table is specified as the
replication target.

Reported-by: Maxim Boguk
Author: Hayato Kuroda
Reviewed-by: Amit Kapila, Peter Smith, Vignesh C
Discussion: https://postgr.es/m/18644-6866bbd22178ee16@postgresql.org

6 months agopgbench: Fix typo.
Tatsuo Ishii [Fri, 25 Oct 2024 06:06:16 +0000 (15:06 +0900)]
pgbench: Fix typo.

Fix typo in commit cae0f3c405.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/70eaa41b-805b-ce19-6004-5a0dccd3f731%40gmail.com

6 months agoRefactor code converting a publication name List to a StringInfo
Michael Paquier [Fri, 25 Oct 2024 03:02:04 +0000 (12:02 +0900)]
Refactor code converting a publication name List to a StringInfo

The existing get_publications_str() is renamed to GetPublicationsStr()
and is moved to pg_subscription.c, so as it is possible to reuse it at
two locations of the tablesync code where the same logic was duplicated.

fetch_remote_table_info() was doing two List->StringInfo conversions
when dealing with a server of version 15 or newer.  The conversion
happens only once now.

This refactoring leads to less code overall.

Author: Peter Smith
Reviewed-by: Michael Paquier, Masahiko Sawada
Discussion: https://postgr.es/m/CAHut+PtJMk4bKXqtpvqVy9ckknCgK9P6=FeG8zHF=6+Em_Snpw@mail.gmail.com

6 months agoAdd install rules for Kerberos.pm and AdjustUpgrade.pm
Michael Paquier [Fri, 25 Oct 2024 01:56:34 +0000 (10:56 +0900)]
Add install rules for Kerberos.pm and AdjustUpgrade.pm

For the same reasons as c3a0818460a8, these can be useful for
out-of-core extension testing.  Kerberos.pm has been moved to its
current path recently in 9f899562d420, and AdjustUpgrade.pm has been
introduced in 52585f8f072a, still both lacked [un]installation rules for
both meson and configure.

Reported-by: Ashutosh Bapat
Discussion: https://postgr.es/m/[email protected]

6 months agoinjection_points: Disable one permutation in isolation test "basic"
Michael Paquier [Fri, 25 Oct 2024 01:34:27 +0000 (10:34 +0900)]
injection_points: Disable one permutation in isolation test "basic"

The first permutation done in the test does a wait, a wakeup then a
detach.  It is proving to be unstable in the CI for FreeBSD (Windows and
Linux are stable).  The failure shows that the wait is so slow to finish
after being woken up that the detach has the time to finish before the
wait, messing up with the expected output.

There may be a platform-specific issue going on here, but for now
disable this permutation to make the CI runs more stable.

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

6 months agoRemove the RTE_GROUP RTE if we drop the groupClause
Richard Guo [Fri, 25 Oct 2024 00:52:34 +0000 (09:52 +0900)]
Remove the RTE_GROUP RTE if we drop the groupClause

For an EXISTS subquery, the only thing that matters is whether it
returns zero or more than zero rows.  Therefore, we remove certain SQL
features that won't affect that, among them the GROUP BY clauses.

After we drop the groupClause, we'd better remove the RTE_GROUP RTE
and clear the hasGroupRTE flag, as they depend on the groupClause.
Failing to do so could result in a bogus RTE_GROUP entry in the parent
query, leading to an assertion failure on the hasGroupRTE flag.

Reported-by: David Rowley
Author: Richard Guo
Discussion: https://postgr.es/m/CAApHDvp2_yht8uPLyWO-kVGWZhYvx5zjGfSrg4fBQ9fsC13V0g@mail.gmail.com

6 months agoAdd functions pg_restore_relation_stats(), pg_restore_attribute_stats().
Jeff Davis [Thu, 24 Oct 2024 19:08:00 +0000 (12:08 -0700)]
Add functions pg_restore_relation_stats(), pg_restore_attribute_stats().

Similar to the pg_set_*_stats() functions, except with a variadic
signature that's designed to be more future-proof. Additionally, most
problems are reported as WARNINGs rather than ERRORs, allowing most
stats to be restored even if some cannot.

These functions are intended to be called from pg_dump to avoid the
need to run ANALYZE after an upgrade.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=eErgzn7ECDpwFcptJKOk9SxZEk5Pot4d94eVTZsvj3gw@mail.gmail.com

6 months agoGeneralize plpgsql's heuristic for importing expanded objects.
Tom Lane [Thu, 24 Oct 2024 17:28:22 +0000 (13:28 -0400)]
Generalize plpgsql's heuristic for importing expanded objects.

If a R/W expanded-object pointer is passed as a function parameter,
take ownership of the object, regardless of its type.  Previously
this happened only for expanded arrays, but that was a result of
sloppy thinking.  (If the plpgsql function did not end by returning
the object, the result would be to leak the object until the
surrounding memory context is cleaned up.  That's not awful,
since non-expanded values have always been managed that way,
but we can do better.)

Per discussion with Michel Pelletier.  There's a lot more to do
here to make plpgsql work efficiently with expanded objects that
aren't arrays, but this is an easy first step.

Discussion: https://postgr.es/m/CACxu=vJaKFNsYxooSnW1wEgsAO5u_v1XYBacfVJ14wgJV_PYeg@mail.gmail.com

6 months agoFix parallel worker tracking of new catalog relfilenumbers.
Noah Misch [Thu, 24 Oct 2024 16:16:38 +0000 (09:16 -0700)]
Fix parallel worker tracking of new catalog relfilenumbers.

Reunite RestorePendingSyncs() with RestoreRelationMap().  If
RelationInitPhysicalAddr() ran after RestoreRelationMap() but before
RestorePendingSyncs(), the relcache entry could cause RelationNeedsWAL()
to return true erroneously.  Trouble required commands of the current
transaction to include REINDEX or CLUSTER of a system catalog.  The
parallel leader correctly derived RelationNeedsWAL()==false from the new
relfilenumber, but the worker saw RelationNeedsWAL()==true.  Worker
MarkBufferDirtyHint() then wrote unwanted WAL.  Recovery of that
unwanted WAL could lose tuples like the system could before commit
c6b92041d38512a4176ed76ad06f713d2e6c01a8 introduced this tracking.
RestorePendingSyncs() and RestoreRelationMap() were adjacent till commit
126ec0bc76d044d3a9eb86538b61242bf7da6db4, so no back-patch for now.

Reviewed by Tom Lane.

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

6 months agoStop reading uninitialized memory in heap_inplace_lock().
Noah Misch [Thu, 24 Oct 2024 16:16:14 +0000 (09:16 -0700)]
Stop reading uninitialized memory in heap_inplace_lock().

Stop computing a never-used value.  This removes the read; the read had
no functional implications.  Back-patch to v12, like commit
a07e03fd8fa7daf4d1356f7cb501ffe784ea6257.

Reported by Alexander Lakhin.

Discussion: https://postgr.es/m/6c92f59b-f5bc-e58c-9bdd-d1f21c17c786@gmail.com

6 months agoRefactor GetLockStatusData() to skip backends/groups without fast-path locks.
Fujii Masao [Thu, 24 Oct 2024 15:18:32 +0000 (00:18 +0900)]
Refactor GetLockStatusData() to skip backends/groups without fast-path locks.

Previously, GetLockStatusData() checked all slots for every backend
to gather fast-path lock data, which could be inefficient. This commit
refactors it by skipping backends with PID=0 (since they don't hold
fast-path locks) and skipping groups with no registered fast-path locks,
improving efficiency.

This refactoring is particularly beneficial, for example when
max_connections and max_locks_per_transaction are set high,
as it reduces unnecessary checks across numerous slots.

Author: Fujii Masao
Reviewed-by: Bertrand Drouvot
Discussion: https://postgr.es/m/a0a00c44-31e9-4c67-9846-fb9636213ac9@oss.nttdata.com

6 months agoSupport configuring TLSv1.3 cipher suites
Daniel Gustafsson [Thu, 24 Oct 2024 13:20:32 +0000 (15:20 +0200)]
Support configuring TLSv1.3 cipher suites

The ssl_ciphers GUC can only set cipher suites for TLSv1.2, and lower,
connections. For TLSv1.3 connections a different OpenSSL API must be
used.  This adds a new GUC, ssl_tls13_ciphers, which can be used to
configure a colon separated list of cipher suites to support when
performing a TLSv1.3 handshake.

Original patch by Erica Zhang with additional hacking by me.

Author: Erica Zhang <[email protected]>
Author: Daniel Gustafsson <[email protected]>
Reviewed-by: Jacob Champion <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: Jelte Fennema-Nio <[email protected]>
Discussion: https://postgr.es/m/[email protected]

6 months agoSupport configuring multiple ECDH curves
Daniel Gustafsson [Thu, 24 Oct 2024 13:20:28 +0000 (15:20 +0200)]
Support configuring multiple ECDH curves

The ssl_ecdh_curve GUC only accepts a single value, but the TLS
handshake can list multiple curves in the groups extension (the
extension has been renamed to contain more than elliptic curves).
This changes the GUC to accept a colon-separated list of curves.
This commit also renames the GUC to ssl_groups to match the new
nomenclature for the TLS extension.

Original patch by Erica Zhang with additional hacking by me.

Author: Erica Zhang <[email protected]>
Author: Daniel Gustafsson <[email protected]>
Reviewed-by: Jacob Champion <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: Jelte Fennema-Nio <[email protected]>
Discussion: https://postgr.es/m/[email protected]

6 months agoRaise the minimum supported OpenSSL version to 1.1.1
Daniel Gustafsson [Thu, 24 Oct 2024 13:20:19 +0000 (15:20 +0200)]
Raise the minimum supported OpenSSL version to 1.1.1

Commit a70e01d4306fdbcd retired support for OpenSSL 1.0.2 in order to get
rid of the need for manual initialization of the library.  This left our
API usage compatible with 1.1.0 which was defined as the minimum required
version. Also mention that 3.4 is the minimum version required when using
LibreSSL.

An upcoming commit will introduce support for configuring TLSv1.3 cipher
suites which require an API call in OpenSSL 1.1.1 and onwards.  In order
to support this setting this commit will set v1.1.1 as the new minimum
required version.  The version-specific call for randomness init added
in commit c3333dbc0c0 is removed as it's no longer needed.

Author: Daniel Gustafsson <[email protected]>
Discussion: https://postgr.es/m/909A668B-06AD-47D1-B8EB-A164211AAD16@yesql.se
Discussion: https://postgr.es/m/[email protected]

6 months agoHandle alphanumeric characters in matching GUC names
Daniel Gustafsson [Thu, 24 Oct 2024 13:20:16 +0000 (15:20 +0200)]
Handle alphanumeric characters in matching GUC names

The check for whether all GUCs are present in the sample config
file used the POSIX character class :alpha: which corresponds to
alphabet and not alphanumeric. Since GUC names can contain digits
as well we need to use the :alnum: character class instead.

Author: Daniel Gustafsson <[email protected]>
Discussion: https://postgr.es/m/2CB04559-B1D8-4558-B6F0-8F09093D629F@yesql.se

6 months agoAdd 'no_error' argument to pg_wal_replay_wait()
Alexander Korotkov [Thu, 24 Oct 2024 11:40:23 +0000 (14:40 +0300)]
Add 'no_error' argument to pg_wal_replay_wait()

This argument allow skipping throwing an error.  Instead, the result status
can be obtained using pg_wal_replay_wait_status() function.

Catversion is bumped.

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/ZtUF17gF0pNpwZDI%40paquier.xyz
Reviewed-by: Pavel Borisov
6 months agoRefactor WaitForLSNReplay() to return the result of waiting
Alexander Korotkov [Thu, 24 Oct 2024 11:38:27 +0000 (14:38 +0300)]
Refactor WaitForLSNReplay() to return the result of waiting

Currently, WaitForLSNReplay() immediately throws an error if waiting for LSN
replay is not successful.  This commit teaches  WaitForLSNReplay() to return
the result of waiting, while making pg_wal_replay_wait() responsible for
throwing an appropriate error.

This is preparation to adding 'no_error' argument to pg_wal_replay_wait() and
new function pg_wal_replay_wait_status(), which returns the last wait result
status.

Additionally, we stop distinguishing situations when we find our instance to
be not in a recovery state before entering the waiting loop and inside
the waiting loop.  Standby promotion may happen at any moment, even between
issuing a procedure call statement and pg_wal_replay_wait() doing a first
check of recovery status.  Thus, there is no pointing distinguishing these
situations.

Also, since we may exit the waiting loop and see our instance not in recovery
without throwing an error, we need to deleteLSNWaiter() in that case. We do
this unconditionally for the sake of simplicity, even if standby was already
promoted after reaching the target LSN, the startup process surely already
deleted us.

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/ZtUF17gF0pNpwZDI%40paquier.xyz
Reviewed-by: Michael Paquier, Pavel Borisov
6 months agoMake WaitForLSNReplay() issue FATAL on postmaster death
Alexander Korotkov [Thu, 24 Oct 2024 11:38:06 +0000 (14:38 +0300)]
Make WaitForLSNReplay() issue FATAL on postmaster death

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/ZvY2C8N4ZqgCFaLu%40paquier.xyz
Reviewed-by: Pavel Borisov
6 months agoMove LSN waiting declarations and definitions to better place
Alexander Korotkov [Thu, 24 Oct 2024 11:37:53 +0000 (14:37 +0300)]
Move LSN waiting declarations and definitions to better place

3c5db1d6b implemented the pg_wal_replay_wait() stored procedure.  Due to
the patch development history, the implementation resided in
src/backend/commands/waitlsn.c (src/include/commands/waitlsn.h for headers).

014f9f34d moved pg_wal_replay_wait() itself to
src/backend/access/transam/xlogfuncs.c near to the WAL-manipulation functions.
But most of the implementation stayed in place.

The code in src/backend/commands/waitlsn.c has nothing to do with commands,
but is related to WAL.  So, this commit moves this code into
src/backend/access/transam/xlogwait.c (src/include/access/xlogwait.h for
headers).

Reported-by: Peter Eisentraut
Discussion: https://postgr.es/m/18c0fa64-0475-415e-a1bd-665d922c5201%40eisentraut.org
Reviewed-by: Pavel Borisov
6 months agoAvoid looping over all type cache entries in TypeCacheRelCallback()
Alexander Korotkov [Thu, 24 Oct 2024 11:35:52 +0000 (14:35 +0300)]
Avoid looping over all type cache entries in TypeCacheRelCallback()

Currently, when a single relcache entry gets invalidated,
TypeCacheRelCallback() has to loop over all type cache entries to find
appropriate typentry to invalidate.  Unfortunately, using the syscache here
is impossible, because this callback could be called outside a transaction
and this makes impossible catalog lookups.  This is why present commit
introduces RelIdToTypeIdCacheHash to map relation OID to its composite type
OID.

We are keeping RelIdToTypeIdCacheHash entry while corresponding type cache
entry have something to clean.  Therefore, RelIdToTypeIdCacheHash shouldn't
get bloat in the case of temporary tables flood.

There are many places in lookup_type_cache() where syscache invalidation,
user interruption, or even error could occur.  In order to handle this, we
keep an array of in-progress type cache entries.  In the case of
lookup_type_cache() interruption this array is processed to keep
RelIdToTypeIdCacheHash in a consistent state.

Discussion: https://postgr.es/m/5812a6e5-68ae-4d84-9d85-b443176966a1%40sigaev.ru
Author: Teodor Sigaev
Reviewed-by: Aleksander Alekseev, Tom Lane, Michael Paquier, Roman Zharkov
Reviewed-by: Andrei Lepikhov, Pavel Borisov, Jian He, Alexander Lakhin
Reviewed-by: Artur Zakirov
6 months agoUpdate header comment for lookup_type_cache()
Alexander Korotkov [Thu, 24 Oct 2024 11:34:16 +0000 (14:34 +0300)]
Update header comment for lookup_type_cache()

Describe the way we handle concurrent invalidation messages.

Discussion: https://postgr.es/m/CAPpHfdsQhwUrnB3of862j9RgHoJM--eRbifvBMvtQxpC57dxCA%40mail.gmail.com
Reviewed-by: Andrei Lepikhov, Artur Zakirov, Pavel Borisov
6 months agoTrack more precisely query locations for nested statements
Michael Paquier [Thu, 24 Oct 2024 00:28:51 +0000 (09:28 +0900)]
Track more precisely query locations for nested statements

Previously, a Query generated through the transform phase would have
unset stmt_location, tracking the starting point of a query string.

Extensions relying on the statement location to extract its relevant
parts in the source text string would fallback to use the whole
statement instead, leading to confusing results like in
pg_stat_statements for queries relying on nested queries, like:
- EXPLAIN, with top-level and nested query using the same query string,
and a query ID coming from the nested query when the non-top-level
entry.
- Multi-statements, with only partial portions of queries being
normalized.
- COPY TO with a query, SELECT or DMLs.

This patch improves things by keeping track of the statement locations
and propagate it to Query during transform, allowing PGSS to only show
the relevant part of the query for nested query.  This leads to less
bloat in entries for non-top-level entries, as queries can now be
grouped within the same (toplevel, queryid) duos in pg_stat_statements.
The result gives a stricter one-one mapping between query IDs and its
query strings.

The regression tests introduced in 45e0ba30fc40 produce differences
reflecting the new logic.

Author: Anthonin Bonnefoy
Reviewed-by: Michael Paquier, Jian He
Discussion: https://postgr.es/m/CAO6_XqqM6S9bQ2qd=75W+yKATwoazxSNhv5sjW06fjGAtHbTUA@mail.gmail.com

6 months agoImprove pg_set_attribute_stats() error message.
Jeff Davis [Wed, 23 Oct 2024 23:11:45 +0000 (16:11 -0700)]
Improve pg_set_attribute_stats() error message.

Previously, an invalid attribute name was caught, but the error
message was unhelpful.

6 months agoFix typo in tidstore.h.
Masahiko Sawada [Wed, 23 Oct 2024 22:37:00 +0000 (15:37 -0700)]
Fix typo in tidstore.h.

An oversight in commit f6bef362c.

Reviewed-by: David Rowley
Discussion: https://postgr.es/m/CAD21AoB8MJ5OHtpUw1UEGf7spioFmP3PNH44KNx6Yb3FiZSwKA%40mail.gmail.com

6 months agoAnother documentation fixup.
Jeff Davis [Wed, 23 Oct 2024 17:28:31 +0000 (10:28 -0700)]
Another documentation fixup.

Reported-by: Erik Rijkers
6 months agoFix compiler warning.
Jeff Davis [Wed, 23 Oct 2024 17:24:17 +0000 (10:24 -0700)]
Fix compiler warning.

Some buildfarm members complained about an always-true test in the
SOFT_ERROR_OCCURRED macro. Fix by reading the field directly rather
than using the macro.

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

6 months agoDocumentation fixup.
Jeff Davis [Wed, 23 Oct 2024 16:43:06 +0000 (09:43 -0700)]
Documentation fixup.

Wrong return type for pg_clear_attribute_stats().

Author: Noriyoshi Shinoda
Discussion: https://postgr.es/m/DM4PR84MB17347944F27A552F0CCDF84CEE4C2@DM4PR84MB1734.NAMPRD84.PROD.OUTLOOK.COM

6 months agoFix incorrect struct reference in comment
Daniel Gustafsson [Wed, 23 Oct 2024 14:13:28 +0000 (16:13 +0200)]
Fix incorrect struct reference in comment

SASL frontend mechanisms are implemented with pg_fe_sasl_mech and
not the _be_ variant which is the backend implementation. Spotted
while reading adjacent code.

6 months agoMake SASL max message length configurable
Daniel Gustafsson [Wed, 23 Oct 2024 14:10:27 +0000 (16:10 +0200)]
Make SASL max message length configurable

The proposed OAUTHBEARER SASL mechanism will need to allow larger
messages in the exchange, since tokens are sent directly by the
client.  Move this limit into the pg_be_sasl_mech struct so that
it can be changed per-mechanism.

Author: Jacob Champion <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Discussion: https://postgr.es/m/CAOYmi+nqX_5=Se0W0Ynrr55Fha3CMzwv_R9P3rkpHb=1kG7ZTQ@mail.gmail.com

6 months agodoc: Fix INSERT statement syntax for identity columns
Daniel Gustafsson [Wed, 23 Oct 2024 12:58:17 +0000 (14:58 +0200)]
doc: Fix INSERT statement syntax for identity columns

The INSERT statements in the examples were erroneously using
VALUE instead of VALUES. Backpatch to v17 where the examples
were added through a37bb7c1399.

Reported-by: [email protected]
Discussion: https://postgr.es/m/172958472112.696.6075270400394560263@wrigleys.postgresql.org
Backpatch-through: 17

6 months agoRemove unnecessary word in a comment
Amit Langote [Wed, 23 Oct 2024 08:54:48 +0000 (17:54 +0900)]
Remove unnecessary word in a comment

Relations opened by the executor are only closed once in
ExecCloseRangeTableRelations(), so the word "again" in the comment
for ExecGetRangeTableRelation() is misleading and unnecessary.

Discussion: https://postgr.es/m/CA+HiwqHnw-zR+u060i3jp4ky5UR0CjByRFQz50oZ05de7wUg=Q@mail.gmail.com
Backpatch-through: 12

6 months agoecpg: Fix out-of-bound read in DecodeDateTime()
Michael Paquier [Tue, 22 Oct 2024 23:33:54 +0000 (08:33 +0900)]
ecpg: Fix out-of-bound read in DecodeDateTime()

It was possible for the code to read out-of-bound data from the
"day_tab" table with some crafted input data.  Let's treat these as
invalid input as the month number is incorrect.

A test is added to test this case with a check on the errno returned by
the decoding routine.  A test close to the new one added in this commit
was testing for a failure, but did not look at the errno generated, so
let's use this commit to also change it, adding a check on the errno
returned by DecodeDateTime().

Like the other test scripts, dt_test should likely be expanded to
include more checks based on the errnos generated in these code paths.
This is left as future work.

This issue exists since 2e6f97560a83, so backpatch all the way down.

Reported-by: Pavel Nekrasov
Author: Bruce Momjian, Pavel Nekrasov
Discussion: https://postgr.es/m/18614-6bbe00117352309e@postgresql.org
Backpatch-through: 12

6 months agoAdd functions pg_set_attribute_stats() and pg_clear_attribute_stats().
Jeff Davis [Tue, 22 Oct 2024 22:06:55 +0000 (15:06 -0700)]
Add functions pg_set_attribute_stats() and pg_clear_attribute_stats().

Enable manipulation of attribute statistics. Only superficial
validation is performed, so it's possible to add nonsense, and it's up
to the planner (or other users of statistics) to behave reasonably in
that case.

Bump catalog version.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=eErgzn7ECDpwFcptJKOk9SxZEk5Pot4d94eVTZsvj3gw@mail.gmail.com

6 months agoChange pg_*_relation_stats() functions to return type to void.
Jeff Davis [Tue, 22 Oct 2024 19:48:01 +0000 (12:48 -0700)]
Change pg_*_relation_stats() functions to return type to void.

These functions will either raise an ERROR or run to normal
completion, so no return value is necessary.

Bump catalog version.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=cBF8rnphuTyHFi3KYzB9ByDgx57HwK9Rz2yp7S+Om87w@mail.gmail.com

6 months agoImprove reporting of errors in extension script files.
Tom Lane [Tue, 22 Oct 2024 15:31:45 +0000 (11:31 -0400)]
Improve reporting of errors in extension script files.

Previously, CREATE/ALTER EXTENSION gave basically no useful
context about errors reported while executing script files.
I think the idea was that you could run the same commands
manually to see the error, but that's often quite inconvenient.
Let's improve that.

If we get an error during raw parsing, we won't have a current
statement identified by a RawStmt node, but we should always get
a syntax error position.  Show the portion of the script from
the last semicolon-newline before the error position to the first
one after it.  There are cases where this might show only a
fragment of a statement, but that should be uncommon, and it
seems better than showing the whole script file.

Without an error cursor, if we have gotten past raw parsing (which
we probably have), we can report just the current SQL statement as
an item of error context.

In any case also report the script file name as error context,
since it might not be entirely obvious which of a series of
update scripts failed.  We can also show an approximate script
line number in case whatever we printed of the query isn't
sufficiently identifiable.

The error-context code path is already exercised by some
test_extensions test cases, but add tests for the syntax-error
path.

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

6 months agoImprove parser's reporting of statement start locations.
Tom Lane [Tue, 22 Oct 2024 15:26:05 +0000 (11:26 -0400)]
Improve parser's reporting of statement start locations.

Up to now, the parser's reporting of a statement's stmt_location
included any preceding whitespace or comments.  This isn't really
desirable but was done to avoid accounting honestly for nonterminals
that reduce to empty.  It causes problems for pg_stat_statements,
which partially compensates by manually stripping whitespace, but
is not bright enough to strip /*-style comments.  There will be
more problems with an upcoming patch to improve reporting of errors
in extension scripts, so it's time to do something about this.

The thing we have to do to make it work right is to adjust
YYLLOC_DEFAULT to scan the inputs of each production to find the
first one that has a valid location (i.e., did not reduce to
empty).  In theory this adds a little bit of per-reduction overhead,
but in practice it's negligible.  I checked by measuring the time
to run raw_parser() on the contents of information_schema.sql, and
there was basically no change.

Having done that, we can rely on any nonterminal that didn't reduce
to completely empty to have a correct starting location, and we don't
need the kluges the stmtmulti production formerly used.

This should have a side benefit of allowing parse error reports to
include an error position in some cases where they formerly failed to
do so, due to trying to report the position of an empty nonterminal.
I did not go looking for an example though.  The one previously known
case where that could happen (OptSchemaEltList) no longer needs the
kluge it had; but I rather doubt that that was the only case.

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

6 months agoecpg: Refactor ecpg_log() to skip unnecessary calls to ECPGget_sqlca().
Fujii Masao [Tue, 22 Oct 2024 14:56:37 +0000 (23:56 +0900)]
ecpg: Refactor ecpg_log() to skip unnecessary calls to ECPGget_sqlca().

Previously, ecpg_log() always called ECPGget_sqlca() to retrieve sqlca,
even though it was only needed for debug logging. This commit updates
ecpg_log() to call ECPGget_sqlca() only when debug logging is enabled.

Author: Yuto Sasaki
Reviewed-by: Alvaro Herrera, Tom Lane, Fujii Masao
Discussion: https://postgr.es/m/TY2PR01MB3628A85689649BABC9A1C6C3C1782@TY2PR01MB3628.jpnprd01.prod.outlook.com

6 months agoRestructure foreign key handling code for ATTACH/DETACH
Álvaro Herrera [Tue, 22 Oct 2024 14:01:18 +0000 (16:01 +0200)]
Restructure foreign key handling code for ATTACH/DETACH

... to fix bugs when the referenced table is partitioned.

The catalog representation we chose for foreign keys connecting
partitioned tables (in commit f56f8f8da6af) is inconvenient, in the
sense that a standalone table has a different way to represent the
constraint when referencing a partitioned table, than when the same
table becomes a partition (and vice versa).  Because of this, we need to
create additional catalog rows on detach (pg_constraint and pg_trigger),
and remove them on attach.  We were doing some of those things, but not
all of them, leading to missing catalog rows in certain cases.

The worst problem seems to be that we are missing action triggers after
detaching a partition, which means that you could update/delete rows
from the referenced partitioned table that still had referencing rows on
that table, the server failing to throw the required errors.

!!!
Note that this means existing databases with FKs that reference
partitioned tables might have rows that break relational integrity, on
tables that were once partitions on the referencing side of the FK.

Another possible problem is that trying to reattach a table
that had been detached would fail indicating that internal triggers
cannot be found, which from the user's point of view is nonsensical.

In branches 15 and above, we fix this by creating a new helper function
addFkConstraint() which is in charge of creating a standalone
pg_constraint row, and repurposing addFkRecurseReferencing() and
addFkRecurseReferenced() so that they're only the recursive routine for
each side of the FK, and they call addFkConstraint() to create
pg_constraint at each partitioning level and add the necessary triggers.
These new routines can be used during partition creation, partition
attach and detach, and foreign key creation.  This reduces redundant
code and simplifies the flow.

In branches 14 and 13, we have a much simpler fix that consists on
simply removing the constraint on detach.  The reason is that those
branches are missing commit f4566345cf40, which reworked the way this
works in a way that we didn't consider back-patchable at the time.

We opted to leave branch 12 alone, because it's different from branch 13
enough that the fix doesn't apply; and because it is going in EOL mode
very soon, patching it now might be worse since there's no way to undo
the damage if it goes wrong.

Existing databases might need to be repaired.

In the future we might want to rethink the catalog representation to
avoid this problem, but for now the code seems to do what's required to
make the constraints operate correctly.

Co-authored-by: Jehan-Guillaume de Rorthais <[email protected]>
Co-authored-by: Tender Wang <[email protected]>
Co-authored-by: Alvaro Herrera <[email protected]>
Reported-by: Guillaume Lelarge <[email protected]>
Reported-by: Jehan-Guillaume de Rorthais <[email protected]>
Reported-by: Thomas Baehler (SBB CFF FFS) <[email protected]>
Discussion: https://postgr.es/m/20230420144344.40744130@karst
Discussion: https://postgr.es/m/20230705233028.2f554f73@karst
Discussion: https://postgr.es/m/GVAP278MB02787E7134FD691861635A8BC9032@GVAP278MB0278.CHEP278.PROD.OUTLOOK.COM
Discussion: https://postgr.es/m/18541-628a61bc267cd2d3@postgresql.org

6 months agoMake all Perl warnings fatal in 043_wal_replay_wait.pl
Alexander Korotkov [Tue, 22 Oct 2024 10:25:10 +0000 (13:25 +0300)]
Make all Perl warnings fatal in 043_wal_replay_wait.pl

This file was committed after c5385929593, but accidentally missed changing
all warnings into fatal errors.

Reported-by: Anton Voloshin
Discussion: https://postgr.es/m/aa8a55d5-554a-4027-a491-1b0ca7c85f7a%40postgrespro.ru

6 months agoFix C23 compiler warning
Peter Eisentraut [Tue, 22 Oct 2024 06:12:43 +0000 (08:12 +0200)]
Fix C23 compiler warning

The approach of declaring a function pointer with an empty argument
list and hoping that the compiler will not complain about casting it
to another type no longer works with C23, because foo() is now
equivalent to foo(void).

We don't need to do this here.  With a few struct forward declarations
we can supply a correct argument list without having to pull in
another header file.

(This is the only new warning with C23.  Together with the previous
fix a67a49648d9, this makes the whole code compile cleanly under C23.)

Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/95c6a9bf-d306-43d8-b880-664ef08f2944%40eisentraut.org

6 months agopg_stat_statements: Add tests for nested queries with level tracking
Michael Paquier [Tue, 22 Oct 2024 04:05:51 +0000 (13:05 +0900)]
pg_stat_statements: Add tests for nested queries with level tracking

There have never been any regression tests in PGSS for various query
patterns for nested queries combined with level tracking, like:
- Multi-statements.
- CREATE TABLE AS
- CREATE/REFRESH MATERIALIZED VIEW
- DECLARE CURSOR
- EXPLAIN, with a subset of the above supported.
- COPY.

All the tests added here track historical, sometimes confusing, existing
behaviors.  For example, EXPLAIN stores two PGSS entries with the same
top-level query string but two different query IDs as one is calculated
for the top-level EXPLAIN (this part is right) and a second one for the
inner query in the EXPLAIN (this part is not right).

A couple of patches are under discussion to improve the situation, and
all the tests added here will prove useful to evaluate the changes
discussed.

Author: Anthonin Bonnefoy
Reviewed-by: Michael Paquier, Jian He
Discussion: https://postgr.es/m/CAO6_XqqM6S9bQ2qd=75W+yKATwoazxSNhv5sjW06fjGAtHbTUA@mail.gmail.com

6 months agoFix wrong assertion and poor error messages in "COPY (query) TO".
Tom Lane [Mon, 21 Oct 2024 19:08:22 +0000 (15:08 -0400)]
Fix wrong assertion and poor error messages in "COPY (query) TO".

If the query is rewritten into a NOTIFY command by a DO INSTEAD
rule, we'd get an assertion failure, or in non-assert builds
issue a rather confusing error message.  Improve that.

Also fix a longstanding grammar mistake in a nearby error message.

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

Tender Wang and Tom Lane

Discussion: https://postgr.es/m/18664-ffd0ebc2386598df@postgresql.org

6 months agoUpdate outdated comment on WAL-logged locks with invalid XID
Heikki Linnakangas [Mon, 21 Oct 2024 11:28:43 +0000 (14:28 +0300)]
Update outdated comment on WAL-logged locks with invalid XID

We haven't generated those for a long time.

Discussion: https://www.postgresql.org/message-id/b439edfc-c5e5-43a9-802d-4cb51ec20646@iki.fi

6 months agoFix race condition in committing a serializable transaction
Heikki Linnakangas [Mon, 21 Oct 2024 06:49:21 +0000 (09:49 +0300)]
Fix race condition in committing a serializable transaction

The finished transaction list can contain XIDs that are older than the
serializable global xmin. It's a short-lived state;
ClearOldPredicateLocks() removes any such transactions from the list,
and it's called whenever the global xmin advances. But if another
backend calls SummarizeOldestCommittedSxact() in that window, it will
call SerialAdd() on an XID that's older than the global xmin, or if
there are no more transactions running, when global xmin is
invalid. That trips the assertion in SerialAdd().

Fixes bug #18658 reported by Andrew Bille. Thanks to Alexander Lakhin
for analysis. Backpatch to all versions.

Discussion: https://www.postgresql.org/message-id/18658-7dab125ec688c70b%40postgresql.org

6 months agoFix grammar of a comment in bufmgr.c
Michael Paquier [Mon, 21 Oct 2024 02:25:29 +0000 (11:25 +0900)]
Fix grammar of a comment in bufmgr.c

Author: Junwang Zhao
Discussion: https://postgr.es/m/CAEG8a3L5YjxXCjx0LhkwHdDGsNgpFGEqH7SqtXRPNP+dwFMVZQ@mail.gmail.com

6 months agoinjection_points: Add basic isolation test
Michael Paquier [Mon, 21 Oct 2024 02:10:51 +0000 (11:10 +0900)]
injection_points: Add basic isolation test

This test can act as a template when implementing an isolation test with
injection points, and tracks in a much simpler way some of the behaviors
implied in the existing isolation test "inplace" that has been added in
c35f419d6efb.  Particularly, a detach does not affect a backend wait; a
wait needs to be interrupted by a wakeup.

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

6 months agoNote that index_name in ALTER INDEX ATTACH PARTITION can be schema-qualified
Álvaro Herrera [Sun, 20 Oct 2024 13:36:20 +0000 (15:36 +0200)]
Note that index_name in ALTER INDEX ATTACH PARTITION can be schema-qualified

Missed in 8b08f7d4820f; backpatch to all supported branches.

Reported-by: [email protected]
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/172924785099.698.15236991344616673753@wrigleys.postgresql.org