postgresql.git
17 hours agonbtree: Always set skipScan flag on rescan. master github/master
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

21 hours 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

22 hours 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.

22 hours 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

24 hours 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>
43 hours 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.

44 hours 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

44 hours 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

46 hours 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

2 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

2 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

2 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

2 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

2 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

2 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

2 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

2 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

2 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

2 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

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

2 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

2 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

3 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

3 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

3 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

3 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

3 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

3 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

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

3 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

3 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

3 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

3 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

3 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

3 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

4 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

4 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

4 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

4 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

4 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

4 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

4 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

5 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

5 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

5 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

5 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

5 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>
5 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

6 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

6 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

6 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

6 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

6 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

6 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

6 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

6 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

6 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

8 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

9 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

9 days agobufmgr: Use consistent naming of the clock-sweep algorithm
Andres Freund [Fri, 5 Sep 2025 16:25:59 +0000 (12:25 -0400)]
bufmgr: Use consistent naming of the clock-sweep algorithm

Minor edits to comments only.

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

9 days agoAdd assert and log message to visibilitymap_set
Melanie Plageman [Fri, 5 Sep 2025 13:33:36 +0000 (09:33 -0400)]
Add assert and log message to visibilitymap_set

Add an assert to visibilitymap_set() that the provided heap buffer is
exclusively locked, which is expected.

Also, enhance the debug logging message to specify which VM flags were
set.

Based on a related suggestion by Kirill Reshke on an in-progress
patchset.

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

9 days agoFix concurrent update issue with MERGE.
Dean Rasheed [Fri, 5 Sep 2025 07:18:18 +0000 (08:18 +0100)]
Fix concurrent update issue with MERGE.

When executing a MERGE UPDATE action, if there is more than one
concurrent update of the target row, the lock-and-retry code would
sometimes incorrectly identify the latest version of the target tuple,
leading to incorrect results.

This was caused by using the ctid field from the TM_FailureData
returned by table_tuple_lock() in a case where the result was TM_Ok,
which is unsafe because the TM_FailureData struct is not guaranteed to
be fully populated in that case. Instead, it should use the tupleid
passed to (and updated by) table_tuple_lock().

To reduce the chances of similar errors in the future, improve the
commentary for table_tuple_lock() and TM_FailureData to make it
clearer that table_tuple_lock() updates the tid passed to it, and most
fields of TM_FailureData should not be relied on in non-failure cases.
An exception to this is the "traversed" field, which is set in both
success and failure cases.

Reported-by: Dmitry <dsy.075@yandex.ru>
Author: Yugo Nagata <nagata@sraoss.co.jp>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/1570d30e-2b95-4239-b9c3-f7bf2f2f8556@yandex.ru
Backpatch-through: 15

9 days agoFix outdated comments in slru.c
Michael Paquier [Fri, 5 Sep 2025 05:10:08 +0000 (14:10 +0900)]
Fix outdated comments in slru.c

SlruRecentlyUsed() is an inline function since 53c2a97a9266, not a
macro.  The description of long_segment_names was missing at the top of
SimpleLruInit(), part forgotten in 4ed8f0913bfd.

Author: Julien Rouhaud <rjuju123@gmail.com>
Discussion: https://postgr.es/m/aLpBLMOYwEQkaleF@jrouhaud
Backpatch-through: 17

9 days agoSwitch some numeric-related functions to use soft error reporting
Michael Paquier [Fri, 5 Sep 2025 04:53:47 +0000 (13:53 +0900)]
Switch some numeric-related functions to use soft error reporting

This commit changes some functions related to the data type numeric to
use the soft error reporting rather than a custom boolean flag (called
"have_error") that callers of these functions could rely on to bypass
the generation of ERROR reports, letting the callers do their own error
handling (timestamp, jsonpath and numeric_to_char() require them).

This results in the removal of some boilerplate code that was required
to handle both the ereport() and the "have_error" code paths bypassing
ereport(), unifying everything under the soft error reporting facility.

While on it, some duplicated error messages are removed.  The function
upgraded in this commit were suffixed with "_opt_error" in their names.
They are renamed to "_safe" instead.

This change relies on d9f7f5d32f20, that has introduced the soft error
reporting infrastructure.

Author: Amul Sul <sulamul@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Discussion: https://postgr.es/m/CAAJ_b96No5h5tRuR+KhcC44YcYUCw8WAHuLoqqyyop8_k3+JDQ@mail.gmail.com

9 days agoChange pg_lsn_in_internal() to use soft error reporting
Michael Paquier [Fri, 5 Sep 2025 03:59:29 +0000 (12:59 +0900)]
Change pg_lsn_in_internal() to use soft error reporting

pg_lsn includes pg_lsn_in_internal() for the purpose of parsing a LSN
position for the GUC recovery_target_lsn (21f428ebde39).  It relies on a
boolean called "have_error" that would be set when the LSN parsing
fails, then let its callers handle any errors.

d9f7f5d32f20 has added support for soft error reporting.  This commit
removes some boilerplate code and switches the routine to use soft error
reporting directly, giving to the callers of pg_lsn_in_internal()
the possibility to be fed the error message generated on failure.

pg_lsn_in_internal() routine is renamed to pg_lsn_in_safe(), for
consistency with other similar routines that are given an escontext.

Author: Amul Sul <sulamul@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Discussion: https://postgr.es/m/CAAJ_b96No5h5tRuR+KhcC44YcYUCw8WAHuLoqqyyop8_k3+JDQ@mail.gmail.com

9 days agoRevert recent change to RequestNamedLWLockTranche().
Nathan Bossart [Thu, 4 Sep 2025 20:34:48 +0000 (15:34 -0500)]
Revert recent change to RequestNamedLWLockTranche().

Commit 38b602b028 modified this function to allocate enough space
for MAX_NAMED_TRANCHES (256) requests, which is likely far more
than most clusters need.  This commit reverts that change so that
it first allocates enough space for only 16 requests and resizes
the array when necessary.  While at it, remove the check for too
many tranches from this function.  We can now rely on
InitializeLWLocks() to do that check via its calls to
LWLockNewTrancheId() for the named tranches.

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

10 days agoClean up newly added guc_tables.inc.c
Peter Eisentraut [Thu, 4 Sep 2025 10:57:03 +0000 (12:57 +0200)]
Clean up newly added guc_tables.inc.c

There was a missing makefile rule to clean up the guc_tables.inc.c
symlink in src/include/.  Oversight in commit 63599896545.

Author: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/dae6fe89-1e0c-4c3f-8d92-19d23374fb10%40eisentraut.org

10 days agoAdjust commentary for WaitEventLWLock in wait_event_names.txt.
Nathan Bossart [Thu, 4 Sep 2025 15:18:42 +0000 (10:18 -0500)]
Adjust commentary for WaitEventLWLock in wait_event_names.txt.

In addition to changing a couple of references for clarity, this
commit combines the two similar comments.

10 days agoFix replica identity check for MERGE.
Dean Rasheed [Thu, 4 Sep 2025 10:45:44 +0000 (11:45 +0100)]
Fix replica identity check for MERGE.

When executing a MERGE, check that the target relation supports all
actions mentioned in the MERGE command. Specifically, check that it
has a REPLICA IDENTITY if it publishes updates or deletes and the
MERGE command contains update or delete actions. Failing to do this
can silently break replication.

Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Tested-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/OS3PR01MB57180C87E43A679A730482DF94B62@OS3PR01MB5718.jpnprd01.prod.outlook.com
Backpatch-through: 15

10 days agoFix replica identity check for INSERT ON CONFLICT DO UPDATE.
Dean Rasheed [Thu, 4 Sep 2025 10:27:53 +0000 (11:27 +0100)]
Fix replica identity check for INSERT ON CONFLICT DO UPDATE.

If an INSERT has an ON CONFLICT DO UPDATE clause, the executor must
check that the target relation supports UPDATE as well as INSERT. In
particular, it must check that the target relation has a REPLICA
IDENTITY if it publishes updates. Formerly, it was not doing this
check, which could lead to silently breaking replication.

Fix by adding such a check to CheckValidResultRel(), which requires
adding a new onConflictAction argument. In back-branches, preserve ABI
compatibility by introducing a wrapper function with the original
signature.

Author: Zhijie Hou <houzj.fnst@fujitsu.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Tested-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/OS3PR01MB57180C87E43A679A730482DF94B62@OS3PR01MB5718.jpnprd01.prod.outlook.com
Backpatch-through: 13

10 days agoFix incorrect comment in pgstat_backend.c
Michael Paquier [Wed, 3 Sep 2025 23:34:51 +0000 (08:34 +0900)]
Fix incorrect comment in pgstat_backend.c

The counters saved from pgWalUsage, used for the difference calculations
when flushing the backend WAL stats, are updated when calling
pgstat_flush_backend() under PGSTAT_BACKEND_FLUSH_WAL, and not
pgstat_report_wal().  The comment updated in this commit referenced the
latter, but it is perfectly OK to flush the backend stats independently
of the WAL stats.

Noticed while looking at this area of the code, introduced by
76def4cdd7c2 as a copy-pasto.

Backpatch-through: 18

10 days agoMake libpq_pipeline.c shorter and more uniform via helper functions.
Tom Lane [Wed, 3 Sep 2025 20:07:57 +0000 (16:07 -0400)]
Make libpq_pipeline.c shorter and more uniform via helper functions.

There are many places in this test program that need to consume a
PGresult while checking that its PQresultStatus is as-expected, or
related tasks such as checking that PQgetResult has nothing more to
return.  These tasks were open-coded in a rather inconsistent way,
leading to some outright bugs, some memory leakage, and frequent
inconsistencies about what would be reported in event of an error.
Invent a few helper functions to standardize the behavior and
reduce code duplication.  Also, rename the one pre-existing helper
function from confirm_query_canceled to consume_query_cancel, per
Álvaro's suggestion that "confirm" is a poor choice of verb for a
function that will discard the PGresult.

While at it, clean up assorted other places that were leaking
PGresults or even server connections.  This is pure neatnik-ism,
since the test doesn't run long enough for those leaks to be of
any real-world concern.

While this fixes some things that are clearly bugs, it's only
a test program, and none of the bugs seem serious enough to
justify back-patching.

Bug: #18960
Reported-by: Dmitry Kovalenko <d.kovalenko@postgrespro.ru>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/18960-09cd4a5100152e58@postgresql.org

10 days agoMove dynamically-allocated LWLock tranche names to shared memory.
Nathan Bossart [Wed, 3 Sep 2025 18:57:48 +0000 (13:57 -0500)]
Move dynamically-allocated LWLock tranche names to shared memory.

There are two ways for shared libraries to allocate their own
LWLock tranches.  One way is to call RequestNamedLWLockTranche() in
a shmem_request_hook, which requires the library to be loaded via
shared_preload_libraries.  The other way is to call
LWLockNewTrancheId(), which is not subject to the same
restrictions.  However, LWLockNewTrancheId() does require each
backend to store the tranche's name in backend-local memory via
LWLockRegisterTranche().  This API is a little cumbersome and leads
to things like unhelpful pg_stat_activity.wait_event values in
backends that haven't loaded the library.

This commit moves these LWLock tranche names to shared memory, thus
eliminating the need for each backend to call
LWLockRegisterTranche().  Instead, the tranche name must be
provided to LWLockNewTrancheId(), which immediately makes the name
available to all backends.  Since the tranche name array is
append-only, lookups can ordinarily avoid locking as long as their
local copy of the LWLock counter is greater than the requested
tranche ID.

One downside of this approach is that we now have a hard limit on
both the length of tranche names (NAMEDATALEN-1 bytes) and the
number of dynamically-allocated tranches (256).  Besides a limit of
NAMEDATALEN-1 bytes for tranche names registered via
RequestNamedLWLockTranche(), no such limits previously existed.  We
could avoid these new limits by using dynamic shared memory, but
the complexity involved didn't seem worth it.  We briefly
considered making the tranche limit user-configurable but
ultimately decided against that, too.  Since there is still a lot
of time left in the v19 development cycle, it's possible we will
revisit this choice.

Author: Sami Imseih <samimseih@gmail.com>
Reviewed-by: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Rahila Syed <rahilasyed90@gmail.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CAA5RZ0vvED3naph8My8Szv6DL4AxOVK3eTPS0qXsaKi%3DbVdW2A%40mail.gmail.com

11 days agoci: Explicitly enable Meson features
Jacob Champion [Wed, 3 Sep 2025 14:54:24 +0000 (07:54 -0700)]
ci: Explicitly enable Meson features

Meson's "auto" feature mode silently disables features with missing
prerequisites, which is nice for development but can lead to false
positives in the CI (such as my commit b0635bfda, which broke OAuth
detection on OpenBSD). Use an explicit feature list in the Cirrus config
instead; this mirrors the --with-XXX experience of Autoconf.

While we're here, also move common configuration options into a single
variable, MESON_COMMON_PG_CONFIG_ARGS, as suggested by Peter. The
resulting hierarchy is as follows:

MESON_COMMON_PG_CONFIG_ARGS   "global" Meson configuration options

MESON_COMMON_FEATURES         the default set of CI features, to be used
                              unless there's a specific reason not to

MESON_FEATURES                per-OS feature configuration, overriding
                              the above

The current exceptions to the use of MESON_COMMON_FEATURES are
- SanityCheck, which uses almost no dependencies;
- Windows - VS, whose feature list has diverged significantly from the
  others; and
- Linux, which continues to use 'auto' features so that autodetection is
  still tested in the CI. (Options shared between 64- and 32-bit builds
  can go into LINUX_MESON_FEATURES instead.)

Author: Nazir Bilal Yavuz <byavuz81@gmail.com>
Suggested-by: Jacob Champion <jacob.champion@enterprisedb.com>
Suggested-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Jacob Champion <jacob.champion@enterprisedb.com>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/flat/CAN55FZ0aO8d_jkyRijcGP8qO%3DXH09qG%3Dpw0ZZDvB4LMzuXYU1w%40mail.gmail.com

11 days agoci: Remove extra PG_TEST_EXTRA from NetBSD/OpenBSD
Jacob Champion [Wed, 3 Sep 2025 14:54:15 +0000 (07:54 -0700)]
ci: Remove extra PG_TEST_EXTRA from NetBSD/OpenBSD

The PG_TEST_EXTRA environment variable is already set at the top level.
As of 3d1aec225, Meson tasks will use this by default, so there's no
need for another intermediate variable.

Author: Nazir Bilal Yavuz <byavuz81@gmail.com>
Suggested-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/flat/CAN55FZ0aO8d_jkyRijcGP8qO%3DXH09qG%3Dpw0ZZDvB4LMzuXYU1w%40mail.gmail.com

11 days agoFix mistake in new GUC tables source
Peter Eisentraut [Wed, 3 Sep 2025 09:48:35 +0000 (11:48 +0200)]
Fix mistake in new GUC tables source

Commit 63599896545 had it so that the parameter "debug_discard_caches"
did not exist unless DISCARD_CACHES_ENABLED was defined (typically via
enabling asserts).  This was a mistake, it did not correspond to the
prior setup.  Several tests use this parameter, so they were now
failing if you did not have asserts enabled.

11 days agoGenerate GUC tables from .dat file
Peter Eisentraut [Wed, 3 Sep 2025 07:11:48 +0000 (09:11 +0200)]
Generate GUC tables from .dat file

Store the information in guc_tables.c in a .dat file similar to the
catalog data in src/include/catalog/, and generate a part of
guc_tables.c from that.  The goal is to make it easier to edit that
information, and to be able to make changes to the downstream data
structures more easily.  (Essentially, those are the same reasons as
for the original adoption of the .dat format.)

Reviewed-by: John Naylor <johncnaylorls@gmail.com>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: David E. Wheeler <david@justatheory.com>
Discussion: https://www.postgresql.org/message-id/flat/dae6fe89-1e0c-4c3f-8d92-19d23374fb10%40eisentraut.org

11 days agoFix planner error when estimating SubPlan cost
Richard Guo [Wed, 3 Sep 2025 07:00:38 +0000 (16:00 +0900)]
Fix planner error when estimating SubPlan cost

SubPlan nodes are typically built very early, before any RelOptInfos
have been constructed for the parent query level.  As a result, the
simple_rel_array in the parent root has not yet been initialized.
Currently, during cost estimation of a SubPlan's testexpr, we may call
examine_variable() to look up statistical data about the expressions.
This can lead to "no relation entry for relid" errors.

To fix, pass root as NULL to cost_qual_eval() in cost_subplan(), since
the root does not yet contain enough information to safely consult
statistics.

One exception is SubPlan nodes built for the initplans of MIN/MAX
aggregates from indexes.  In this case, having a NULL root is safe
because testexpr will be NULL.  Additionally, an initplan will by
definition not consult anything from the parent plan.

Backpatch to all supported branches.  Although the reported call path
that triggers this error is not reachable prior to v17, there's no
guarantee that other code paths -- especially in extensions -- could
not encounter the same issue when cost_qual_eval() is called with a
root that lacks a valid simple_rel_array.  The test case is not
included in pre-v17 branches though.

Bug: #19037
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Diagnosed-by: Tom Lane <tgl@sss.pgh.pa.us>
Author: Richard Guo <guofenglinux@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19037-3d1c7bb553c7ce84@postgresql.org
Backpatch-through: 13

11 days agoFix use-after-free issue in slot synchronization.
Amit Kapila [Wed, 3 Sep 2025 06:31:05 +0000 (06:31 +0000)]
Fix use-after-free issue in slot synchronization.

Author: Shlok Kyal <shlok.kyal.oss@gmail.com>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Backpatch-through: 18, where it was introduced
Discussion: https://postgr.es/m/CANhcyEXMrcEdzj-RNGJam0nJHM4y+ttdWsgUCFmXciM7BNKc7A@mail.gmail.com

11 days agolibpq: Fix PQtrace() format for non-printable characters
Michael Paquier [Wed, 3 Sep 2025 03:54:23 +0000 (12:54 +0900)]
libpq: Fix PQtrace() format for non-printable characters

PQtrace() was generating its output for non-printable characters without
casting the characters printed with unsigned char, leading to some extra
"\xffffff" generated in the output due to the fact that char may be
signed.

Oversights introduced by commit 198b3716dba6, so backpatch down to v14.

Author: Ran Benita <ran@unusedvar.com>
Discussion: https://postgr.es/m/a3383211-4539-459b-9d51-95c736ef08e0@app.fastmail.com
Backpatch-through: 14

11 days agoUpdate outdated references to the SLRU ControlLock
Michael Paquier [Wed, 3 Sep 2025 01:20:28 +0000 (10:20 +0900)]
Update outdated references to the SLRU ControlLock

SLRU bank locks are referred as "bank locks" or "SLRU bank locks" in the
code comments.  The comments updated in this commit use the latter term.

Oversight in 53c2a97a9266, that has replaced the single ControlLock by
the bank control locks.

Author: Julien Rouhaud <julien.rouhaud@free.fr>
Discussion: https://postgr.es/m/aLUT2UO8RjJOzZNq@jrouhaud
Backpatch-through: 17

11 days agoAdd HINT for COPY TO when WHERE clause is used.
Fujii Masao [Tue, 2 Sep 2025 23:33:54 +0000 (08:33 +0900)]
Add HINT for COPY TO when WHERE clause is used.

COPY TO does not support a WHERE clause, and currently fails with the error:

    ERROR:  WHERE clause not allowed with COPY TO

Since the intended behavior can be achieved by using
COPY (SELECT ... WHERE ...) TO, this commit adds a HINT
to the error message:

    HINT:  Try the COPY (SELECT ... WHERE ...) TO variant.

This makes the error more informative and helps users
quickly find the alternative usage.

Author: Atsushi Torikoshi <torikoshia@oss.nttdata.com>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Discussion: https://postgr.es/m/3520c224c5ffac0113aef84a9179f37e@oss.nttdata.com

11 days agoChange ReplicationSlotPersistentData's "synced" member to a bool.
Nathan Bossart [Tue, 2 Sep 2025 21:53:54 +0000 (16:53 -0500)]
Change ReplicationSlotPersistentData's "synced" member to a bool.

Note that this doesn't require bumping SLOT_VERSION because we
require sizeof(bool) == 1, thanks to commit 97525bc5c8.

Overight in commit ddd5f4f54a.

Discussion: Ranier Vilela <ranier.vf@gmail.com>

12 days agoImprove error message for duplicate labels when creating an enum type.
Tom Lane [Tue, 2 Sep 2025 17:50:56 +0000 (13:50 -0400)]
Improve error message for duplicate labels when creating an enum type.

Previously, duplicate labels in CREATE TYPE AS ENUM were caught by
the unique index on pg_enum, resulting in a generic error message.
While this was evidently intentional, it's not terribly user-friendly,
nor consistent with the ALTER TYPE cases which take more care with
such errors.  This patch adds an explicit check to produce a more
user-friendly and descriptive error message.

A potential objection to this implementation is that it adds O(N^2)
work to the creation operation.  However, quick testing finds that
that's pretty negligible below 1000 enum labels, and tolerable even
at 10000.  So it doesn't really seem worth being smarter.

Author: Yugo Nagata <nagata@sraoss.co.jp>
Reviewed-by: Rahila Syed <rahilasyed90@gmail.com>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/20250704000402.37e605ab0c59c300965a17ee@sraoss.co.jp

12 days agoGenerate pgstat_count_slru*() functions for slru using macros
Michael Paquier [Tue, 2 Sep 2025 07:22:03 +0000 (16:22 +0900)]
Generate pgstat_count_slru*() functions for slru using macros

This change replaces seven functions definitions by macros, reducing a
bit some repetitive patterns in the code.  An interesting side effect is
that this removes an inconsistency in the naming of SLRU increment
functions with the field names.

This change is similar to 850f4b4c8cab8018ffbf5895 or 83a1a1b56645.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Discussion: https://postgr.es/m/aLHA//gr4dTpDHHC@ip-10-97-1-34.eu-west-3.compute.internal

12 days agoAdd max_retention_duration option to subscriptions.
Amit Kapila [Tue, 2 Sep 2025 03:20:18 +0000 (03:20 +0000)]
Add max_retention_duration option to subscriptions.

This commit introduces a new subscription parameter,
max_retention_duration, aimed at mitigating excessive accumulation of dead
tuples when retain_dead_tuples is enabled and the apply worker lags behind
the publisher.

When the time spent advancing a non-removable transaction ID exceeds the
max_retention_duration threshold, the apply worker will stop retaining
conflict detection information. In such cases, the conflict slot's xmin
will be set to InvalidTransactionId, provided that all apply workers
associated with the subscription (with retain_dead_tuples enabled) confirm
the retention duration has been exceeded.

To ensure retention status persists across server restarts, a new column
subretentionactive has been added to the pg_subscription catalog. This
prevents unnecessary reactivation of retention logic after a restart.

The conflict detection slot will not be automatically re-initialized
unless a new subscription is created with retain_dead_tuples = true, or
the user manually re-enables retain_dead_tuples.

A future patch will introduce support for automatic slot re-initialization
once at least one apply worker confirms that the retention duration is
within the configured max_retention_duration.

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

13 days agopostgres_fdw: Use psql variables for connection parameters
Michael Paquier [Mon, 1 Sep 2025 00:02:03 +0000 (09:02 +0900)]
postgres_fdw: Use psql variables for connection parameters

Several statements need to reference the current connection's current
database name and current port value.  Until now, this has been
accomplished by creating dynamic SQL statements inside of a DO block,
which is not as easy to parse.  It also takes away some of the
granularity of any error messages that might occur, making debugging
harder.

By capturing the connection-specific settings into psql variables, it
becomes possible to write simpler SQL statements for the FDW objects.
This eliminates most of DO blocks used in this test, making it a bit
more readable and shorter.

Author: Author: Corey Huinker <corey.huinker@gmail.com>
Discussion: https://postgr.es/m/CADkLM=cpUiJ3QF7aUthTvaVMmgQcm7QqZBRMDLhBRTR+gJX-Og@mail.gmail.com

2 weeks agoFix const-simplification for constraints and stats
Richard Guo [Sat, 30 Aug 2025 23:59:48 +0000 (08:59 +0900)]
Fix const-simplification for constraints and stats

Constraint expressions and statistics expressions loaded from the
system catalogs need to be run through const-simplification, because
the planner will be comparing them to similarly-processed qual
clauses.  Without this step, the planner may fail to detect valid
matches.

Currently, NullTest clauses in these expressions may not be reduced
correctly during const-simplification.  This happens because their Var
nodes do not yet have the correct varno when eval_const_expressions is
applied.  Since eval_const_expressions relies on varno to reduce
NullTest quals, incorrect varno can cause problems.

Additionally, for statistics expressions, eval_const_expressions is
called with root set to NULL, which also inhibits NullTest reduction.

This patch fixes the issue by ensuring that Vars are updated to have
the correct varno before const-simplification, and that a valid root
is passed to eval_const_expressions when needed.

Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/19007-4cc6e252ed8aa54a@postgresql.org

2 weeks agoadd_commit_links.pl: error out if missing major version number
Bruce Momjian [Sat, 30 Aug 2025 22:26:08 +0000 (18:26 -0400)]
add_commit_links.pl:  error out if missing major version number

Reported-by: Tom Lane
Author: Tom Lane

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

2 weeks agoPrepare DSM registry for upcoming changes to LWLock tranche names.
Nathan Bossart [Sat, 30 Aug 2025 01:34:53 +0000 (20:34 -0500)]
Prepare DSM registry for upcoming changes to LWLock tranche names.

A proposed patch would place a limit of NAMEDATALEN-1 (i.e., 63)
bytes on the names of dynamically-allocated LWLock tranches, but
GetNamedDSA() and GetNamedDSHash() may register tranches with
longer names.  This commit lowers the maximum DSM registry entry
name length to NAMEDATALEN-1 bytes and modifies GetNamedDSHash() to
create only one tranche, thereby allowing us to keep the DSM
registry's tranche names below NAMEDATALEN bytes.

Author: Sami Imseih <samimseih@gmail.com>
Discussion: https://postgr.es/m/aKzIg1JryN1qhNuy%40nathan

2 weeks agoProvide error context when an error is thrown within WaitOnLock().
Tom Lane [Fri, 29 Aug 2025 19:43:34 +0000 (15:43 -0400)]
Provide error context when an error is thrown within WaitOnLock().

Show the requested lock level and the object being waited on,
in the same format we use for deadlock reports and similar errors.
This is particularly helpful for debugging lock-timeout errors,
since otherwise the user has very little to go on about which
lock timed out.  The performance cost of setting up the callback
should be negligible compared to the other tracing support already
present in WaitOnLock.

As in the deadlock-report case, we just show numeric object OIDs,
because it seems too scary to try to perform catalog lookups
in this context.

Reported-by: Steve Baldwin <steve.baldwin@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/1602369.1752167154@sss.pgh.pa.us

2 weeks agopg_dump: Fix compression API errorhandling
Daniel Gustafsson [Fri, 29 Aug 2025 17:28:46 +0000 (19:28 +0200)]
pg_dump: Fix compression API errorhandling

Compression in pg_dump is abstracted using an API with multiple
implementations which can be selected at runtime by the user.
The API and its implementations have evolved over time, notable
commits include bf9aa490dbe9960732a984adc8e20, and 0da243fed.
The errorhandling defined by the API was however problematic and
the implementations had a few bugs and/or were not following the
API specification.  This commit modifies the API to ensure that
callers can perform errorhandling efficiently and fixes all the
implementations such that they all implement the API in the same
way.  A full list of the changes can be seen below.

 * write_func:
   - Make write_func throw an error on all error conditions.  All
     callers of write_func were already checking for success and
     calling pg_fatal on all errors, so we might as well make the
     API support that case directly with simpler errorhandling as
     a result.

 * open_func:
   - zstd: move stream initialization from the open function to
     the read and write functions as they can have fatal errors.
     Also ensure to dup the file descriptor like none and gzip.
   - lz4: Ensure to dup the file descriptor like none and gzip.

 * close_func:
   - zstd: Ensure to close the file descriptor even if closing
     down the compressor fails, and clean up state allocation on
     fclose failures.  Make sure to capture errors set by fclose.
   - lz4: Ensure to close the file descriptor even if closing
     down the compressor fails, and instead of calling pg_fatal
     log the failures using pg_log_error. Make sure to capture
     errors set by fclose.
   - none: Make sure to catch errors set by fclose.

 * read_func / gets_func:
   - Make read_func unconditionally return the number of read
     bytes instead of making it optional per implementation.
   - lz4: Make sure to call throw an error and not return -1
   - gzip: gzread returning zero cannot be assumed to indicate
     EOF as it is documented to return zero for some types of
     errors.
   - lz4, zstd: Convert the _read_internal helper functions to
     not call pg_fatal on errors to be able to handle gets_func
     returning NULL on error.

 * getc_func:
   - zstd: Use an unsigned char rather than an int to read char
     into.

 * LZ4Stream_init:
   - Make sure to not switch to inited state until we know that
     initialization succeeded and reset errno just in case.

On top of these changes there are minor comment cleanups and
improvements as well as an attempt to consistently reset errno
in codepaths where it is inspected.

This work was initiated by a report of API misuse, which turned
into a larger body of work.  As this is an internal API these
changes can be backpatched into all affected branches.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Author: Daniel Gustafsson <daniel@yesql.se>
Reported-by: Evgeniy Gorbanev <gorbanyoves@basealt.ru>
Discussion: https://postgr.es/m/517794.1750082166@sss.pgh.pa.us
Backpatch-through: 16

2 weeks agoMake LWLockCounter a global variable.
Nathan Bossart [Fri, 29 Aug 2025 17:13:37 +0000 (12:13 -0500)]
Make LWLockCounter a global variable.

Using the LWLockCounter requires first calculating its address in
shared memory like this:

LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));

Commit 82e861fbe1 started this trend in order to fix EXEC_BACKEND
builds, but it could also be fixed by adding it to the
BackendParameters struct.  The current approach is somewhat
difficult to follow, so this commit switches to the latter.  While
at it, swap around the code in LWLockShmemSize() to match the order
of assignments in CreateLWLocks() for added readability.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Discussion: https://postgr.es/m/aLDLnan9gNCS9fHx%40nathan

2 weeks agoFix .gitignore for src/interfaces/libpq-oauth.
Tom Lane [Fri, 29 Aug 2025 16:05:58 +0000 (12:05 -0400)]
Fix .gitignore for src/interfaces/libpq-oauth.

This missed files created when running the oauth tests.

2 weeks agoRemove unused parameter from ProcessSlotSyncInterrupts().
Nathan Bossart [Fri, 29 Aug 2025 15:56:10 +0000 (10:56 -0500)]
Remove unused parameter from ProcessSlotSyncInterrupts().

Oversight in commit 93db6cbda0.

Author: ChangAo Chen <cca5507@qq.com>
Discussion: https://postgr.es/m/tencent_7B42BBE8D0A5C28DDAB91436192CBCCB8307%40qq.com

2 weeks agoSilence -Wmissing-variable-declarations in headerscheck.
Tom Lane [Fri, 29 Aug 2025 14:46:13 +0000 (10:46 -0400)]
Silence -Wmissing-variable-declarations in headerscheck.

Newer gcc versions will emit warnings about missing extern
declarations if certain header files are compiled by themselves.
Add the "extern" declarations needed to quiet that.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/1127775.1754417387@sss.pgh.pa.us

2 weeks agoFix possible use after free in expand_partitioned_rtentry()
David Rowley [Fri, 29 Aug 2025 12:50:50 +0000 (00:50 +1200)]
Fix possible use after free in expand_partitioned_rtentry()

It's possible that if the only live partition is concurrently dropped
and try_table_open() fails, that the bms_del_member() will pfree the
live_parts Bitmapset.  Since the bms_del_member() call does not assign
the result back to the live_parts local variable, the while loop could
segfault as that variable would still reference the pfree'd Bitmapset.

Backpatch to 15. 52f3de874 was backpatched to 14, but there's no
bms_del_member() there due to live_parts not yet existing in RelOptInfo in
that version.  Technically there's no bug in version 15 as
bms_del_member() didn't pfree when the set became empty prior to
00b41463c (from v16).  Applied to v15 anyway to keep the code similar and
to avoid the bad coding pattern.

Author: Bernd Reiß <bd_reiss@gmx.at>
Reviewed-by: David Rowley <dgrowleyml@gmail.com>
Discussion: https://postgr.es/m/6b88f27a-c45c-4826-8e37-d61a04d90182@gmx.at
Backpatch-through: 15

2 weeks agoCREATE STATISTICS: improve misleading error message
Álvaro Herrera [Fri, 29 Aug 2025 12:43:47 +0000 (14:43 +0200)]
CREATE STATISTICS: improve misleading error message

I think the error message for a different condition was inadvertently
copied.

This problem seems to have been introduced by commit a4d75c86bf15.

Author: Álvaro Herrera <alvherre@kurilemu.de>
Reported-by: jian he <jian.universality@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Backpatch-through: 14
Discussion: https://postgr.es/m/CACJufxEZ48toGH0Em_6vdsT57Y3L8pLF=DZCQ_gCii6=C3MeXw@mail.gmail.com

2 weeks agoFix typo in isolation test spec
Daniel Gustafsson [Fri, 29 Aug 2025 11:08:32 +0000 (13:08 +0200)]
Fix typo in isolation test spec

Replace 'committs' with 'commits'.

Author: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://postgr.es/m/CAEoWx2=BESkfXsZ9jQW+1NcGTazKuj2wEXsPm1_EpgzHs0BHDQ@mail.gmail.com

2 weeks agoheaderscheck: Document that --with-llvm is required
Peter Eisentraut [Fri, 29 Aug 2025 07:30:50 +0000 (09:30 +0200)]
headerscheck: Document that --with-llvm is required

We already documented that other --with-* options are required for a
successful run.  It turns out --with-llvm is also required.

Suggested-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/flat/1127775.1754417387%40sss.pgh.pa.us