postgresql.git
4 hours agoAdd optional pid parameter to pg_replication_origin_session_setup(). master github/master
Amit Kapila [Fri, 19 Sep 2025 05:38:40 +0000 (05:38 +0000)]
Add optional pid parameter to pg_replication_origin_session_setup().

Commit 216a784829c introduced parallel apply workers, allowing multiple
processes to share a replication origin. To support this,
replorigin_session_setup() was extended to accept a pid argument
identifying the process using the origin.

This commit exposes that capability through the SQL interface function
pg_replication_origin_session_setup() by adding an optional pid parameter.
This enables multiple processes to coordinate replication using the same
origin when using SQL-level replication functions.

This change allows the non-builtin logical replication solutions to
implement parallel apply for large transactions.

Additionally, an existing internal error was made user-facing, as it can
now be triggered via the exposed SQL API.

Author: Doruk Yilmaz <doruk@mixrank.com>
Author: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Euler Taveira <euler@eulerto.com>
Discussion: https://postgr.es/m/CAMPB6wfe4zLjJL8jiZV5kjjpwBM2=rTRme0UCL7Ra4L8MTVdOg@mail.gmail.com
Discussion: https://postgr.es/m/CAE2gYzyTSNvHY1+iWUwykaLETSuAZsCWyryokjP6rG46ZvRgQA@mail.gmail.com

5 hours agoImprove few errdetail messages introduced in commit 0d48d393d46.
Amit Kapila [Fri, 19 Sep 2025 04:52:59 +0000 (04:52 +0000)]
Improve few errdetail messages introduced in commit 0d48d393d46.

Based on suggestions by Tom Lane

Reported-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/20250916.114644.275726106301941878.horikyota.ntt@gmail.com

5 hours agoMake XLogFlush() and XLogNeedsFlush() decision-making more consistent
Michael Paquier [Fri, 19 Sep 2025 04:47:28 +0000 (13:47 +0900)]
Make XLogFlush() and XLogNeedsFlush() decision-making more consistent

When deciding which code path to use depending on the state of recovery,
XLogFlush() and XLogNeedsFlush() have been relying on different
criterias:
- XLogFlush() relied on XLogInsertAllowed().
- XLogNeedsFlush() relied on RecoveryInProgress().

Currently, the checkpointer is allowed to insert WAL records while
RecoveryInProgress() returns true for an end-of-recovery checkpoint,
where XLogInsertAllowed() matters.  Using RecoveryInProgress() in
XLogNeedsFlush() did not really matter for its existing callers, as the
checkpointer only called XLogFlush().  However, a feature under
discussion, by Melanie Plageman, needs XLogNeedsFlush() to be able to
work in more contexts, the end-of-recovery checkpoint being one.

This commit changes XLogNeedsFlush() to use XLogInsertAllowed() instead
of RecoveryInProgress(), making the checks in both routines more
consistent.  While on it, an assertion based on XLogNeedsFlush() is
added at the end of XLogFlush(), triggered when flushing a physical
position (not for the normal recovery patch that checks for updates of
the minimum recovery point).  This assertion would fail for example in
the recovery test 015_promotion_pages if XLogNeedsFlush() is changed to
use RecoveryInProgress().  This should be hopefully enough to ensure
that the checks done in both routines remain consistent.

Author: Melanie Plageman <melanieplageman@gmail.com>
Co-authored-by: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: Jeff Davis <pgsql@j-davis.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/CAAKRu_a1vZRZRWO3_jv_X13RYoqLRVipGO0237g5PKzPa2YX6g@mail.gmail.com

7 hours agoFix EPQ crash from missing partition pruning state in EState
Amit Langote [Fri, 19 Sep 2025 02:38:29 +0000 (11:38 +0900)]
Fix EPQ crash from missing partition pruning state in EState

Commit bb3ec16e14 moved partition pruning metadata into PlannedStmt.
At executor startup this metadata is used to initialize the EState
fields es_part_prune_infos, es_part_prune_states, and
es_part_prune_results.  EvalPlanQualStart() failed to copy those
fields into the child EState, causing NULL dereference when Append
ran partition pruning during a recheck. This can occur with DELETE
or UPDATE on partitioned tables that use runtime pruning, e.g. with
generic plans.

Fix by copying all partition pruning state into the EPQ estate.

Add an isolation test that reproduces the crash with concurrent
UPDATE and DELETE on a partitioned table, where the DELETE session
hits the crash during its EPQ recheck after the UPDATE commits.

Bug: #19056
Reported-by: Fei Changhong <feichanghong@qq.com>
Diagnozed-by: Fei Changhong <feichanghong@qq.com>
Author: David Rowley <dgrowleyml@gmail.com>
Co-authored-by: Amit Langote <amitlangote09@gmail.com>
Discussion: https://postgr.es/m/19056-a677cef9b54d76a0%40postgresql.org

9 hours agoDocument and check that PgStat_HashKey has no padding
Michael Paquier [Fri, 19 Sep 2025 00:54:05 +0000 (09:54 +0900)]
Document and check that PgStat_HashKey has no padding

This change is a tighter rework of 7d85d87f4d5c, which tried to improve
the code so as it would work should PgStat_HashKey gain new fields that
create padding bytes.  However, the previous change is proving to not be
enough as some code paths of pgstats do not pass PgStat_HashKey by
reference (valgrind would warn when padding is added to the structure,
through a new field).

Per discussion, let's document and check that PgStat_HashKey has no
padding rather than try to complicate the code of pgstats so as it is
able to work around that.

This removes a couple of memset(0) calls that should not be required.
While on it, this commit adds a static assertion checking that no
padding is introduced in the structure, by checking that the size of
PgStat_HashKey matches with the sum of the size of all its fields.

The object ID part of the hash key is already 8 bytes, which should be
plenty enough already.  A comment is added to discourage the addition of
new fields.

Author: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Sami Imseih <samimseih@gmail.com>
Discussion: https://postgr.es/m/CAA5RZ0t9omat+HVSakJXwTMWvhpYFcAZb41RPWKwrKFUgmAFBQ@mail.gmail.com

13 hours agoAdd a test harness for the LWLock tranche code.
Nathan Bossart [Thu, 18 Sep 2025 20:23:11 +0000 (15:23 -0500)]
Add a test harness for the LWLock tranche code.

This code is heavily used and already has decent test coverage, but
it lacks a dedicated test suite.  This commit changes that.

Author: Sami Imseih <samimseih@gmail.com>
Co-authored-by: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Discussion: https://postgr.es/m/CAA5RZ0tQ%2BEYSTOd2hQ8RXdsNfGBLAtOe-YmnsTE6ZVg0E-4qew%40mail.gmail.com
Discussion: https://postgr.es/m/CAA5RZ0vpr0P2rbA%3D_K0_SCHM7bmfVX4wEO9FAyopN1eWCYORhA%40mail.gmail.com

19 hours agoFix re-initialization of LWLock-related shared memory.
Nathan Bossart [Thu, 18 Sep 2025 14:55:39 +0000 (09:55 -0500)]
Fix re-initialization of LWLock-related shared memory.

When shared memory is re-initialized after a crash, the named
LWLock tranche request array that was copied to shared memory will
no longer be accessible.  To fix, save the pointer to the original
array in postmaster's local memory, and switch to it when
re-initializing the LWLock-related shared memory.

Oversight in commit ed1aad15e0.  Per buildfarm member batta.

Reported-by: Michael Paquier <michael@paquier.xyz>
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/aMoejB3iTWy1SxfF%40paquier.xyz
Discussion: https://postgr.es/m/f8ca018f-3479-49f6-a92c-e31db9f849d7%40gmail.com

31 hours agopgbench: Remove unused argument from create_sql_command().
Fujii Masao [Thu, 18 Sep 2025 02:22:21 +0000 (11:22 +0900)]
pgbench: Remove unused argument from create_sql_command().

Author: Yugo Nagata <nagata@sraoss.co.jp>
Reviewed-by: Steven Niu <niushiji@gmail.com>
Discussion: https://postgr.es/m/20250917112814.096f660ea4c3c64630475e62@sraoss.co.jp

31 hours agopg_restore: Fix security label handling with --no-publications/subscriptions.
Fujii Masao [Thu, 18 Sep 2025 02:09:15 +0000 (11:09 +0900)]
pg_restore: Fix security label handling with --no-publications/subscriptions.

Previously, pg_restore did not skip security labels on publications or
subscriptions even when --no-publications or --no-subscriptions was specified.
As a result, it could issue SECURITY LABEL commands for objects that were
never created, causing those commands to fail.

This commit fixes the issue by ensuring that security labels on publications
and subscriptions are also skipped when the corresponding options are used.

Backpatch to all supported versions.

Author: Jian He <jian.universality@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CACJufxHCt00pR9h51AVu6+yPD5J7JQn=7dQXxqacj0XyDhc-fA@mail.gmail.com
Backpatch-through: 13

33 hours agoMark shared buffer lookup table HASH_FIXED_SIZE
Andres Freund [Thu, 18 Sep 2025 00:28:43 +0000 (20:28 -0400)]
Mark shared buffer lookup table HASH_FIXED_SIZE

StrategyInitialize() calls InitBufTable() with maximum number of entries that
the buffer lookup table can ever have. Thus there should not be any need to
allocate more element after initialization. Hence mark the hash table as fixed
sized.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://postgr.es/m/CAExHW5v0jh3F_wj86yC=qBfWk0uiT94qy=Z41uzAHLHh0SerRA@mail.gmail.com

37 hours agoCalculate agglevelsup correctly when Aggref contains a CTE.
Tom Lane [Wed, 17 Sep 2025 20:32:57 +0000 (16:32 -0400)]
Calculate agglevelsup correctly when Aggref contains a CTE.

If an aggregate function call contains a sub-select that has
an RTE referencing a CTE outside the aggregate, we must treat
that reference like a Var referencing the CTE's query level
for purposes of determining the aggregate's level.  Otherwise
we might reach the nonsensical conclusion that the aggregate
should be evaluated at some query level higher than the CTE,
ending in a planner error or a broken plan tree that causes
executor failures.

Bug: #19055
Reported-by: BugForge <dllggyx@outlook.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19055-6970cfa8556a394d@postgresql.org
Backpatch-through: 13

2 days agojit: Fix type used for Datum values in LLVM IR.
Thomas Munro [Wed, 17 Sep 2025 00:00:16 +0000 (12:00 +1200)]
jit: Fix type used for Datum values in LLVM IR.

Commit 2a600a93 made Datum 8 bytes wide everywhere.  It was no longer
appropriate to use TypeSizeT on 32 bit systems, and JIT compilation
would fail with various type check errors.  Introduce a separate
LLVMTypeRef with the name TypeDatum.  TypeSizeT is still used in some
places for actual size_t values.

Reported-by: Dmitry Mityugov <d.mityugov@postgrespro.ru>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Tested-by: Dmitry Mityugov <d.mityugov@postgrespro.ru>
Discussion: https://postgr.es/m/0a9f0be59171c2e8f1b3bc10f4fcf267%40postgrespro.ru

2 days agoinjection_points: Fix incrementation of variable-numbered stats
Michael Paquier [Wed, 17 Sep 2025 01:15:13 +0000 (10:15 +0900)]
injection_points: Fix incrementation of variable-numbered stats

The pending entry was not used when incrementing its data, directly
manipulating the shared memory pointer, without even locking it.  This
could mean losing statistics under concurrent activity.  The flush
callback was a no-op.

This code serves as a base template for extensions for the custom
cumulative statistics, so let's be clean and use a pending entry for the
incrementations, whose data is then flushed to the corresponding entry
in the shared hashtable when all the stats are reported, in its own
flush callback.

Author: Sami Imseih <samimseih@gmail.com>
Discussion: https://postgr.es/m/CAA5RZ0v0U0yhPbY+bqChomkPbyUrRQ3rQXnZf_SB-svDiQOpgQ@mail.gmail.com
Backpatch-through: 18

2 days agoFix shared memory calculation size of PgAioCtl
Michael Paquier [Wed, 17 Sep 2025 00:33:32 +0000 (09:33 +0900)]
Fix shared memory calculation size of PgAioCtl

The shared memory size was calculated based on an offset of io_handles,
which is itself a pointer included in the structure.  We tend to
overestimate the shared memory size overall, so this was unlikely an
issue in practice, but let's be correct and use the full size of the
structure in the calculation, so as the pointer for io_handles is
included.

Oversight in da7226993fd4.

Author: Madhukar Prasad <madhukarprasad@google.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
Discussion: https://postgr.es/m/CAKi+wrbC2dTzh_vKJoAZXV5wqTbhY0n4wRNpCjJ=e36aoo0kFw@mail.gmail.com
Backpatch-through: 18

2 days agoAdd missing EPQ recheck for TID Range Scan
David Rowley [Wed, 17 Sep 2025 00:19:15 +0000 (12:19 +1200)]
Add missing EPQ recheck for TID Range Scan

The EvalPlanQual recheck for TID Range Scan wasn't rechecking the TID qual
still passed after following update chains.  This could result in tuples
being updated or deleted by plans using TID Range Scans where the ctid of
the new (updated) tuple no longer matches the clause of the scan.  This
isn't desired behavior, and isn't consistent with what would happen if the
chosen plan had used an Index or Seq Scan, and that could lead to hard to
predict behavior for scans that contain TID quals and other quals as the
planner has freedom to choose TID Range or some other non-TID scan method
for such queries, and the chosen plan could change at any moment.

Here we fix this by properly implementing the recheck function for TID
Range Scans.

Backpatch to 14, where TID Range Scans were added

Reported-by: Sophie Alpert <pg@sophiebits.com>
Author: Sophie Alpert <pg@sophiebits.com>
Author: David Rowley <dgrowleyml@gmail.com>
Reviewed-by: David Rowley <dgrowleyml@gmail.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/4a6268ff-3340-453a-9bf5-c98d51a6f729@app.fastmail.com
Backpatch-through: 14

2 days agoAdd missing EPQ recheck for TID Scan
David Rowley [Tue, 16 Sep 2025 23:48:55 +0000 (11:48 +1200)]
Add missing EPQ recheck for TID Scan

The EvalPlanQual recheck for TID Scan wasn't rechecking the TID qual
still passed after following update chains.  This could result in tuples
being updated or deleted by plans using TID Scans where the ctid of the
new (updated) tuple no longer matches the clause of the scan.  This isn't
desired behavior, and isn't consistent with what would happen if the
chosen plan had used an Index or Seq Scan, and that could lead to hard to
predict behavior for scans that contain TID quals and other quals as the
planner has freedom to choose TID or some other scan method for such
queries, and the chosen plan could change at any moment.

Here we fix this by properly implementing the recheck function for TID
Scans.

Backpatch to 13, oldest supported version

Reported-by: Sophie Alpert <pg@sophiebits.com>
Author: Sophie Alpert <pg@sophiebits.com>
Author: David Rowley <dgrowleyml@gmail.com>
Reviewed-by: David Rowley <dgrowleyml@gmail.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/4a6268ff-3340-453a-9bf5-c98d51a6f729@app.fastmail.com
Backpatch-through: 13

2 days agoAdd regression expected-files for older OpenSSL in FIPS mode.
Tom Lane [Tue, 16 Sep 2025 18:36:51 +0000 (14:36 -0400)]
Add regression expected-files for older OpenSSL in FIPS mode.

Cover contrib/pgcrypto, per buildfarm.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/443709.1757876535@sss.pgh.pa.us
Backpatch-through: 17

2 days agoRevert "Avoid race condition between "GRANT role" and "DROP ROLE"".
Tom Lane [Tue, 16 Sep 2025 17:05:53 +0000 (13:05 -0400)]
Revert "Avoid race condition between "GRANT role" and "DROP ROLE"".

This reverts commit 98fc31d6499163a0a781aa6f13582a07f09cd7c6.
That change allowed DROP OWNED BY to drop grants of the target
role to other roles, arguing that nobody would need those
privileges anymore.  But that's not so: if you're not superuser,
you still need admin privilege on the target role so you can
drop it.

It's not clear whether or how the dependency-based approach
to solving the original problem can be adapted to keep these
grants.  Since v18 release is fast approaching, the sanest
thing to do seems to be to revert this patch for now.  The
race-condition problem is low severity and not worth taking
risks for.

I didn't force a catversion bump in 98fc31d64, so I won't do
so here either.

Reported-by: Dipesh Dhameliya <dipeshdhameliya125@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CABgZEgczOFicCJoqtrH9gbYMe_BV3Hq8zzCBRcMgmU6LRsihUA@mail.gmail.com
Backpatch-through: 18

2 days agoFix pg_dump COMMENT dependency for separate domain constraints.
Noah Misch [Tue, 16 Sep 2025 16:40:44 +0000 (09:40 -0700)]
Fix pg_dump COMMENT dependency for separate domain constraints.

The COMMENT should depend on the separately-dumped constraint, not the
domain.  Sufficient restore parallelism might fail the COMMENT command
by issuing it before the constraint exists.  Back-patch to v13, like
commit 0858f0f96ebb891c8960994f023ed5a17b758a38.

Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/20250913020233.fa.nmisch@google.com
Backpatch-through: 13

2 days agoProvide more-specific error details/hints for function lookup failures.
Tom Lane [Tue, 16 Sep 2025 16:17:02 +0000 (12:17 -0400)]
Provide more-specific error details/hints for function lookup failures.

Up to now we've contented ourselves with a one-size-fits-all error
hint when we fail to find any match to a function or procedure call.
That was mostly okay in the beginning, but it was never great, and
since the introduction of named arguments it's really not adequate.
We at least ought to distinguish "function name doesn't exist" from
"function name exists, but not with those argument names".  And the
rules for named-argument matching are arcane enough that some more
detail seems warranted if we match the argument names but the call
still doesn't work.

This patch creates a framework for dealing with these problems:
FuncnameGetCandidates and related code will now pass back a bitmask of
flags showing how far the match succeeded.  This allows a considerable
amount of granularity in the reports.  The set-bits-in-a-bitmask
approach means that when there are multiple candidate functions, the
report will reflect the match(es) that got the furthest, which seems
correct.  Also, we can avoid mentioning "maybe add casts" unless
failure to match argument types is actually the issue.

Extend the same return-a-bitmask approach to OpernameGetCandidates.
The issues around argument names don't apply to operator syntax,
but it still seems worth distinguishing between "there is no
operator of that name" and "we couldn't match the argument types".

While at it, adjust these messages and related ones to more strictly
separate "detail" from "hint", following our message style guidelines'
distinction between those.

Reported-by: Dominique Devienne <ddevienne@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/1756041.1754616558@sss.pgh.pa.us

2 days agoAdd regression expected-files for older OpenSSL in FIPS mode.
Tom Lane [Tue, 16 Sep 2025 14:09:49 +0000 (10:09 -0400)]
Add regression expected-files for older OpenSSL in FIPS mode.

In our previous discussions around making our regression tests
pass in FIPS mode, we concluded that we didn't need to support
the different error message wording observed with pre-3.0 OpenSSL.
However there are still a few LTS distributions soldiering along
with such versions, and now we have some in the buildfarm.
So let's add the variant expected-files needed to make them happy.

This commit only covers the core regression tests.  Previous
discussion suggested that we might need some adjustments in
contrib as well, but it's not totally clear to me what those
would be.  Rather than work it out from first principles,
I'll wait to see what the buildfarm shows.

Back-patch to v17 which is the oldest branch that claims
to support this case.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/443709.1757876535@sss.pgh.pa.us
Backpatch-through: 17

3 days agoTreat JsonConstructorExpr as non-strict
Richard Guo [Tue, 16 Sep 2025 09:42:20 +0000 (18:42 +0900)]
Treat JsonConstructorExpr as non-strict

JsonConstructorExpr can produce non-NULL output with a NULL input, so
it should be treated as a non-strict construct.  Failing to do so can
lead to incorrect query behavior.

For example, in the reported case, when pulling up a subquery that is
under an outer join, if the subquery's target list contains a
JsonConstructorExpr that uses subquery variables and it is mistakenly
treated as strict, it will be pulled up without being wrapped in a
PlaceHolderVar.  As a result, the expression will be evaluated at the
wrong place and will not be forced to null when the outer join should
do so.

Back-patch to v16 where JsonConstructorExpr was introduced.

Bug: #19046
Reported-by: Runyuan He <runyuan@berkeley.edu>
Author: Tender Wang <tndrwang@gmail.com>
Co-authored-by: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/19046-765b6602b0a8cfdf@postgresql.org
Backpatch-through: 16

3 days agoGenerate GB18030 mappings from the Unicode Consortium's UCM file
John Naylor [Tue, 16 Sep 2025 09:29:08 +0000 (16:29 +0700)]
Generate GB18030 mappings from the Unicode Consortium's UCM file

Previously we built the .map files for GB18030 (version 2000) from an
XML file. The 2022 version for this encoding is only available as a
Unicode Character Mapping (UCM) file, so as preparatory refactoring
switch to this format as the source for building version 2000.

As we do with most input files for the conversion mappings, download
the file on demand. In order to generate the same mappings we have
now, we must download from a previous upstream commit, rather than
the head since the latter contains a correction not present in our
current .map files.

The XML file is still used by EUC_CN, so we cannot delete it from our
repository. GB18030 is a superset of EUC_CN, so it may be possible to
build EUC_CN from the same UCM file, but that is left for future work.

Author: Chao Li <lic@highgo.com>
Discussion: https://postgr.es/m/966d9fc.169.198741fe60b.Coremail.jiaoshuntian%40highgo.com

3 days agoMove pg_int64 back to postgres_ext.h
Peter Eisentraut [Tue, 16 Sep 2025 06:59:12 +0000 (08:59 +0200)]
Move pg_int64 back to postgres_ext.h

Fix for commit 3c86223c998.  That commit moved the typedef of pg_int64
from postgres_ext.h to libpq-fe.h, because the only remaining place
where it might be used is libpq users, and since the type is obsolete,
the intent was to limit its scope.

The problem is that if someone builds an extension against an
older (pre-PG18) server version and a new (PG18) libpq, they might get
two typedefs, depending on include file order.  This is not allowed
under C99, so they might get warnings or errors, depending on the
compiler and options.  The underlying types might also be
different (e.g., long int vs. long long int), which would also lead to
errors.  This scenario is plausible when using the standard Debian
packaging, which provides only the newest libpq but per-major-version
server packages.

The fix is to undo that part of commit 3c86223c998.  That way, the
typedef is in the same header file across versions.  At least, this is
the safest fix doable before PostgreSQL 18 releases.

Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://www.postgresql.org/message-id/25144219-5142-4589-89f8-4e76948b32db%40eisentraut.org

3 days agopg_dump: Fix dumping of security labels on subscriptions and event triggers.
Fujii Masao [Tue, 16 Sep 2025 07:44:58 +0000 (16:44 +0900)]
pg_dump: Fix dumping of security labels on subscriptions and event triggers.

Previously, pg_dump incorrectly queried pg_seclabel to retrieve security labels
for subscriptions, which are stored in pg_shseclabel as they are global objects.
This could result in security labels for subscriptions not being dumped.

This commit fixes the issue by updating pg_dump to query the pg_seclabels view,
which aggregates entries from both pg_seclabel and pg_shseclabel.
While querying pg_shseclabel directly for subscriptions was an alternative,
using pg_seclabels is simpler and sufficient.

In addition, pg_dump is updated to dump security labels on event triggers,
which were previously omitted.

Backpatch to all supported versions.

Author: Jian He <jian.universality@gmail.com>
Co-authored-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CACJufxHCt00pR9h51AVu6+yPD5J7JQn=7dQXxqacj0XyDhc-fA@mail.gmail.com
Backpatch-through: 13

3 days agoFix intermittent BF failures in 035_conflicts.
Amit Kapila [Tue, 16 Sep 2025 06:16:23 +0000 (06:16 +0000)]
Fix intermittent BF failures in 035_conflicts.

This commit addresses two sources of instability in the 035_conflicts
test:

Unstable VACUUM usage:
The test previously relied on VACUUM to remove a deleted column, which can
be unreliable due to concurrent background writer or checkpoint activity
that may lock the page containing the deleted tuple. Since the test
already verifies that replication_slot.xmin has advanced sufficiently to
confirm the feature's correctness, so, the VACUUM step is removed to
improve test stability.

Timing-sensitive retention resumption check:
The test includes a check to confirm that retention of conflict-relevant
information resumes after setting max_retention_duration to 0. However, in
some cases, the apply worker resumes retention immediately after the
inactive slot is removed from synchronized_standby_slots, even before
max_retention_duration is updated. This can happen if remote changes are
applied in under 1ms, causing the test to timeout while waiting for a
later log position. To ensure consistent behavior, this commit delays the
removal of synchronized_standby_slots until after max_retention_duration
is set to 0.

Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: shveta malik <shveta.malik@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/TY4PR01MB16907805DE4816E53C54708159414A@TY4PR01MB16907.jpnprd01.prod.outlook.com

3 days agoFix incorrect const qualifier
Peter Eisentraut [Tue, 16 Sep 2025 05:23:50 +0000 (07:23 +0200)]
Fix incorrect const qualifier

Commit 7202d72787d added in passing some const qualifiers, but the one
on the postmaster_child_launch() startup_data argument was incorrect,
because the function itself modifies the pointed-to data.  This is
hidden from the compiler because of casts.  The qualifiers on the
functions called by postmaster_child_launch() are still correct.

3 days agopg_restore: Fix comment handling with --no-policies.
Fujii Masao [Tue, 16 Sep 2025 02:54:23 +0000 (11:54 +0900)]
pg_restore: Fix comment handling with --no-policies.

Previously, pg_restore did not skip comments on policies even when
--no-policies was specified. As a result, it could issue COMMENT commands
for policies that were never created, causing those commands to fail.

This commit fixes the issue by ensuring that comments on policies
are also skipped when --no-policies is used.

Backpatch to v18, where --no-policies was added in pg_restore.

Author: Jian He <jian.universality@gmail.com>
Co-authored-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CACJufxHCt00pR9h51AVu6+yPD5J7JQn=7dQXxqacj0XyDhc-fA@mail.gmail.com
Backpatch-through: 18

3 days agopg_restore: Fix comment handling with --no-publications / --no-subscriptions.
Fujii Masao [Tue, 16 Sep 2025 01:35:12 +0000 (10:35 +0900)]
pg_restore: Fix comment handling with --no-publications / --no-subscriptions.

Previously, pg_restore did not skip comments on publications or subscriptions
even when --no-publications or --no-subscriptions was specified. As a result,
it could issue COMMENT commands for objects that were never created,
causing those commands to fail.

This commit fixes the issue by ensuring that comments on publications and
subscriptions are also skipped when the corresponding options are used.

Backpatch to all supported versions.

Author: Jian He <jian.universality@gmail.com>
Co-authored-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CACJufxHCt00pR9h51AVu6+yPD5J7JQn=7dQXxqacj0XyDhc-fA@mail.gmail.com
Backpatch-through: 13

3 days agoTeach nbtree to avoid evaluating row compare keys.
Peter Geoghegan [Mon, 15 Sep 2025 20:56:49 +0000 (16:56 -0400)]
Teach nbtree to avoid evaluating row compare keys.

Add logic to _bt_set_startikey that determines whether row compare keys
are guaranteed to be satisfied by every tuple on a page that is about to
be read by _bt_readpage.  This works in essentially the same way as the
existing scalar inequality logic.  Testing has shown that the new logic
improves performance to about the same degree as the existing scalar
inequality logic (compared to the unoptimized case).  In other words,
the new logic makes many row compare scans significantly faster.

Note that the new row compare inequality logic is only effective when
the same individual row member is the deciding subkey for all tuples on
the page (obviously, all tuples have to satisfy the row compare, too).
This is what makes the new row compare logic very similar to the
existing logic for scalar inequalities.  Note, in particular, that this
makes it safe to ignore whether all row compare members are against
either ASC or DESC index attributes (i.e. it doesn't matter if
individual subkeys don't all use the same inequality strategy).

Also stop refusing to set pstate.startikey to an offset beyond any
nonrequired key (don't add logic that'll do that for an individual row
compare subkey, either).  We can fully rely on our firstchangingattnum
tests instead.  This will do the right thing when a page has a group of
tuples with NULLs in a lower-order attribute that makes the tuples fail
to satisfy a row compare key -- we won't incorrectly conclude that all
tuples must satisfy the row compare, just because firsttup and lasttup
happen to.  Our firstchangingattnum test prevents that from happening.
(Note that the original "avoid evaluating nbtree scan keys" mechanism
added by commit e0b1ee17 couldn't support row compares due to issues
with tuples that contain NULLs in a lower-order subkey's attribute.
That original mechanism relied on requiredness markings, which the
replacement _bt_set_startikey mechanism never really needed.)

Follow up to commit 8a510275, which added the _bt_set_startikey
optimization.  _bt_set_startikey is now feature complete; there's no
remaining kind of nbtree scan key that it still doesn't support.

Author: Peter Geoghegan <pg@bowt.ie>
Reviewed-By: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/CAH2-WznL6Z3H_GTQze9d8T_Ls=cYbnd-_9f-Jo7aYgTGRUD58g@mail.gmail.com

3 days agoExpand virtual generated columns in constraint expressions
Peter Eisentraut [Mon, 15 Sep 2025 14:27:50 +0000 (16:27 +0200)]
Expand virtual generated columns in constraint expressions

Virtual generated columns in constraint expressions need to be
expanded because the optimizer matches these expressions to qual
clauses.  Failing to do so can cause us to miss opportunities for
constraint exclusion.

Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/204804c0-798f-4c72-bd1f-36116024fda3%40eisentraut.org

4 days agoCREATE STATISTICS: improve misleading error message
Peter Eisentraut [Mon, 15 Sep 2025 09:38:58 +0000 (11:38 +0200)]
CREATE STATISTICS: improve misleading error message

The previous change (commit f225473cbae) was still not on target,
because it talked about relation kinds, which are not what is being
checked here.  Provide a more accurate message.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CACJufxEZ48toGH0Em_6vdsT57Y3L8pLF=DZCQ_gCii6=C3MeXw@mail.gmail.com

4 days agoChange fmgr.h typedefs to use original names
Peter Eisentraut [Mon, 15 Sep 2025 08:48:30 +0000 (10:48 +0200)]
Change fmgr.h typedefs to use original names

fmgr.h defined some types such as fmNodePtr which is just Node *, but
it made its own types to avoid having to include various header files.
With C11, we can now instead typedef the original names without fear
of conflicts.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/10d32190-f31b-40a5-b177-11db55597355@eisentraut.org

4 days agoRemove hbaPort type
Peter Eisentraut [Mon, 15 Sep 2025 08:48:30 +0000 (10:48 +0200)]
Remove hbaPort type

This was just a workaround to avoid including the header file that
defines the Port type.  With C11, we can now just re-define the Port
type without the possibility of a conflict.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/10d32190-f31b-40a5-b177-11db55597355@eisentraut.org

4 days agoUpdate various forward declarations to use typedef
Peter Eisentraut [Mon, 15 Sep 2025 08:48:30 +0000 (10:48 +0200)]
Update various forward declarations to use typedef

There are a number of forward declarations that use struct but not the
customary typedef, because that could have led to repeat typedefs,
which was not allowed.  This is now allowed in C11, so we can update
these to provide the typedefs as well, so that the later uses of the
types look more consistent.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/10d32190-f31b-40a5-b177-11db55597355@eisentraut.org

4 days agoImprove ExplainState type handling in header files
Peter Eisentraut [Mon, 15 Sep 2025 08:48:30 +0000 (10:48 +0200)]
Improve ExplainState type handling in header files

Now that we can have repeat typedefs with C11, we don't need to use
"struct ExplainState" anymore but can instead make a typedef where
necessary.  This doesn't change anything but makes it look nicer.

(There are more opportunities for similar changes, but this is broken
out because there was a separate discussion about it, and it's
somewhat bulky on its own.)

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/f36c0a45-98cd-40b2-a7cc-f2bf02b12890%40eisentraut.org#a12fb1a2c1089d6d03010f6268871b00
Discussion: https://www.postgresql.org/message-id/flat/10d32190-f31b-40a5-b177-11db55597355@eisentraut.org

4 days agoRemove workarounds against repeat typedefs
Peter Eisentraut [Mon, 15 Sep 2025 08:53:14 +0000 (10:53 +0200)]
Remove workarounds against repeat typedefs

This is allowed in C11, so we don't need the workarounds anymore.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/10d32190-f31b-40a5-b177-11db55597355@eisentraut.org

4 days agoResume conflict-relevant data retention automatically.
Amit Kapila [Mon, 15 Sep 2025 08:44:54 +0000 (08:44 +0000)]
Resume conflict-relevant data retention automatically.

This commit resumes automatic retention of conflict-relevant data for a
subscription. Previously, retention would stop if the apply process failed
to advance its xmin (oldest_nonremovable_xid) within the configured
max_retention_duration and user needs to manually re-enable
retain_dead_tuples option. With this change, retention will resume
automatically once the apply worker catches up and begins advancing its
xmin (oldest_nonremovable_xid) within the configured threshold.

Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: shveta malik <shveta.malik@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Discussion: https://postgr.es/m/OS0PR01MB5716BE80DAEB0EE2A6A5D1F5949D2@OS0PR01MB5716.jpnprd01.prod.outlook.com

4 days agojit: fix build with LLVM-21
Peter Eisentraut [Mon, 15 Sep 2025 06:13:21 +0000 (08:13 +0200)]
jit: fix build with LLVM-21

LLVM-21 renamed llvm::GlobalValue::getGUID() to
getGUIDAssumingExternalLinkage(), so add a version guard.

Author: Holger Hoffstätte <holger@applied-asynchrony.com>
Discussion: https://www.postgresql.org/message-id/flat/d25e6e4a-d1b4-84d3-2f8a-6c45b975f53d%40applied-asynchrony.com

4 days agoSome stylistic improvements in toast_save_datum()
Peter Eisentraut [Mon, 15 Sep 2025 05:27:31 +0000 (07:27 +0200)]
Some stylistic improvements in toast_save_datum()

Move some variables to a smaller scope.  Initialize chunk_data before
storing a pointer to it; this avoids compiler warnings on clang-21, or
respectively us having to work around it by initializing it to zero
before the variable is used (as was done in commit e92677e8633).

Discussion: https://www.postgresql.org/message-id/flat/6604ad6e-5934-43ac-8590-15113d6ae4b1%40eisentraut.org

4 days agoHide duplicate names from extension views
Peter Eisentraut [Mon, 15 Sep 2025 05:25:22 +0000 (07:25 +0200)]
Hide duplicate names from extension views

If extensions of equal names were installed in different directories
in the path, the views pg_available_extensions and
pg_available_extension_versions would show all of them, even though
only the first one was actually reachable by CREATE EXTENSION.  To
fix, have those views skip extensions found later in the path if they
have names already found earlier.

Also add a bit of documentation that only the first extension in the
path can be used.

Reported-by: Pierrick <pierrick.chovelon@dalibo.com>
Discussion: https://www.postgresql.org/message-id/flat/8f5a0517-1cb8-4085-ae89-77e7454e27ba%40dalibo.com

5 days agonbtree: Always set skipScan flag on rescan.
Peter Geoghegan [Sun, 14 Sep 2025 01:01:33 +0000 (21:01 -0400)]
nbtree: Always set skipScan flag on rescan.

The TimescaleDB extension expects to be able to change an nbtree scan's
keys across rescans.  The issue arises in the extension's implementation
of loose index scan.  This is arguably a misuse of the index AM API,
though apparently it worked until recently.  It stopped working when the
skipScan flag was added to BTScanOpaqueData by commit 8a510275, though.
The flag wouldn't reliably track whether the scan (actually, the current
rescan) has any skip arrays, leading to confusion in _bt_set_startikey.

nbtree preprocessing will now defensively initialize the scan's skipScan
flag in all cases, including the case where _bt_preprocess_array_keys
returns early due to the (re)scan not using arrays.  While nbtree isn't
obligated to support this use case (at least not according to my reading
of the index AM API), it still seems like a good idea to be consistent
here, on general robustness grounds.

Author: Peter Geoghegan <pg@bowt.ie>
Reported-By: Natalya Aksman <natalya@timescale.com>
Discussion: https://postgr.es/m/CAJumhcirfMojbk20+W0YimbNDkwdECvJprQGQ-XqK--ph09nQw@mail.gmail.com
Backpatch-through: 18

5 days agoAmend recent fix for SIMILAR TO regex conversion.
Tom Lane [Sat, 13 Sep 2025 20:55:51 +0000 (16:55 -0400)]
Amend recent fix for SIMILAR TO regex conversion.

Commit e3ffc3e91 fixed the translation of character classes in
SIMILAR TO regular expressions.  Unfortunately the fix broke a corner
case: if there is an escape character right after the opening bracket
(for example in "[\q]"), a closing bracket right after the escape
sequence would not be seen as closing the character class.

There were two more oversights: a backslash or a nested opening bracket
right at the beginning of a character class should remove the special
meaning from any following caret or closing bracket.

This bug suggests that this code needs to be more readable, so also
rename the variables "charclass_depth" and "charclass_start" to
something more meaningful, rewrite an "if" cascade to be more
consistent, and improve the commentary.

Reported-by: Dominique Devienne <ddevienne@gmail.com>
Reported-by: Stephan Springl <springl-psql@bfw-online.de>
Author: Laurenz Albe <laurenz.albe@cybertec.at>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAFCRh-8NwJd0jq6P=R3qhHyqU7hw0BTor3W0SvUcii24et+zAw@mail.gmail.com
Backpatch-through: 13

5 days agoAdd commit 7e9c216b52 to .git-blame-ignore-revs.
Nathan Bossart [Sat, 13 Sep 2025 19:55:38 +0000 (14:55 -0500)]
Add commit 7e9c216b52 to .git-blame-ignore-revs.

5 days agoRe-pgindent nbtpreprocesskeys.c after commit 796962922e.
Nathan Bossart [Sat, 13 Sep 2025 19:50:02 +0000 (14:50 -0500)]
Re-pgindent nbtpreprocesskeys.c after commit 796962922e.

Backpatch-through: 18

5 days agoSpecify locale provider for pg_regress --no-locale
Alexander Korotkov [Sat, 13 Sep 2025 17:38:52 +0000 (20:38 +0300)]
Specify locale provider for pg_regress --no-locale

pg_regress has a --no-locale option that forces the temporary database to
have C locale.  However, currently, locale C only exists in the 'builtin'
locale provider.  This makes 'pg_regress --no-locale' fail when the default
locale provider is not 'builtin'.  This commit makes 'pg_regress --no-locale'
specify both LOCALE='C' and LOCALE_PROVIDER='builtin'.

Discussion: https://postgr.es/m/b54921f95e23b4391b1613e9053a3d58%40postgrespro.ru
Author: Oleg Tselebrovskiy <o.tselebrovskiy@postgrespro.ru>
Reviewed-by: Alexander Korotkov <aekorotkov@gmail.com>
6 days agoAvoid context dependency in test case added by 9a71989a8.
Tom Lane [Fri, 12 Sep 2025 22:45:06 +0000 (18:45 -0400)]
Avoid context dependency in test case added by 9a71989a8.

It's not quite clear to me why this didn't show up in my local
check-world testing, but some of the buildfarm evidently runs
this test with a different database name.  Adjust the test
so that that doesn't affect the reported error messages.

6 days agoReject "ALTER DATABASE/USER ... RESET foo" with invalid GUC name.
Tom Lane [Fri, 12 Sep 2025 22:10:11 +0000 (18:10 -0400)]
Reject "ALTER DATABASE/USER ... RESET foo" with invalid GUC name.

If the database or user had no entry in pg_db_role_setting,
RESET silently did nothing --- including not checking the
validity of the given GUC name.  This is quite inconsistent
and surprising, because you *would* get such an error if there
were any pg_db_role_setting entry, even though it contains
values for unrelated GUCs.

While this is clearly a bug, changing it in stable branches seems
unwise.  The effect will be that some ALTER commands that formerly
were no-ops will now be errors, and people don't like that sort of
thing in minor releases.

Author: Vitaly Davydov <v.davydov@postgrespro.ru>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/30783e-68c28a00-9-41004480@130449754

6 days agoFix oversights in pg_event_trigger_dropped_objects() fixes.
Tom Lane [Fri, 12 Sep 2025 21:43:15 +0000 (17:43 -0400)]
Fix oversights in pg_event_trigger_dropped_objects() fixes.

Commit a0b99fc12 caused pg_event_trigger_dropped_objects()
to not fill the object_name field for schemas, which it
should have; and caused it to fill the object_name field
for default values, which it should not have.

In addition, triggers and RLS policies really should behave
the same way as we're making column defaults do; that is,
they should have is_temporary = true if they belong to a
temporary table.

Fix those things, and upgrade event_trigger.sql's woefully
inadequate test coverage of these secondary output columns.

As before, back-patch only to v15.

Reported-by: Sergey Shinderuk <s.shinderuk@postgrespro.ru>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/bd7b4651-1c26-4d30-832b-f942fabcb145@postgrespro.ru
Backpatch-through: 15

6 days agoReplace tests of ALTER DATABASE RESET TABLESPACE.
Noah Misch [Fri, 12 Sep 2025 19:44:14 +0000 (12:44 -0700)]
Replace tests of ALTER DATABASE RESET TABLESPACE.

This unblocks rejection of that syntax.  One copy was a misspelling of
"SET TABLESPACE pg_default" that instead made no persistent changes.
The other copy just needed to populate a DATABASEOID syscache entry.
This slightly raises database.sql test coverage of catcache.c, while
dbcommands.c coverage remains the same.

Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/1802710.1757608564@sss.pgh.pa.us

6 days agoAlways commute strategy when preprocessing DESC keys.
Peter Geoghegan [Fri, 12 Sep 2025 17:23:00 +0000 (13:23 -0400)]
Always commute strategy when preprocessing DESC keys.

A recently added nbtree preprocessing step failed to account for the
fact that DESC columns already had their B-Tree strategy number commuted
at this point in preprocessing.  As a result, preprocessing could output
a set of scan keys where one or more keys had the correct strategy
number, but used the wrong comparison routine.

To fix, make the faulty code path that looks up a more restrictive
replacement operator/comparison routine commute its requested inequality
strategy (while outputting the transformed strategy number as before).
This makes the final transformed scan key comport with the approach
preprocessing has always used to deal with DESC columns (which is
described by comments above _bt_fix_scankey_strategy).

Oversight in commit commit b3f1a13f, which made nbtree preprocessing
perform transformations on skip array inequalities that can reduce the
total number of index searches.

Author: Peter Geoghegan <pg@bowt.ie>
Reported-By: Natalya Aksman <natalya@timescale.com>
Discussion: https://postgr.es/m/19049-b7df801e71de41b2@postgresql.org
Backpatch-through: 18

6 days agoAvoid unexpected changes of CurrentResourceOwner and CurrentMemoryContext
Álvaro Herrera [Fri, 12 Sep 2025 16:47:25 +0000 (18:47 +0200)]
Avoid unexpected changes of CurrentResourceOwner and CurrentMemoryContext

Users of logical decoding can encounter an unexpected change of
CurrentResourceOwner and CurrentMemoryContext.  The problem is that,
unlike other call sites of RollbackAndReleaseCurrentSubTransaction(), in
reorderbuffer.c we fail to restore the original values of these global
variables after being clobbered by subtransaction abort.  This patch
saves the values prior to the call and restores them eventually.

In addition, logical.c and logicalfuncs.c had a hack to restore resource
owner, presumably because of lack of this restore.  Remove that.
Instead, because the test coverage here is not very consistent, add an
Assert() to ensure that the resowner is kept identical; this would make
it easy to detect other cases of bugs were we fail to restore resowner
properly.  This could be removed later.

This is arguably an old bug, but there appears to be no reason to
backpatch it and it's risky to do so, so refrain for now.

Author: Antonin Houska <ah@cybertec.at>
Reported-by: Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Reviewed-by: Euler Taveira <euler@eulerto.com>
Discussion: https://postgr.es/m/119497.1756892972@localhost

6 days agoci: openbsd: Increase RAM disk's size
Andres Freund [Fri, 12 Sep 2025 14:18:31 +0000 (10:18 -0400)]
ci: openbsd: Increase RAM disk's size

Its size was ~3.8GB before, which sometimes was not enough. OpenBSD CI task
often were failing due to no space left on device. Increase the RAM disk size
to ~4.6 GB.

Author: Nazir Bilal Yavuz <byavuz81@gmail.com>
Discussion: https://postgr.es/m/CAN55FZ2XVVPJRJmGB2DsL3gOrOinWh=HWvj6GO1cHzJ=6LwTag@mail.gmail.com
Backpatch-through: 18, where openbsd was added to CI

7 days agoAllow redeclaration of typedef yyscan_t
Peter Eisentraut [Fri, 12 Sep 2025 06:13:05 +0000 (08:13 +0200)]
Allow redeclaration of typedef yyscan_t

This is allowed in C11, so we don't need the workaround guards against
it anymore.  This effectively reverts commit 382092a0cd2 that put
these guards in place.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/10d32190-f31b-40a5-b177-11db55597355@eisentraut.org

7 days agoImprove pgbench definition of yyscan_t
Peter Eisentraut [Fri, 12 Sep 2025 06:13:05 +0000 (08:13 +0200)]
Improve pgbench definition of yyscan_t

It was defining yyscan_t as a macro while the rest of the code uses a
typedef with #ifdef guards around it.  The latter is also what the
flex generated code uses.  So it seems best to make it look like those
other places for consistency.

The old way also had a potential for conflict if some code included
multiple headers providing yyscan_t.  exprscan.l includes

    #include "fe_utils/psqlscan_int.h"
    #include "pgbench.h"

and fe_utils/psqlscan_int.h contains

    #ifndef YY_TYPEDEF_YY_SCANNER_T
    #define YY_TYPEDEF_YY_SCANNER_T
    typedef void *yyscan_t;
    #endif

which was then followed by pgbench.h

    #define yyscan_t  void *

and then the generated code in exprscan.c

    #ifndef YY_TYPEDEF_YY_SCANNER_T
    #define YY_TYPEDEF_YY_SCANNER_T
    typedef void* yyscan_t;
    #endif

This works, but if the #ifdef guard in psqlscan_int.h is removed, this
fails.

We want to move toward allowing repeat typedefs, per C11, but for that
we need to make sure they are all the same.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/10d32190-f31b-40a5-b177-11db55597355@eisentraut.org

7 days agoDefault to log_lock_waits=on
Peter Eisentraut [Fri, 12 Sep 2025 05:57:06 +0000 (07:57 +0200)]
Default to log_lock_waits=on

If someone is stuck behind a lock for more than a second, that is
almost always a problem that is worth a log entry.

Author: Laurenz Albe <laurenz.albe@cybertec.at>
Reviewed-By: Michael Banck <mbanck@gmx.net>
Reviewed-By: Robert Haas <robertmhaas@gmail.com>
Reviewed-By: Christoph Berg <myon@debian.org>
Reviewed-By: Stephen Frost <sfrost@snowman.net>
Discussion: https://postgr.es/m/b8b8502915e50f44deb111bc0b43a99e2733e117.camel%40cybertec.at

7 days agoRemove traces of support for Sun Studio compiler
Peter Eisentraut [Thu, 11 Sep 2025 09:55:29 +0000 (11:55 +0200)]
Remove traces of support for Sun Studio compiler

Per discussion, this compiler suite is no longer maintained, and
it has not been able to compile PostgreSQL since at least PostgreSQL
17.

This removes all the remaining support code for this compiler.

Note that the Solaris operating system continues to be supported, but
using GCC as the compiler.

Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/flat/a0f817ee-fb86-483a-8a14-b6f7f5991b6e%40eisentraut.org

7 days agoSilence compiler warnings on clang 21
Peter Eisentraut [Fri, 12 Sep 2025 05:27:48 +0000 (07:27 +0200)]
Silence compiler warnings on clang 21

Clang 21 shows some new compiler warnings, for example:

warning: variable 'dstsize' is uninitialized when passed as a const pointer argument here [-Wuninitialized-const-pointer]

The fix is to initialize the variables when they are defined.  This is
similar to, for example, the existing situation in gistKeyIsEQ().

Discussion: https://www.postgresql.org/message-id/flat/6604ad6e-5934-43ac-8590-15113d6ae4b1%40eisentraut.org

7 days agoFix misuse of Relids for storing attribute numbers
Richard Guo [Fri, 12 Sep 2025 02:12:19 +0000 (11:12 +0900)]
Fix misuse of Relids for storing attribute numbers

The typedef Relids (Bitmapset *) is intended to represent set of
relation identifiers, but was incorrectly used in several places to
store sets of attribute numbers.  This is my oversight in e2debb643.

Fix that by replacing such usages with Bitmapset * to reflect the
correct semantics.

Author: Junwang Zhao <zhjwpku@gmail.com>
Reviewed-by: Tender Wang <tndrwang@gmail.com>
Reviewed-by: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAEG8a3LJhp_xriXf39iCz0TsK+M-2biuhDhpLC6Baxw8+ZYT3A@mail.gmail.com

7 days agoAdd more information for WAL records of hash index AMs
Michael Paquier [Fri, 12 Sep 2025 01:29:02 +0000 (10:29 +0900)]
Add more information for WAL records of hash index AMs

hashdesc.c was missing a couple of fields in its record descriptions, as
of:
- is_prev_bucket_same_wrt for SQUEEZE_PAGE.
- procid for INIT_META_PAGE.
- old_bucket_flag and new_bucket_flag for SPLIT_ALLOCATE_PAGE.

The author has noted the first hole, and I have spotted the others while
double-checking this area of the code.  Note that the only data missing
now are the offsets stored in VACUUM_ONE_PAGE.  We could perhaps add
them, if somebody sees value in this data, even if it makes the output
larger.  These are discarded here.

Author: Kirill Reshke <reshkekirill@gmail.com>
Discussion: https://postgr.es/m/CALdSSPjc-OVwtZH0Xrkvg7n=2ZwdbMJzqrm_ed_CfjiAzuKVGg@mail.gmail.com

7 days agoRemove whitespace in comment of pg_stat_statements.c
Michael Paquier [Fri, 12 Sep 2025 00:55:16 +0000 (09:55 +0900)]
Remove whitespace in comment of pg_stat_statements.c

Introduced by 6b4d23feef6e, spotted while reading this area of the code.

7 days agoMove named LWLock tranche requests to shared memory.
Nathan Bossart [Thu, 11 Sep 2025 21:13:55 +0000 (16:13 -0500)]
Move named LWLock tranche requests to shared memory.

In EXEC_BACKEND builds, GetNamedLWLockTranche() can segfault when
called outside of the postmaster process, as it might access
NamedLWLockTrancheRequestArray, which won't be initialized.  Given
the lack of reports, this is apparently unusual, presumably because
it is usually called from a shmem_startup_hook like this:

    mystruct = ShmemInitStruct(..., &found);
    if (!found)
    {
        mystruct->locks = GetNamedLWLockTranche(...);
        ...
    }

This genre of shmem_startup_hook evades the aforementioned
segfaults because the struct is initialized in the postmaster, so
all other callers skip the !found path.

We considered modifying the documentation or requiring
GetNamedLWLockTranche() to be called from the postmaster, but
ultimately we decided to simply move the request array to shared
memory (and add it to the BackendParameters struct), thereby
allowing calls outside postmaster on all platforms.  Since the main
shared memory segment is initialized after accepting LWLock tranche
requests, postmaster builds the request array in local memory first
and then copies it to shared memory later.

Given the lack of reports, back-patching seems unnecessary.

Reported-by: Sami Imseih <samimseih@gmail.com>
Reviewed-by: Sami Imseih <samimseih@gmail.com>
Discussion: https://postgr.es/m/CAA5RZ0v1_15QPg5Sqd2Qz5rh_qcsyCeHHmRDY89xVHcy2yt5BQ%40mail.gmail.com

7 days agoReport the correct is_temporary flag for column defaults.
Tom Lane [Thu, 11 Sep 2025 21:11:54 +0000 (17:11 -0400)]
Report the correct is_temporary flag for column defaults.

pg_event_trigger_dropped_objects() would report a column default
object with is_temporary = false, even if it belongs to a
temporary table.  This seems clearly wrong, so adjust it to
report the table's temp-ness.

While here, refactor EventTriggerSQLDropAddObject to make its
handling of namespace objects less messy and avoid duplication
of the schema-lookup code.  And add some explicit test coverage
of dropped-object reports for dependencies of temp tables.

Back-patch to v15.  The bug exists further back, but the
GetAttrDefaultColumnAddress function this patch depends on does not,
and it doesn't seem worth adjusting it to cope with the older code.

Author: Antoine Violin <violin.antuan@gmail.com>
Co-authored-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAFjUV9x3-hv0gihf+CtUc-1it0hh7Skp9iYFhMS7FJjtAeAptA@mail.gmail.com
Backpatch-through: 15

7 days agoImprove comment about snapshot macros
Álvaro Herrera [Thu, 11 Sep 2025 17:49:57 +0000 (19:49 +0200)]
Improve comment about snapshot macros

The comment mistakenly had "the others" for "the other", but this
commit also reorders the comment so it matches the macros below.  Now we
describe the levels in increasing strictness.  In addition, it seems
easier to follow if we introduce one level at a time, rather than
describing two, followed by "the other" (and then jumping back to one of
the first two).  Finally, reword the sentence about the purpose of the
macros, which was slightly off-point.

Author: Paul Jungwirth <pj@illuminatedcomputing.com>
Reviewed-by: Rustam ALLAKOV <rustamallakov@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/CA+renyUp=xja80rBaB6NpY3RRdi750y046x28bo_xg29zKY72Q@mail.gmail.com

7 days agoAdd test for temporal referential integrity
Álvaro Herrera [Thu, 11 Sep 2025 16:13:09 +0000 (18:13 +0200)]
Add test for temporal referential integrity

This commit adds an isolation test showing that temporal foreign keys do
not permit referential integrity violations under concurrency, like
fk-snapshot-2.  You can show that the test fails by passing false for
detectNewRows to ri_PerformCheck in ri_restrict.

Author: Paul Jungwirth <pj@illuminatedcomputing.com>
Reviewed-by: Rustam ALLAKOV <rustamallakov@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/CA+renyUp=xja80rBaB6NpY3RRdi750y046x28bo_xg29zKY72Q@mail.gmail.com

7 days agoFill testing gap for possible referential integrity violation
Álvaro Herrera [Thu, 11 Sep 2025 16:11:46 +0000 (18:11 +0200)]
Fill testing gap for possible referential integrity violation

This commit adds a missing isolation test for (non-PERIOD) foreign keys.
With REPEATABLE READ, one transaction can insert a referencing row while
another deletes the referenced row, and both see a valid state.  But
after they have committed, the table violates referential integrity.

If the INSERT precedes the DELETE, we use a crosscheck snapshot to see
the just-added row, so that the DELETE can raise a foreign key error.
You can see the table violate referential integrity if you change
ri_restrict to pass false for detectNewRows to ri_PerformCheck.

A crosscheck snapshot is not needed when the DELETE comes first, because
the INSERT's trigger takes a FOR KEY SHARE lock that sees the row now
marked for deletion, waits for that transaction to commit, and raises a
serialization error.  I (Paul) added a test for that too though.

We already have a similar test (in ri-triggers.spec) for SERIALIZABLE
snapshot isolation showing that you can implement foreign keys with just
pl/pgSQL, but that test does nothing to validate ri_triggers.c.  We also
have tests (in fk-snapshot.spec) for other concurrency scenarios, but
not this one: we test concurrently deleting both the referencing and
referenced row, when the constraint activates a cascade/set null action.
But those tests don't exercise ri_restrict, and the consequence of
omitting a crosscheck comparison is different: a serialization failure,
not a referential integrity violation.

Author: Paul Jungwirth <pj@illuminatedcomputing.com>
Reviewed-by: Rustam ALLAKOV <rustamallakov@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/CA+renyUp=xja80rBaB6NpY3RRdi750y046x28bo_xg29zKY72Q@mail.gmail.com

7 days agoRemove checks for no longer supported GCC versions
Peter Eisentraut [Thu, 11 Sep 2025 09:55:29 +0000 (11:55 +0200)]
Remove checks for no longer supported GCC versions

Since commit f5e0186f865 (Raise C requirement to C11), we effectively
require at least GCC version 4.7, so checks for older versions can be
removed.

Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/flat/a0f817ee-fb86-483a-8a14-b6f7f5991b6e%40eisentraut.org

7 days agoRemove stray semicolon at global scope
Peter Eisentraut [Thu, 11 Sep 2025 09:55:29 +0000 (11:55 +0200)]
Remove stray semicolon at global scope

The Sun Studio compiler complains about an empty declaration here.

Note for future historians:  This does not mean that this compiler is
still of current interest for anyone using PostgreSQL.  But we can let
this small fix be its parting gift.

Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/flat/a0f817ee-fb86-483a-8a14-b6f7f5991b6e%40eisentraut.org

8 days agoFix intermittent test failure introduced in 6456c6e2c4.
Amit Kapila [Thu, 11 Sep 2025 09:33:48 +0000 (09:33 +0000)]
Fix intermittent test failure introduced in 6456c6e2c4.

The test assumes that a backend will execute COMMIT PREPARED on the
publisher and hit the injection point commit-after-delay-checkpoint within
the commit critical section. This should cause the apply worker on the
subscriber to wait for the transaction to complete.

However, the test does not guarantee that the injection point is actually
triggered, creating a race condition where the apply worker may proceed
prematurely during COMMIT PREPARED.

This commit resolves the issue by explicitly waiting for the injection
point to be hit before continuing with the test, ensuring consistent and
reliable behavior.

Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: shveta malik <shveta.malik@gmail.com>
Discussion: https://postgr.es/m/TY4PR01MB1690751D1CA8C128B0770EC6F9409A@TY4PR01MB16907.jpnprd01.prod.outlook.com

8 days agodoc: Fix indentation in func-datetime.sgml.
Dean Rasheed [Thu, 11 Sep 2025 08:48:12 +0000 (09:48 +0100)]
doc: Fix indentation in func-datetime.sgml.

Incorrect indentation introduced by commit faf071b5538.

8 days agodoc: Improve description of new random(min, max) functions.
Dean Rasheed [Thu, 11 Sep 2025 08:25:47 +0000 (09:25 +0100)]
doc: Improve description of new random(min, max) functions.

Mention that the new variants of random(min, max) are affected by
setseed(), like the original functions.

Reported-by: Marcos Pegoraro <marcos@f10.com.br>
Discussion: https://postgr.es/m/CAB-JLwb1=drA3Le6uZXDBi_tCpeS1qm6XQU7dKwac_x91Z4qDg@mail.gmail.com

8 days agoFix description of WAL record blocks in hash_xlog.h
Michael Paquier [Thu, 11 Sep 2025 08:17:04 +0000 (17:17 +0900)]
Fix description of WAL record blocks in hash_xlog.h

hash_xlog.h included descriptions for the blocks used in WAL records
that were was not completely consistent with how the records are
generated, with one block missing for SQUEEZE_PAGE, and inconsistent
descriptions used for block 0 in VACUUM_ONE_PAGE and MOVE_PAGE_CONTENTS.

This information was incorrect since c11453ce0aea, cross-checking the
logic for the record generation.

Author: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Discussion: https://postgr.es/m/CALdSSPj1j=a1d1hVA3oabRFz0hSU3KKrYtZPijw4UPUM7LY9zw@mail.gmail.com
Backpatch-through: 13

8 days agoFix incorrect file reference in guc.h
Michael Paquier [Thu, 11 Sep 2025 01:15:33 +0000 (10:15 +0900)]
Fix incorrect file reference in guc.h

GucSource_Names was documented as being in guc.c, but since 0a20ff54f5e6
it is located in guc_tables.c.  The reference to the location of
GucSource_Names is important, as GucSource needs to be kept in sync with
GucSource_Names.

Author: David G. Johnston <david.g.johnston@gmail.com>
Discussion: https://postgr.es/m/CAKFQuwYPgAHWPYjPzK7iXzhSZ6MKR8w20_Nz7ZXpOvx=kZbs7A@mail.gmail.com
Backpatch-through: 16

8 days agoAvoid faulty alignment of Datums in build_sorted_items().
Tom Lane [Wed, 10 Sep 2025 21:51:24 +0000 (17:51 -0400)]
Avoid faulty alignment of Datums in build_sorted_items().

If sizeof(Pointer) is 4 then sizeof(SortItem) will be 12, so that
if data->numrows is odd then we placed the values array at a location
that's not a multiple of 8.  That was fine when sizeof(Datum) was also
4, but in the wake of commit 2a600a93c it makes some alignment-picky
machines unhappy.  (You need a 32-bit machine that nonetheless expects
8-byte alignment of 8-byte quantities, which is an odd-seeming
combination but it does exist outside the Intel universe.)

To fix, MAXALIGN the space allocated to the SortItem array.
In passing, let's make the "len" variable be Size not int,
just for paranoia's sake.

This code was arguably not too safe even before 2a600a93c, but at
present I don't see a strong argument for back-patching.

Reported-by: Tomas Vondra <tomas@vondra.me>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/87036018-8d70-40ad-a0ac-192b07bd7b04@vondra.me

8 days agoEliminate duplicative hashtempcxt in nodeSubplan.c.
Tom Lane [Wed, 10 Sep 2025 20:15:08 +0000 (16:15 -0400)]
Eliminate duplicative hashtempcxt in nodeSubplan.c.

Instead of building a separate memory context that's used just
for running hash functions, make the hash functions run in the
per-tuple context of the node's innerecontext.  This saves a
little space at runtime, and it avoids needing to reset two
contexts instead of one inside buildSubPlanHash's main loop.

This largely reverts commit 133924e13.  That's safe to do now
because bf6c614a2 decoupled the evaluation context used by
TupleHashTableMatch from that used for hash function evaluation,
so that there's no longer a risk of resetting the innerecontext
too soon.

Per discussion of bug #19040, although this is not directly
a fix for that.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Haiyang Li <mohen.lhy@alibaba-inc.com>
Reviewed-by: Fei Changhong <feichanghong@qq.com>
Discussion: https://postgr.es/m/19040-c9b6073ef814f48c@postgresql.org

8 days agoFix memory leakage in nodeSubplan.c.
Tom Lane [Wed, 10 Sep 2025 20:05:03 +0000 (16:05 -0400)]
Fix memory leakage in nodeSubplan.c.

If the hash functions used for hashing tuples leaked any memory,
we failed to clean that up, resulting in query-lifespan memory
leakage in queries using hashed subplans.  One way that could
happen is if the values being hashed require de-toasting, since
most of our hash functions don't trouble to clean up de-toasted
inputs.

Prior to commit bf6c614a2, this leakage was largely masked
because TupleHashTableMatch would reset hashtable->tempcxt
(via execTuplesMatch).  But it doesn't do that anymore, and
that's not really the right place for this anyway: doing it
there could reset the tempcxt many times per hash lookup,
or not at all.  Instead put reset calls into ExecHashSubPlan
and buildSubPlanHash.  Along the way to that, rearrange
ExecHashSubPlan so that there's just one place to call
MemoryContextReset instead of several.

This amounts to accepting the de-facto API spec that the caller
of the TupleHashTable routines is responsible for resetting the
tempcxt adequately often.  Although the other callers seem to
get this right, it was not documented anywhere, so add a comment
about it.

Bug: #19040
Reported-by: Haiyang Li <mohen.lhy@alibaba-inc.com>
Author: Haiyang Li <mohen.lhy@alibaba-inc.com>
Reviewed-by: Fei Changhong <feichanghong@qq.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19040-c9b6073ef814f48c@postgresql.org
Backpatch-through: 13

8 days agomeson: Build numeric.c with -ftree-vectorize.
Nathan Bossart [Wed, 10 Sep 2025 16:21:12 +0000 (11:21 -0500)]
meson: Build numeric.c with -ftree-vectorize.

autoconf builds have compiled this file with -ftree-vectorize since
commit 8870917623, but meson builds seem to have missed the memo.

Reviewed-by: Jeff Davis <pgsql@j-davis.com>
Discussion: https://postgr.es/m/aL85CeasM51-0D1h%40nathan
Backpatch-through: 16

8 days agoFix CREATE TABLE LIKE with not-valid check constraint
Peter Eisentraut [Wed, 10 Sep 2025 09:49:53 +0000 (11:49 +0200)]
Fix CREATE TABLE LIKE with not-valid check constraint

In CREATE TABLE ... LIKE, any check constraints copied from the source
table should be set to valid if they are ENFORCED (the default).

Bug introduced in commit ca87c415e2f.

Author: jian he <jian.universality@gmail.com>
Discussion: https://www.postgresql.org/message-id/CACJufxH%3D%2Bod8Wy0P4L3_GpapNwLUP3oAes5UFRJ7yTxrM_M5kg%40mail.gmail.com

9 days agoRemove dynahash.h
Michael Paquier [Wed, 10 Sep 2025 05:11:50 +0000 (14:11 +0900)]
Remove dynahash.h

All the callers of my_log2() are now limited inside dynahash.c, so let's
remove this header.  The same capability is provided by pg_bitutils.h
already.

Discussion: https://postgr.es/m/CAEZATCUJPQD_7sC-wErak2CQGNa6bj2hY-mr8wsBki=kX7f2_A@mail.gmail.com

9 days agoReplace callers of dynahash.h's my_log() by equivalent in pg_bitutils.h
Michael Paquier [Wed, 10 Sep 2025 02:20:46 +0000 (11:20 +0900)]
Replace callers of dynahash.h's my_log() by equivalent in pg_bitutils.h

All the calls replaced by this commit use 4-byte integers for their
variables used in input of my_log2().  Hence, the limit against
too-large inputs does not really apply.  Thresholds are also applied, as
of:
- In nodeAgg.c, the number of partitions is limited by
HASHAGG_MAX_PARTITIONS.
- In nodeHash.c, ExecChooseHashTableSize() caps its maximum number of
buckets based on HashJoinTuple and palloc() allocation limit.
- In worker.c, the number of subxacts tracked by ApplySubXactData uses
uint32, making pg_ceil_log2_64() safe to use directly.

Several approaches have been discussed, like an integration with
thresholds in pg_bitutils.h, but it was found confusing.  This uses
Dean's idea, which gives a simpler result than what I came up with to be
able to remove dynahash.h.  dynahash.h will be removed in a follow-up
commit, removing some duplication with the ceil log2 routines.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Discussion: https://postgr.es/m/CAEZATCUJPQD_7sC-wErak2CQGNa6bj2hY-mr8wsBki=kX7f2_A@mail.gmail.com

9 days agoFix leak with SMgrRelations in startup process
Michael Paquier [Tue, 9 Sep 2025 22:23:05 +0000 (07:23 +0900)]
Fix leak with SMgrRelations in startup process

The startup process does not process shared invalidation messages, only
sending them, and never calls AtEOXact_SMgr() which clean up any
unpinned SMgrRelations.  Hence, it is never able to free SMgrRelations
on a periodic basis, bloating its hashtable over time.

Like the checkpointer and the bgwriter, this commit takes a conservative
approach by freeing periodically SMgrRelations when replaying a
checkpoint record, either online or shutdown, so as the startup process
has a way to perform a periodic cleanup.

Issue caused by 21d9c3ee4ef7, so backpatch down to v17.

Author: Jingtang Zhang <mrdrivingduck@gmail.com>
Reviewed-by: Yuhang Qiu <iamqyh@gmail.com>
Discussion: https://postgr.es/m/28C687D4-F335-417E-B06C-6612A0BD5A10@gmail.com
Backpatch-through: 17

9 days agoFix documentation for shmem_startup_hook.
Nathan Bossart [Tue, 9 Sep 2025 19:35:30 +0000 (14:35 -0500)]
Fix documentation for shmem_startup_hook.

This section claims that each backend executes the
shmem_startup_hook shortly after attaching to shared memory, which
is true for EXEC_BACKEND builds, but not for others.  This commit
adds this important detail.

Oversight in commit 964152c476.

Reported-by: Sami Imseih <samimseih@gmail.com>
Reviewed-by: Sami Imseih <samimseih@gmail.com>
Discussion: https://postgr.es/m/CAA5RZ0vEGT1eigGbVt604LkXP6mUPMwPMxQoRCbFny44w%2B9EUQ%40mail.gmail.com
Backpatch-through: 17

9 days agotest_slru: Fix LWLock tranche allocation in EXEC_BACKEND builds.
Nathan Bossart [Tue, 9 Sep 2025 19:09:36 +0000 (14:09 -0500)]
test_slru: Fix LWLock tranche allocation in EXEC_BACKEND builds.

Currently, test_slru's shmem_startup_hook unconditionally generates
new LWLock tranche IDs.  This is fine on non-EXEC_BACKEND builds,
where only the postmaster executes this hook, but on EXEC_BACKEND
builds, every backend executes it, too.  To fix, only generate the
tranche IDs in the postmaster process by checking the
IsUnderPostmaster variable.

This is arguably a bug fix and could be back-patched, but since the
damage is limited to some extra unused tranche IDs in a test
module, I'm not going to bother.

Reported-by: Sami Imseih <samimseih@gmail.com>
Reviewed-by: Sami Imseih <samimseih@gmail.com>
Discussion: https://postgr.es/m/CAA5RZ0vaAuonaf12CeDddQJu5xKL%2B6xVyS%2B_q1%2BcH%3D33JXV82w%40mail.gmail.com

9 days agoFix typo in comment
Peter Eisentraut [Tue, 9 Sep 2025 13:33:46 +0000 (15:33 +0200)]
Fix typo in comment

Author: Alexandra Wang <alexandra.wang.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAK98qZ0whQ%3Dc%2BJGXbGSEBxCtLgy6sf-YGYqsKTAGsS-wt0wj%2BA%40mail.gmail.com

10 days agoAdd date and timestamp variants of random(min, max).
Dean Rasheed [Tue, 9 Sep 2025 09:39:30 +0000 (10:39 +0100)]
Add date and timestamp variants of random(min, max).

This adds 3 new variants of the random() function:

    random(min date, max date) returns date
    random(min timestamp, max timestamp) returns timestamp
    random(min timestamptz, max timestamptz) returns timestamptz

Each returns a random value x in the range min <= x <= max.

Author: Damien Clochard <damien@dalibo.info>
Reviewed-by: Greg Sabino Mullane <htamfids@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Reviewed-by: Vik Fearing <vik@postgresfriends.org>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/f524d8cab5914613d9e624d9ce177d3d@dalibo.info

10 days agoFix Coverity issue reported in commit a850be2fe.
Amit Kapila [Tue, 9 Sep 2025 03:18:22 +0000 (03:18 +0000)]
Fix Coverity issue reported in commit a850be2fe.

Address a potential SIGSEGV that may occur when the tablesync worker
attempts to locate a deleted row while applying changes. This situation
arises during conflict detection for update-deleted scenarios.

To prevent this crash, ensure that the operation is errored out early if
the leader apply worker is unavailable. Since the leader worker maintains
the necessary conflict detection metadata, proceeding without it serves no
purpose and risks reporting incorrect conflict type.

In the passing, improve a nearby comment.

Reported by Tom Lane as per Coverity
Author: shveta malik <shveta.malik@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/334468.1757280992@sss.pgh.pa.us

10 days agoAdd error codes when vacuum discovers VM corruption
Melanie Plageman [Mon, 8 Sep 2025 21:13:31 +0000 (17:13 -0400)]
Add error codes when vacuum discovers VM corruption

Commit fd6ec93bf890314a and other previous work established the
principle that when an error is potentially reachable in case of on-disk
corruption but is not expected to be reached otherwise,
ERRCODE_DATA_CORRUPTED should be used. This allows log monitoring
software to search for evidence of corruption by filtering on the error
code.

Enhance the existing log messages emitted when the heap page is found to
be inconsistent with the VM by adding this error code.

Suggested-by: Andrey Borodin <x4mmm@yandex-team.ru>
Author: Melanie Plageman <melanieplageman@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/87DD95AA-274F-4F4F-BAD9-7738E5B1F905%40yandex-team.ru

10 days agomeson: build checksums with extra optimization flags.
Jeff Davis [Mon, 8 Sep 2025 19:29:42 +0000 (12:29 -0700)]
meson: build checksums with extra optimization flags.

Use -funroll-loops and -ftree-vectorize when building checksum.c to
match what autoconf does.

Discussion: https://postgr.es/m/a81f2f7ef34afc24a89c613671ea017e3651329c.camel@j-davis.com
Reviewed-by: Andres Freund <andres@anarazel.de>
10 days agopg_upgrade: Transfer pg_largeobject_metadata's files when possible.
Nathan Bossart [Mon, 8 Sep 2025 19:19:48 +0000 (14:19 -0500)]
pg_upgrade: Transfer pg_largeobject_metadata's files when possible.

Commit 161a3e8b68 taught pg_upgrade to use COPY for large object
metadata for upgrades from v12 and newer, which is much faster to
restore than the proper large object commands.  For upgrades from
v16 and newer, we can take this a step further and transfer the
large object metadata files as if they were user tables.  We can't
transfer the files from older versions because the aclitem data
type (needed by pg_largeobject_metadata.lomacl) changed its storage
format in v16 (see commit 7b378237aa).  Note that this commit is
essentially a revert of commit 12a53c732c.

There are a couple of caveats.  First, we still need to COPY the
corresponding pg_shdepend rows for large objects.  Second, we need
to COPY anything in pg_largeobject_metadata with a comment or
security label, else restoring those will fail.  This means that an
upgrade in which every large object has a comment or security label
won't gain anything from this commit, but it should at least avoid
making those unusual use-cases any worse.

pg_upgrade must also take care to transfer the relfilenodes of
pg_largeobject_metadata and its index, as was done for
pg_largeobject in commits d498e052b4 and bbe08b8869.

Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/aJ3_Gih_XW1_O2HF%40nathan

10 days agoRemove unused xl_heap_prune member, reason
Melanie Plageman [Mon, 8 Sep 2025 18:25:10 +0000 (14:25 -0400)]
Remove unused xl_heap_prune member, reason

f83d709760d8 refactored xl_heap_prune and added an unused member,
reason. While PruneReason is used when constructing this WAL record to
set the WAL record definition, it doesn't need to be stored in a
separate field in the record. Remove it.

We won't backport this, since modifying an exposed struct definition to
remove an unused field would do more harm than good.

Author: Melanie Plageman <melanieplageman@gmail.com>
Reported-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/tvvtfoxz5ykpsctxjbzxg3nldnzfc7geplrt2z2s54pmgto27y%40hbijsndifu45

10 days agoDon't generate fake "*TLOCRN*" or "*TROCRN*" aliases, either.
Robert Haas [Mon, 8 Sep 2025 16:58:07 +0000 (12:58 -0400)]
Don't generate fake "*TLOCRN*" or "*TROCRN*" aliases, either.

This is just like the previous two commits, except that this fix
actually doesn't change any regression test outputs.

Author: Robert Haas <rhaas@postgresql.org>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CA+TgmoYSYmDA2GvanzPMci084n+mVucv0bJ0HPbs6uhmMN6HMg@mail.gmail.com

10 days agoDon't generate fake "ANY_subquery" aliases, either.
Robert Haas [Mon, 8 Sep 2025 16:24:02 +0000 (12:24 -0400)]
Don't generate fake "ANY_subquery" aliases, either.

This is just like the previous commit, but for a different invented
alias name.

Author: Robert Haas <rhaas@postgresql.org>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CA+TgmoYSYmDA2GvanzPMci084n+mVucv0bJ0HPbs6uhmMN6HMg@mail.gmail.com

10 days agoDon't generate fake "*SELECT*" or "*SELECT* %d" subquery aliases.
Robert Haas [Mon, 8 Sep 2025 15:50:33 +0000 (11:50 -0400)]
Don't generate fake "*SELECT*" or "*SELECT* %d" subquery aliases.

rte->alias should point only to a user-written alias, but in these
cases that principle was violated. Fixing this causes some regression
test output changes: wherever rte->alias previously had a value and
is now NULL, rte->eref is now set to a generated name rather than to
rte->alias; and the scheme used to generate eref names differs from
what we were doing for aliases.

The upshot is that instead of "*SELECT*" or "*SELECT* %d",
EXPLAIN will now emit "unnamed_subquery" or "unnamed_subquery_%d".
But that's a reasonable descriptor, and we were already producing
that in yet other cases, so this seems not too objectionable.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Co-authored-by: Robert Haas <rhaas@postgresql.org>
Discussion: https://postgr.es/m/CA+TgmoYSYmDA2GvanzPMci084n+mVucv0bJ0HPbs6uhmMN6HMg@mail.gmail.com

10 days agoRemove unneeded VM pin from VM replay
Melanie Plageman [Mon, 8 Sep 2025 14:22:42 +0000 (10:22 -0400)]
Remove unneeded VM pin from VM replay

Previously, heap_xlog_visible() called visibilitymap_pin() even after
getting a buffer from XLogReadBufferForRedoExtended() -- which returns a
pinned buffer containing the specified block of the visibility map.

This would just have resulted in visibilitymap_pin() returning early
since the specified page was already present and pinned, but it was
confusing extraneous code, so remove it. It doesn't seem worth
backporting, though.

It appears to be an oversight in 2c03216.

While we are at it, remove two VM-related redundant asserts in the COPY
FREEZE code path. visibilitymap_set() already asserts that
PD_ALL_VISIBLE is set on the heap page and checks that the vmbuffer
contains the bits corresponding to the specified heap block, so callers
do not also need to check this.

Author: Melanie Plageman <melanieplageman@gmail.com>
Reported-by: Melanie Plageman <melanieplageman@gmail.com>
Reported-by: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CALdSSPhu7WZd%2BEfQDha1nz%3DDC93OtY1%3DUFEdWwSZsASka_2eRQ%40mail.gmail.com

10 days agoAdd test to prevent premature removal of conflict-relevant data.
Amit Kapila [Mon, 8 Sep 2025 11:38:02 +0000 (11:38 +0000)]
Add test to prevent premature removal of conflict-relevant data.

A test has been added to ensure that conflict-relevant data is not
prematurely removed when a concurrent prepared transaction is being
committed on the publisher.

This test introduces an injection point that simulates the presence of a
prepared transaction in the commit phase, validating that the system
correctly delays conflict slot advancement until the transaction is fully
committed.

Additionally, the test serves as a safeguard for developers, ensuring that
the acquisition of the commit timestamp does not occur before marking
DELAY_CHKPT_IN_COMMIT in RecordTransactionCommitPrepared.

Reported-by: Robert Haas <robertmhaas@gmail.com>
Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: shveta malik <shveta.malik@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/OS9PR01MB16913F67856B0DA2A909788129400A@OS9PR01MB16913.jpnprd01.prod.outlook.com

11 days agoFix corruption of pgstats shared hashtable due to OOM failures
Michael Paquier [Mon, 8 Sep 2025 06:52:23 +0000 (15:52 +0900)]
Fix corruption of pgstats shared hashtable due to OOM failures

A new pgstats entry is created as a two-step process:
- The entry is looked at in the shared hashtable of pgstats, and is
inserted if not found.
- When not found and inserted, its fields are then initialized.  This
part include a DSA chunk allocation for the stats data of the new entry.

As currently coded, if the DSA chunk allocation fails due to an
out-of-memory failure, an ERROR is generated, leaving in the pgstats
shared hashtable an inconsistent entry due to the first step, as the
entry has already been inserted in the hashtable.  These broken entries
can then be found by other backends, crashing them.

There are only two callers of pgstat_init_entry(), when loading the
pgstats file at startup and when creating a new pgstats entry.  This
commit changes pgstat_init_entry() so as we use dsa_allocate_extended()
with DSA_ALLOC_NO_OOM, making it return NULL on allocation failure
instead of failing.  This way, a backend failing an entry creation can
take appropriate cleanup actions in the shared hashtable before throwing
an error.  Currently, this means removing the entry from the shared
hashtable before throwing the error for the allocation failure.

Out-of-memory errors unlikely happen in the wild, and we do not bother
with back-patches when these are fixed, usually.  However, the problem
dealt with here is a degree worse as it breaks the shared memory state
of pgstats, impacting other processes that may look at an inconsistent
entry that a different process has failed to create.

Author: Mikhail Kot <mikhail.kot@databricks.com>
Discussion: https://postgr.es/m/CAAi9E7jELo5_-sBENftnc2E8XhW2PKZJWfTC3i2y-GMQd2bcqQ@mail.gmail.com
Backpatch-through: 15

11 days agoPost-commit review fixes for 228c370868.
Amit Kapila [Mon, 8 Sep 2025 06:10:15 +0000 (06:10 +0000)]
Post-commit review fixes for 228c370868.

This commit fixes three issues:

1) When a disabled subscription is created with retain_dead_tuples set to true,
the launcher is not woken up immediately, which may lead to delays in creating
the conflict detection slot.

Creating the conflict detection slot is essential even when the subscription is
not enabled. This ensures that dead tuples are retained, which is necessary for
accurately identifying the type of conflict during replication.

2) Conflict-related data was unnecessarily retained when the subscription does
not have a table.

3) Conflict-relevant data could be prematurely removed before applying
prepared transactions on the publisher that are in the commit critical section.

This issue occurred because the backend executing COMMIT PREPARED was not
accounted for during the computation of oldestXid in the commit phase on
the publisher. As a result, the subscriber could advance the conflict
slot's xmin without waiting for such COMMIT PREPARED transactions to
complete.

We fixed this issue by identifying prepared transactions that are in the
commit critical section during computation of oldestXid in commit phase.

Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: shveta malik <shveta.malik@gmail.com>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: Nisha Moond <nisha.moond412@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/OS9PR01MB16913DACB64E5721872AA5C02943BA@OS9PR01MB16913.jpnprd01.prod.outlook.com
Discussion: https://postgr.es/m/OS9PR01MB16913F67856B0DA2A909788129400A@OS9PR01MB16913.jpnprd01.prod.outlook.com

11 days agoUpdate parser README to include parse_jsontable.c
Michael Paquier [Mon, 8 Sep 2025 01:07:14 +0000 (10:07 +0900)]
Update parser README to include parse_jsontable.c

The README was missing parse_jsontable.c which handles JSON_TABLE.
Oversight in de3600452b61.

Author: Karthik S <karthikselvaam@gmail.com>
Discussion: https://postgr.es/m/CAK4gQD9gdcj+vq_FZGp=Rv-W+41v8_C7cmCUmDeu=cfrOdfXEw@mail.gmail.com
Backpatch-through: 17

13 days agoAllow to log raw parse tree.
Tatsuo Ishii [Fri, 5 Sep 2025 22:49:51 +0000 (07:49 +0900)]
Allow to log raw parse tree.

This commit allows to log the raw parse tree in the same way we
currently log the parse tree, rewritten tree, and plan tree.

To avoid unnecessary log noise for users not interested in this
detail, a new GUC option, "debug_print_raw_parse", has been added.

When starting the PostgreSQL process with "-d N", and N is 3 or higher,
debug_print_raw_parse is enabled automatically, alongside
debug_print_parse.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Tender Wang <tndrwang@gmail.com>
Reviewed-by: Tatsuo Ishii <ishii@postgresql.org>
Reviewed-by: John Naylor <johncnaylorls@gmail.com>
Discussion: https://postgr.es/m/CAEoWx2mcO0Gpo4vd8kPMAFWeJLSp0MeUUnaLdE1x0tSVd-VzUw%40mail.gmail.com

13 days agobufmgr: Remove freelist, always use clock-sweep
Andres Freund [Fri, 5 Sep 2025 16:25:59 +0000 (12:25 -0400)]
bufmgr: Remove freelist, always use clock-sweep

This set of changes removes the list of available buffers and instead simply
uses the clock-sweep algorithm to find and return an available buffer.  This
also removes the have_free_buffer() function and simply caps the
pg_autoprewarm process to at most NBuffers.

While on the surface this appears to be removing an optimization it is in fact
eliminating code that induces overhead in the form of synchronization that is
problematic for multi-core systems.

The main reason for removing the freelist, however, is not the moderate
improvement in scalability, but that having the freelist would require
dedicated complexity in several upcoming patches. As we have not been able to
find a case benefiting from the freelist...

Author: Greg Burd <greg@burd.me>
Reviewed-by: Tomas Vondra <tomas@vondra.me>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/70C6A5B5-2A20-4D0B-BC73-EB09DD62D61C@getmailspring.com