postgresql.git
3 weeks 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

3 weeks 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 weeks 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 weeks agoFix description of WAL record blocks in hash_xlog.h
Michael Paquier [Thu, 11 Sep 2025 08:17:24 +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 weeks agoFix incorrect file reference in guc.h
Michael Paquier [Thu, 11 Sep 2025 01:15:37 +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 weeks 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

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

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

3 weeks agomeson: build checksums with extra optimization flags.
Jeff Davis [Tue, 9 Sep 2025 23:04:04 +0000 (16:04 -0700)]
meson: build checksums with extra optimization flags.

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

Missed backport of 9af672bcb2, noticed by Nathan Bossart.

Reported-by: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://postgr.es/m/a81f2f7ef34afc24a89c613671ea017e3651329c.camel@j-davis.com
Reviewed-by: Andres Freund <andres@anarazel.de>
Backpatch-through: 16

3 weeks agoFix leak with SMgrRelations in startup process
Michael Paquier [Tue, 9 Sep 2025 22:23:22 +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

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

3 weeks agoFix corruption of pgstats shared hashtable due to OOM failures
Michael Paquier [Mon, 8 Sep 2025 06:52:48 +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

3 weeks agoUpdate parser README to include parse_jsontable.c
Michael Paquier [Mon, 8 Sep 2025 01:07:18 +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

4 weeks agoFix concurrent update issue with MERGE.
Dean Rasheed [Fri, 5 Sep 2025 07:21:35 +0000 (08:21 +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

4 weeks agoFix outdated comments in slru.c
Michael Paquier [Fri, 5 Sep 2025 05:10:24 +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

4 weeks agoFix replica identity check for MERGE.
Dean Rasheed [Thu, 4 Sep 2025 10:47:15 +0000 (11:47 +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

4 weeks agoFix replica identity check for INSERT ON CONFLICT DO UPDATE.
Dean Rasheed [Thu, 4 Sep 2025 10:32:00 +0000 (11:32 +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

4 weeks agoFix incorrect comment in pgstat_backend.c
Michael Paquier [Wed, 3 Sep 2025 23:34:57 +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

4 weeks 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

4 weeks agoFix use-after-free issue in slot synchronization.
Amit Kapila [Wed, 3 Sep 2025 06:17:08 +0000 (06:17 +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

4 weeks agolibpq: Fix PQtrace() format for non-printable characters
Michael Paquier [Wed, 3 Sep 2025 03:54:27 +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

4 weeks agoUpdate outdated references to the SLRU ControlLock
Michael Paquier [Wed, 3 Sep 2025 01:20:33 +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

4 weeks agoStamp 18rc1. REL_18_RC1
Tom Lane [Mon, 1 Sep 2025 20:03:08 +0000 (16:03 -0400)]
Stamp 18rc1.

4 weeks agoTranslation updates
Peter Eisentraut [Mon, 1 Sep 2025 11:07:49 +0000 (13:07 +0200)]
Translation updates

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

4 weeks agodoc PG 18 relnotes: adjust attribution for commit a252ed7fba6
Bruce Momjian [Sat, 30 Aug 2025 22:21:05 +0000 (18:21 -0400)]
doc PG 18 relnotes:  adjust attribution for commit a252ed7fba6

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

Backpatch-through: 18

4 weeks agodoc PG 18 relnotes: add attribution and rewrite text search item
Bruce Momjian [Sat, 30 Aug 2025 21:52:06 +0000 (17:52 -0400)]
doc PG 18 relnotes: add attribution and rewrite text search item

Discussion: https://postgr.es/m/aLMo7lJKg8bWUs3y@momjian.us

Backpatch-through: 18

4 weeks agodoc PG 18 relnotes: update to current
Bruce Momjian [Fri, 29 Aug 2025 19:54:47 +0000 (15:54 -0400)]
doc PG 18 relnotes:  update to current

Backpatch-through: 18 only

4 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

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

4 weeks agoFix possible use after free in expand_partitioned_rtentry()
David Rowley [Fri, 29 Aug 2025 12:51:39 +0000 (00:51 +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

4 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

5 weeks agodoc PG 18 relnotes: Add migration note about tsearch
Peter Eisentraut [Fri, 29 Aug 2025 08:18:10 +0000 (10:18 +0200)]
doc PG 18 relnotes: Add migration note about tsearch

Document the small migration hazard introduced in commit fb1a18810f0,
as suggested there.

Reviewed-by: Daniel Verite <daniel@manitou-mail.org>
Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi>
Discussion: https://www.postgresql.org/message-id/flat/653f3b84-fc87-45a7-9a0c-bfb4fcab3e7d%40eisentraut.org

5 weeks agoFix semijoin unique-ification for child relations
Richard Guo [Fri, 29 Aug 2025 04:16:47 +0000 (13:16 +0900)]
Fix semijoin unique-ification for child relations

For a child relation, we should not assume that its parent's
unique-ified relation (or unique-ified path in v18) always exists.  In
cases where all RHS columns that need to be unique-ified are equated
to constants, the unique-ified relation/path for the parent table is
not built, as there are no columns left to unique-ify.  Failing to
account for this can result in a SIGSEGV crash during planning.

This patch checks whether the parent's unique-ified relation or path
exists and skips unique-ification of the child relation if it does
not.

Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAMbWs49MOdLW2c+qbLHHBt8VBu=4ONpM91D19=AWeW93eFUF6A@mail.gmail.com
Backpatch-through: 18

5 weeks agoUse LW_SHARED in walsummarizer.c for WALSummarizerLock lock where possible.
Masahiko Sawada [Fri, 29 Aug 2025 00:06:44 +0000 (17:06 -0700)]
Use LW_SHARED in walsummarizer.c for WALSummarizerLock lock where possible.

Previously, we used LW_EXCLUSIVE in several places despite only reading
WalSummarizerCtl fields. This patch reduces the lock level to LW_SHARED
where we are only reading the shared fields.

Backpatch to 17, where wal summarization was introduced.

Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://postgr.es/m/CAD21AoDdKhf_9oriEYxY-JCdF+Oe_muhca3pcdkMEdBMzyHyKw@mail.gmail.com
Backpatch-through: 17

5 weeks agoFix "variable not found in subplan target lists" in semijoin de-duplication.
Tom Lane [Thu, 28 Aug 2025 17:49:20 +0000 (13:49 -0400)]
Fix "variable not found in subplan target lists" in semijoin de-duplication.

One mechanism we have for implementing semi-joins is to de-duplicate
the output of the RHS and then treat the join as a plain inner join.
Initial construction of the join's SpecialJoinInfo identifies the
RHS columns that need to be de-duplicated, but later we may find that
some of those don't need to be handled explicitly, either because
they're known to be constant or because they are redundant with some
previous column.

Up to now, while sort-based de-duplication handled such cases well,
hash-based de-duplication didn't: we'd still hash on all of the
originally-identified columns.  This is probably not a very big
deal performance-wise, but in the wake of commit a3179ab69 it can
cause planner errors.  That happens when join elimination causes
recalculation of variables' attr_needed bitmapsets, and we decide
that a variable mentioned in a semijoin clause doesn't need to be
propagated up to the join level anymore.

There are a number of ways we could slice the blame for this, but the
only fix that doesn't result in pessimizing plans for loosely-related
cases is to be more careful about not hashing columns we don't
actually need to de-duplicate.  We can install that consideration
into create_unique_paths in master, or the predecessor code in
create_unique_path in v18, without much refactoring.

(As follow-up work, it might be a good idea to look at more-invasive
refactoring, in hopes of preventing other bugs in this area.  But
with v18 release so close, there's not time for that now, nor would
we be likely to want to put such refactoring into v18 anyway.)

Reported-by: Sergey Soloviev <sergey.soloviev@tantorlabs.ru>
Diagnosed-by: Richard Guo <guofenglinux@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/1fd1a421-4609-4d46-a1af-ab74d5de504a@tantorlabs.ru
Backpatch-through: 18

5 weeks agoMessage style improvements
Peter Eisentraut [Wed, 27 Aug 2025 19:17:58 +0000 (21:17 +0200)]
Message style improvements

An improvement pass over the new stats import functionality.

5 weeks agoaio: Stop using enum bitfields due to bad code generation
Andres Freund [Wed, 27 Aug 2025 23:12:11 +0000 (19:12 -0400)]
aio: Stop using enum bitfields due to bad code generation

During an investigation into rather odd aio related errors on macos, observed
by Alexander and Konstantin, we started to wonder if bitfield access is
related to the error. At the moment it looks like it is related, we cannot
reproduce the failures when replacing the bitfields. In addition, the problem
can only be reproduced with some compiler [versions] and not everyone has been
able to reproduce the issue.

The observed problem is that, very rarely, PgAioHandle->{state,target} are in
an inconsistent state, after having been checked to be in a valid state not
long before, triggering an assertion failure. Unfortunately, this could be
caused by wrong compiler code generation or somehow of missing memory barriers
- we don't really know. In theory there should not be any concurrent write
access to the handle in the state the bug is triggered, as the handle was idle
and is just being initialized.

Separately from the bug, we observed that at least gcc and clang generate
rather terrible code for the bitfield access. Even if it's not clear if the
observed assertion failure is actually caused by the bitfield somehow, the bad
code generation alone is sufficient reason to stop using bitfields.

Therefore, replace the enum bitfields with uint8s and instead cast in each
switch statement.

Reported-by: Alexander Lakhin <exclusion@gmail.com>
Reported-by: Konstantin Knizhnik <knizhnik@garret.ru>
Discussion: https://postgr.es/m/1500090.1745443021@sss.pgh.pa.us
Backpatch-through: 18

5 weeks agoPut back intra-grant-inplace.spec test coverage
Peter Eisentraut [Wed, 27 Aug 2025 14:47:23 +0000 (16:47 +0200)]
Put back intra-grant-inplace.spec test coverage

Commit d31bbfb6590 lost some test coverage, because the situation
being tested, a concurrent DROP, cannot happen anymore.  Put the test
coverage back with a bit of a trick, by deleting directly from the
catalog table.

Co-authored-by: Noah Misch <noah@leadboat.com>
Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi>
Discussion: https://www.postgresql.org/message-id/flat/bf72b82c-124d-4efa-a484-bb928e9494e4@eisentraut.org

5 weeks agoImprove objectNamesToOids() comment
Peter Eisentraut [Wed, 27 Aug 2025 14:46:51 +0000 (16:46 +0200)]
Improve objectNamesToOids() comment

Commit d31bbfb6590 removed the comment at objectNamesToOids() that
there is no locking, because that commit added locking.  But to fix
all the problems, we'd still need a stronger lock.  So put the comment
back with more a detailed explanation.

Co-authored-by: Noah Misch <noah@leadboat.com>
Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi>
Discussion: https://www.postgresql.org/message-id/flat/bf72b82c-124d-4efa-a484-bb928e9494e4@eisentraut.org

5 weeks agoFix: Don't strip $libdir from nested module_pathnames
Peter Eisentraut [Wed, 27 Aug 2025 13:46:39 +0000 (15:46 +0200)]
Fix: Don't strip $libdir from nested module_pathnames

This patch fixes a bug in how 'load_external_function' handles
'$libdir/ prefixes in module paths.

Previously, 'load_external_function' would unconditionally strip
'$libdir/' from the beginning of the 'filename' string.  This caused
an issue when the path was nested, such as "$libdir/nested/my_lib".
Stripping the prefix resulted in a path of "nested/my_lib", which
would fail to be found by the expand_dynamic_library_name function
because the original '$libdir' macro was removed.

To fix this, the code now checks for the presence of an additional
directory separator ('/' or '\') after the '$libdir/' prefix.  The
prefix is only stripped if the remaining string does not contain a
separator.  This ensures that simple filenames like '"$libdir/my_lib"'
are correctly handled, while nested paths are left intact for
'expand_dynamic_library_name' to process correctly.

Reported-by: Dilip Kumar <dilipbalaut@gmail.com>
Co-authored-by: Matheus Alcantara <matheusssilv97@gmail.com>
Co-authored-by: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/CAFiTN-uKNzAro4tVwtJhF1UqcygfJ%2BR%2BRL%3Db-_ZMYE3LdHoGhA%40mail.gmail.com

5 weeks agoCheck for more Unicode functions during upgrade.
Jeff Davis [Wed, 27 Aug 2025 05:55:14 +0000 (22:55 -0700)]
Check for more Unicode functions during upgrade.

When checking for expression indexes that may be affected by a Unicode
update during upgrade, check for a few more functions. Specifically,
check for documented regexp functions, as well as the new CASEFOLD()
function.

Also, fully-qualify references to pg_catalog.text and
pg_catalog.regtype.

Discussion: https://postgr.es/m/399b656a3abb0c9283538a040f72199c0601525c.camel@j-davis.com
Backpatch-through: 18

5 weeks agooauth: Explicitly depend on -pthread
Jacob Champion [Tue, 26 Aug 2025 21:28:05 +0000 (14:28 -0700)]
oauth: Explicitly depend on -pthread

Followup to 4e1e41733 and 52ecd05ae. oauth-utils.c uses
pthread_sigmask(), requiring -pthread on Debian bullseye at minimum.

Reported-by: Christoph Berg <myon@debian.org>
Tested-by: Christoph Berg <myon@debian.org>
Discussion: https://postgr.es/m/aK4PZgC0wuwQ5xSK%40msg.df7cb.de
Backpatch-through: 18

5 weeks agoMessage style improvements
Peter Eisentraut [Tue, 26 Aug 2025 20:48:00 +0000 (22:48 +0200)]
Message style improvements

Mostly adding some quoting.

5 weeks agoDocument privileges required for vacuumdb --missing-stats-only.
Nathan Bossart [Tue, 26 Aug 2025 19:49:01 +0000 (14:49 -0500)]
Document privileges required for vacuumdb --missing-stats-only.

When vacuumdb's --missing-stats-only option is used, the catalog
query for retrieving the list of relations to process must read
pg_statistic and pg_statistic_ext_data.  However, those catalogs
can only be read by superusers by default, so --missing-stats-only
is effectively superuser-only.  This is unfortunate, but since the
option is primarily intended for use by administrators after
running pg_upgrade, let's just live with it for v18.  This commit
adds a note about the aforementioned privilege requirements to the
documentation for --missing-stats-only.

We first tried to improve matters by modifying the query to read
the pg_stats and pg_stats_ext system views instead.  While that is
indeed more lenient from a privilege standpoint, it is also
borderline incomprehensible.  pg_stats shows rows for which the
user has the SELECT privilege on the corresponding column, and
pg_stats_ext shows rows for tables the user owns.  Meanwhile,
ANALYZE requires either MAINTAIN on the table or, for non-shared
relations, ownership of the database.  But even if the privilege
discrepancies were tolerable, the performance impact was not.
Ultimately, the modified query was substantially more expensive, so
we abandoned the idea.

For v19, perhaps we could introduce a simple, inexpensive way to
discover which relations are missing statistics, such as a system
function or view with similar privilege requirements to ANALYZE.
Unfortunately, it is far too late for anything like that in v18.

Reviewed-by: Yugo Nagata <nagata@sraoss.co.jp>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CAHGQGwHh43suEfss1wvBsk7vqiou%3DUY0zcy8HGyE5hBp%2BHZ7SQ%40mail.gmail.com
Backpatch-through: 18

5 weeks agoPut "excludeOnly" GIN scan keys at the end of the scankey array.
Tom Lane [Tue, 26 Aug 2025 16:08:57 +0000 (12:08 -0400)]
Put "excludeOnly" GIN scan keys at the end of the scankey array.

Commit 4b754d6c1 introduced the concept of an excludeOnly scan key,
which cannot select matching index entries but can reject
non-matching tuples, for example a tsquery such as '!term'.  There are
poorly-documented assumptions that such scan keys do not appear as the
first scan key.  ginNewScanKey did nothing to ensure that, however,
with the result that certain GIN index searches could go into an
infinite loop while apparently-equivalent queries with the clauses in
a different order were fine.

Fix by teaching ginNewScanKey to place all excludeOnly scan keys
after all not-excludeOnly ones.  So far as we know at present,
it might be sufficient to avoid the case where the very first
scan key is excludeOnly; but I'm not very convinced that there
aren't other dependencies on the ordering.

Bug: #19031
Reported-by: Tim Wood <washwithcare@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19031-0638148643d25548@postgresql.org
Backpatch-through: 13

5 weeks agoDo CHECK_FOR_INTERRUPTS inside, not before, scanGetItem.
Tom Lane [Tue, 26 Aug 2025 15:38:41 +0000 (11:38 -0400)]
Do CHECK_FOR_INTERRUPTS inside, not before, scanGetItem.

The CHECK_FOR_INTERRUPTS call in gingetbitmap turns out to be
inadequate to prevent a long uninterruptible loop, because
we now know a case where looping occurs within scanGetItem.
While the next patch will fix the bug that caused that, it
seems foolish to assume that no similar patterns are possible.
Let's do the CFI within scanGetItem's retry loop, instead.
This demonstrably allows canceling out of the loop exhibited
in bug #19031.

Bug: #19031
Reported-by: Tim Wood <washwithcare@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19031-0638148643d25548@postgresql.org
Backpatch-through: 13

5 weeks agoImprove RowMark handling during Self-Join Elimination
Alexander Korotkov [Sun, 24 Aug 2025 00:34:22 +0000 (03:34 +0300)]
Improve RowMark handling during Self-Join Elimination

The Self-Join Elimination SJE feature messes up keeping and removing RowMark's
in remove_self_joins_one_group().  That didn't lead to user-level error,
because the planned RowMark is only used to reference a rtable entry in later
execution stages.  An RTE entry for keeping and removing relations is
identical and refers to the same relation OID.

To reduce confusion and prevent future issues, this commit cleans up the code
and fixes the incorrect behaviour.  Furthermore, it includes sanity checks in
setrefs.c on existing non-null RTE and RelOptInfo entries for each RowMark.

Discussion: https://postgr.es/m/18c6bd6c-6d2a-419a-b0da-dfedef34b585%40gmail.com
Author: Andrei Lepikhov <lepihov@gmail.com>
Reviewed-by: Greg Sabino Mullane <htamfids@gmail.com>
Backpatch-through: 18

5 weeks agoRefactor variable names in remove_self_joins_one_group()
Alexander Korotkov [Tue, 26 Aug 2025 09:51:32 +0000 (12:51 +0300)]
Refactor variable names in remove_self_joins_one_group()

Rename inner and outer to rrel and krel, respectively, to highlight their
connection to r and k indexes.  For the same reason, rename imark and omark
to rmark and kmark.

Discussion: https://postgr.es/m/18c6bd6c-6d2a-419a-b0da-dfedef34b585%40gmail.com
Author: Andrei Lepikhov <lepihov@gmail.com>
Reviewed-by: Greg Sabino Mullane <htamfids@gmail.com>
Backpatch-through: 18

5 weeks agoMessage wording improvements
Peter Eisentraut [Mon, 25 Aug 2025 20:59:00 +0000 (22:59 +0200)]
Message wording improvements

Use "row" instead of "tuple" for user-facing information for
logical replication conflicts.

5 weeks agooauth: Always link with -lm for floor()
Jacob Champion [Mon, 25 Aug 2025 16:31:24 +0000 (09:31 -0700)]
oauth: Always link with -lm for floor()

libpq-oauth uses floor() but did not link against libm. Since libpq
itself uses -lm, nothing in the buildfarm has had problems with
libpq-oauth yet, and it seems difficult to hit a failure in practice.

But commit 1443b6c0e attempted to add an executable based on
libpq-oauth, which ran into link-time failures with Clang due to this
omission. It seems prudent to fix this for both the module and the
executable simultaneously so that no one trips over it in the future.

This is a Makefile-only change. The Meson side already pulls in libm,
through the os_deps dependency.

Discussion: https://postgr.es/m/CAOYmi%2Bn6ORcmV10k%2BdAs%2Bp0b9QJ4bfpk0WuHQaF5ODXxM8Y36A%40mail.gmail.com
Backpatch-through: 18

5 weeks agoRewrite previous commit's test for TestUpgradeXversion compatibility.
Noah Misch [Sat, 23 Aug 2025 23:46:20 +0000 (16:46 -0700)]
Rewrite previous commit's test for TestUpgradeXversion compatibility.

v17 introduced the MAINTAIN ON TABLES privilege.  That changed the
applicable "baseacls" reaching buildACLCommands().  That yielded
spurious TestUpgradeXversion diffs.  Change to use a TYPES privilege.
Types have the same one privilege in all supported versions, so they
avoid the problem.  Per buildfarm.  Back-patch to v13, like that commit.

Discussion: https://postgr.es/m/20250823144505.88.nmisch@google.com
Backpatch-through: 13

5 weeks agoSort DO_DEFAULT_ACL dump objects independent of OIDs.
Noah Misch [Sat, 23 Aug 2025 03:50:28 +0000 (20:50 -0700)]
Sort DO_DEFAULT_ACL dump objects independent of OIDs.

Commit 0decd5e89db9f5edb9b27351082f0d74aae7a9b6 missed DO_DEFAULT_ACL,
leading to assertion failures, potential dump order instability, and
spurious schema diffs.  Back-patch to v13, like that commit.

Reported-by: Alexander Lakhin <exclusion@gmail.com>
Author: Kirill Reshke <reshkekirill@gmail.com>
Discussion: https://postgr.es/m/d32aaa8d-df7c-4f94-bcb3-4c85f02bea21@gmail.com
Backpatch-through: 13

5 weeks agoRevert "Get rid of WALBufMappingLock"
Alexander Korotkov [Fri, 22 Aug 2025 15:44:39 +0000 (18:44 +0300)]
Revert "Get rid of WALBufMappingLock"

This reverts commit bc22dc0e0ddc2dcb6043a732415019cc6b6bf683.
It appears that conditional variables are not suitable for use inside
critical sections.  If WaitLatch()/WaitEventSetWaitBlock() face postmaster
death, they exit, releasing all locks instead of PANIC.  In certain
situations, this leads to data corruption.

Reported-by: Andrey Borodin <x4mmm@yandex-team.ru>
Discussion: https://postgr.es/m/B3C69B86-7F82-4111-B97F-0005497BB745%40yandex-team.ru
Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Reviewed-by: Aleksander Alekseev <aleksander@tigerdata.com>
Reviewed-by: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Reviewed-by: Tomas Vondra <tomas@vondra.me>
Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Yura Sokolov <y.sokolov@postgrespro.ru>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Backpatch-through: 18

5 weeks agovacuumdb: Fix --missing-stats-only with virtual generated columns.
Nathan Bossart [Fri, 22 Aug 2025 16:11:28 +0000 (11:11 -0500)]
vacuumdb: Fix --missing-stats-only with virtual generated columns.

Statistics aren't created for virtual generated columns, so
"vacuumdb --missing-stats-only" always chooses to analyze tables
that have them.  To fix, modify vacuumdb's query for retrieving
relations that are missing statistics to exclude those columns.

Oversight in commit edba754f05.

Author: Yugo Nagata <nagata@sraoss.co.jp>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Discussion: https://postgr.es/m/20250820104226.8ba51e43164cd590b863ce41%40sraoss.co.jp
Backpatch-through: 18

5 weeks agoRevert unnecessary check for NULL
Heikki Linnakangas [Fri, 22 Aug 2025 11:47:19 +0000 (14:47 +0300)]
Revert unnecessary check for NULL

Jelte pointed out that this was unnecessary, but I failed to remove it
before pushing f6f0542266. Oops.

Reviewed-by: Jelte Fennema-Nio <postgres@jeltef.nl>
Discussion: https://www.postgresql.org/message-id/CAGECzQT%3DxNV-V%2BvFC7YQwYQMj0wGN61b3p%3DJ1_rL6M0vbjTtrA@mail.gmail.com
Backpatch-through: 18

5 weeks agolibpq: Be strict about cancel key lengths
Heikki Linnakangas [Fri, 22 Aug 2025 11:39:29 +0000 (14:39 +0300)]
libpq: Be strict about cancel key lengths

The protocol documentation states that the maximum length of a cancel
key is 256 bytes. This starts checking for that limit in libpq.
Otherwise third party backend implementations will probably start
using more bytes anyway. We also start requiring that a protocol 3.0
connection does not send a longer cancel key, to make sure that
servers don't start breaking old 3.0-only clients by accident. Finally
this also restricts the minimum key length to 4 bytes (both in the
protocol spec and in the libpq implementation).

Author: Jelte Fennema-Nio <postgres@jeltef.nl>
Reviewed-by: Jacob Champion <jchampion@postgresql.org>
Discussion: https://www.postgresql.org/message-id/df892f9f-5923-4046-9d6f-8c48d8980b50@iki.fi
Backpatch-through: 18

5 weeks agolibpq: Handle OOM by disconnecting instead of hanging or skipping msgs
Heikki Linnakangas [Fri, 22 Aug 2025 11:39:25 +0000 (14:39 +0300)]
libpq: Handle OOM by disconnecting instead of hanging or skipping msgs

In most cases, if an out-of-memory situation happens, we attach the
error message to the connection and report it at the next
PQgetResult() call. However, there are a few cases, while processing
messages that are not associated with any particular query, where we
handled failed allocations differently and not very nicely:

- If we ran out of memory while processing an async notification,
  getNotify() either returned EOF, which stopped processing any
  further data until more data was received from the server, or
  silently dropped the notification. Returning EOF is problematic
  because if more data never arrives, e.g. because the connection was
  used just to wait for the notification, or because the next
  ReadyForQuery was already received and buffered, it would get stuck
  forever. Silently dropping a notification is not nice either.

- (New in v18) If we ran out of memory while receiving BackendKeyData
  message, getBackendKeyData() returned EOF, which has the same issues
  as in getNotify().

- If we ran out of memory while saving a received a ParameterStatus
  message, we just skipped it. A later call to PQparameterStatus()
  would return NULL, even though the server did send the status.

Change all those cases to terminate the connnection instead. Our
options for reporting those errors are limited, but it seems better to
terminate than try to soldier on. Applications should handle
connection loss gracefully, whereas silently missing a notification,
parameter status, or cancellation key could cause much weirder
problems.

This also changes the error message on OOM while expanding the input
buffer. It used to report "cannot allocate memory for input buffer",
followed by "lost synchronization with server: got message type ...".
The "lost synchronization" message seems unnecessary, so remove that
and report only "cannot allocate memory for input buffer". (The
comment speculated that the out of memory could indeed be caused by
loss of sync, but that seems highly unlikely.)

This evolved from a more narrow patch by Jelte Fennema-Nio, which was
reviewed by Jacob Champion.

Somewhat arbitrarily, backpatch to v18 but no further. These are
long-standing issues, but we haven't received any complaints from the
field. We can backpatch more later, if needed.

Co-authored-by: Jelte Fennema-Nio <postgres@jeltef.nl>
Reviewed-by: Jelte Fennema-Nio <postgres@jeltef.nl>
Reviewed-by: Jacob Champion <jchampion@postgresql.org>
Discussion: https://www.postgresql.org/message-id/df892f9f-5923-4046-9d6f-8c48d8980b50@iki.fi
Backpatch-through: 18

5 weeks agoRevert GetTransactionSnapshot() to return historic snapshot during LR
Heikki Linnakangas [Fri, 22 Aug 2025 10:07:46 +0000 (13:07 +0300)]
Revert GetTransactionSnapshot() to return historic snapshot during LR

Commit 1585ff7387 changed GetTransactionSnapshot() to throw an error
if it's called during logical decoding, instead of returning the
historic snapshot. I made that change for extra protection, because a
historic snapshot can only be used to access catalog tables while
GetTransactionSnapshot() is usually called when you're executing
arbitrary queries. You might get very subtle visibility problems if
you tried to use the historic snapshot for arbitrary queries.

There's no built-in code in PostgreSQL that calls
GetTransactionSnapshot() during logical decoding, but it turns out
that the pglogical extension does just that, to evaluate row filter
expressions. You would get weird results if the row filter runs
arbitrary queries, but it is sane as long as you don't access any
non-catalog tables. Even though there are no checks to enforce that in
pglogical, a typical row filter expression does not access any tables
and works fine. Accessing tables marked with the user_catalog_table =
true option is also OK.

To fix pglogical with row filters, and any other extensions that might
do similar things, revert GetTransactionSnapshot() to return a
historic snapshot during logical decoding.

To try to still catch the unsafe usage of historic snapshots, add
checks in heap_beginscan() and index_beginscan() to complain if you
try to use a historic snapshot to scan a non-catalog table. We're very
close to the version 18 release however, so add those new checks only
in master.

Backpatch-through: 18
Reported-by: Noah Misch <noah@leadboat.com>
Reviewed-by: Noah Misch <noah@leadboat.com>
Discussion: https://www.postgresql.org/message-id/20250809222338.cc.nmisch@google.com

6 weeks agoDoc: Fix typo in logicaldecoding.sgml.
Amit Kapila [Fri, 22 Aug 2025 05:19:50 +0000 (05:19 +0000)]
Doc: Fix typo in logicaldecoding.sgml.

Author: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Backpatch-through: 17, where it was introduced
Discussion: https://postgr.es/m/OSCPR01MB149662EC5467B4135398E3731F532A@OSCPR01MB14966.jpnprd01.prod.outlook.com

6 weeks agoIgnore temporary relations in RelidByRelfilenumber()
Michael Paquier [Fri, 22 Aug 2025 00:06:34 +0000 (09:06 +0900)]
Ignore temporary relations in RelidByRelfilenumber()

Temporary relations may share the same RelFileNumber with a permanent
relation, or other temporary relations associated with other sessions.

Being able to uniquely identify a temporary relation would require
RelidByRelfilenumber() to know about the proc number of the temporary
relation it wants to identify, something it is not designed for since
its introduction in f01d1ae3a104.

There are currently three callers of RelidByRelfilenumber():
- autoprewarm.
- Logical decoding, reorder buffer.
- pg_filenode_relation(), that attempts to find a relation OID based on
a tablespace OID and a RelFileNumber.

This makes the situation problematic particularly for the first two
cases, leading to the possibility of random ERRORs due to
inconsistencies that temporary relations can create in the cache
maintained by RelidByRelfilenumber().  The third case should be less of
an issue, as I suspect that there are few direct callers of
pg_filenode_relation().

The window where the ERRORs are happen is very narrow, requiring an OID
wraparound to create a lookup conflict in RelidByRelfilenumber() with a
temporary table reusing the same OID as another relation already cached.
The problem is easier to reach in workloads with a high OID consumption
rate, especially with a higher number of temporary relations created.

We could get pg_filenode_relation() and RelidByRelfilenumber() to work
with temporary relations if provided the means to identify them with an
optional proc number given in input, but the years have also shown that
we do not have a use case for it, yet.  Note that this could not be
backpatched if pg_filenode_relation() needs changes.  It is simpler to
ignore temporary relations.

Reported-by: Shenhao Wang <wangsh.fnst@fujitsu.com>
Author: Vignesh C <vignesh21@gmail.com>
Reviewed-By: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-By: Robert Haas <robertmhaas@gmail.com>
Reviewed-By: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-By: Takamichi Osumi <osumi.takamichi@fujitsu.com>
Reviewed-By: Michael Paquier <michael@paquier.xyz>
Reviewed-By: Masahiko Sawada <sawada.mshk@gmail.com>
Reported-By: Shenhao Wang <wangsh.fnst@fujitsu.com>
Discussion: https://postgr.es/m/bbaaf9f9-ebb2-645f-54bb-34d6efc7ac42@fujitsu.com
Backpatch-through: 13

6 weeks agoUse consistent type for pgaio_io_get_id() result
Peter Eisentraut [Thu, 21 Aug 2025 17:40:12 +0000 (19:40 +0200)]
Use consistent type for pgaio_io_get_id() result

The result of pgaio_io_get_id() was being assigned to a mix of int and
uint32 variables.  This fixes it to use int consistently, which seems
the most correct.  Also change the queue empty special value in
method_worker.c to -1 from UINT32_MAX.

Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://www.postgresql.org/message-id/70c784b3-f60b-4652-b8a6-75e5f051243e%40eisentraut.org

6 weeks agodoc: Improve description of wal_compression
Michael Paquier [Thu, 21 Aug 2025 04:25:50 +0000 (13:25 +0900)]
doc: Improve description of wal_compression

The description of this GUC provides a list of the situations where
full-page writes are generated.  However, it is not completely exact,
mentioning only the cases where full_page_writes=on or base backups.  It
is possible to generate full-page writes in more situations than these
two, making the description confusing as it implies that no other cases
exist.

The description is slightly reworded to take into account that other
cases are possible, without mentioning them directly to minimize the
maintenance burden should FPWs be generated in more contexts in the
future.

Author: Jingtang Zhang <mrdrivingduck@gmail.com>
Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Reviewed-by: Xuneng Zhou <xunengzhou@gmail.com>
Discussion: https://postgr.es/m/CAPsk3_CtAYa_fy4p6=x7qtoutrdKvg1kGk46D5fsE=sMt2546g@mail.gmail.com
Backpatch-through: 13

6 weeks agoFix re-execution of a failed SQLFunctionCache entry.
Tom Lane [Wed, 20 Aug 2025 20:09:18 +0000 (16:09 -0400)]
Fix re-execution of a failed SQLFunctionCache entry.

If we error out during execution of a SQL-language function, we will
often leave behind non-null pointers in its SQLFunctionCache's cplan
and eslist fields.  This is problematic if the SQLFunctionCache is
re-used, because those pointers will point at resources that were
released during error cleanup.  This problem escaped detection so far
because ordinarily we won't re-use an FmgrInfo+SQLFunctionCache struct
after a query error.  However, in the rather improbable case that
someone implements an opclass support function in SQL language, there
will be long-lived FmgrInfos for it in the relcache, and then the
problem is reachable after the function throws an error.

To fix, add a flag to SQLFunctionCache that tracks whether execution
escapes out of fmgr_sql, and clear out the relevant fields during
init_sql_fcache if so.  (This is going to need more thought if we ever
try to share FMgrInfos across threads; but it's very far from being
the only problem such a project will encounter, since many functions
regard fn_extra as being query-local state.)

This broke at commit 0313c5dc6; before that we did not try to re-use
SQLFunctionCache state across calls.  Hence, back-patch to v18.

Bug: #19026
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19026-90aed5e71d0c8af3@postgresql.org
Backpatch-through: 18

6 weeks agoFix assertion failure with replication slot release in single-user mode
Michael Paquier [Wed, 20 Aug 2025 06:00:08 +0000 (15:00 +0900)]
Fix assertion failure with replication slot release in single-user mode

Some replication slot manipulations (logical decoding via SQL,
advancing) were failing an assertion when releasing a slot in
single-user mode, because active_pid was not set in a ReplicationSlot
when its slot is acquired.

ReplicationSlotAcquire() has some logic to be able to work with the
single-user mode.  This commit sets ReplicationSlot->active_pid to
MyProcPid, to let the slot-related logic fall-through, considering the
single process as the one holding the slot.

Some TAP tests are added for various replication slot functions with the
single-user mode, while on it, for slot creation, drop, advancing, copy
and logical decoding with multiple slot types (temporary, physical vs
logical).  These tests are skipped on Windows, as direct calls of
postgres --single would fail on permission failures.  There is no
platform-specific behavior that needs to be checked, so living with this
restriction should be fine.  The CI is OK with that, now let's see what
the buildfarm tells.

Author: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Reviewed-by: Paul A. Jungwirth <pj@illuminatedcomputing.com>
Reviewed-by: Mutaamba Maasha <maasha@gmail.com>
Discussion: https://postgr.es/m/OSCPR01MB14966ED588A0328DAEBE8CB25F5FA2@OSCPR01MB14966.jpnprd01.prod.outlook.com
Backpatch-through: 13

6 weeks agoAdd CHECK_FOR_INTERRUPTS in contrib/pg_buffercache functions.
Masahiko Sawada [Tue, 19 Aug 2025 19:11:39 +0000 (12:11 -0700)]
Add CHECK_FOR_INTERRUPTS in contrib/pg_buffercache functions.

This commit adds CHECK_FOR_INTERRUPTS to loops iterating over shared
buffers in several pg_buffercache functions, allowing them to be
interrupted during long-running operations.

Backpatch to all supported versions. Add CHECK_FOR_INTERRUPTS to the
loop in pg_buffercache_pages() in all supported branches, and to
pg_buffercache_summary() and pg_buffercache_usage_counts() in version
16 and newer.

Author: SATYANARAYANA NARLAPURAM <satyanarlapuram@gmail.com>
Discussion: https://postgr.es/m/CAHg+QDcejeLx7WunFT3DX6XKh1KshvGKa8F5au8xVhqVvvQPRw@mail.gmail.com
Backpatch-through: 13

6 weeks agoFix self-deadlock during DROP SUBSCRIPTION.
Amit Kapila [Tue, 19 Aug 2025 05:18:24 +0000 (05:18 +0000)]
Fix self-deadlock during DROP SUBSCRIPTION.

The DROP SUBSCRIPTION command performs several operations: it stops the
subscription workers, removes subscription-related entries from system
catalogs, and deletes the replication slot on the publisher server.
Previously, this command acquired an AccessExclusiveLock on
pg_subscription before initiating these steps.

However, while holding this lock, the command attempts to connect to the
publisher to remove the replication slot. In cases where the connection is
made to a newly created database on the same server as subscriber, the
cache-building process during connection tries to acquire an
AccessShareLock on pg_subscription, resulting in a self-deadlock.

To resolve this issue, we reduce the lock level on pg_subscription during
DROP SUBSCRIPTION from AccessExclusiveLock to RowExclusiveLock. Earlier,
the higher lock level was used to prevent the launcher from starting a new
worker during the drop operation, as a restarted worker could become
orphaned.

Now, instead of relying on a strict lock, we acquire an AccessShareLock on
the specific subscription being dropped and re-validate its existence
after acquiring the lock. If the subscription is no longer valid, the
worker exits gracefully. This approach avoids the deadlock while still
ensuring that orphan workers are not created.

Reported-by: Alexander Lakhin <exclusion@gmail.com>
Author: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: vignesh C <vignesh21@gmail.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Backpatch-through: 13
Discussion: https://postgr.es/m/18988-7312c868be2d467f@postgresql.org

6 weeks agoFix missing "use Test::More" in Kerberos.pm.
Tom Lane [Mon, 18 Aug 2025 18:54:59 +0000 (14:54 -0400)]
Fix missing "use Test::More" in Kerberos.pm.

Apparently the only Test::More function this script uses is
BAIL_OUT, so this omission just results in the wrong error
output appearing in the cases where it bails out.

Seems to have been an oversight in commit 9f899562d which
split Kerberos.pm out of another script.

Author: Maxim Orlov <orlovmg@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CACG=ezY1Dp-S94b78nN0ZuaBGGcMUB6_nF-VyYUwPt1ArFqmGA@mail.gmail.com
Backpatch-through: 17

6 weeks agoUpdate obsolete comments in ResultRelInfo struct.
Etsuro Fujita [Sun, 17 Aug 2025 10:40:01 +0000 (19:40 +0900)]
Update obsolete comments in ResultRelInfo struct.

Commit c5b7ba4e6 changed things so that the ri_RootResultRelInfo field
of this struct is set for both partitions and inheritance children and
used for tuple routing and transition capture (before that commit, it
was only set for partitions to route tuples into), but failed to update
these comments.

Author: Etsuro Fujita <etsuro.fujita@gmail.com>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Discussion: https://postgr.es/m/CAPmGK14NF5CcdCmTZpxrvpvBiT0y4EqKikW1r_wAu1CEHeOmUA%40mail.gmail.com
Backpatch-through: 14

6 weeks agoFix constant when extracting timestamp from UUIDv7.
Masahiko Sawada [Fri, 15 Aug 2025 18:58:56 +0000 (11:58 -0700)]
Fix constant when extracting timestamp from UUIDv7.

When extracting a timestamp from a UUIDv7, a conversion from
milliseconds to microseconds was using the incorrect constant
NS_PER_US instead of US_PER_MS. Although both constants have the same
value, this fix improves code clarity by using the semantically
correct constant.

Backpatch to v18, where UUIDv7 was introduced.

Author: Erik Nordstrรถm <erik@tigerdata.com>
Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Discussion: https://postgr.es/m/CACAa4V+i07eaP6h4MHNydZeX47kkLPwAg0sqe67R=M5tLdxNuQ@mail.gmail.com
Backpatch-through: 18

7 weeks agoFix git whitespace warning
Peter Eisentraut [Fri, 15 Aug 2025 08:29:16 +0000 (10:29 +0200)]
Fix git whitespace warning

Recent changes to src/tools/ci/README triggered warnings like

    src/tools/ci/README:88: leftover conflict marker

Raise conflict-marker-size in .gitattributes to avoid these.

7 weeks agoFix invalid format string in HASH_DEBUG code
David Rowley [Fri, 15 Aug 2025 06:06:13 +0000 (18:06 +1200)]
Fix invalid format string in HASH_DEBUG code

This seems to have been broken back in be0a66666.

Reported-by: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
Author: David Rowley <dgrowleyml@gmail.com>
Discussion: https://postgr.es/m/OSCPR01MB14966E11EEFB37D7857FCEDB7F535A@OSCPR01MB14966.jpnprd01.prod.outlook.com
Backpatch-through: 14

7 weeks agoFix failing -D HASH_STATISTICS builds
David Rowley [Fri, 15 Aug 2025 05:24:21 +0000 (17:24 +1200)]
Fix failing -D HASH_STATISTICS builds

This seems to have been broken for a few years by cc5ef90ed.

Author: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
Reviewed-by: David Rowley <dgrowleyml@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/OSCPR01MB14966E11EEFB37D7857FCEDB7F535A@OSCPR01MB14966.jpnprd01.prod.outlook.com
Backpatch-through: 17

7 weeks agoci: Simplify ci-os-only handling
Andres Freund [Thu, 14 Aug 2025 15:48:04 +0000 (11:48 -0400)]
ci: Simplify ci-os-only handling

Handle 'ci-os-only' occurrences in the .cirrus.star file instead of
.cirrus.tasks.yml file. Now, 'ci-os-only' occurrences are controlled
from one central place instead of dealing with them in each task.

Author: Andres Freund <andres@anarazel.de>
Reviewed-by: Nazir Bilal Yavuz <byavuz81@gmail.com>
Discussion: https://postgr.es/m/20240413021221.hg53rvqlvldqh57i%40awork3.anarazel.de
Backpatch: 15-, where CI support was added

7 weeks agoci: Per-repo configuration for manually trigger tasks
Andres Freund [Thu, 14 Aug 2025 15:33:44 +0000 (11:33 -0400)]
ci: Per-repo configuration for manually trigger tasks

We do not want to trigger some tasks by default, to avoid using too many
compute credits. These tasks have to be manually triggered to be run. But
e.g. for cfbot we do have sufficient resources, so we always want to start
those tasks.

With this commit, an individual repository can be configured to trigger
them automatically using an environment variable defined under
"Repository Settings", for example:

REPO_CI_AUTOMATIC_TRIGGER_TASKS="mingw netbsd openbsd"

This will enable cfbot to turn them on by default when running tests for the
Commitfest app.

Backpatch this back to PG 15, even though PG 15 does not have any manually
triggered task. Keeping the CI infrastructure the same seems advantageous.

Author: Andres Freund <andres@anarazel.de>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Co-authored-by: Nazir Bilal Yavuz <byavuz81@gmail.com>
Reviewed-by: Nazir Bilal Yavuz <byavuz81@gmail.com>
Discussion: https://postgr.es/m/20240413021221.hg53rvqlvldqh57i%40awork3.anarazel.de
Backpatch-through: 16

7 weeks agoFix compilation warning with SerializeClientConnectionInfo()
Michael Paquier [Thu, 14 Aug 2025 07:21:58 +0000 (16:21 +0900)]
Fix compilation warning with SerializeClientConnectionInfo()

This function uses an argument named "maxsize" that is only used in
assertions, being set once outside the assertion area.  Recent gcc
versions with -Wunused-but-set-parameter complain about a warning when
building without assertions enabled, because of that.

In order to fix this issue, PG_USED_FOR_ASSERTS_ONLY is added to the
function argument of SerializeClientConnectionInfo(), which is the first
time we are doing so in the tree.  The CI is fine with the change, but
let's see what the buildfarm has to say on the matter.

Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Jacob Champion <jchampion@postgresql.org>
Discussion: https://postgr.es/m/pevajesswhxafjkivoq3yvwxga77tbncghlf3gq5fvchsvfuda@6uivg25sb3nx
Backpatch-through: 16

7 weeks agoci: windows: Stop using DEBUG:FASTLINK
Andres Freund [Wed, 13 Aug 2025 19:52:48 +0000 (15:52 -0400)]
ci: windows: Stop using DEBUG:FASTLINK

Currently the pdb file for libpq and some other libraries are named the same
for the static and shared libraries. That has been the case for a long time,
but recently started failing, after an image update started using a newer
ninja version. The issue is not itself caused by ninja, but just made visible,
as the newer version optimizes the build order and builds the shared libpq
earlier than the static library. Previously both static and shared libraries
were built at the same time, which prevented msvc from detecting the issue.

When using /DEBUG:FASTLINK pdb files cannot be updated, triggering the error.

We were using /DEBUG:FASTLINK due to running out of memory in the past, but
that was when using container based CI images, rather than full VMs.

This isn't really the correct fix (that'd be to deconflict the pdb file
names), but we'd like to get CI to become green again, and a proper fix (in
meson) will presumably take longer.

Suggested-by: Andres Freund <andres@anarazel.de>
Author: Nazir Bilal Yavuz <byavuz81@gmail.com>
Reviewed-by: Jacob Champion <jacob.champion@enterprisedb.com>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAN55FZ1RuBhJmPWs3Oi%3D9UoezDfrtO-VaU67db5%2B0_uy19uF%2BA%40mail.gmail.com
Backpatch-through: 16

7 weeks agoDon't treat EINVAL from semget() as a hard failure.
Tom Lane [Wed, 13 Aug 2025 15:59:47 +0000 (11:59 -0400)]
Don't treat EINVAL from semget() as a hard failure.

It turns out that on some platforms (at least current macOS, NetBSD,
OpenBSD) semget(2) will return EINVAL if there is a pre-existing
semaphore set with the same key and too few semaphores.  Our code
expects EEXIST in that case and treats EINVAL as a hard failure,
resulting in failure during initdb or postmaster start.

POSIX does document EINVAL for too-few-semaphores-in-set, and is
silent on its priority relative to EEXIST, so this behavior arguably
conforms to spec.  Nonetheless it's quite problematic because EINVAL
is also documented to mean that nsems is greater than the system's
limit on the number of semaphores per set (SEMMSL).  If that is
where the problem lies, retrying would just become an infinite loop.

To resolve this contradiction, retry after EINVAL, but also install a
loop limit that will make us give up regardless of the specific errno
after trying 1000 different keys.  (1000 is a pretty arbitrary number,
but it seems like it should be sufficient.)  I like this better than
the previous infinite-looping behavior, since it will also keep us out
of trouble if (say) we get EACCES due to a system-level permissions
problem rather than anything to do with a specific semaphore set.

This problem has only been observed in the field in PG 17, which uses
a higher nsems value than other branches (cf. 38da05346810a8b1c8).
That makes it possible to get the failure if a new v17 postmaster
has a key collision with an existing postmaster of another branch.
In principle though, we might see such a collision against a semaphore
set created by some other application, in which case all branches are
vulnerable on these platforms.  Hence, backpatch.

Reported-by: Gavin Panella <gavinpanella@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CALL7chmzY3eXHA7zHnODUVGZLSvK3wYCSP0RmcDFHJY8f28Q3g@mail.gmail.com
Backpatch-through: 13

7 weeks agopostgres_fdw: Fix tests with ANALYZE and remote sampling
Michael Paquier [Wed, 13 Aug 2025 04:11:48 +0000 (13:11 +0900)]
postgres_fdw: Fix tests with ANALYZE and remote sampling

The tests fixed in this commit were changing the sampling setting of a
foreign server, but then were analyzing a local table instead of a
foreign table, meaning that the test was not running for its original
purpose.

This commit changes the ANALYZE commands to analyze the foreign table,
and changes the foreign table definition to point to a valid remote
table.  Attempting to analyze the foreign table "analyze_ftable" would
have failed before this commit, because "analyze_rtable1" is not defined
on the remote side.

Issue introduced by 8ad51b5f446b.

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

7 weeks agoStamp 18beta3. REL_18_BETA3
Tom Lane [Mon, 11 Aug 2025 21:02:23 +0000 (17:02 -0400)]
Stamp 18beta3.

7 weeks agoRestrict psql meta-commands in plain-text dumps.
Nathan Bossart [Mon, 11 Aug 2025 14:00:00 +0000 (09:00 -0500)]
Restrict psql meta-commands in plain-text dumps.

A malicious server could inject psql meta-commands into plain-text
dump output (i.e., scripts created with pg_dump --format=plain,
pg_dumpall, or pg_restore --file) that are run at restore time on
the machine running psql.  To fix, introduce a new "restricted"
mode in psql that blocks all meta-commands (except for \unrestrict
to exit the mode), and teach pg_dump, pg_dumpall, and pg_restore to
use this mode in plain-text dumps.

While at it, encourage users to only restore dumps generated from
trusted servers or to inspect it beforehand, since restoring causes
the destination to execute arbitrary code of the source superusers'
choice.  However, the client running the dump and restore needn't
trust the source or destination superusers.

Reported-by: Martin Rakhmanov
Reported-by: Matthieu Denais <litezeraw@gmail.com>
Reported-by: RyotaK <ryotak.mail@gmail.com>
Suggested-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Noah Misch <noah@leadboat.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Security: CVE-2025-8714
Backpatch-through: 13

7 weeks agoConvert newlines to spaces in names written in v11+ pg_dump comments.
Noah Misch [Mon, 11 Aug 2025 13:18:59 +0000 (06:18 -0700)]
Convert newlines to spaces in names written in v11+ pg_dump comments.

Maliciously-crafted object names could achieve SQL injection during
restore.  CVE-2012-0868 fixed this class of problem at the time, but
later work reintroduced three cases.  Commit
bc8cd50fefd369b217f80078585c486505aafb62 (back-patched to v11+ in
2023-05 releases) introduced the pg_dump case.  Commit
6cbdbd9e8d8f2986fde44f2431ed8d0c8fce7f5d (v12+) introduced the two
pg_dumpall cases.  Move sanitize_line(), unchanged, to dumputils.c so
pg_dumpall has access to it in all supported versions.  Back-patch to
v13 (all supported versions).

Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Backpatch-through: 13
Security: CVE-2025-8715

7 weeks agoTranslation updates
Peter Eisentraut [Mon, 11 Aug 2025 12:38:06 +0000 (14:38 +0200)]
Translation updates

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

7 weeks agoFix security checks in selectivity estimation functions.
Dean Rasheed [Mon, 11 Aug 2025 08:07:36 +0000 (09:07 +0100)]
Fix security checks in selectivity estimation functions.

Commit e2d4ef8de86 (the fix for CVE-2017-7484) added security checks
to the selectivity estimation functions to prevent them from running
user-supplied operators on data obtained from pg_statistic if the user
lacks privileges to select from the underlying table. In cases
involving inheritance/partitioning, those checks were originally
performed against the child RTE (which for plain inheritance might
actually refer to the parent table). Commit 553d2ec2710 then extended
that to also check the parent RTE, allowing access if the user had
permissions on either the parent or the child. It turns out, however,
that doing any checks using the child RTE is incorrect, since
securityQuals is set to NULL when creating an RTE for an inheritance
child (whether it refers to the parent table or the child table), and
therefore such checks do not correctly account for any RLS policies or
security barrier views. Therefore, do the security checks using only
the parent RTE. This is consistent with how RLS policies are applied,
and the executor's ACL checks, both of which use only the parent
table's permissions/policies. Similar checks are performed in the
extended stats code, so update that in the same way, centralizing all
the checks in a new function.

In addition, note that these checks by themselves are insufficient to
ensure that the user has access to the table's data because, in a
query that goes via a view, they only check that the view owner has
permissions on the underlying table, not that the current user has
permissions on the view itself. In the selectivity estimation
functions, there is no easy way to navigate from underlying tables to
views, so add permissions checks for all views mentioned in the query
to the planner startup code. If the user lacks permissions on a view,
a permissions error will now be reported at planner-startup, and the
selectivity estimation functions will not be run.

Checking view permissions at planner-startup in this way is a little
ugly, since the same checks will be repeated at executor-startup.
Longer-term, it might be better to move all the permissions checks
from the executor to the planner so that permissions errors can be
reported sooner, instead of creating a plan that won't ever be run.
However, such a change seems too far-reaching to be back-patched.

Back-patch to all supported versions. In v13, there is the added
complication that UPDATEs and DELETEs on inherited target tables are
planned using inheritance_planner(), which plans each inheritance
child table separately, so that the selectivity estimation functions
do not know that they are dealing with a child table accessed via its
parent. Handle that by checking access permissions on the top parent
table at planner-startup, in the same way as we do for views. Any
securityQuals on the top parent table are moved down to the child
tables by inheritance_planner(), so they continue to be checked by the
selectivity estimation functions.

Author: Dean Rasheed <dean.a.rasheed@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Noah Misch <noah@leadboat.com>
Backpatch-through: 13
Security: CVE-2025-8713

7 weeks agoRemove, from stable branches, the new assertion of no pg_dump OID sort.
Noah Misch [Sun, 10 Aug 2025 20:05:13 +0000 (13:05 -0700)]
Remove, from stable branches, the new assertion of no pg_dump OID sort.

Commit 0decd5e89db9f5edb9b27351082f0d74aae7a9b6 recently added the
assertion to confirm dump order remains independent of OID values.  The
assertion remained reachable via DO_DEFAULT_ACL.  Given the release wrap
tomorrow, make the assertion master-only.

Reported-by: Alexander Lakhin <exclusion@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/d32aaa8d-df7c-4f94-bcb3-4c85f02bea21@gmail.com
Backpatch-through: 13-18

7 weeks agoFix rare bug in read_stream.c's split IO handling.
Thomas Munro [Sat, 9 Aug 2025 00:33:06 +0000 (12:33 +1200)]
Fix rare bug in read_stream.c's split IO handling.

The internal queue of buffers could become corrupted in a rare edge case
that failed to invalidate an entry, causing a stale buffer to be
"forwarded" to StartReadBuffers().  This is a simple fix for the
immediate problem.

A small API change might be able to remove this and related fragility
entirely, but that will have to wait a bit.

Defect in commit ed0b87ca.

Bug: 19006
Backpatch-through: 18
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Xuneng Zhou <xunengzhou@gmail.com>
Discussion: https://postgr.es/m/19006-80fcaaf69000377e%40postgresql.org

7 weeks agopostgres_fdw and dblink should check if backend has MyProcPort
Peter Eisentraut [Fri, 8 Aug 2025 17:34:31 +0000 (19:34 +0200)]
postgres_fdw and dblink should check if backend has MyProcPort

before checking ->has_scram_keys.  MyProcPort is NULL in background
workers.  So this could crash for example if a background worker
accessed a suitable configured foreign table.

Author: Alexander Pyhalov <a.pyhalov@postgrespro.ru>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Matheus Alcantara <matheusssilv97@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/27b29a35-9b96-46a9-bc1a-914140869dac%40gmail.com

7 weeks agooauth: Track total call count during a client flow
Jacob Champion [Fri, 8 Aug 2025 15:44:56 +0000 (08:44 -0700)]
oauth: Track total call count during a client flow

Tracking down the bugs that led to the addition of comb_multiplexer()
and drain_timer_events() was difficult, because an inefficient flow is
not visibly different from one that is working properly. To help
maintainers notice when something has gone wrong, track the number of
calls into the flow as part of debug mode, and print the total when the
flow finishes.

A new test makes sure the total count is less than 100. (We expect
something on the order of 10.) This isn't foolproof, but it is able to
catch several regressions in the logic of the prior two commits, and
future work to add TLS support to the oauth_validator test server should
strengthen it as well.

Backpatch-through: 18
Discussion: https://postgr.es/m/CAOYmi+nDZxJHaWj9_jRSyf8uMToCADAmOfJEggsKW-kY7aUwHA@mail.gmail.com

7 weeks agooauth: Remove expired timers from the multiplexer
Jacob Champion [Fri, 8 Aug 2025 15:44:52 +0000 (08:44 -0700)]
oauth: Remove expired timers from the multiplexer

In a case similar to the previous commit, an expired timer can remain
permanently readable if Curl does not remove the timeout itself. Since
that removal isn't guaranteed to happen in real-world situations,
implement drain_timer_events() to reset the timer before calling into
drive_request().

Moving to drain_timer_events() happens to fix a logic bug in the
previous caller of timer_expired(), which treated an error condition as
if the timer were expired instead of bailing out.

The previous implementation of timer_expired() gave differing results
for epoll and kqueue if the timer was reset. (For epoll, a reset timer
was considered to be expired, and for kqueue it was not.) This didn't
previously cause problems, since timer_expired() was only called while
the timer was known to be set, but both implementations now use the
kqueue logic.

Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Backpatch-through: 18
Discussion: https://postgr.es/m/CAOYmi+nDZxJHaWj9_jRSyf8uMToCADAmOfJEggsKW-kY7aUwHA@mail.gmail.com

7 weeks agooauth: Ensure unused socket registrations are removed
Jacob Champion [Fri, 8 Aug 2025 15:44:46 +0000 (08:44 -0700)]
oauth: Ensure unused socket registrations are removed

If Curl needs to switch the direction of a socket's registration (e.g.
from CURL_POLL_IN to CURL_POLL_OUT), it expects the old registration to
be discarded. For epoll, this happened via EPOLL_CTL_MOD, but for
kqueue, the old registration would remain if it was not explicitly
removed by Curl.

Explicitly remove the opposite-direction event during registrations. (If
that event doesn't exist, we'll just get an ENOENT, which will be
ignored by the same code that handles CURL_POLL_REMOVE.) A few
assertions are also added to strengthen the relationship between the
number of events added, the number of events pulled off the queue, and
the lengths of the kevent arrays.

Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Backpatch-through: 18
Discussion: https://postgr.es/m/CAOYmi+nDZxJHaWj9_jRSyf8uMToCADAmOfJEggsKW-kY7aUwHA@mail.gmail.com

7 weeks agooauth: Remove stale events from the kqueue multiplexer
Jacob Champion [Fri, 8 Aug 2025 15:44:37 +0000 (08:44 -0700)]
oauth: Remove stale events from the kqueue multiplexer

If a socket is added to the kqueue, becomes readable/writable, and
subsequently becomes non-readable/writable again, the kqueue itself will
remain readable until either the socket registration is removed, or the
stale event is cleared via a call to kevent().

In many simple cases, Curl itself will remove the socket registration
quickly, but in real-world usage, this is not guaranteed to happen. The
kqueue can then remain stuck in a permanently readable state until the
request ends, which results in pointless wakeups for the client and
wasted CPU time.

Implement comb_multiplexer() to call kevent() and unstick any stale
events that would cause unnecessary callbacks. This is called right
after drive_request(), before we return control to the client to wait.

Suggested-by: Thomas Munro <thomas.munro@gmail.com>
Co-authored-by: Thomas Munro <thomas.munro@gmail.com>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Backpatch-through: 18
Discussion: https://postgr.es/m/CAOYmi+nDZxJHaWj9_jRSyf8uMToCADAmOfJEggsKW-kY7aUwHA@mail.gmail.com

7 weeks agoRemove obsolete comment.
Thomas Munro [Fri, 8 Aug 2025 13:40:17 +0000 (01:40 +1200)]
Remove obsolete comment.

Remove a comment about potential for AIO in StartReadBuffersImpl(),
because that change happened.

7 weeks agoFix incorrect lack of Datum conversion in _int_matchsel()
Peter Eisentraut [Fri, 8 Aug 2025 10:06:06 +0000 (12:06 +0200)]
Fix incorrect lack of Datum conversion in _int_matchsel()

The code used

    return (Selectivity) 0.0;

where

    PG_RETURN_FLOAT8(0.0);

would be correct.

On 64-bit systems, these are pretty much equivalent, but on 32-bit
systems, PG_RETURN_FLOAT8() correctly produces a pointer, but the old
wrong code would return a null pointer, possibly leading to a crash
elsewhere.

We think this code is actually not reachable because bqarr_in won't
accept an empty query, and there is no other function that will
create query_int values.  But better be safe and not let such
incorrect code lie around.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/flat/8246d7ff-f4b7-4363-913e-827dadfeb145%40eisentraut.org

8 weeks agoFix oversight in FindTriggerIncompatibleWithInheritance.
Etsuro Fujita [Fri, 8 Aug 2025 08:35:00 +0000 (17:35 +0900)]
Fix oversight in FindTriggerIncompatibleWithInheritance.

This function is called from ATExecAttachPartition/ATExecAddInherit,
which prevent tables with row-level triggers with transition tables from
becoming partitions or inheritance children, to check if there is such a
trigger on the given table, but failed to check if a found trigger is
row-level, causing the caller functions to needlessly prevent a table
with only a statement-level trigger with transition tables from becoming
a partition or inheritance child.  Repair.

Oversight in commit 501ed02cf.

Author: Etsuro Fujita <etsuro.fujita@gmail.com>
Discussion: https://postgr.es/m/CAPmGK167mXzwzzmJ_0YZ3EZrbwiCxtM1vogH_8drqsE6PtxRYw%40mail.gmail.com
Backpatch-through: 13

8 weeks agopg_dump: Fix incorrect parsing of object types in pg_dump --filter.
Fujii Masao [Fri, 8 Aug 2025 05:36:39 +0000 (14:36 +0900)]
pg_dump: Fix incorrect parsing of object types in pg_dump --filter.

Previously, pg_dump --filter could misinterpret invalid object types
in the filter file as valid ones. For example, the invalid object type
"table-data" (likely a typo for the valid "table_data") could be
mistakenly recognized as "table", causing pg_dump to succeed
when it should have failed.

This happened because pg_dump identified keywords as sequences of
ASCII alphabetic characters, treating non-alphabetic characters
(like hyphens) as keyword boundaries. As a result, "table-data" was
parsed as "table".

To fix this, pg_dump --filter now treats keywords as strings of
non-whitespace characters, ensuring invalid types like "table-data"
are correctly rejected.

Back-patch to v17, where the --filter option was introduced.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Xuneng Zhou <xunengzhou@gmail.com>
Reviewed-by: Srinath Reddy <srinath2133@gmail.com>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/CAHGQGwFzPKUwiV5C-NLBqz1oK1+z9K8cgrF+LcxFem-p3_Ftug@mail.gmail.com
Backpatch-through: 17

8 weeks agoDisallow collecting transition tuples from child foreign tables.
Etsuro Fujita [Fri, 8 Aug 2025 01:50:01 +0000 (10:50 +0900)]
Disallow collecting transition tuples from child foreign tables.

Commit 9e6104c66 disallowed transition tables on foreign tables, but
failed to account for cases where a foreign table is a child table of a
partitioned/inherited table on which transition tables exist, leading to
incorrect transition tuples collected from such foreign tables for
queries on the parent table triggering transition capture.  This
occurred not only for inherited UPDATE/DELETE but for partitioned INSERT
later supported by commit 3d956d956, which should have handled it at
least for the INSERT case, but didn't.

To fix, modify ExecAR*Triggers to throw an error if the given relation
is a foreign table requesting transition capture.  Also, this commit
fixes make_modifytable so that in case of an inherited UPDATE/DELETE
triggering transition capture, FDWs choose normal operations to modify
child foreign tables, not DirectModify; which is needed because they
would otherwise skip the calls to ExecAR*Triggers at execution, causing
unexpected behavior.

Author: Etsuro Fujita <etsuro.fujita@gmail.com>
Reviewed-by: Amit Langote <amitlangote09@gmail.com>
Discussion: https://postgr.es/m/CAPmGK14QJYikKzBDCe3jMbpGENnQ7popFmbEgm-XTNuk55oyHg%40mail.gmail.com
Backpatch-through: 13

8 weeks agoAdd information about "generation" when dropping twice pgstats entry
Michael Paquier [Fri, 8 Aug 2025 00:07:49 +0000 (09:07 +0900)]
Add information about "generation" when dropping twice pgstats entry

Dropping twice a pgstats entry should not happen, and the error report
generated was missing the "generation" counter (tracking when an entry
is reused) that has been added in 818119afccd3.

Like d92573adcb02, backpatch down to v15 where this information is
useful to have, to gather more information from instances where the
problem shows up.  A report has shown that this error path has been
reached on a standby based on 17.3, for a relation stats entry and an
OID close to wraparound.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Discussion: https://postgr.es/m/CAN4RuQvYth942J2+FcLmJKgdpq6fE5eqyFvb_PuskxF2eL=Wzg@mail.gmail.com
Backpatch-through: 15

8 weeks agomeson: Fix install-quiet after clean
Jacob Champion [Thu, 7 Aug 2025 22:31:36 +0000 (15:31 -0700)]
meson: Fix install-quiet after clean

libpq-oauth was missing from the installed_targets list, so

    $ ninja clean && ninja install-quiet

failed with the error message

    ERROR: File 'src/interfaces/libpq-oauth/libpq-oauth.a' could not be found

It seems a little odd to have to tell Meson what's missing, since it
clearly knows how to build that file during regular installation. But
the "quiet" variant we've created must use --no-rebuild, to avoid
spawning concurrent ninja processes that would step on each other.

Reported-by: Andres Freund <andres@anarazel.de>
Backpatch-through: 18
Discussion: https://postgr.es/m/hbpqdwxkfnqijaxzgdpvdtp57s7gwxa5d6sbxswovjrournlk6%404jnb2gzan4em

8 weeks agodoc: add float as an alias for double precision.
Tom Lane [Thu, 7 Aug 2025 22:04:45 +0000 (18:04 -0400)]
doc: add float as an alias for double precision.

Although the "Floating-Point Types" section says that "float" data
type is taken to mean "double precision", this information was not
reflected in the data type table that lists all data type aliases.

Reported-by: alexander.kjall@hafslund.no
Author: Euler Taveira <euler@eulerto.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/175456294638.800.12038559679827947313@wrigleys.postgresql.org
Backpatch-through: 13

8 weeks agodoc: Formatting improvements
Peter Eisentraut [Thu, 7 Aug 2025 11:29:08 +0000 (13:29 +0200)]
doc: Formatting improvements

Small touch-up on commits 25505082f0e and 50fd428b2b9.  Fix the
formatting of the example messages in the documentation and adjust the
wording to match the code.

8 weeks agoFix checkpointer shared memory allocation
Alexander Korotkov [Thu, 7 Aug 2025 11:29:02 +0000 (14:29 +0300)]
Fix checkpointer shared memory allocation

Use Min(NBuffers, MAX_CHECKPOINT_REQUESTS) instead of NBuffers in
CheckpointerShmemSize() to match the actual array size limit set in
CheckpointerShmemInit().  This prevents wasting shared memory when
NBuffers > MAX_CHECKPOINT_REQUESTS.  Also, fix the comment.

Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/1439188.1754506714%40sss.pgh.pa.us
Author: Xuneng Zhou <xunengzhou@gmail.com>
Co-authored-by: Alexander Korotkov <aekorotkov@gmail.com>