]> git.ipfire.org Git - thirdparty/postgresql.git/log
thirdparty/postgresql.git
5 hours agopsql: Add missing IO option to EXPLAIN tab completion master github/master
Fujii Masao [Sat, 23 May 2026 00:39:58 +0000 (09:39 +0900)] 
psql: Add missing IO option to EXPLAIN tab completion

Commit 681daed9316 added EXPLAIN (IO) as a boolean option, but did
not update psql's tab completion to include it. Add IO to both the
option keyword list and the boolean ON/OFF completion.

Author: Afrah Razzak <mypg.afrah@gmail.com>
Reviewed-by: Zhenwei Shang <a934172442@gmail.com>
Discussion: https://postgr.es/m/CAAJ6gzGi9gK6nGjsGCch0nFPdd2+odWatTS1uAGwRDPbHkmSVQ@mail.gmail.com

6 hours agoAvoid exposing WAL receiver raw conninfo during timeline jumps
Michael Paquier [Fri, 22 May 2026 23:10:07 +0000 (08:10 +0900)] 
Avoid exposing WAL receiver raw conninfo during timeline jumps

When reusing an existing WAL receiver after it has reached
WALRCV_WAITING for new instructions, RequestXLogStreaming() copied
PrimaryConnInfo into WalRcv->conninfo before switching the state to
WALRCV_RESTARTING.  At that point ready_to_display could still be true,
so pg_stat_wal_receiver could expose the raw connection string,
including sensitive fields, but it should only show the user-displayable
version of the connection string.

WALRCV_RESTARTING does not establish a new connection.  The waiting WAL
receiver reuses its existing connection and only needs a new startpoint
and timeline, so there is no need to copy the raw connection string into
shared memory again.  Let's only copy conninfo when launching a new WAL
receiver after WALRCV_STOPPED, not while waiting for instructions.

This commit adds coverage for the case fixed by this commit to the
timeline-switch test by verifying that the WAL receiver conninfo remains
consistent across the jump.

Backpatch all the way down, as this issue is possible since
pg_stat_wal_receiver has been introduced.

Author: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/EF91FF76-1E2B-4F3B-9162-290B4DC517FF@gmail.com
Backpatch-through: 14

10 hours agoImprove pg_stat_wal_receiver for CONNECTING status
Michael Paquier [Fri, 22 May 2026 19:04:26 +0000 (04:04 +0900)] 
Improve pg_stat_wal_receiver for CONNECTING status

Commit a36164e7465 added a CONNECTING status for the WAL receiver, but
pg_stat_wal_receiver returned no information while the connection to the
primary was attempted, limiting the usability of the feature in
high-latency environments where the connection attempt to the primary
could take time.

This commit improves the report of the status by splitting the way the
shared memory state of the WAL receiver is filled before and after the
connection to the primary is attempted with walrcv_connect():
- Before the attempt, reset all the connection fields, switch
ready_to_display to true.
- After the attempt, fill in the connection fields.

This change means two spinlock acquisitions instead of one, but at least
monitoring tools can know about the connection attempt before its
completion, enlarging the usability of the feature.  This code path is
taken only once when a WAL receiver is spawned, so the extra acquisition
does not matter performance-wise.

Reported-by: Chao Li <li.evan.chao@gmail.com>
Author: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/EF91FF76-1E2B-4F3B-9162-290B4DC517FF@gmail.com

14 hours agoSet notice receiver before libpq connection startup completes
Fujii Masao [Fri, 22 May 2026 15:25:48 +0000 (00:25 +0900)] 
Set notice receiver before libpq connection startup completes

Commit 112faf1378e added custom notice receivers for replication,
postgres_fdw, and dblink so that remote NOTICE, WARNING, and similar
messages are reported via ereport(). However, those notice receivers were
installed only after libpqsrv_connect() and libpqsrv_connect_params()
returned, by which point libpq connection startup had already completed.
As a result, messages emitted during connection establishment could be
missed.

This commit fixes the issue by splitting libpqsrv_connect() and
libpqsrv_connect_params() into separate start and complete phases:
libpqsrv_connect_start(), libpqsrv_connect_params_start(), and
libpqsrv_connect_complete(). This allows callers to perform
per-connection setup, such as installing a notice receiver, after the
connection has been started but before startup completes.

Note that callers of libpqsrv_connect_start() and
libpqsrv_connect_params_start() must still call
libpqsrv_connect_complete(), even if the start function returns NULL, so
that any external FDs reserved during startup are released properly.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Vignesh C <vignesh21@gmail.com>
Reviewed-by: Rafia Sabih <rafia.pghackers@gmail.com>
Discussion: https://postgr.es/m/A2B8B7DE-C119-492F-A9FA-14CF86849777@gmail.com

14 hours agoPrevent setting NO INHERIT on partitioned NOT NULL constraints
Fujii Masao [Fri, 22 May 2026 14:59:04 +0000 (23:59 +0900)] 
Prevent setting NO INHERIT on partitioned NOT NULL constraints

The documentation states that NOT NULL constraints on partitioned tables
are always inherited by all partitions, and therefore cannot be declared
NO INHERIT. While a check already existed to reject creating such
constraints with NO INHERIT, previously the same check was missing for
ALTER TABLE ... ALTER CONSTRAINT ... NO INHERIT.

This commit adds the missing check so that attempting to set NO INHERIT
on a partitioned NOT NULL constraint now fails.

Backpatch to v18, where ALTER TABLE ... ALTER CONSTRAINT ... [NO] INHERIT
was added.

Author: Andreas Karlsson <andreas@proxel.se>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/ecc985ad-6ec1-4094-a315-317943ca5f3f@proxel.se
Backpatch-through: 18

2 days agoRevert "Reject degenerate SPLIT PARTITION with DEFAULT partition"
Alexander Korotkov [Wed, 20 May 2026 20:23:49 +0000 (23:23 +0300)] 
Revert "Reject degenerate SPLIT PARTITION with DEFAULT partition"

This reverts commit d8af73010033cb8ad6c941942d6b03d74d7e4f7e.  Per buildfarm
failures.

2 days agoReject degenerate SPLIT PARTITION with DEFAULT partition
Alexander Korotkov [Wed, 20 May 2026 11:32:57 +0000 (14:32 +0300)] 
Reject degenerate SPLIT PARTITION with DEFAULT partition

ALTER TABLE ... SPLIT PARTITION allows a DEFAULT partition to be created
as one of the replacement partitions when the parent table does not
already have one.  However, it should not allow the degenerate case where
a non-DEFAULT partition keeps exactly the same bound as the split
partition and the command merely adds a DEFAULT partition through the
SPLIT PARTITION path.

Detect that case by comparing the bound of the split partition with the
bound of the only non-DEFAULT replacement partition, and raise an error
when they are the same.  Users should add a DEFAULT partition directly
with CREATE TABLE ... PARTITION OF ... DEFAULT or ALTER TABLE ... ATTACH
PARTITION ... DEFAULT instead.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Alexander Korotkov <aekorotkov@gmail.com>
Discussion: https://postgr.es/m/C18878AB-DEB2-4A61-9995-A035DD644B81@gmail.com

2 days agopg_recvlogical: Add tests for output file permissions
Fujii Masao [Wed, 20 May 2026 07:01:56 +0000 (16:01 +0900)] 
pg_recvlogical: Add tests for output file permissions

Commit 263d1e6dfee changed pg_recvlogical to honor source cluster file
permissions when creating output files. This commit adds tests verifying
that output files are created with mode 0600 when the source cluster is
initialized without group access, and with mode 0640 when group access is
enabled.

Author: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Author: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CAHGQGwHhpizYzMo3nFP4GkNMueSNMY3QfC-gBN1VTXtuiANDvw@mail.gmail.com

2 days agopg_recvlogical: Honor source cluster file permissions for output files
Fujii Masao [Wed, 20 May 2026 06:54:13 +0000 (15:54 +0900)] 
pg_recvlogical: Honor source cluster file permissions for output files

Commit c37b3d08ca6 attempted to preserve group permissions on pg_recvlogical
output files when group access was enabled on the source cluster. However,
the output files were still created with a fixed S_IRUSR | S_IWUSR mode,
preventing group-read permissions from being applied.

This commit fixes the issue by creating output files with pg_file_create_mode
instead of a hard-coded mode. This allows pg_recvlogical to correctly preserve
group permissions from the source cluster.

Backpatch to all supported branches.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Discussion: https://postgr.es/m/CAHGQGwHhpizYzMo3nFP4GkNMueSNMY3QfC-gBN1VTXtuiANDvw@mail.gmail.com
Backpatch-through: 14

3 days agoFix REPACK decoding worker not cleaned up on FATAL exit
Álvaro Herrera [Tue, 19 May 2026 18:37:46 +0000 (11:37 -0700)] 
Fix REPACK decoding worker not cleaned up on FATAL exit

When the launching backend of REPACK (CONCURRENTLY) is terminated via
pg_terminate_backend(), ProcDiePending causes ereport(FATAL) which
bypasses PG_FINALLY blocks.  As a result, stop_repack_decoding_worker()
is never called, leaving the decoding worker running indefinitely and
holding its temporary replication slot.

Fix by using PG_ENSURE_ERROR_CLEANUP, which handles both ERROR and
FATAL exits.

Author: Baji Shaik <baji.pgdev@gmail.com>
Reviewed-by: Sami Imseih <samimseih@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/CA+fm-RNoPxL2N7db_A0anMXV_aDu6jWj4PNOPtMtBUAPDPvSXQ@mail.gmail.com

3 days agoClarify SPLIT PARTITION bound requirements in docs
Alexander Korotkov [Tue, 19 May 2026 10:39:53 +0000 (13:39 +0300)] 
Clarify SPLIT PARTITION bound requirements in docs

The documentation said that the bounds of new partitions should not
overlap and that their combined bounds should equal the bounds of the
split partition.  That is misleading when a new DEFAULT partition is
specified, because the explicit partitions may cover only part of the
split partition while the DEFAULT partition covers the rest.

Clarify that new non-DEFAULT partition bounds must not overlap with
other new or existing partitions and must be contained within the bounds
of the split partition.  Also state that the combined bounds must exactly
match the split partition only when no new DEFAULT partition is specified.

While here, improve nearby wording about hash-partitioned target tables
and splitting a DEFAULT partition with the same partition name.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Alexander Korotkov <aekorotkov@gmail.com>
Discussion: https://postgr.es/m/C18878AB-DEB2-4A61-9995-A035DD644B81@gmail.com

3 days agoFix SPLIT PARTITION hint for DEFAULT partition bounds
Alexander Korotkov [Tue, 19 May 2026 10:39:39 +0000 (13:39 +0300)] 
Fix SPLIT PARTITION hint for DEFAULT partition bounds

When ALTER TABLE ... SPLIT PARTITION specifies a DEFAULT partition, the
explicit partitions do not need to cover the split partition's bound
exactly.  They may cover only part of it, with the DEFAULT partition
covering the remaining range.

However, the existing hint said that the combined bounds of the new
partitions must exactly match the bound of the split partition, which is
misleading for this case and inconsistent with the code comment.

Fix the hint to state the actual requirement: explicit partition bounds
must stay within the bounds of the split partition when a DEFAULT
partition is specified.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Alexander Korotkov <aekorotkov@gmail.com>
Discussion: https://postgr.es/m/C18878AB-DEB2-4A61-9995-A035DD644B81@gmail.com

3 days agoFix SPLIT PARTITION range bound validation with DEFAULT
Alexander Korotkov [Tue, 19 May 2026 10:38:55 +0000 (13:38 +0300)] 
Fix SPLIT PARTITION range bound validation with DEFAULT

When splitting a range partition and defining a new DEFAULT partition, the
validation checked the lower bound of the first explicit partition and the
upper bound of explicit partitions only when they were not first.  If there
was exactly one explicit non-DEFAULT partition, its upper bound was therefore
not checked.

This could allow the replacement partition to extend beyond the upper bound
of the partition being split, potentially overlapping another existing
partition.

Fix this by checking the upper bound whenever the explicit partition is the
last one.  Add a regression test covering the single explicit partition plus
DEFAULT case.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Zhenwei Shang <a934172442@gmail.com>
Reviewed-by: Dmitry Koval <d.koval@postgrespro.ru>
Reviewed-by: Alexander Korotkov <aekorotkov@gmail.com>
Discussion: https://postgr.es/m/C18878AB-DEB2-4A61-9995-A035DD644B81@gmail.com

4 days agoFix COPY FROM ON_ERROR SET_NULL with selective column list
Fujii Masao [Tue, 19 May 2026 01:11:41 +0000 (10:11 +0900)] 
Fix COPY FROM ON_ERROR SET_NULL with selective column list

When using COPY FROM ... ON_ERROR SET_NULL with a selective column list, the
domain_with_constraint array was incorrectly allocated based on the length of
the target column list. While the array was populated sequentially,
CopyFromTextLikeOneRow attempted to access it using the physical attribute
index (attnum - 1). This mismatch caused out-of-bounds reads when targeting
high-numbered columns, allowing NULL values to bypass NOT NULL domain checks
and be silently inserted.

Fix by allocating the array to match the total number of physical attributes
(num_phys_attrs) and indexing via attnum - 1, bringing it into alignment with
other per-column arrays in BeginCopyFrom.

Author: SATYANARAYANA NARLAPURAM <satyanarlapuram@gmail.com>
Reviewed-by: Jian He <jian.universality@gmail.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CAHg+QDdej0c0gWJi2FnbirzhgzyZNPiTwC1P5B_-dSNCzq-91A@mail.gmail.com

4 days agoRemove support for 8 byte tear free read/write on 32-bit
Daniel Gustafsson [Mon, 18 May 2026 15:59:59 +0000 (08:59 -0700)] 
Remove support for 8 byte tear free read/write on 32-bit

The macro for enabling single-copy atomicity on i586+ when using
GCC has been incorrect since 2017 (commit e8fdbd58f) without any
complaints, and getting it to work is non-trivial.

Getting this to work reliably require C11 atomics, which in turn
also bumps the required MSVC version. For now, simply remove the
attempted support which doesn't work anyways.

Author: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Reported-by: Jakub Wartak <jakub.wartak@enterprisedb.com>
Suggested-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CAKZiRmycHOOJyEPc9FUss1_69_U62WoSx32jT7wyES-YkStZKA@mail.gmail.com
Discussion: https://posrgr.es/m/CA+hUKGKFvu3zyvv3aaj5hHs9VtWcjFAmisOwOc7aOZNc5AF3NA@mail.gmail.com

4 days agoRemove obsolete comment in AtEOXact_Inval
Daniel Gustafsson [Mon, 18 May 2026 15:43:12 +0000 (08:43 -0700)] 
Remove obsolete comment in AtEOXact_Inval

This comment was originally added to RegisterInvalid() in POSTGRES before
Postgres95, and came in via the Postgres95 import.  It has been obsolote
for quite some time so remove.

Author: Steven Niu <niushiji@highgo.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/MN2PR15MB30219837B2381AE2518A4C45A7FCA@MN2PR15MB3021.namprd15.prod.outlook.com

4 days agopsql: Make ParseVariableDouble reject values above max
Daniel Gustafsson [Mon, 18 May 2026 15:33:36 +0000 (08:33 -0700)] 
psql: Make ParseVariableDouble reject values above max

ParseVariableDouble missed returning false after logging an error when
the parsed value exceeded max, making the value assigned rather than
rejected.  Backpatch down to v18 where this was introduced as part of
the \WATCH_INTERVAL.

Author: Sven Klemm <sven@tigerdata.com>
Co-authored-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/CAMCrgp31p_5SDVi7dwnP39tTW5icQ0MWHA+N4kJdXgkL0PEy8w@mail.gmail.com
Backpatch-through: 18

4 days agooauth: Fix missing quote in errormessage
Daniel Gustafsson [Mon, 18 May 2026 15:03:09 +0000 (08:03 -0700)] 
oauth: Fix missing quote in errormessage

The error message for incorrect oauth validator configuration was missing
a quote character. OAuth was introduced in v18 but there is no need for a
backpatch since this was introduced in 22f9207aaa37.

Author: Jonathan Gonzalez V. <jonathan.abdiel@gmail.com>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/ff9b84b9e6d5a3fef1f320ee5d63ec7dae722739.camel@gmail.com

5 days agoFix issues with handling of expressions in extended stats restore
Michael Paquier [Mon, 18 May 2026 04:18:35 +0000 (13:18 +0900)] 
Fix issues with handling of expressions in extended stats restore

This commit addresses some defects with the handling of expressions in
pg_restore_extended_stats() and pg_clear_extended_stats():
- Misleading WARNING for an incorrect number of expressions, where the
number of required expressions was reported as the number of elements
given in input rather than the actual number of expressions expected by
the extstats object definition.
- Incorrect matching of expression names, where a key name was
considered as valid as long as it matched with the prefix of a legit key
name.  For example "correlatio" given in input would match with
"correlation", and be considered valid.  The consequence of this bug was
a silent discard of the input data, where the operation would be
considered a success.  The value associated to the prefixed key was not
inserted in the catalogs, just ignored.  pg_dump would not generate such
input data patterns, but a user doing manual stats injection could.
- Missing heap_freetuple() in pg_clear_extended_stats(), for the case
where the extstats object in input does not match with its parent
relation.

Author: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/A7C11B83-7534-4A09-9071-FBD09175CFC8@gmail.com

5 days agoFix parsing of REPACK options
Fujii Masao [Mon, 18 May 2026 04:14:49 +0000 (13:14 +0900)] 
Fix parsing of REPACK options

Previously, REPACK option parsing had two bugs.

First, REPACK (CONCURRENTLY OFF) failed with:

    ERROR:  unrecognized REPACK option "concurrently"

while CONCURRENTLY ON was accepted correctly.

Second, when the same option was specified multiple times, the last value
specified was not always honored. If any occurrence set the option to ON,
the option was treated as enabled even when the final setting was OFF.

This commit fixes these issues by correctly accepting CONCURRENTLY
regardless of its value, and by making the last specified value take precedence
when an option appears multiple times.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/CAHGQGwGAY4kfDtC4i+hAOX-a3u0yOA6__6EDTQz-ytsDHgh-yQ@mail.gmail.com

5 days agoFix IGNORE NULLS nullness cache for volatile window arguments.
Tatsuo Ishii [Mon, 18 May 2026 03:09:37 +0000 (12:09 +0900)] 
Fix IGNORE NULLS nullness cache for volatile window arguments.

The IGNORE NULLS implementation caches whether a window function argument
evaluated to NULL or NOT NULL for a given partition row.  That is safe for
ordinary expressions, but not for volatile expressions, where evaluating the
same argument on the same row can produce a different NULL/NOT NULL result
later.

This could produce wrong results in two ways.  A row previously cached as
NULL could be skipped even though a later evaluation would return NOT NULL.
Conversely, a row cached as NOT NULL could be chosen as the target row, then
re-evaluated to fetch the actual value and return NULL.

Make the nullness cache conditional per argument.  Do not use it for
arguments containing volatile functions or subplans, following the same
conservative approach used for moving window aggregates.  Also avoid
re-evaluating non-cacheable partition arguments after the scan has already
found the target row.

Add regression tests covering volatile arguments and subplan arguments with
IGNORE NULLS.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Tatsuo Ishii <ishii@postgresql.org>
Discussion: https://postgr.es/m/42B42506-6972-4266-8422-FB73E61D9DA7@gmail.com

5 days agoinjection_points: Move some structs to new header injection_points.h
Michael Paquier [Mon, 18 May 2026 02:11:40 +0000 (11:11 +0900)] 
injection_points: Move some structs to new header injection_points.h

This commit moves the definitions of InjectionPointConditionType and
InjectionPointCondition into a new header local to the test module
injection_points.h, so as these can be shared across more files in the
module.  A patch for a bug fix is under discussion, whose proposed test
will benefit from this refactoring.

Backpatch down to where the module exists, as this should be useful for
future bug fixes, even cases unrelated to the thread where this change
has been discussed.

Author: Andrey Borodin <x4mmm@yandex-team.ru>
Author: Vlad Lesin <vladlesin@gmail.com>
Discussion: https://postgr.es/m/d2983796-2603-41b7-a66e-fc8489ddb954@gmail.com
Backpatch-through: 17

6 days agoUse ereport(ERROR), not Assert(), for publisher tuples missing columns.
Noah Misch [Sun, 17 May 2026 01:01:35 +0000 (18:01 -0700)] 
Use ereport(ERROR), not Assert(), for publisher tuples missing columns.

Three locations use Assert() to guard against a mismatch between the
number of columns advertised in the RELATION message and the number
actually received in the subsequent INSERT/UPDATE tuple message. Since
these values originate from the publisher, the check must survive into
production builds.

A malicious or buggy publisher can send a RELATION claiming N columns
and an INSERT claiming M < N columns. The subscriber's apply worker
indexes into colvalues[]/colstatus[] using column indices from the
RELATION message's attribute map, causing a heap out-of-bounds read when
the tuple's column array is smaller than expected. We've looked, without
success, for a scenario in which the publisher holds sufficient control
over these out-of-bounds bytes to exploit this or even to reach a
SIGSEGV. Despite not finding one, the code has been fragile. Back-patch
to v14 (all supported versions).

Reported-by: Varik Matevosyan <varikmatevosyan@gmail.com>
Author: Varik Matevosyan <varikmatevosyan@gmail.com>
Discussion: https://postgr.es/m/CA+bBoog3cCogktzfLb9bppUByu-10B3CFp8u=iKXG_OvtAguCw@mail.gmail.com
Backpatch-through: 14

6 days agoSimplify signature of ProcessStartupPacket()
Michael Paquier [Sat, 16 May 2026 22:44:17 +0000 (07:44 +0900)] 
Simplify signature of ProcessStartupPacket()

There is now only one caller of ProcessStartupPacket().  Let's simplify
the routine so as the GSS and SSL states are tracked inside it.   If
future callers are added, there is less guessing to do.

Suggested-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi>
Discussion: https://postgr.es/m/aga7lCWluyc5zLb5@paquier.xyz

6 days agodoc: Fix example of pg_restore_extended_stats()
Michael Paquier [Sat, 16 May 2026 22:36:04 +0000 (07:36 +0900)] 
doc: Fix example of pg_restore_extended_stats()

Oversight in ba97bf9cb7b4, probably due to an incorrect rebase.

Author: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/8A72720A-55AC-4D41-B9DF-5610307600E6@gmail.com

6 days agopg_test_timing: Show additional TSC clock source debug info
Andres Freund [Sat, 16 May 2026 15:51:34 +0000 (11:51 -0400)] 
pg_test_timing: Show additional TSC clock source debug info

In some cases its necessary to understand whether TSC frequency data was
sourced from CPUID, and which of the registers. Show this debug info at
the end of pg_test_timing, and rework TSC functions to support that.

This would have helped debug the buildfarm report fixed in 7fc36c5db550
and is likely going to aid in any TSC-related issues reported during the
beta period or later.

Additionally, emit a warning if TSC frequency from calibration differs
by more than 10% from the TSC frequency in use, and suggest the use
of timing_clock_source = 'system'.

In passing, add an explicit early return in the output function if the
loop count is zero. This can't happen in practice, but coverity complained
because we unconditionally call output for the fast TSC measurement.

Author: Lukas Fittl <lukas@fittl.com>
Suggested-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Haibo Yan <tristan.yim@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us> (coverity fix only)
Discussion: https://postgr.es/m/CAP53Pkw3Gzb+KTF5pu_o7tzbfZ7+qm2m6uDWuGtTJjZpV9yNpg@mail.gmail.com

6 days agopostgres_fdw: Replace buffers in RemoteAttributeMapping with pointers.
Etsuro Fujita [Sat, 16 May 2026 08:55:00 +0000 (17:55 +0900)] 
postgres_fdw: Replace buffers in RemoteAttributeMapping with pointers.

Commit 28972b6fc ("Add support for importing statistics from remote
servers.") stored the names of local/remote columns for a foreign table
into the buffers of NAMEDATALEN bytes in this structure, without
accounting for the possibility that the remote column name in particular
could be longer than NAMEDATALEN - 1.  If it was longer than that, this
would leave it unterminated/truncated in the buffer, invoking undefined
behavior when match_attrmap() processes it, which assumes that it's
fully-contained/terminated in the buffer.

To fix, replace the buffers with char pointers, pstrdup the local/remote
column names, and store the results into the pointers.  This commit also
adds a function to clean up the nested data structure.

Per Coverity and Tom Lane.

Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Author: Corey Huinker <corey.huinker@gmail.com>
Reviewed-by: Etsuro Fujita <etsuro.fujita@gmail.com>
Discussion: https://postgr.es/m/342868.1776017700%40sss.pgh.pa.us

7 days agoCheck retain_dead_tuples for ALTER SUBSCRIPTION ... SERVER.
Jeff Davis [Fri, 15 May 2026 22:52:33 +0000 (15:52 -0700)] 
Check retain_dead_tuples for ALTER SUBSCRIPTION ... SERVER.

Previously, the subscription setting retain_dead_tuples didn't cause
ALTER SUBSCRIPTION ... SERVER to check the publisher. And if the
publisher was checked for some other reason, then it would use the old
conninfo.

Fix ALTER SUBSCRIPTION ... SERVER to always check the publisher when
retain_dead_tuples is set, and to use the new connection info, like
ALTER SUBSCRIPTION ... CONNECTION.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/f13a8e29410bbbf9999290f2c04513a8884fa51c.camel@j-davis.com

7 days agoDon't accept length of -1 in pg_locale.h APIs.
Jeff Davis [Fri, 15 May 2026 18:09:15 +0000 (11:09 -0700)] 
Don't accept length of -1 in pg_locale.h APIs.

Reverts ac30021356. Per discussion, that commit interfered with useful
tooling, and was not worth the special cases.

Suggested-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/s32n3tm2mjh247f3xkkxkdk7cf77hglbr3ia3hrsdjylajou7y@nlldpag3tjd5

7 days agodoc PG 19 relnotes: remove "Add fake LSN support to hash index"
Bruce Momjian [Fri, 15 May 2026 17:26:50 +0000 (13:26 -0400)] 
doc PG 19 relnotes: remove "Add fake LSN support to hash index"

Also add missing commit link to json_array() item.

Reported-by: Peter Geoghegan
Discussion: https://postgr.es/m/CAH2-Wzm1UAuv9ih6_ATbwbmrmusKPoJ2qSo3HBF-JaUEkVYUPg@mail.gmail.com

8 days agoRe-add regression tests for ltree and intarray
Michael Paquier [Fri, 15 May 2026 05:27:30 +0000 (14:27 +0900)] 
Re-add regression tests for ltree and intarray

These tests have been removed by 906ea101d0d5, due to some of them being
unstable in the buildfarm with low max_stack_depth values.  They are now
reworked so as they should be more portable.

The tests to cover the findoprnd() overflows use a balanced tree to
avoid using too much stack, per a suggestion and an investigation by Tom
Lane.

Note: This is initially applied only on HEAD; a backpatch will follow
should the buildfarm be fine with the situation.

Discussion: https://postgr.es/m/agZc6XecyE7E7fep@paquier.xyz
Backpatch-through: 14

8 days agopsql: Fix tab completion for REPACK boolean options
Fujii Masao [Fri, 15 May 2026 05:24:45 +0000 (14:24 +0900)] 
psql: Fix tab completion for REPACK boolean options

Previously, tab completion for REPACK parenthesized boolean options
(ANALYZE, CONCURRENTLY, and VERBOSE) did not suggest the boolean values
ON and OFF, unlike VACUUM.

This commit fixes the issue by adding ON/OFF completion for those options.

Author: Baji Shaik <baji.pgdev@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CA+fm-RNZpy7MAceR9gSyy833H_uL-fTx0LxO73RnvwEaprpuRA@mail.gmail.com

8 days agodoc PG 19 relnotes: update to current
Bruce Momjian [Thu, 14 May 2026 20:37:28 +0000 (16:37 -0400)] 
doc PG 19 relnotes:  update to current

8 days agorefint: Fix segfault in check_foreign_key().
Nathan Bossart [Thu, 14 May 2026 18:11:49 +0000 (13:11 -0500)] 
refint: Fix segfault in check_foreign_key().

When an UPDATE statement triggers check_foreign_key() with the
action set to "cascade", it generates more UPDATE statements to
modify the key values in referencing relations.  If a new key value
is NULL, SPI_getvalue() returns a NULL pointer, which is
subsequently passed to quote_literal_cstr(), causing a segfault.
To fix, skip quoting when a new key value is NULL and insert an
unquoted NULL keyword instead.

Oversight in commit 260e97733b.  While the refint documentation
recommends marking primary key columns NOT NULL, the aforementioned
scenario accidentally worked on platforms where snprintf()
substitutes "(null)" for NULL pointers.  Note that for
character-type columns, the old code quoted "(null)" as a string
literal, so this didn't always produce correct results.  But it
still seems better to fix this than to reject cases that previously
worked.

Reported-by: Nikita Kalinin <n.kalinin@postgrespro.ru>
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Reviewed-by: Pierre Forstmann <pierre.forstmann@gmail.com>
Discussion: https://postgr.es/m/19476-bd04ea6241345303%40postgresql.org
Backpatch-through: 14

8 days agoFix attribute mapping for COPY TO on partitioned tables.
Masahiko Sawada [Thu, 14 May 2026 17:32:34 +0000 (10:32 -0700)] 
Fix attribute mapping for COPY TO on partitioned tables.

Commit 4bea91f21f61 enabled COPY TO on a partitioned table to read
tuples from its partitions and mapped them to the root table's tuple
descriptor before output. However, it incorrectly built the attribute
map from the root table to the partition.

This commit fixes by building the attribute map from the partition to
the root table, ensuring that partition attributes are correctly
mapped to their corresponding root attributes.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Discussion: https://postgr.es/m/85EA70F3-C3DB-477B-B856-EA569FDAAE7C@gmail.com

8 days agoPrevent access to other sessions' temp tables
Alexander Korotkov [Thu, 14 May 2026 09:25:19 +0000 (12:25 +0300)] 
Prevent access to other sessions' temp tables

Commit b7b0f3f2724 ("Use streaming I/O in sequential scans") routed
sequential scans through read_stream_next_buffer(), bypassing the
RELATION_IS_OTHER_TEMP() check in ReadBufferExtended().  As a result,
a superuser can attempt to read or modify temp tables of other
sessions through the read-stream path.  When the query plan uses no index,
SELECT/UPDATE/DELETE/MERGE silently see no rows / report zero affected rows,
and COPY produces an empty output -- because the buffer manager has no
visibility into the owning session's local buffers and silently returns
nothing.  Any query plan that uses, for instance, a btree index
still errors out via the existing check in ReadBufferExtended(), which
is reached from hio.c and nbtree respectively, but this is incidental.

Fix by enforcing RELATION_IS_OTHER_TEMP() at the three additional
buffer-manager entry points:

- read_stream_begin_impl() rejects the read at stream setup time,
  covering sequential and bitmap scans that go through the
  read-stream path.
- ReadBuffer_common() becomes the canonical place for the check,
  consolidating the existing one previously kept in
  ReadBufferExtended().  All ReadBufferExtended() callers go through
  ReadBuffer_common(), so the consolidation is behavior-preserving.
- StartReadBuffersImpl() catches direct callers of StartReadBuffers()
  that bypass both of the above.  This is currently defense-in-depth,
  but documents the contract for future code.

The companion test in src/test/modules/test_misc was added in the
preceding commit; this commit updates the assertions for SELECT,
UPDATE, DELETE, MERGE, and COPY (which previously documented the
bug as silent success) to expect the new error.

Author: Jim Jones <jim.jones@uni-muenster.de>
Author: Daniil Davydov <3danissimo@gmail.com>
Co-authored-by: Alexander Korotkov <aekorotkov@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Soumya S Murali <soumyamurali.work@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAJDiXghdFcZ8%3Dnh4G69te7iRr3Q0uFyXxb3ZdG09_GTNZXwH0g%40mail.gmail.com
Backpatch-through: 17

8 days agoAdd tests for cross-session temp table access
Alexander Korotkov [Thu, 14 May 2026 09:21:03 +0000 (12:21 +0300)] 
Add tests for cross-session temp table access

Add a TAP test in src/test/modules/test_misc that documents what
happens when one session attempts to read or modify another session's
temporary table.  This commit only adds tests; it does not change
backend behavior, so the assertions reflect current behavior:

- SELECT, UPDATE, DELETE, MERGE, COPY on a table without an index
  silently succeed with no error and zero rows / zero affected rows.
  These commands run through the read-stream path, which currently
  bypasses the RELATION_IS_OTHER_TEMP() check.  This is the
  underlying bug to be fixed in a follow-up.
- INSERT errors with "cannot access temporary tables of other
  sessions" because hio.c calls ReadBufferExtended() to find a page
  with free space and is caught by the existing check there.
- Index scan errors via the same existing check, reached through
  nbtree -> ReadBuffer -> ReadBufferExtended.
- TRUNCATE / ALTER TABLE / ALTER INDEX / CLUSTER fail with their
  command-specific error messages.
- VACUUM is silently skipped to avoid noise during database-wide
  VACUUM (vacuum_rel() returns without warning).
- DROP TABLE is intentionally allowed: DROP does not touch the
  table's contents, and autovacuum relies on this to clean up
  temp relations orphaned by a crashed backend.
- ALTER FUNCTION / DROP FUNCTION on an owner-created function over
  its own temp row type work as catalog operations -- they don't
  read the underlying data.
- CREATE FUNCTION from a separate session, using another session's
  temp row type as an argument, is allowed but emits a NOTICE: the
  function is moved into the creator's pg_temp namespace with an
  auto-dependency on the borrowed type, so it disappears together
  with the session that created it.
- A bare DROP TABLE on a temp table that has a cross-session
  dependent function fails with a catalog-level dependency error.
- LOCK TABLE in ACCESS SHARE mode on another session's temp table
  succeeds and properly blocks the owner's session-exit cleanup
  (which acquires AccessExclusiveLock via findDependentObjects).
  This exercises the same LockRelationOid path used by autovacuum
  when cleaning up orphaned temp relations.
- When the owner session ends, the normal session-exit cleanup
  cascades through DEPENDENCY_NORMAL and removes both the temp
  objects and any cross-session functions that depended on them.

Also, document the contract for RELATION_IS_OTHER_TEMP() so that
future buffer-access entry points enforce the same rule.

Backpatch this through PostgreSQL 17, where b7b0f3f27241 introduces a code
path bypassing this check.

Author: Jim Jones <jim.jones@uni-muenster.de>
Author: Daniil Davydov <3danissimo@gmail.com>
Co-authored-by: Alexander Korotkov <aekorotkov@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Soumya S Murali <soumyamurali.work@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAJDiXghdFcZ8%3Dnh4G69te7iRr3Q0uFyXxb3ZdG09_GTNZXwH0g%40mail.gmail.com
Backpatch-through: 17

8 days agopostgres_fdw: Fix deparsing of remote column names in stats import.
Etsuro Fujita [Thu, 14 May 2026 08:05:00 +0000 (17:05 +0900)] 
postgres_fdw: Fix deparsing of remote column names in stats import.

build_remattrmap() deparses a list of remote column names for a query
that retrieves attribute stats for them from the remote server.
Previously, it did so by using the array-literal syntax with each column
name individually quoted by quote_identifier(), causing the query to
fail on the remote server with a syntax error or no results when that
column name included a single quote or backslash, as quote_identifier()
doesn't escape those characters, making the query invalid or incorrect.
Fix by switching from the array-literal syntax to the ARRAY constructor
syntax with each column name individually quoted by
deparseStringLiteral().

Oversight in commit 28972b6fc.

Reported-by: Satya Narlapuram <satyanarlapuram@gmail.com>
Reported-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Reviewed-by: Alex Guo <guo.alex.hengchen@gmail.com>
Reviewed-by: Zhenwei Shang <a934172442@gmail.com>
Reviewed-by: Etsuro Fujita <etsuro.fujita@gmail.com>
Discussion: https://postgr.es/m/CAHg%2BQDc9%3DWtYi%3DJW6QUL6ASOJc6PcGPTuxoMkhnkQ7oi7j5atg%40mail.gmail.com
Discussion: https://postgr.es/m/CAJTYsWWGhVDFjr%2BsmdYdU-Q_TT9YMzXA4QcLCr7rizDOyrEEow%40mail.gmail.com

8 days agoFix jsonpath .split_part() to honor silent mode
Michael Paquier [Thu, 14 May 2026 07:02:07 +0000 (16:02 +0900)] 
Fix jsonpath .split_part() to honor silent mode

The jsonpath .split_part() method passed its field-position argument
through numeric_int4(), that can fail hard if called directly.

This commit switches the code to use numeric_int4_safe() with an error
context for soft reporting, so as the overflow and zero field-position
cases can be handled in silent mode.

Oversight in bd4f879a9cdd.

Author:  Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Nazir Bilal Yavuz <byavuz81@gmail.com>
Discussion: https://postgr.es/m/FCF996D0-580B-431C-8DE1-A540C58E444C@gmail.com

9 days agopgbench: fix verbose error message corruption with multiple threads
Fujii Masao [Thu, 14 May 2026 03:30:34 +0000 (12:30 +0900)] 
pgbench: fix verbose error message corruption with multiple threads

When pgbench runs with multiple threads and verbose error reporting is
enabled (--verbose-errors), multiple clients can build verbose error
messages concurrently. Previously, a function-local static
PQExpBuffer was used for these messages, causing the buffer to be
shared across threads. This was not thread-safe and could result in
corrupted or incorrect log output.

Fix this by using a local PQExpBufferData instead of a static buffer.
This keeps verbose error messages correct during concurrent execution.

Backpatch to v15, where this issue was introduced.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Alex Guo <guo.alex.hengchen@gmail.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/CAHGQGwER1AjGXpkKB9t9820NBhMQ_Ghv7=HsKeodUr3=SZsF4g@mail.gmail.com
Backpatch-through: 15

9 days agoAdd several commits to .git-blame-ignore-revs.
Nathan Bossart [Wed, 13 May 2026 19:53:48 +0000 (14:53 -0500)] 
Add several commits to .git-blame-ignore-revs.

9 days agoFix style in a few REPACK ereports
Álvaro Herrera [Wed, 13 May 2026 16:28:31 +0000 (18:28 +0200)] 
Fix style in a few REPACK ereports

Use consistent "REPACK (CONCURRENTLY)" naming in errhint messages,
matching the actual command syntax and the errmsg text used elsewhere
in the same file.  Also improve the ereport() after XLogReadRecord
failure to be like others in the tree.

While at it, remove direct mentions of the DDL in the translatable
strings, both in the same errhint() calls as well as some errmsg()
calls.  Add periods where missing.

There are all oversights in 28d534e2ae0a.

Reported-by: Baji Shaik <baji.pgdev@gmail.com>
Discussion: https://postgr.es/m/CA+fm-RPxX1xTcYY4qQGPRDXB2-Fy2SDNdZi=zVjr0j=MPg2PaA@mail.gmail.com

9 days agoUse "grep -E" not "egrep".
Tom Lane [Wed, 13 May 2026 16:07:19 +0000 (12:07 -0400)] 
Use "grep -E" not "egrep".

"egrep" has never been in POSIX; the standard way to access this
functionality is "grep -E".  Recent versions of GNU grep have
started to warn about this, so stop using "egrep".

This could be back-patched, but I see little need to do so
because the affected places are not code that runs during
normal builds.  (Perhaps src/backend/port/aix/mkldexport.sh
is an exception, but let's wait to see if any AIX users
complain before touching that.)

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

9 days agoPre-beta updates: run src/tools/copyright.pl.
Tom Lane [Wed, 13 May 2026 15:01:57 +0000 (11:01 -0400)] 
Pre-beta updates: run src/tools/copyright.pl.

As usual, post-1-Jan patches missed some copyright-year updates.

9 days agoDo pre-release housekeeping on catalog data.
Tom Lane [Wed, 13 May 2026 14:54:44 +0000 (10:54 -0400)] 
Do pre-release housekeeping on catalog data.

Run renumber_oids.pl to move high-numbered OIDs down, as per pre-beta
tasks specified by RELEASE_CHANGES.  For reference, the command was

./renumber_oids.pl --first-mapped-oid 8000 --target-oid 6400

(but there were already some used OIDs at 6400, so the first one
actually assigned was 6434).

9 days agoAdd preceding commits to .git-blame-ignore-revs.
Tom Lane [Wed, 13 May 2026 14:44:36 +0000 (10:44 -0400)] 
Add preceding commits to .git-blame-ignore-revs.

9 days agoPre-beta mechanical code beautification, step 3: run reformat-dat-files.
Tom Lane [Wed, 13 May 2026 14:41:33 +0000 (10:41 -0400)] 
Pre-beta mechanical code beautification, step 3: run reformat-dat-files.

9 days agoPre-beta mechanical code beautification, step 2: run pgperltidy.
Tom Lane [Wed, 13 May 2026 14:37:42 +0000 (10:37 -0400)] 
Pre-beta mechanical code beautification, step 2: run pgperltidy.

It's as opinionated as ever.

9 days agoPre-beta mechanical code beautification, step 1: run pgindent.
Tom Lane [Wed, 13 May 2026 14:34:17 +0000 (10:34 -0400)] 
Pre-beta mechanical code beautification, step 1: run pgindent.

Update typedefs.list from the buildfarm, and run pgindent.
The changes from the new typedefs list are pretty minimal,
since we'd been pretty good (not perfect) about updating
typedefs.list by hand.  But the pgindent behavior changes
installed by a3e6beba6b518ba4af, and 60f9467c3 add up
to make this a relatively sizable diff.

9 days agopgindent: improve formatting of multiline comments.
Tom Lane [Wed, 13 May 2026 14:21:54 +0000 (10:21 -0400)] 
pgindent: improve formatting of multiline comments.

Enforce this standard formatting of multiline comments that start
in column 1:

/*
 * line 1
 * line 2
 */

Unlike indented comments, we don't reconsider line breaks, except
for forcing the initial /* and trailing */ onto their own lines.
We do make each line start with " *", with some whitespace following.

We preserve pgindent's existing behavior of not touching comments
that begin with /**... or /*-...  Also, if the first line looks like
/* === or /* ---, we don't split that line; similarly for the last
line.

The vast majority of multiline comments in our tree already look
like this, but this change will clean up some stragglers.

Author: Aleksander Alekseev <aleksander@tigerdata.com>
Reported-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Arseniy Mukhin <arseniy.mukhin.dev@gmail.com>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAJ7c6TPQ0kkHQG-AqeAJ3PV_YtmDzcc7s%2B_V4%3Dt%2BxgSnZm1cFw%40mail.gmail.com
Discussion: https://postgr.es/m/EB0141C5-ACC2-4F0B-85EA-0E3AFBCE322F@umbc.edu

9 days agoMake pg_bsd_indent add a space between comma and period.
Tom Lane [Wed, 13 May 2026 14:17:57 +0000 (10:17 -0400)] 
Make pg_bsd_indent add a space between comma and period.

Formatting of variadic functions and struct literals with named fields
used to be ugly due to pg_bsd_indent treating period as always being a
binary operator.  After a comma, it's not that, so insert a space.

Bump pg_bsd_indent's version so that people who use out-of-tree
copies will know they need to update.  (This also covers the other
pg_bsd_indent behavioral change introduced in a3e6beba6.)

Author: Andreas Karlsson <andreas@proxel.se>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/c3327be8-09e2-46a1-88b4-228a339d6916@proxel.se

9 days agopgindent: Fix spacing after != when member name matches typedef.
Nathan Bossart [Wed, 13 May 2026 14:10:50 +0000 (09:10 -0500)] 
pgindent: Fix spacing after != when member name matches typedef.

When a struct member name matches a registered typedef, pgindent
removes the space after "!=" (and some other operators), like so:

    entry->dsh.dsa_handle !=DSA_HANDLE_INVALID

The problem is that the related code in lexi.c sets last_u_d to
true before jumping to found_typename, causing the next operator to
be classified as unary and suppressing the following space.  This
is correct for type names, but not for struct members.  For
example, "Datum *x" needs "*" to be unary to suppress the space
before "x".  To fix, only set last_u_d before jumping to
found_typename if the typedef name doesn't appear after "." or
"->".

Note that this does not bump INDENT_VERSION.  We'll do that just
once after some other changes to pg_bsd_indent are committed.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/aS9hkwnkWf3dZIA_%40nathan

9 days agoFix FOR PORTION OF with non-updatable view columns
Peter Eisentraut [Wed, 13 May 2026 11:34:09 +0000 (13:34 +0200)] 
Fix FOR PORTION OF with non-updatable view columns

Both UPDATE and DELETE were failing to test that the application-time
column was updatable.  The column is not part of
perminfo->updatedCols, because it should not be checked for
permissions.  And it needs to be checked in the DELETE case as well,
since we might insert leftovers with a value for that column.

Author: Paul A. Jungwirth <pj@illuminatedcomputing.com>
Co-authored-by: jian he <jian.universality@gmail.com>
Discussion: https://www.postgresql.org/message-id/CACJufxFRqg8%3DgbZ-Q6ZS_UQ%2BYdwfZpk%2B9rf7jgWrk8m4RMUm%3DA%40mail.gmail.com

9 days agopg_stat_statements: Set PlannedStmt to NULL after nested utility execution
Michael Paquier [Wed, 13 May 2026 06:39:44 +0000 (15:39 +0900)] 
pg_stat_statements: Set PlannedStmt to NULL after nested utility execution

As mentioned in 8268e41aca23, pgss_ProcessUtility() may free the
PlannedStmt after an internal ROLLBACK.  This commit sets the
PlannedStmt "pstmt" to NULL once it is no longer safe to rely on it,
making bugs similar to the one fixed by the previous commit easier to
detect.

Suggested-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/0A9A8DAC-BC3C-4C7A-9504-2C6050405544@anarazel.de

10 days agoAdd more tests for corrupted data with pglz_decompress()
Michael Paquier [Wed, 13 May 2026 05:43:42 +0000 (14:43 +0900)] 
Add more tests for corrupted data with pglz_decompress()

Two cases fixed by 2b5ba2a0a141 were not covered, to emulate the
handling of corrupted data, for:
- set control bit with a valid 2-byte match tag where offset is 0.
- set control bit with a valid 2-byte match tag where offset exceeds
output written.

Oversight in 67d318e70402.

Reviewed-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Discussion: https://postgr.es/m/agF4xkIdRcrCIprs@paquier.xyz
Backpatch-through: 14

10 days agoFix stale COPY progress during logical replication table sync
Fujii Masao [Wed, 13 May 2026 02:44:31 +0000 (11:44 +0900)] 
Fix stale COPY progress during logical replication table sync

Previously, pg_stat_progress_copy in the subscriber could continue to show
the initial COPY operation for logical replication table synchronization as
active even after the data copy had finished. The stale progress entry
remained visible until synchronization caught up with the publisher.

This happened because the table synchronization code called BeginCopyFrom()
and CopyFrom(), but failed to call EndCopyFrom() afterward.

This commit fixes the issue by adding the missing EndCopyFrom() call so that
the COPY progress state in the subscriber is cleared as soon as the initial
data copy completes.

Backpatch to all supported branches.

Author: Shinya Kato <shinya11.kato@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: ChangAo Chen <cca5507@qq.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/CAOzEurQKuy3RiPkd=25PEwEzaqHuGvEOf=X7vaVzhgNjaukYzA@mail.gmail.com
Backpatch-through: 14

10 days agopsql: save/restore truePrint/falsePrint printQueryOpt values
Bruce Momjian [Tue, 12 May 2026 22:28:20 +0000 (18:28 -0400)] 
psql:  save/restore truePrint/falsePrint printQueryOpt values

Reported-by: a.kozhemyakin
Author: David G. Johnston

Discussion: https://postgr.es/m/83e247ed-0b2d-4aba-bc42-e7bbc20be0d6@postgrespro.ru

10 days agodoc PG 19 relnotes: add two optimizer hooks
Bruce Momjian [Tue, 12 May 2026 20:16:14 +0000 (16:16 -0400)] 
doc PG 19 relnotes:  add two optimizer hooks

Reported-by: Jian He
Discussion: https://postgr.es/m/CACJufxE8Ew_DCXtd1VZSC=pNPHqZRa4RJkbCr7z6ZPJJ3o3hGQ@mail.gmail.com

10 days agoDe-obfuscate the comment in tsrank.c's calc_rank_or().
Tom Lane [Tue, 12 May 2026 19:04:42 +0000 (15:04 -0400)] 
De-obfuscate the comment in tsrank.c's calc_rank_or().

Oleg's original comment was intelligible only to him.
Aleksander has reverse-engineered what seems like a plausible
explanation of what the code is trying to do, so replace the
comment with that.  (Also, re-order the final expression to
match the new comment.)

In passing, this makes the comment satisfy our usual formatting
conventions.  pgindent has let it pass as-is so far, but planned
changes would mess it up without some sort of intervention.

Author: Aleksander Alekseev <aleksander@tigerdata.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAJ7c6TO0xvunpeOv89i1eKQBhKF9=GEETkTz+yAGs1xGYH25MQ@mail.gmail.com

10 days agodoc PG 19 relnotes: remove "Optionally" for CPU optimizations
Bruce Momjian [Tue, 12 May 2026 19:13:46 +0000 (15:13 -0400)] 
doc PG 19 relnotes:  remove "Optionally" for CPU optimizations

Reported-by: John Naylor
Discussion: https://postgr.es/m/CANWCAZZWfdoMcemSaTMon+e6aCkSABN3+sco0aStC90cFPVE4A@mail.gmail.com

10 days agoAdd psql tab completion for FOR PORTION OF clause
Peter Eisentraut [Tue, 12 May 2026 15:19:15 +0000 (17:19 +0200)] 
Add psql tab completion for FOR PORTION OF clause

Add tab completion support in psql for the FOR PORTION OF clause
used in UPDATE and DELETE statements with temporal tables.

For both UPDATE and DELETE, completion now guides users through:
  <table> FOR -> PORTION -> OF -> <column> -> FROM

Author: Kiran Kaki <itskkpg@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/CAD0dvCQLqLzPrQJRjjA2qXDH%3DD%2BXShcxhbSPxNhVruC8HGhkbQ%40mail.gmail.com

11 days agopg_stat_statements: Fix potential use-after-free of PlannedStmt
Michael Paquier [Tue, 12 May 2026 04:36:38 +0000 (13:36 +0900)] 
pg_stat_statements: Fix potential use-after-free of PlannedStmt

pgss_ProcessUtility() included a reference to a portion of a PlannedStmt
after the point where this data's structure could have been freed,
causing an incorrect memory access.  There was a comment documenting
this requirement, missed in 3357471cf9f5.

This commit includes a test able to make valgrind complain with a
PlannedStmt freed by an internal ROLLBACK query.  Similarly to what is
mentioned in 495e73c2079e, this can be triggered by using the extended
query protocol, something that can be now tested thanks to the recent
meta-command additions in psql.  This commit mentions potential other
cases, but as far as I can see the extended protocol case with an
internal ROLLBACK is the only problematic pattern reachable in practice.

Issue introduced by 3357471cf9f5, gone unnoticed due to a lack of test
coverage.  The fix is authored by Chao, my contribution being the new
test.

Author: Chao Li <li.evan.chao@gmail.com>
Co-authored-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/2F91906A-F2B5-4A6B-9695-D136957D4545@gmail.com

11 days agodoc PG 19 relnotes: adjustments/removal of items
Bruce Momjian [Mon, 11 May 2026 21:43:15 +0000 (17:43 -0400)] 
doc PG 19 relnotes:  adjustments/removal of items

Reported-by: John Naylor
Discussion: https://postgr.es/m/CANWCAZZWfdoMcemSaTMon+e6aCkSABN3+sco0aStC90cFPVE4A@mail.gmail.com

11 days agoUse palloc_array() in a few more places to avoid overflow
Heikki Linnakangas [Mon, 11 May 2026 18:18:06 +0000 (21:18 +0300)] 
Use palloc_array() in a few more places to avoid overflow

These could overflow on 32-bit systems.

Backpatch-through: 14
Security: CVE-2026-6473

11 days agoFix REPACK with WITHOUT OVERLAPS replica identity indexes
Álvaro Herrera [Mon, 11 May 2026 16:17:46 +0000 (18:17 +0200)] 
Fix REPACK with WITHOUT OVERLAPS replica identity indexes

REPACK replay builds scan keys for the replica identity index, but it
hard-coded BTEqualStrategyNumber when looking up the equality operator.
That is not correct for non-btree identity indexes, such as the GiST
indexes created for WITHOUT OVERLAPS primary keys.  In addition,
find_target_tuple() accepted the first tuple returned by the identity
index scan, which is unsafe for lossy index scans because the index AM may
return false positives with xs_recheck set.

Fix this by using IndexAmTranslateCompareType() to translate COMPARE_EQ
to the equality strategy number for the index AM, and by continuing the
scan when recheck is required until a candidate tuple matches the locator
tuple on all replica identity key columns.

The recheck uses the same equality operator functions as the identity
index scan keys, preserving ScanKey argument ordering.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/7B0EC0EC-5461-41EF-9B31-F9BBE608DEA5@gmail.com

11 days agoRemove test cases for field overflows in intarray and ltree.
Tom Lane [Mon, 11 May 2026 16:12:03 +0000 (12:12 -0400)] 
Remove test cases for field overflows in intarray and ltree.

These checks are failing in the buildfarm, reporting stack overflows
rather than the expected errors, though seemingly only on ppc64 and
s390x platforms.  Perhaps there is something off about our tests
for stack depth on those architectures?  But there's no time to
debug that right now, and surely these tests aren't too essential.
Revert for now and plan to revisit after the release dust settles.

Backpatch-through: 14
Security: CVE-2026-6473

11 days agorefint: Fix SQL injection and buffer overruns.
Nathan Bossart [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
refint: Fix SQL injection and buffer overruns.

Maliciously crafted key value updates could achieve SQL injection
within check_foreign_key().  To fix, ensure new key values are
properly quoted and escaped in the internally generated SQL
statements.  While at it, avoid potential buffer overruns by
replacing the stack buffers for internally generated SQL statements
with StringInfo.

Reported-by: Nikolay Samokhvalov <nik@postgres.ai>
Author: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Noah Misch <noah@leadboat.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Security: CVE-2026-6637
Backpatch-through: 14

11 days agoMark PQfn() unsafe and fix overrun in frontend LO interface.
Nathan Bossart [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
Mark PQfn() unsafe and fix overrun in frontend LO interface.

When result_is_int is set to 0, PQfn() cannot validate that the
result fits in result_buf, so it will write data beyond the end of
the buffer when the server returns more data than requested.  Since
this function is insecurable and obsolete, add a warning to the top
of the pertinent documentation advising against its use.

The only in-tree caller of PQfn() is the frontend large object
interface.  To fix that, add a buf_size parameter to
pqFunctionCall3() that is used to protect against overruns, and use
it in a private version of PQfn() that also accepts a buf_size
parameter.

Reported-by: Yu Kunpeng <yu443940816@live.com>
Reported-by: Martin Heistermann <martin.heistermann@unibe.ch>
Author: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Noah Misch <noah@leadboat.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Etsuro Fujita <etsuro.fujita@gmail.com>
Security: CVE-2026-6477
Backpatch-through: 14

11 days agoFix integer overflow in array_agg(), when the array grows too large
Heikki Linnakangas [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
Fix integer overflow in array_agg(), when the array grows too large

If you accumulate many arrays full of NULLs, you could overflow
'nitems', before reaching the MaxAllocSize limit on the allocations.
Add an explicit check that the number of items doesn't grow too large.
With more than MaxArraySize items, getting the final result with
makeArrayResultArr() would fail anyway, so better to error out early.

Reported-by: Xint Code
Author: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoFix integer-overflow and alignment hazards in locale-related code.
Tom Lane [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
Fix integer-overflow and alignment hazards in locale-related code.

pg_locale_icu.c was full of places where a very long input string
could cause integer overflow while calculating a buffer size,
leading to buffer overruns.

It also was cavalier about using char-type local arrays as buffers
holding arrays of UChar.  The alignment of a char[] variable isn't
guaranteed, so that this risked failure on alignment-picky platforms.
The lack of complaints suggests that such platforms are very rare
nowadays; but it's likely that we are paying a performance price on
rather more platforms.  Declare those arrays as UChar[] instead,
keeping their physical size the same.

pg_locale_libc.c's strncoll_libc_win32_utf8() also had the
disease of assuming it could double or quadruple the input
string length without concern for overflow.

Reported-by: Xint Code
Reported-by: Pavel Kohout <pavel.kohout@aisle.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoPrevent path traversal in pg_basebackup and pg_rewind
Michael Paquier [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
Prevent path traversal in pg_basebackup and pg_rewind

pg_rewind and pg_basebackup could be fed paths from rogue endpoints that
could overwrite the contents of the client when received, achieving path
traversal.

There were two areas in the tree that were sensitive to this problem:
- pg_basebackup, through the astreamer code, where no validation was
performed before building an output path when streaming tar data.  This
is an issue in v15 and newer versions.
- pg_rewind file operations for paths received through libpq, for all
the stable branches supported.

In order to address this problem, this commit adds a helper function in
path.c, that reuses path_is_relative_and_below_cwd() after applying
canonicalize_path().  This can be used to validate the paths received
from a connection point.  A path is considered invalid if any of the two
following conditions is satisfied:
- The path is absolute.
- The path includes a direct parent-directory reference.

Reported-by: XlabAI Team of Tencent Xuanwu Lab
Reported-by: Valery Gubanov <valerygubanov95@gmail.com>
Author: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Backpatch-through: 14
Security: CVE-2026-6475

11 days agoAvoid overflow in size calculations in formatting.c.
Nathan Bossart [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
Avoid overflow in size calculations in formatting.c.

A few functions in this file were incautious about multiplying a
possibly large integer by a factor more than 1 and then using it as
an allocation size.  This is harmless on 64-bit systems where we'd
compute a size exceeding MaxAllocSize and then fail, but on 32-bit
systems we could overflow size_t, leading to an undersized
allocation and buffer overrun.  To fix, use palloc_array() or
mul_size() instead of handwritten multiplication.

Reported-by: Sven Klemm <sven@tigerdata.com>
Reported-by: Xint Code
Author: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Tatsuo Ishii <ishii@postgresql.org>
Security: CVE-2026-6473
Backpatch-through: 14

11 days agoCheck CREATE privilege on multirange type schema in CREATE TYPE.
Nathan Bossart [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
Check CREATE privilege on multirange type schema in CREATE TYPE.

This omission allowed roles to create multirange types in any
schema, potentially leading to privilege escalations.  Note that
when a multirange type name is not specified in CREATE TYPE, it is
automatically placed in the range type's schema, which is checked
at the beginning of DefineRange().

Reported-by: Jelte Fennema-Nio <postgres@jeltef.nl>
Author: Jelte Fennema-Nio <postgres@jeltef.nl>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Tomas Vondra <tomas@vondra.me>
Security: CVE-2026-6472
Backpatch-through: 14

11 days agopg_createsubscriber: Obstruct SQL injection via subscription names.
Nathan Bossart [Mon, 11 May 2026 12:13:47 +0000 (05:13 -0700)] 
pg_createsubscriber: Obstruct SQL injection via subscription names.

drop_existing_subscription() neglected to escape the subscription
name when generating its query string.  To fix, use
PQescapeIdentifier() to construct a properly escaped name, and use
it in the ALTER SUBSCRIPTION and DROP SUBSCRIPTION commands.

Reported-by: Yu Kunpeng <yu443940816@live.com>
Author: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Security: CVE-2026-6476
Backpatch-through: 17

11 days agoFix MCV input array checks in statistics restore functions
Michael Paquier [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Fix MCV input array checks in statistics restore functions

The SQL functions for the restore of attribute and expression statistics
accept "most_common_vals" and "most_common_freqs" as independent arrays.
The planner assumes these have the same number of elements, but it was
possible to insert in the catalogs data that would cause an over-read
when the catalog data is loaded in the planner.

There were two holes in the stats restore logic:
- Both arrays should match in size.
- The input array must be one-dimensional, and it should match with what
is delivered by pg_dump when scanning the pg_stats catalogs.

The multivariate extended statistics MCV path (import_mcv) already
validated these inputs via check_mcvlist_array(), and is not affected.
These problems exist in v18 and newer versions for the restore of
attribute statistics.  These problems affect only HEAD for the restore
of the expression statistics.

Reported-by: Jeroen Gui <jeroen.gui1@proton.me>
Author: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Amit Langote <amitlangote09@gmail.com>
Reviewed-by: John Naylor <johncnaylorls@gmail.com>
Security: CVE-2026-6575
Backpatch-through: 18

11 days agoGuard against unsafe conditions in usage of pg_strftime().
Tom Lane [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Guard against unsafe conditions in usage of pg_strftime().

Although pg_strftime() has defined error conditions, no callers bother
to check for errors.  This is problematic because the output string is
very likely not null-terminated if an error occurs, so that blindly
using it is unsafe.  Rather than trusting that we can find and fix all
the callers, let's alter the function's API spec slightly: make it
guarantee a null-terminated result so long as maxsize > 0.

Furthermore, if we do get an error, let's make that null-terminated
result be an empty string.  We could instead truncate at the buffer
length, but that risks producing mis-encoded output if the tz_name
string contains multibyte characters.  It doesn't seem reasonable for
src/timezone/ to make use of our encoding-aware truncation logic.
Also, the only really likely source of a failure is a user-supplied
timezone name that is intentionally trying to overrun our buffers.
I don't feel a need to be particularly friendly about that case.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: John Naylor <johncnaylorls@gmail.com>
Backpatch-through: 14
Security: CVE-2026-6474

11 days agoAvoid passing unintended format codes to snprintf().
Tom Lane [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Avoid passing unintended format codes to snprintf().

timeofday() assumed that the output of pg_strftime() could not contain
% signs, other than the one it explicitly asks for with %%.  However,
we don't have that guarantee with respect to the time zone name (%Z).
A crafted time zone setting could abuse the subsequent snprintf()
call, resulting in crashes or disclosure of server memory.

To fix, split the pg_strftime() call into two and then treat the
outputs as literal strings, not a snprintf format string.  The
extra pg_strftime() call doesn't really cost anything, since the
bulk of the conversion work was done by pg_localtime().

Also, adjust buffer widths so that we're not risking string truncation
during the snprintf() step, as that would create a hazard of producing
mis-encoded output.

This also fixes a latent portability issue: the format string expects
an int, but tp.tv_usec is long int on many platforms.

Reported-by: Xint Code
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: John Naylor <johncnaylorls@gmail.com>
Backpatch-through: 14
Security: CVE-2026-6474

11 days agoFix SQL injection in logical replication origin checks.
Noah Misch [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Fix SQL injection in logical replication origin checks.

ALTER SUBSCRIPTION ... REFRESH PUBLICATION interpolates schema and
relation names into SQL without quoting them.  A crafted subscriber
relation name can inject arbitrary SQL on the publisher.  Test such a
name.  Back-patch to v16, where commit
875693019053b8897ec3983e292acbb439b088c3 first appeared.

Reported-by: Pavel Kohout <pavel.kohout@aisle.com>
Author: Pavel Kohout <pavel.kohout@aisle.com>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Backpatch-through: 16
Security: CVE-2026-6638

11 days agoApply timingsafe_bcmp() in authentication paths
Michael Paquier [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Apply timingsafe_bcmp() in authentication paths

This commit applies timingsafe_bcmp() to authentication paths that
handle attributes or data previously compared with memcpy() or strcmp(),
which are sensitive to timing attacks.

The following data is concerned by this change, some being in the
backend and some in the frontend:
- For a SCRAM or MD5 password, the computed key or the MD5 hash compared
with a password during a plain authentication.
- For a SCRAM exchange, the stored key, the client's final nonce and the
server nonce.
- RADIUS (up to v18), the encrypted password.
- For MD5 authentication, the MD5(MD5()) hash.

Reported-by: Joe Conway <mail@joeconway.com>
Security: CVE-2026-6478
Author: Michael Paquier <michael@paquier.xyz>
Reviewed-by: John Naylor <johncnaylorls@gmail.com>
Backpatch-through: 14

11 days agoGuard against overflow in "left" fields of query_int and ltxtquery.
Tom Lane [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Guard against overflow in "left" fields of query_int and ltxtquery.

contrib/intarray's query_int type uses an int16 field to hold the
offset from a binary operator node to its left operand.  However, it
allows the number of nodes to be as much as will fit in MaxAllocSize,
so there is a risk of overflowing int16 depending on the precise shape
of the tree.  Simple right-associative cases like "a | b | c | ..."
work fine, so we should not solve this by restricting the overall
number of nodes.  Instead add a direct test of whether each individual
offset is too large.

contrib/ltree's ltxtquery type uses essentially the same logic and
has the same 16-bit restriction.

(The core backend's tsquery.c has a variant of this logic too, but
in that case the target field is 32 bits, so it is okay so long
as varlena datums are restricted to 1GB.)

In v16 and up, these types support soft error reporting, so we have
to complicate the recursive findoprnd function's API a bit to allow
the complaint to be reported softly.  v14/v15 don't need that.

Undocumented and overcomplicated code like this makes my head hurt,
so add some comments and simplify while at it.

Reported-by: Xint Code
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoFix unbounded recursive handling of SSL/GSS in ProcessStartupPacket()
Michael Paquier [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Fix unbounded recursive handling of SSL/GSS in ProcessStartupPacket()

The handling of SSL and GSS negotiation messages in
ProcessStartupPacket() could cause a recursion of the backend,
ultimately crashing the server as the negotiation attempts were not
tracked across multiple calls processing startup packets.

A malicious client could therefore alternate rejected SSL and GSS
requests indefinitely, each adding a stack frame, until the backend
crashed with a stack overflow, taking down a server.

This commit addresses this issue by modifying ProcessStartupPacket() so
as processed negotiation attempts are tracked, preventing infinite
recursive attempts.  A TAP test is added to check this problem, where
multiple SSL and GSS negotiated attempts are stacked.

Reported-by: Calif.io in collaboration with Claude and Anthropic
Research
Author: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Security: CVE-2026-6479
Backpatch-through: 14

11 days agoFix assorted places that need to use palloc_array().
Tom Lane [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Fix assorted places that need to use palloc_array().

multirange_recv and BlockRefTableReaderNextRelation were incautious
about multiplying a possibly-large integer by a factor more than 1
and then using it as an allocation size.  This is harmless on 64-bit
systems where we'd compute a size exceeding MaxAllocSize and then
fail, but on 32-bit systems we could overflow size_t leading to an
undersized allocation and buffer overrun.

Fix these places by using palloc_array() instead of a handwritten
multiplication.  (In HEAD, some of them were fixed already, but
none of that work got back-patched at the time.)

In addition, BlockRefTableReaderNextRelation passes the same value
to BlockRefTableRead's "int length" parameter.  If built for
64-bit frontend code, palloc_array() allows a larger array size
than it otherwise would, potentially allowing that parameter to
overflow.  Add an explicit check to forestall that and keep the
behavior the same cross-platform.

Reported-by: Xint Code
Author: Tom Lane <tgl@sss.pgh.pa.us>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoPrevent buffer overrun in unicode_normalize().
Tom Lane [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Prevent buffer overrun in unicode_normalize().

Some UTF8 characters decompose to more than a dozen codepoints.
It is possible for an input string that fits into well under
1GB to produce more than 4G decomposed codepoints, causing
unicode_normalize()'s decomp_size variable to wrap around to a
small positive value.  This results in a small output buffer
allocation and subsequent buffer overrun.

To fix, test after each addition to see if we've overrun MaxAllocSize,
and break out of the loop early if so.  In frontend code we want to
just return NULL for this failure (treating it like OOM).  In the
backend, we can rely on the following palloc() call to throw error.

I also tightened things up in the calling functions in varlena.c,
using size_t rather than int and allocating the input workspace
with palloc_array().  These changes are probably unnecessary
given the knowledge that the original input and the normalized
output_chars array must fit into 1GB, but it's a lot easier to
believe the code is safe with these changes.

Reported-by: Xint Code
Reported-by: Bruce Dang <bruce@calif.io>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Co-authored-by: Heikki Linnakangas <hlinnaka@iki.fi>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoHarden our regex engine against integer overflow in size calculations.
Tom Lane [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Harden our regex engine against integer overflow in size calculations.

The number of NFA states, number of NFA arcs, and number of colors
are all bounded to reasonably small values.  However, there are
places where we try to allocate arrays sized by products of those
quantities, and those calculations could overflow, enabling
buffer-overrun attacks.  In practice there's no problem on 64-bit
machines, but there are some live scenarios on 32-bit machines.

A related problem is that citerdissect() and creviterdissect()
allocate arrays based on the length of the input string, which
potentially could overflow.

To fix, invent MALLOC_ARRAY and REALLOC_ARRAY macros that rely on
palloc_array_extended and repalloc_array_extended with the NO_OOM
option, similarly to the existing MALLOC and REALLOC macros.
(Like those, they'll throw an error not return a NULL result for
oversize requests.  This doesn't really fit into the regex code's
view of error handling, but it'll do for now.  We can consider
whether to change that behavior in a non-security follow-up patch.)

I installed similar defenses in the colormap construction code.
It's not entirely clear whether integer overflow is possible
there, but analyzing the behavior in detail seems not worth
the trouble, as the risky spots are not in hot code paths.

I left a bunch of calls as-is after verifying that they can't
overflow given reasonable limits on nstates and narcs.  Those
limits were enforced already via REG_MAX_COMPILE_SPACE, but
add commentary to document the interactions.

In passing, also fix a related edge case, which is that the
special color numbers used in LACON carcs could overflow the
"color" data type, if ncolors is close to MAX_COLOR.

In v14 and v15, the regex engine calls malloc() directly instead
of using palloc(), so MALLOC_ARRAY and REALLOC_ARRAY do likewise.

Reported-by: Xint Code
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoMake palloc_array() and friends safe against integer overflow.
Tom Lane [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Make palloc_array() and friends safe against integer overflow.

Sufficiently large "count" arguments could result in undetected
overflow, causing the allocated memory chunk to be much smaller
than what the caller will subsequently write into it.  This is
unlikely to be a hazard with 64-bit size_t but can sometimes
happen on 32-bit builds, primarily where a function allocates
workspace that's significantly larger than its input data.
Rather than trying to patch the at-risk callers piecemeal,
let's just redefine these macros so that they always check.

To do that, move the longstanding add_size() and mul_size() functions
into palloc.h and mcxt.c, and adjust them to not be specific to
shared-memory allocation.  Then invent palloc_mul(), palloc0_mul(),
palloc_mul_extended() to use these functions.  Actually, the latter
use inlined copies to save one function call.  repalloc_array() gets
similar treatment.  I didn't bother trying to inline the calls for
repalloc0_array() though.

In v14 and v15, this also adds repalloc_extended(), which previously
was only available in v16 and up.

We need copies of all this in fe_memutils.[hc] as well, since that
module also provides palloc_array() etc.

Reported-by: Xint Code
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoFix overflows with ts_headline()
Michael Paquier [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
Fix overflows with ts_headline()

The options "StartSel", "StopSel" and "FragmentDelimiter" given by a
caller of the SQL function ts_headline() have their lengths stored as
int16.  When providing values larger than PG_INT16_MAX, it was possible
to overflow the length values stored, leading to incorrect behaviors in
generateHeadline(), in most cases translating to a crash.

Attempting to use values for these options larger than PG_INT16_MAX is
now blocked.  Some test cases are added to cover our tracks.

Reported-by: Xint Code
Author: Michael Paquier <michael@paquier.xyz>
Backpatch-through: 14
Security: CVE-2026-6473

11 days agoltree: Fix overflows with lquery parsing
Michael Paquier [Mon, 11 May 2026 12:13:46 +0000 (05:13 -0700)] 
ltree: Fix overflows with lquery parsing

The lquery parser in contrib/ltree/ had two overflow problems:
- A single lquery level with many OR-separated variants (e.g.,
'label1|label2|...'), could cause an overflow of totallen, this being
stored as a uint16, meaning a maximum value of UINT16_MAX or 65k.  Each
variant contributes MAXALIGN(LVAR_HDRSIZE + len) bytes.  With enough
long variants, the value would wraparound.  This would corrupt the data
written by LQL_NEXT(), leading to a stack corruption, most likely
translating into a crash, but it would allow incorrect memory access.
- numvar, labelled as a uint16, counts the number of OR-variants in a
single level, and it is incremented without bounds checking.  With more
than PG_UINT16_MAX (65k) variants in a single level, and a minimum of
131kB of input data, it would wrap to 0.  When a (wildcard) '*' is
used, this would change the query results silently.

For both issues, a set of overflows checks are added to guard against
these problematic patterns.

The first issue has been reported by the three people listed below,
affecting v16 and newer versions due to b1665bf01e5f.  Its coding was
still unsafe in v14 and v15.  The second issue affects all the stable
branches; I have bumped into while reviewing the code of the module.

Reported-by: Vergissmeinnicht <vergissmeinnichtzh@gmail.com>
Reported-by: A1ex <alex000young@gmail.com>
Reported-by: Jihe Wang <wangjihe.mail@gmail.com>
Author: Michael Paquier <michael@paquier.xyz>
Security: CVE-2026-6473
Backpatch-through: 14

11 days agopg_upgrade: Message improvements
Peter Eisentraut [Mon, 11 May 2026 09:38:20 +0000 (11:38 +0200)] 
pg_upgrade: Message improvements

2 weeks agoFix universal builds on MacOS
John Naylor [Fri, 8 May 2026 09:44:25 +0000 (16:44 +0700)] 
Fix universal builds on MacOS

Commit 16743db06 assumed that the CPUID instruction was always
available when the usual x86 symbols were defined. That is not the
case, so zero out the info rather than error out.

Reported-by: Jakob Egger <jakob@eggerapps.at>
Reported-by: Tobias Bussmann <t.bussmann@gmx.net>
Suggested-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/223EA201-A0E8-4A13-B220-EB903E8DF817@eggerapps.at

2 weeks agoEnforce RETURNING typmod for empty-set JSON_ARRAY(query)
Richard Guo [Fri, 8 May 2026 08:21:48 +0000 (17:21 +0900)] 
Enforce RETURNING typmod for empty-set JSON_ARRAY(query)

Commit 8d829f5a0 introduced a COALESCE wrapper around the
JSON_ARRAYAGG subquery so that JSON_ARRAY(query) returns '[]' rather
than NULL when the subquery yields no rows, per the SQL/JSON standard.

The empty-array Const used as the COALESCE fallback was, however,
built with typmod -1 and the type input function was likewise invoked
with typmod -1.  As a result, any length restriction from the
RETURNING clause was silently bypassed on the empty-set path, while
the non-empty path enforced it via the JSON_ARRAYAGG coercion.

Build the empty-array Const using the typmod of the COALESCE's
non-empty argument, and pass that typmod to OidInputFunctionCall as
well so the value is length-checked at parse time.  This makes the
empty-set and non-empty-set paths behave consistently.

Reported-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAJTYsWXPYqa58YXrU+SQMVonsAhjLS46HNUMU=wO5zm9MgY3_g@mail.gmail.com

2 weeks agoUse schema-qualified names in EXCEPT clause error messages.
Amit Kapila [Fri, 8 May 2026 04:30:26 +0000 (10:00 +0530)] 
Use schema-qualified names in EXCEPT clause error messages.

Error messages in check_publication_add_relation() previously reported
only the relation name when a table in an EXCEPT clause could not be
processed, which is ambiguous when the same name exists in multiple
schemas. Use schema-qualified names instead, consistent with other error
messages that reference relation names.

Author: Dilip Kumar <dilipbalaut@gmail.com>
Author: vignesh C <vignesh21@gmail.com>
Reviewed-by: shveta malik <shveta.malik@gmail.com>
Reviewed-by: Euler Taveira <euler@eulerto.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Peter Smith <smithpb2250@gmail.com>
Discussion: https://postgr.es/m/CAFiTN-scG7b11Jsp+VoDRT8ZFE84eSKLcDsSB18dZ8AaP=R-mw@mail.gmail.com

2 weeks agopostgres_fdw: Fix syntax error in fetch_attstats().
Etsuro Fujita [Fri, 8 May 2026 04:15:00 +0000 (13:15 +0900)] 
postgres_fdw: Fix syntax error in fetch_attstats().

When importing remote stats for a foreign table backed by a pre-v17
remote server, the query built/executed in this function has three NULL
placeholders for the range stats supported in v17 at the end of the
SELECT list.  Previously, it included a trailing comma after the last
NULL, like "SELECT ..., NULL, NULL, NULL, FROM pg_catalog.pg_stats ...",
causing a syntax error on the remote server.  Fix by removing the comma.

Oversight in commit 28972b6fc.

Author: Satya Narlapuram <satyanarlapuram@gmail.com>
Discussion: https://postgr.es/m/CAHg%2BQDdEE7wp1S60Fn9Kmna8KfdMo5Tu6dROLpMn_-EOUBKmWQ%40mail.gmail.com

2 weeks agoConsider opfamily and collation when removing redundant GROUP BY columns
Richard Guo [Fri, 8 May 2026 03:45:51 +0000 (12:45 +0900)] 
Consider opfamily and collation when removing redundant GROUP BY columns

remove_useless_groupby_columns() uses a relation's unique indexes to
prove that some GROUP BY columns are functionally dependent on others,
and so can be dropped from the GROUP BY clause.  The match between
index columns and GROUP BY columns was done by attno alone, ignoring
two equality-relation issues.

A type may belong to multiple btree opfamilies whose notions of
equality differ.  The record type, for instance, has record_ops
(per-field equality) and record_image_ops (bytewise equality).  A
unique index under one opfamily does not prove uniqueness under the
equality used by GROUP BY when the SortGroupClause's eqop comes from a
different opfamily.

Likewise, since nondeterministic collations were introduced in PG 12,
two collations may disagree on equality, and a unique index under one
collation does not prove uniqueness under another.

In either case, rows that the index considers distinct can collapse
into a single GROUP BY group, taking ungrouped columns of differing
values with them, so the planner drops a column that is not in fact
functionally dependent and produces wrong results.

Fix by requiring, for each unique-index key column, that some GROUP BY
item on the same column has an eqop in the index's opfamily and a
collation that agrees on equality with the index's collation.  This
mirrors the combined check relation_has_unique_index_for() applies to
join clauses.

This is a v18 regression: commit bd10ec529 extended
remove_useless_groupby_columns() from primary-key constraints to
arbitrary unique indexes.  Before that, the function consulted only
primary keys, whose enforcement index is required by parse_utilcmd.c
to use the default opclass and the column's declared collation, so
neither mismatch could arise.  Back-patch to v18 only.

Author: Richard Guo <guofenglinux@gmail.com>
Reviewed-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Discussion: https://postgr.es/m/CAMbWs49t6uArWoTT-cHY+nhsi23nJJKcF9Xb9cYGzaZ9kNJ98g@mail.gmail.com
Backpatch-through: 18

2 weeks agoFix HAVING-to-WHERE pushdown for simple-CASE form
Richard Guo [Fri, 8 May 2026 01:57:50 +0000 (10:57 +0900)] 
Fix HAVING-to-WHERE pushdown for simple-CASE form

Commit f76686ce7 added a walker that detects when a HAVING clause uses
a collation that conflicts with the GROUP BY's nondeterministic
collation, keeping such clauses in HAVING.  The walker uses
exprInputCollation() to identify each ancestor's comparison collation,
but missed the simple-CASE case: parse analysis builds each WHEN as
OpExpr(CaseTestExpr op val), where CaseTestExpr is a placeholder for
the arg, while the actual arg expression sits at cexpr->arg, outside
the OpExpr that carries the comparison's inputcollid.  A GROUP Var at
cexpr->arg was therefore visited with the WHEN's inputcollid absent
from the ancestor stack, the conflict went undetected, and the clause
was wrongly pushed to WHERE.

Fix by handling simple CASE explicitly: before walking cexpr->arg,
push every WHEN's inputcollid onto the ancestor stack so a GROUP Var
at the arg is checked against the same collations the WHEN comparisons
would apply.  Then walk the WHEN bodies and defresult under the
unchanged stack, where their own collation contexts are picked up by
the default path.

Back-patch to v18 only; this fix extends the walker added by commit
f76686ce7 and inherits its dependency on the v18 RTE_GROUP mechanism.

Author: SATYANARAYANA NARLAPURAM <satyanarlapuram@gmail.com>
Reviewed-by: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAHg+QDcqPdd=2V0PQ_oNYj50OUeqSqznqFaYtP3RdokLBDXBqw@mail.gmail.com
Backpatch-through: 18

2 weeks agodoc PG 19 relnotes: add UTF-8 case folding performance item
Bruce Momjian [Fri, 8 May 2026 00:53:22 +0000 (20:53 -0400)] 
doc PG 19 relnotes:  add UTF-8 case folding performance item

Reported-by: Andreas Karlsson
Discussion: https://postgr.es/m/9dae1593-4441-4a20-a1ab-ce5018db9878@proxel.se

2 weeks agoFix use-after-free of qs in AfterTriggerEndQuery.
Amit Langote [Thu, 7 May 2026 23:26:04 +0000 (08:26 +0900)] 
Fix use-after-free of qs in AfterTriggerEndQuery.

afterTriggerInvokeEvents() may repalloc afterTriggers.query_stack
while firing trigger events, leaving any precomputed entry pointer
dangling.  The loop body in AfterTriggerEndQuery() recomputes qs
after each afterTriggerInvokeEvents() call for that reason, but the
"all fired" break path exits without the recompute, and the
subsequent FireAfterTriggerBatchCallbacks(qs->batch_callbacks)
dereferences the freed pointer.

Fix by recomputing qs immediately before
FireAfterTriggerBatchCallbacks(), as the loop body already does
after each afterTriggerInvokeEvents() call.

The hazard was introduced in 34a30786293, which added the
qs->batch_callbacks dereference at this site.

Reported-by: Amul Sul <sulamul@gmail.com>
Author: Amul Sul <sulamul@gmail.com>
Reviewed-by: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
Reviewed-by: Amit Langote <amitlangote09@gmail.com>
Discussion: https://postgr.es/m/CAAJ_b95p6-qiVpE2Gpr=bUsNAqTcejD_rPgLnfjx9m=fo3Rf3Q@mail.gmail.com

2 weeks agodoc PG 19 relnotes: correct two items
Bruce Momjian [Fri, 8 May 2026 00:21:16 +0000 (20:21 -0400)] 
doc PG 19 relnotes:  correct two items

Reported-by: jian he
Discussion: https://postgr.es/m/CACJufxG_ZTCTtFMxKiVji-s10jHt99krfH+Kn+Ww2prF=X6g6Q@mail.gmail.com

2 weeks agodoc PG 19 relnotes: add missing commits and details
Bruce Momjian [Thu, 7 May 2026 22:02:02 +0000 (18:02 -0400)] 
doc PG 19 relnotes:  add missing commits and details

Reported-by: Xuneng Zhou
Discussion: https://postgr.es/m/CABPTF7VxrFB_4Qoo2=PyrczGyq8CqOpQ5D5yye3DyxDC=so_0Q@mail.gmail.com

2 weeks agoFix race condition in XLogLogicalInfo and ProcSignal initialization.
Masahiko Sawada [Thu, 7 May 2026 17:09:42 +0000 (10:09 -0700)] 
Fix race condition in XLogLogicalInfo and ProcSignal initialization.

Previously, InitializeProcessXLogLogicalInfo() was called before
ProcSignalInit(). This created a window where a process could miss a
signal barrier if it was issued between these two calls. As a result,
the process could fail to update its local XLogLogicalInfo cache,
leading to an inconsistent logical decoding state.

This commit fixes this by moving InitializeProcessXLogLogicalInfo()
after ProcSignalInit(). This ensures that the process is registered to
participate in signal barriers before its state is initialized,
preventing it from missing any state changes propagated during the
startup sequence.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
Discussion: https://postgr.es/m/CAD21AoBzdeSyLSSPM5E6ysN1r8qzp8u_BRmnLvuAp_S8QxS_fQ@mail.gmail.com
Discussion: https://postgr.es/m/CAD21AoBj+zKvgw_Q8gjr4YbKccW_uMe3OFQ5+KT246FHUuNXSQ@mail.gmail.com

2 weeks agoRationalize error comments in partition split/merge tests
John Naylor [Thu, 7 May 2026 12:10:51 +0000 (19:10 +0700)] 
Rationalize error comments in partition split/merge tests

The regression tests had a copy of the full error, detail, and hint
text in comments above each failing statement in the .sql files. This
is a maintenance hazard, so simplify to "-- ERROR", in line with
other tests.

Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Reviewed-by: Jian He <jian.universality@gmail.com>
Discussion: https://postgr.es/m/CANWCAZap26BRLwtd+A7GFDSD6-+C3F0NVdUGUAu2LUfvpOTy=w@mail.gmail.com