postgresql.git
57 min agodoc: Add example file for COPY master github/master
Daniel Gustafsson [Wed, 16 Jul 2025 22:21:18 +0000 (00:21 +0200)]
doc: Add example file for COPY

The paragraph for introducing INSERT and COPY discussed how a file
could be used for bulk loading with COPY, without actually showing
what the file would look like.  This adds a programlisting for the
file contents.

Backpatch to all supported branches since this example has lacked
the file contents since PostgreSQL 7.2.

Author: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/158017814191.19852.15019251381150731439@wrigleys.postgresql.org
Backpatch-through: 13

2 hours agoForce LC_COLLATE to C in postmaster.
Jeff Davis [Wed, 16 Jul 2025 21:13:18 +0000 (14:13 -0700)]
Force LC_COLLATE to C in postmaster.

Avoid dependence on setlocale().

strcoll(), etc., are not called directly; all collation-sensitive
calls should go through pg_locale.c and use the appropriate
provider. By setting LC_COLLATE to C, we avoid accidentally depending
on libc behavior when using a different provider.

No behavior change in the backend, but it's possible that some
extensions will be affected. Such extensions should be updated to use
the pg_locale_t APIs.

Discussion: https://postgr.es/m/9875f7f9-50f1-4b5d-86fc-ee8b03e8c162@eisentraut.org
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
5 hours agoFix dumping of comments on invalid constraints on domains
Álvaro Herrera [Wed, 16 Jul 2025 17:22:53 +0000 (19:22 +0200)]
Fix dumping of comments on invalid constraints on domains

We skip dumping constraints together with domains if they are invalid
('separate') so that they appear after data -- but their comments were
dumped together with the domain definition, which in effect leads to the
comment being dumped when the constraint does not yet exist.  Delay
them in the same way.

Oversight in 7eca575d1c28; backpatch all the way back.

Author: jian he <jian.universality@gmail.com>
Discussion: https://postgr.es/m/CACJufxF_C2pe6J_+nPr6C5jf5rQnbYP8XOKr4HM8yHZtp2aQqQ@mail.gmail.com

6 hours agonbtree: Use only one notnullkey ScanKeyData.
Peter Geoghegan [Wed, 16 Jul 2025 17:05:44 +0000 (13:05 -0400)]
nbtree: Use only one notnullkey ScanKeyData.

_bt_first need only store one ScanKeyData struct on the stack for the
purposes of building an IS NOT NULL key based on an implied NOT NULL
constraint.  We don't need INDEX_MAX_KEYS-many ScanKeyData structs.

This saves us a little over 2KB in stack space.  It's possible that this
has some performance benefit.  It also seems simpler and more direct.

It isn't possible for more than a single index attribute to need its own
implied IS NOT NULL key: the first such attribute/IS NOT NULL key always
makes _bt_first stop adding additional boundary keys to startKeys[].
Using INDEX_MAX_KEYS-many ScanKeyData entries was (at best) misleading.

Author: Peter Geoghegan <pg@bowt.ie>
Reviewed-By: Mircea Cadariu <cadariu.mircea@gmail.com>
Discussion: https://postgr.es/m/CAH2-Wzm=1kJMSZhhTLoM5BPbwQNWxUj-ynOEh=89ptDZAVgauw@mail.gmail.com

6 hours agopg_dumpall: Skip global objects with --statistics-only or --no-schema.
Jeff Davis [Wed, 16 Jul 2025 16:57:12 +0000 (09:57 -0700)]
pg_dumpall: Skip global objects with --statistics-only or --no-schema.

Previously, pg_dumpall would still dump global objects such as roles
and tablespaces even when --statistics-only or --no-schema was specified.
Since these global objects are treated as schema-level data, they should
be skipped in these cases.

This commit fixes the issue by ensuring that global objects are not
dumped when either --statistics-only or --no-schema is used.

Author: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Discussion: https://postgr.es/m/08129593-6f3c-4fb9-94b7-5aa2eefb99b0@oss.nttdata.com
Backpatch-through: 18

6 hours agopsql: Fix note on project naming in output of \copyright.
Nathan Bossart [Wed, 16 Jul 2025 16:50:34 +0000 (11:50 -0500)]
psql: Fix note on project naming in output of \copyright.

This adjusts the wording to match the changes in commits
5987553fdea233a603ba, and pgweb commit 2d764dbc08.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/aHVo791guQR6uqwT%40nathan
Backpatch-through: 13

20 hours agoRefactor non-supported compression error message in toast_compression.c
Michael Paquier [Wed, 16 Jul 2025 02:59:22 +0000 (11:59 +0900)]
Refactor non-supported compression error message in toast_compression.c

This code used a NO_LZ4_SUPPORT() macro to issue an error in the code
paths where LZ4 [de]compression is attempted but the build does not
support it.  This commit refactors the code to use a more flexible error
message so as it can be used for other compression methods, where the
method is given in input of macro.

Extracted from a larger patch by the same author.

Author: Nikhil Kumar Veldanda <veldanda.nikhilkumar17@gmail.com>
Reviewed-by: Kirill Reshke <reshkekirill@gmail.com>
Discussion: https://postgr.es/m/CAFAfj_HX84EK4hyRYw50AOHOcdVi-+FFwAAPo7JHx4aShCvunQ@mail.gmail.com

21 hours agopgoutput: Initialize missing default for "origin" parameter.
Fujii Masao [Wed, 16 Jul 2025 01:31:51 +0000 (10:31 +0900)]
pgoutput: Initialize missing default for "origin" parameter.

The pgoutput plugin initializes optional parameters like "binary" with
default values at the start of processing. However, the "origin"
parameter was previously missed and left without explicit initialization.

Although the PGOutputData struct, which holds these settings,
is zero-initialized at allocation (resulting in publish_no_origin field
for "origin" parameter being false by default), this default was not
set explicitly, unlike other parameters.

This commit adds explicit initialization of the "origin" parameter to
ensure consistency and clarity in how defaults are handled.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Euler Taveira <euler@eulerto.com>
Discussion: https://postgr.es/m/d2790f10-238d-4cb5-a743-d9d2a9dd900f@oss.nttdata.com

23 hours agodoc: Document default values for pgoutput options in protocol.sgml.
Fujii Masao [Tue, 15 Jul 2025 23:51:04 +0000 (08:51 +0900)]
doc: Document default values for pgoutput options in protocol.sgml.

The pgoutput plugin options are described in the logical streaming
replication protocol documentation, but their default values were
previously not mentioned. This made it less convenient for users,
for example, when specifying those options to use pg_recvlogical
with pgoutput plugin.

This commit adds the explanations of the default values for pgoutput
options to improve clarity and usability.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Euler Taveira <euler@eulerto.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/d2790f10-238d-4cb5-a743-d9d2a9dd900f@oss.nttdata.com

23 hours agodoc: Fix confusing description of streaming option in START_REPLICATION.
Fujii Masao [Tue, 15 Jul 2025 23:32:52 +0000 (08:32 +0900)]
doc: Fix confusing description of streaming option in START_REPLICATION.

Previously, the documentation described the streaming option as a boolean,
which is outdated since it's no longer a boolean as of protocol version 4.
This could confuse users.

This commit updates the description to remove the "boolean" reference and
clearly list the valid values for the streaming option.

Back-patch to v16, where the streaming option changed to a non-boolean.

Author: Euler Taveira <euler@eulerto.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/8d21fb98-5c25-4dee-8387-e5a62b01ea7d@app.fastmail.com
Backpatch-through: 16

24 hours agodoc: Clarify that total_vacuum_time excludes VACUUM FULL.
Fujii Masao [Tue, 15 Jul 2025 23:03:36 +0000 (08:03 +0900)]
doc: Clarify that total_vacuum_time excludes VACUUM FULL.

The last_vacuum and vacuum_count fields in pg_stat_all_tables already
state that they do not include VACUUM FULL. However, total_vacuum_time,
which also excludes VACUUM FULL, did not mention this. This could
mislead users into thinking VACUUM FULL time is included.

To address this, this commit updates the documentation for
pg_stat_all_tables to explicitly state that total_vacuum_time does not
count VACUUM FULL.

Back-patched to v18, where total_vacuum_time was introduced.

Additionally, this commit clarifies that n_ins_since_vacuum also
excludes VACUUM FULL. Although n_ins_since_vacuum was added in v13,
we are not back-patching this change to stable branches, as it is
a documentation improvement, not a bug fix.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Robert Treat <rob@xzilla.net>
Reviewed-by: David G. Johnston <david.g.johnston@gmail.com>
Reviewed-by: Laurenz Albe <laurenz.albe@cybertec.at>
Discussion: https://postgr.es/m/2ac375d1-591b-4f1b-a2af-f24335567866@oss.nttdata.com
Backpatch-through: 18

24 hours agoDoc: clarify description of regexp fields in pg_ident.conf.
Tom Lane [Tue, 15 Jul 2025 22:53:00 +0000 (18:53 -0400)]
Doc: clarify description of regexp fields in pg_ident.conf.

The grammar was a little shaky and confusing here, so word-smith it
a bit.  Also, adjust the comments in pg_ident.conf.sample to use the
same terminology as the SGML docs, in particular "DATABASE-USERNAME"
not "PG-USERNAME".

Back-patch appropriate subsets.  I did not risk changing
pg_ident.conf.sample in released branches, but it still seems OK
to change it in v18.

Reported-by: Alexey Shishkin <alexey.shishkin@enterprisedb.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: David G. Johnston <david.g.johnston@gmail.com>
Discussion: https://postgr.es/m/175206279327.3157504.12519088928605422253@wrigleys.postgresql.org
Backpatch-through: 13

24 hours agoClarify the ra != rb case in compareJsonbContainers().
Tom Lane [Tue, 15 Jul 2025 22:21:12 +0000 (18:21 -0400)]
Clarify the ra != rb case in compareJsonbContainers().

It's impossible to reach this case with either ra or rb being
WJB_DONE, because our earlier checks that the structure and
length of the inputs match should guarantee that we reach their
ends simultaneously.  However, the comment completely fails to
explain this, and the Asserts don't cover it either.  The comment
is pretty obscure anyway, so rewrite it, and extend the Asserts
to reject WJB_DONE.

This is only cosmetic, so no need for back-patch.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/0c623e8a204187b87b4736792398eaf1@postgrespro.ru

25 hours agoSilence uninitialized-value warnings in compareJsonbContainers().
Tom Lane [Tue, 15 Jul 2025 22:11:18 +0000 (18:11 -0400)]
Silence uninitialized-value warnings in compareJsonbContainers().

Because not every path through JsonbIteratorNext() sets val->type,
some compilers complain that compareJsonbContainers() is comparing
possibly-uninitialized values.  The paths that don't set it return
WJB_DONE, WJB_END_ARRAY, or WJB_END_OBJECT, so it's clear by
manual inspection that the "(ra == rb)" code path is safe, and
indeed we aren't seeing warnings about that.  But the (ra != rb)
case is much less obviously safe.  In Assert-enabled builds it
seems that the asserts rejecting WJB_END_ARRAY and WJB_END_OBJECT
persuade gcc 15.x not to warn, which makes little sense because
it's impossible to believe that the compiler can prove of its
own accord that ra/rb aren't WJB_DONE here.  (In fact they never
will be, so the code isn't wrong, but why is there no warning?)
Without Asserts, the appearance of warnings is quite unsurprising.

We discussed fixing this by converting those two Asserts into
pg_assume, but that seems not very satisfactory when it's so unclear
why the compiler is or isn't warning: the warning could easily
reappear with some other compiler version.  Let's fix it in a less
magical, more future-proof way by changing JsonbIteratorNext()
so that it always does set val->type.  The cost of that should be
pretty negligible, and it makes the function's API spec less squishy.

Reported-by: Erik Rijkers <er@xs4all.nl>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/988bf1bc-3f1f-99f3-bf98-222f1cd9dc5e@xs4all.nl
Discussion: https://postgr.es/m/0c623e8a204187b87b4736792398eaf1@postgrespro.ru
Backpatch-through: 13

26 hours agoDoc: clarify description of current-date/time functions.
Tom Lane [Tue, 15 Jul 2025 20:35:42 +0000 (16:35 -0400)]
Doc: clarify description of current-date/time functions.

Minor wordsmithing of the func.sgml paragraph describing
statement_timestamp() and allied functions: don't switch between
"statement" and "command" when those are being used to mean about
the same thing.

Also, add some text to protocol.sgml describing the perhaps-surprising
behavior these functions have in a multi-statement Query message.

Reported-by: P M <petermittere@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Laurenz Albe <laurenz.albe@cybertec.at>
Reviewed-by: David G. Johnston <david.g.johnston@gmail.com>
Discussion: https://postgr.es/m/175223006802.3157505.14764328206246105568@wrigleys.postgresql.org
Backpatch-through: 13

37 hours agopsql: Fix tab-completion after GRANT/REVOKE on LARGE OBJECT and FOREIGN SERVER.
Fujii Masao [Tue, 15 Jul 2025 09:51:17 +0000 (18:51 +0900)]
psql: Fix tab-completion after GRANT/REVOKE on LARGE OBJECT and FOREIGN SERVER.

Previously, when pressing Tab after GRANT or REVOKE ... ON LARGE OBJECT
or ON FOREIGN SERVER, TO or FROM was incorrectly suggested by psql's
tab-completion. This was not appropriate, as those clauses are not valid
at that point.

This commit fixes the issue by preventing TO and FROM from being offered
immediately after those specific GRANT/REVOKE statements.

Author: Yugo Nagata <nagata@sraoss.co.jp>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/20250408122857.b2b06dde4e6a08290af02336@sraoss.co.jp

40 hours agoFix comments in index.c
Michael Paquier [Tue, 15 Jul 2025 07:05:59 +0000 (16:05 +0900)]
Fix comments in index.c

This comment paragraph referred to text_eq(), but the name of the
function in charge of "text" comparisons is called texteq().

Author: Jian He <jian.universality@gmail.com>
Discussion: https://postgr.es/m/CACJufxHL--XNcCCO1LgKsygzYGiVHZMfTcAxOSG8+ezxWtjddw@mail.gmail.com

2 days agoamcheck: Improve error message for partitioned index target.
Fujii Masao [Mon, 14 Jul 2025 11:01:06 +0000 (20:01 +0900)]
amcheck: Improve error message for partitioned index target.

Previously, amcheck could produce misleading error message when
a partitioned index was passed to functions like bt_index_check().
For example, bt_index_check() with a partitioned btree index produced:

    ERROR:  expected "btree" index as targets for verification
    DETAIL:  Relation ... is a btree index.

Reporting "expected btree index as targets" even when the specified
index was a btree was confusing. In this case, the function should fail
since the partitioned index specified is not valid target. This commit
improves the error reporting to better reflect this actual issue. Now,
bt_index_check() with a partitioned index, the error message is:

    ERROR:  expected index as targets for verification
    DETAIL:  This operation is not supported for partitioned indexes.

This commit also applies the following minor changes:

- Simplifies index_checkable() by using get_am_name() to retrieve
   the access method name.

- Changes index_checkable() from extern to static, as it is only used
   in verify_common.c.

- Updates the error code for invalid indexes to
   ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE,
   aligning with usage in similar modules like pgstattuple.

Author: Masahiro Ikeda <ikedamsh@oss.nttdata.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/8829854bbfc8635ddecd0846bb72dfda@oss.nttdata.com

2 days agopsql: Add variable SERVICEFILE
Michael Paquier [Mon, 14 Jul 2025 00:08:46 +0000 (09:08 +0900)]
psql: Add variable SERVICEFILE

This new psql variable can be used to check which service file has been
used for a connection.  Like other variables, this can be set in a
PROMPT or reported by an \echo, like these commands:
\echo :SERVICEFILE
\set PROMPT1 '=(%:SERVICEFILE:)%# '

This relies on commits 092f3c63efc6 and fef6da9e9c87 to retrieve this
information from the connection's PQconninfoOption.

Author: Ryo Kanbayashi <kanbayashi.dev@gmail.com>
Discussion: https://postgr.es/m/CAKkG4_nCjx3a_F3gyXHSPWxD8Sd8URaM89wey7fG_9g7KBkOCQ@mail.gmail.com

3 days agoIn username-map substitution, cope with more than one \1.
Tom Lane [Sun, 13 Jul 2025 17:52:32 +0000 (13:52 -0400)]
In username-map substitution, cope with more than one \1.

If the system-name field of a pg_ident.conf line is a regex
containing capturing parentheses, you can write \1 in the
user-name field to represent the captured part of the system
name.  But what happens if you write \1 more than once?
The only reasonable expectation IMO is that each \1 gets
replaced, but presently our code replaces only the first.
Fix that.

Also, improve the tests for this feature to exercise cases
where a non-empty string needs to be substituted for \1.
The previous testing didn't inspire much faith that it
was verifying correct operation of the substitution code.

Given the lack of field complaints about this, I don't
feel a need to back-patch.

Reported-by: David G. Johnston <david.g.johnston@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAKFQuwZu6kZ8ZPvJ3pWXig+6UX4nTVK-hdL_ZS3fSdps=RJQQQ@mail.gmail.com

3 days agolibpq: Add "servicefile" connection option
Michael Paquier [Sun, 13 Jul 2025 07:52:19 +0000 (16:52 +0900)]
libpq: Add "servicefile" connection option

This commit adds the possibility to specify a service file in a
connection string, using a new option called "servicefile".  The parsing
of the service file happens so as things are done in this order of
priority:
- The servicefile connection option.
- Environment variable PGSERVICEFILE.
- Default path, depending on the HOME environment.

Note that in the last default case, we need to fill in "servicefile" for
the connection's PQconninfoOption to let clients know which service file
has been used for the connection.  Some TAP tests are added, with a few
tweaks required for Windows when using URIs or connection option values,
for the location paths.

Author: Torsten Förtsch <tfoertsch123@gmail.com>
Co-authored-by: Ryo Kanbayashi <kanbayashi.dev@gmail.com>
Discussion: https://postgr.es/m/CAKkG4_nCjx3a_F3gyXHSPWxD8Sd8URaM89wey7fG_9g7KBkOCQ@mail.gmail.com

4 days agoRemove XLogCtl->ckptFullXid.
Nathan Bossart [Sat, 12 Jul 2025 19:34:57 +0000 (14:34 -0500)]
Remove XLogCtl->ckptFullXid.

A few code paths set this variable, but its value is never used.

Oversight in commit 2fc7af5e96.

Reviewed-by: Aleksander Alekseev <aleksander@tigerdata.com>
Discussion: https://postgr.es/m/aHFyE1bs9YR93dQ1%40nathan

4 days agoReplace float8 with int in date2isoweek() and date2isoyear().
Tom Lane [Sat, 12 Jul 2025 15:50:35 +0000 (11:50 -0400)]
Replace float8 with int in date2isoweek() and date2isoyear().

The values of the "result" variables in these functions are
always integers; using a float8 variable accomplishes nothing
except to incur useless conversions to and from float.  While
that wastes a few nanoseconds, these functions aren't all that
time-critical.  But it seems worth fixing to remove possible
reader confusion.

Also, in the case of date2isoyear(), "result" is a very poorly
chosen variable name because it is *not* the function's result.
Rename it to "week", and do the same in date2isoweek() for
consistency.

Since this is mostly cosmetic, there seems little need
for back-patch.

Author: Sergey Fukanchik <s.fukanchik@postgrespro.ru>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/6323a-68726500-1-7def9d00@137821581

4 days agoRemove long-unused TransactionIdIsActive()
Andres Freund [Sat, 12 Jul 2025 15:00:44 +0000 (11:00 -0400)]
Remove long-unused TransactionIdIsActive()

TransactionIdIsActive() has not been used since bb38fb0d43c, in 2014. There
are no known uses in extensions either and it's hard to see valid uses for
it. Therefore remove TransactionIdIsActive().

Discussion: https://postgr.es/m/odgftbtwp5oq7cxjgf4kjkmyq7ypoftmqy7eqa7w3awnouzot6@hrwnl5tdqrgu

4 days agoaio: Fix configuration reload in IO workers.
Thomas Munro [Sat, 12 Jul 2025 04:20:11 +0000 (16:20 +1200)]
aio: Fix configuration reload in IO workers.

method_worker.c installed SignalHandlerForConfigReload, but it failed to
actually process reload requests.  That hasn't yet produced any concrete
problem reports in terms of GUC changes it should have cared about in
v18, but it was inconsistent.

It did cause problems for a couple of patches in development that need
IO workers to react to ALTER SYSTEM + pg_reload_conf().  Fix extracted
from one of those patches.

Back-patch to 18.

Reported-by: Dmitry Dolgov <9erthalion6@gmail.com>
Discussion: https://postgr.es/m/sh5uqe4a4aqo5zkkpfy5fobe2rg2zzouctdjz7kou4t74c66ql%40yzpkxb7pgoxf

4 days agoaio: Remove obsolete IO worker ID references.
Thomas Munro [Sat, 12 Jul 2025 01:47:59 +0000 (13:47 +1200)]
aio: Remove obsolete IO worker ID references.

In an ancient ancestor of this code, the postmaster assigned IDs to IO
workers.  Now it tracks them in an unordered array and doesn't know
their IDs, so it might be confusing to readers that it still referred to
their indexes as IDs.

No change in behavior, just variable name and error message cleanup.

Back-patch to 18.

Discussion: https://postgr.es/m/CA%2BhUKG%2BwbaZZ9Nwc_bTopm4f-7vDmCwLk80uKDHj9mq%2BUp0E%2Bg%40mail.gmail.com

4 days agoaio: Regularize IO worker internal naming.
Thomas Munro [Sat, 12 Jul 2025 01:43:27 +0000 (13:43 +1200)]
aio: Regularize IO worker internal naming.

Adopt PgAioXXX convention for pgaio module type names.  Rename a
function that didn't use a pgaio_worker_ submodule prefix.  Rename the
internal submit function's arguments to match the indirectly relevant
function pointer declaration and nearby examples.  Rename the array of
handle IDs in PgAioSubmissionQueue to sqes, a term of art seen in the
systems it emulates, also clarifying that they're not IO handle
pointers as the old name might imply.

No change in behavior, just type, variable and function name cleanup.

Back-patch to 18.

Discussion: https://postgr.es/m/CA%2BhUKG%2BwbaZZ9Nwc_bTopm4f-7vDmCwLk80uKDHj9mq%2BUp0E%2Bg%40mail.gmail.com

4 days agoFix stale idle flag when IO workers exit.
Thomas Munro [Fri, 11 Jul 2025 23:18:05 +0000 (11:18 +1200)]
Fix stale idle flag when IO workers exit.

Otherwise we could choose a worker that has exited and crash while
trying to wake it up.

Back-patch to 18.

Reported-by: Tomas Vondra <tomas@vondra.me>
Reported-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/t5aqjhkj6xdkido535pds7fk5z4finoxra4zypefjqnlieevbg%40357aaf6u525j

5 days agoFix inconsistent quoting of role names in ACLs.
Tom Lane [Fri, 11 Jul 2025 22:50:13 +0000 (18:50 -0400)]
Fix inconsistent quoting of role names in ACLs.

getid() and putid(), which parse and deparse role names within ACL
input/output, applied isalnum() to see if a character within a role
name requires quoting.  They did this even for non-ASCII characters,
which is problematic because the results would depend on encoding,
locale, and perhaps even platform.  So it's possible that putid()
could elect not to quote some string that, later in some other
environment, getid() will decide is not a valid identifier, causing
dump/reload or similar failures.

To fix this in a way that won't risk interoperability problems
with unpatched versions, make getid() treat any non-ASCII as a
legitimate identifier character (hence not requiring quotes),
while making putid() treat any non-ASCII as requiring quoting.
We could remove the resulting excess quoting once we feel that
no unpatched servers remain in the wild, but that'll be years.

A lesser problem is that getid() did the wrong thing with an input
consisting of just two double quotes ("").  That has to represent an
empty string, but getid() read it as a single double quote instead.
The case cannot arise in the normal course of events, since we don't
allow empty-string role names.  But let's fix it while we're here.

Although we've not heard field reports of problems with non-ASCII
role names, there's clearly a hazard there, so back-patch to all
supported versions.

Reported-by: Peter Eisentraut <peter@eisentraut.org>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/3792884.1751492172@sss.pgh.pa.us
Backpatch-through: 13

5 days agooauth: Run Autoconf tests with correct compiler flags
Jacob Champion [Fri, 11 Jul 2025 17:06:41 +0000 (10:06 -0700)]
oauth: Run Autoconf tests with correct compiler flags

Commit b0635bfda split off the CPPFLAGS/LDFLAGS/LDLIBS for libcurl into
their own separate Makefile variables, but I neglected to move the
existing AC_CHECKs for Curl into a place where they would make use of
those variables. They instead tested the system libcurl, which 1) is
unhelpful if a different Curl is being used for the build and 2) will
fail the build entirely if no system libcurl exists. Correct the order
of operations here.

Reported-by: Ivan Kush <ivan.kush@tantorlabs.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Ivan Kush <ivan.kush@tantorlabs.com>
Discussion: https://postgr.es/m/8a611028-51a1-408c-b592-832e2e6e1fc9%40tantorlabs.com
Backpatch-through: 18

5 days agoAdd FLUSH_UNLOGGED option to CHECKPOINT command.
Nathan Bossart [Fri, 11 Jul 2025 16:51:25 +0000 (11:51 -0500)]
Add FLUSH_UNLOGGED option to CHECKPOINT command.

This option, which is disabled by default, can be used to request
the checkpoint also flush dirty buffers of unlogged relations.  As
with the MODE option, the server may consolidate the options for
concurrently requested checkpoints.  For example, if one session
uses (FLUSH_UNLOGGED FALSE) and another uses (FLUSH_UNLOGGED TRUE),
the server may perform one checkpoint with FLUSH_UNLOGGED enabled.

Author: Christoph Berg <myon@debian.org>
Reviewed-by: Laurenz Albe <laurenz.albe@cybertec.at>
Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>
Discussion: https://postgr.es/m/aDnaKTEf-0dLiEfz%40msg.df7cb.de

5 days agoAdd MODE option to CHECKPOINT command.
Nathan Bossart [Fri, 11 Jul 2025 16:51:25 +0000 (11:51 -0500)]
Add MODE option to CHECKPOINT command.

This option may be set to FAST (the default) to request the
checkpoint be completed as fast as possible, or SPREAD to request
the checkpoint be spread over a longer interval (based on the
checkpoint-related configuration parameters).  Note that the server
may consolidate the options for concurrently requested checkpoints.
For example, if one session requests a "fast" checkpoint and
another requests a "spread" checkpoint, the server may perform one
"fast" checkpoint.

Author: Christoph Berg <myon@debian.org>
Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Laurenz Albe <laurenz.albe@cybertec.at>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>
Discussion: https://postgr.es/m/aDnaKTEf-0dLiEfz%40msg.df7cb.de

5 days agoAdd option list to CHECKPOINT command.
Nathan Bossart [Fri, 11 Jul 2025 16:51:25 +0000 (11:51 -0500)]
Add option list to CHECKPOINT command.

This commit adds the boilerplate code for supporting a list of
options in CHECKPOINT commands.  No actual options are supported
yet, but follow-up commits will add support for MODE and
FLUSH_UNLOGGED.  While at it, this commit refactors the code for
executing CHECKPOINT commands to its own function since it's about
to become significantly larger.

Author: Christoph Berg <myon@debian.org>
Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Discussion: https://postgr.es/m/aDnaKTEf-0dLiEfz%40msg.df7cb.de

5 days agoRename CHECKPOINT_IMMEDIATE to CHECKPOINT_FAST.
Nathan Bossart [Fri, 11 Jul 2025 16:51:25 +0000 (11:51 -0500)]
Rename CHECKPOINT_IMMEDIATE to CHECKPOINT_FAST.

The new name more accurately reflects the effects of this flag on a
requested checkpoint.  Checkpoint-related log messages (i.e., those
controlled by the log_checkpoints configuration parameter) will now
say "fast" instead of "immediate", too.  Likewise, references to
"immediate" checkpoints in the documentation have been updated to
say "fast".  This is preparatory work for a follow-up commit that
will add a MODE option to the CHECKPOINT command.

Author: Christoph Berg <myon@debian.org>
Discussion: https://postgr.es/m/aDnaKTEf-0dLiEfz%40msg.df7cb.de

5 days agoRename CHECKPOINT_FLUSH_ALL to CHECKPOINT_FLUSH_UNLOGGED.
Nathan Bossart [Fri, 11 Jul 2025 16:51:25 +0000 (11:51 -0500)]
Rename CHECKPOINT_FLUSH_ALL to CHECKPOINT_FLUSH_UNLOGGED.

The new name more accurately relects the effects of this flag on a
requested checkpoint.  Checkpoint-related log messages (i.e., those
controlled by the log_checkpoints configuration parameter) will now
say "flush-unlogged" instead of "flush-all", too.  This is
preparatory work for a follow-up commit that will add a
FLUSH_UNLOGGED option to the CHECKPOINT command.

Author: Christoph Berg <myon@debian.org>
Discussion: https://postgr.es/m/aDnaKTEf-0dLiEfz%40msg.df7cb.de

5 days agoForce LC_NUMERIC to C while running TAP tests.
Tom Lane [Fri, 11 Jul 2025 16:49:07 +0000 (12:49 -0400)]
Force LC_NUMERIC to C while running TAP tests.

We already forced LC_MESSAGES to C in order to get consistent
message output, but that isn't enough to stabilize messages
that include %f or similar formatting.

I'm a bit surprised that this hasn't come up before.  Perhaps
we ought to back-patch this change, but I'll refrain for now.

Reported-by: Bernd Helmle <mailings@oopsware.de>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/6f024eaa7885eddf5e0eb4ba1d095fbc7146519b.camel@oopsware.de

5 days agoFix the handling of two GUCs during upgrade.
Amit Kapila [Fri, 11 Jul 2025 05:16:43 +0000 (10:46 +0530)]
Fix the handling of two GUCs during upgrade.

Previously, the check_hook functions for max_slot_wal_keep_size and
idle_replication_slot_timeout would incorrectly raise an ERROR for values
set in postgresql.conf during upgrade, even though those values were not
actively used in the upgrade process.

To prevent logical slot invalidation during upgrade, we used to set
special values for these GUCs. Now, instead of relying on those values, we
directly prevent WAL removal and logical slot invalidation caused by
max_slot_wal_keep_size and idle_replication_slot_timeout.

Note: PostgreSQL 17 does not include the idle_replication_slot_timeout
GUC, so related changes were not backported.

BUG #18979
Reported-by: jorsol <jorsol@gmail.com>
Author: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed by: vignesh C <vignesh21@gmail.com>
Reviewed by: Alvaro Herrera <alvherre@alvh.no-ip.org>
Backpatch-through: 17, where it was introduced
Discussion: https://postgr.es/m/219561.1751826409@sss.pgh.pa.us
Discussion: https://postgr.es/m/18979-a1b7fdbb7cd181c6@postgresql.org

5 days agoDoc: fix outdated protocol version.
Tatsuo Ishii [Fri, 11 Jul 2025 01:34:57 +0000 (10:34 +0900)]
Doc: fix outdated protocol version.

In the description of StartupMessage, the protocol version was left
3.0. Instead of just updating it, this commit removes the hard coded
protocol version and shows the numbers as an example. This makes that
the part of the doc does not need to be updated when the version is
changed in the future.

Author: Jelte Fennema-Nio <postgres@jeltef.nl>
Reviewed-by: Tatsuo Ishii <ishii@postgresql.org>
Reviewed-by: Aleksander Alekseev <aleksander@timescale.com>
Discussion: https://postgr.es/m/20250626.155608.568829483879866256.ishii%40postgresql.org

5 days agodoc: Clarify meaning of "idle" in idle_replication_slot_timeout.
Fujii Masao [Thu, 10 Jul 2025 23:44:32 +0000 (08:44 +0900)]
doc: Clarify meaning of "idle" in idle_replication_slot_timeout.

This commit updates the documentation to clarify that "idle" in
idle_replication_slot_timeout means the replication slot is inactive,
that is, not currently used by any replication connection.

Without this clarification, "idle" could be misinterpreted to mean
that the slot is not advancing or that no data is being streamed,
even if a connection exists.

Back-patch to v18 where idle_replication_slot_timeout was added.

Author: Laurenz Albe <laurenz.albe@cybertec.at>
Reviewed-by: David G. Johnston <david.g.johnston@gmail.com>
Reviewed-by: Gunnar Morling <gunnar.morling@googlemail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CADGJaX_0+FTguWpNSpgVWYQP_7MhoO0D8=cp4XozSQgaZ40Odw@mail.gmail.com
Backpatch-through: 18

5 days agoChange unit of idle_replication_slot_timeout to seconds.
Fujii Masao [Thu, 10 Jul 2025 23:39:24 +0000 (08:39 +0900)]
Change unit of idle_replication_slot_timeout to seconds.

Previously, the idle_replication_slot_timeout parameter used minutes
as its unit, based on the assumption that values would typically exceed
one minute in production environments. However, this caused unexpected
behavior: specifying a value below 30 seconds would round down to 0,
effectively disabling the timeout. This could be surprising to users.

To allow finer-grained control and avoid such confusion, this commit changes
the unit of idle_replication_slot_timeout to seconds. Larger values can
still be specified easily using standard time suffixes, for example,
'24h' for 24 hours.

Back-patch to v18 where idle_replication_slot_timeout was added.

Reported-by: Gunnar Morling <gunnar.morling@googlemail.com>
Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Laurenz Albe <laurenz.albe@cybertec.at>
Reviewed-by: David G. Johnston <david.g.johnston@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CADGJaX_0+FTguWpNSpgVWYQP_7MhoO0D8=cp4XozSQgaZ40Odw@mail.gmail.com
Backpatch-through: 18

6 days agoFix sslkeylogfile error handling logging
Daniel Gustafsson [Thu, 10 Jul 2025 21:26:51 +0000 (23:26 +0200)]
Fix sslkeylogfile error handling logging

When sslkeylogfile has been set but the file fails to open in an
otherwise successful connection, the log entry added to the conn
object is never printed.  Instead print the error on stderr for
increased visibility.  This is a debugging tool so using stderr
for logging is appropriate.  Also while there, remove the umask
call in the callback as it's not useful.

Issues noted by Peter Eisentraut in post-commit review, backpatch
down to 18 when support for sslkeylogfile was added

Author: Daniel Gustafsson <daniel@yesql.se>
Reported-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/70450bee-cfaa-48ce-8980-fc7efcfebb03@eisentraut.org
Backpatch-through: 18

6 days agopg_dump: Fix object-type sort priority for large objects.
Nathan Bossart [Thu, 10 Jul 2025 20:52:41 +0000 (15:52 -0500)]
pg_dump: Fix object-type sort priority for large objects.

Commit a45c78e328 moved large object metadata from SECTION_PRE_DATA
to SECTION_DATA but neglected to move PRIO_LARGE_OBJECT in
dbObjectTypePriorities accordingly.  While this hasn't produced any
known live bugs, it causes problems for a proposed patch that
optimizes upgrades with many large objects.  Fixing the priority
might also make the topological sort step marginally faster by
reducing the number of ordering violations that have to be fixed.

Reviewed-by: Nitin Motiani <nitinmotiani@google.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/aBkQLSkx1zUJ-LwJ%40nathan
Discussion: https://postgr.es/m/aG_5DBCjdDX6KAoD%40nathan
Backpatch-through: 17

6 days agobtree_gist: Merge the last two versions into version 1.8
Michael Paquier [Thu, 10 Jul 2025 03:23:04 +0000 (12:23 +0900)]
btree_gist: Merge the last two versions into version 1.8

During the development cycle of v18, btree_gist has been bumped once to
1.8 for the addition of translate_cmptype support functions (originally
7406ab623fee, renamed in 32edf732e8dc).  1.9 has added sortsupport
functions (e4309f73f698).

There is no need for two version bumps in a module for a single major
release of PostgreSQL.  This commit unifies both upgrades to a single
SQL script, downgrading btree_gist to 1.8.

Author: Paul A. Jungwirth <pj@illuminatedcomputing.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/13c61807-f702-4afe-9a8d-795e2fd40923@illuminatedcomputing.com
Backpatch-through: 18

6 days agoinjection_points: Add injection_points_list()
Michael Paquier [Thu, 10 Jul 2025 01:01:10 +0000 (10:01 +0900)]
injection_points: Add injection_points_list()

This function can be used to retrieve the information about all the
injection points attached to a cluster, providing coverage for
InjectionPointList() introduced in 7b2eb72b1b8c.

The original proposal turned around a system function, but that would
not be backpatchable to stable branches.  It was also a bit weird to
have a system function that fails depending on if the build allows
injection points or not.

Reviewed-by: Aleksander Alekseev <aleksander@timescale.com>
Reviewed-by: Rahila Syed <rahilasyed90@gmail.com>
Discussion: https://postgr.es/m/Z_xYkA21KyLEHvWR@paquier.xyz

7 days agoUse pg_assume() to avoid compiler warning below exec_set_found()
Andres Freund [Wed, 9 Jul 2025 22:38:05 +0000 (18:38 -0400)]
Use pg_assume() to avoid compiler warning below exec_set_found()

The warning, visible when building with -O3 and a recent-ish gcc, is due to
gcc not realizing that found is a byvalue type and therefore will never be
interpreted as a varlena type.

Discussion: https://postgr.es/m/3prdb6hkep3duglhsujrn52bkvnlkvhc54fzvph2emrsm4vodl@77yy6j4hkemb
Discussion: https://postgr.es/m/20230316172818.x6375uvheom3ibt2%40awork3.anarazel.de
Discussion: https://postgr.es/m/20240207203138.sknifhlppdtgtxnk%40awork3.anarazel.de

7 days agoAdd pg_assume(expr) macro
Andres Freund [Wed, 9 Jul 2025 22:38:05 +0000 (18:38 -0400)]
Add pg_assume(expr) macro

This macro can be used to avoid compiler warnings, particularly when using -O3
and not using assertions, and to get the compiler to generate better code.

A subsequent commit introduces a first user.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/3prdb6hkep3duglhsujrn52bkvnlkvhc54fzvph2emrsm4vodl@77yy6j4hkemb
Discussion: https://postgr.es/m/20230316172818.x6375uvheom3ibt2%40awork3.anarazel.de
Discussion: https://postgr.es/m/20240207203138.sknifhlppdtgtxnk%40awork3.anarazel.de

7 days agoLink libpq with libdl if the platform needs that.
Tom Lane [Wed, 9 Jul 2025 18:21:00 +0000 (14:21 -0400)]
Link libpq with libdl if the platform needs that.

Since b0635bfda, libpq uses dlopen() and related functions.  On some
platforms these are not supplied by libc, but by a separate library
libdl, in which case we need to make sure that that dependency is
known to the linker.  Meson seems to take care of that automatically,
but the Makefile didn't cater for it.

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

7 days agoChange wchar2char() and char2wchar() to accept a locale_t.
Jeff Davis [Wed, 9 Jul 2025 15:45:34 +0000 (08:45 -0700)]
Change wchar2char() and char2wchar() to accept a locale_t.

These are libc-specific functions, so should require a locale_t rather
than a pg_locale_t (which could use another provider).

Discussion: https://postgr.es/m/a8666c391dfcabe79868d95f7160eac533ace718.camel%40j-davis.com

7 days agoMinor tweaks for pg_test_timing.
Tom Lane [Wed, 9 Jul 2025 15:26:53 +0000 (11:26 -0400)]
Minor tweaks for pg_test_timing.

Increase the size of the "direct" histogram to 10K elements,
so that we can precisely track loop times up to 10 microseconds.
(Going further than that seems pretty uninteresting, even for
very old and slow machines.)

Relabel "Per loop time" as "Average loop time" for clarity.

Pre-zero the histogram arrays to make sure that they are loaded
into processor cache and any copy-on-write overhead has happened
before we enter the timing loop.  Also use unlikely() to keep
the compiler from thinking that the clock-went-backwards case
is part of the hot loop.  Neither of these hacks made a lot of
difference on my own machine, but they seem like they might help
on some platforms.

Discussion: https://postgr.es/m/be0339cc-1ae1-4892-9445-8e6d8995a44d@eisentraut.org

7 days agoIntroduce pg_dsm_registry_allocations view.
Nathan Bossart [Wed, 9 Jul 2025 14:17:56 +0000 (09:17 -0500)]
Introduce pg_dsm_registry_allocations view.

This commit adds a new system view that provides information about
entries in the dynamic shared memory (DSM) registry.  Specifically,
it returns the name, type, and size of each entry.  Note that since
we cannot discover the size of dynamic shared memory areas (DSAs)
and hash tables backed by DSAs (dshashes) without first attaching
to them, the size column is left as NULL for those.

Bumps catversion.

Author: Florents Tselai <florents.tselai@gmail.com>
Reviewed-by: Sungwoo Chang <swchangdev@gmail.com>
Discussion: https://postgr.es/m/4D445D3E-81C5-4135-95BB-D414204A0AB4%40gmail.com

7 days agoFix tab-completion for COPY and \copy options.
Masahiko Sawada [Wed, 9 Jul 2025 12:45:34 +0000 (05:45 -0700)]
Fix tab-completion for COPY and \copy options.

Commit c273d9d8ce4 reworked tab-completion of COPY and \copy in psql
and added support for completing options within WITH clauses. However,
the same COPY options were suggested for both COPY TO and COPY FROM
commands, even though some options are only valid for one or the
other.

This commit separates the COPY options for COPY FROM and COPY TO
commands to provide more accurate auto-completion suggestions.

Back-patch to v14 where tab-completion for COPY and \copy options
within WITH clauses was first supported.

Author: Atsushi Torikoshi <torikoshia@oss.nttdata.com>
Reviewed-by: Yugo Nagata <nagata@sraoss.co.jp>
Discussion: https://postgr.es/m/079e7a2c801f252ae8d522b772790ed7@oss.nttdata.com
Backpatch-through: 14

7 days agopsql: Improve psql tab completion for GRANT/REVOKE on large objects.
Fujii Masao [Wed, 9 Jul 2025 11:33:50 +0000 (20:33 +0900)]
psql: Improve psql tab completion for GRANT/REVOKE on large objects.

This commit enhances psql's tab completion to support TO/FROM
after "GRANT/REVOKE ... ON LARGE OBJECT ...". Additionally,
since "ALTER DEFAULT PRIVILEGES" now supports large objects,
tab completion is also updated for "GRANT/REVOKE ... ON LARGE OBJECTS"
with TO/FROM.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Yugo Nagata <nagata@sraoss.co.jp>
Discussion: https://postgr.es/m/ade0ab29-777f-47f6-9d0d-1af67728a86e@oss.nttdata.com

7 days agoHide ICU C++ APIs from pg_locale.h
John Naylor [Wed, 9 Jul 2025 07:20:22 +0000 (14:20 +0700)]
Hide ICU C++ APIs from pg_locale.h

The cpluspluscheck script wraps our headers in `extern "C"`. This
disables name mangling, which is necessary for the C++ templates
in system ICU headers. cpluspluscheck thus fails when the build is
configured with ICU (the default). CI worked around this by disabling
ICU, but let's make it work so others can run the script.

We can specify we only want the C APIs by defining U_SHOW_CPLUSPLUS_API
to be 0 in pg_locale.h. Extensions that want the C++ APIs can include
ICU headers separately before including PostgreSQL headers.

ICU documentation:
https://github.com/unicode-org/icu/blob/main/docs/processes/release/tasks/healthy-code.md#test-icu4c-headers

Suggested-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220323002024.f2g6tivduzrktgfa%40alap3.anarazel.de
Discussion: https://postgr.es/m/CANWCAZbgiaz1_0-F4SD%2B%3D-e9onwAnQdBGJbhg94EqUu4Gb7WyA%40mail.gmail.com

7 days agolibpq: Add TAP test for nested service file
Michael Paquier [Wed, 9 Jul 2025 06:46:31 +0000 (15:46 +0900)]
libpq: Add TAP test for nested service file

This test corresponds to the case of a "service" defined in a service
file, that libpq is not able to support in parseServiceFile().

This has come up during the review of a patch to add more features in
this area, useful on its own.  Piece extracted from a larger patch by
the same author.

Author: Ryo Kanbayashi <kanbayashi.dev@gmail.com>
Discussion: https://postgr.es/m/Zz2AE7NKKLIZTtEh@paquier.xyz

7 days agoDoc: Improve logical replication failover documentation.
Amit Kapila [Wed, 9 Jul 2025 04:14:27 +0000 (09:44 +0530)]
Doc: Improve logical replication failover documentation.

Clarified that the failover steps apply to a specific PostgreSQL subscriber
and added guidance for verifying replication slot synchronization during
planned failover. Additionally, corrected the standby query to avoid false
positives by checking invalidation_reason IS NULL instead of conflicting.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Author: Shveta Malik <shveta.malik@gmail.com>
Backpatch-through: 17, where it was introduced
Discussion: https://www.postgresql.org/message-id/CAExHW5uiZ-fF159=jwBwPMbjZeZDtmcTbN+hd4mrURLCg2uzJg@mail.gmail.com

7 days agolibpq: Remove PQservice()
Michael Paquier [Wed, 9 Jul 2025 03:46:13 +0000 (12:46 +0900)]
libpq: Remove PQservice()

This routine has been introduced as a shortcut to be able to retrieve a
service name from an active connection, for psql.  Per discussion, and
as it is only used by psql, let's remove it to not clutter the libpq API
more than necessary.

The logic in psql is replaced by lookups of PQconninfoOption for the
active connection, instead, updated each time the variables are synced
by psql, the prompt shortcut relying on the variable synced.

Reported-by: Noah Misch <noah@leadboat.com>
Discussion: https://postgr.es/m/20250706161319.c1.nmisch@google.com
Backpatch-through: 18

8 days agoFix up misuse of "volatile" in contrib/xml2.
Tom Lane [Tue, 8 Jul 2025 21:00:34 +0000 (17:00 -0400)]
Fix up misuse of "volatile" in contrib/xml2.

What we want in these places is "xmlChar *volatile ptr",
not "volatile xmlChar *ptr".  The former means that the
pointer variable itself needs to be treated as volatile,
while the latter says that what it points to is volatile.
Since the point here is to ensure that the pointer variables
don't go crazy after a longjmp, it's the former semantics
that we need.  The misplacement of "volatile" also led
to needing to cast away volatile in some places.

Also fix a number of places where variables that are assigned to
within a PG_TRY and then used after it were not initialized or
not marked as volatile.  (A few buildfarm members were issuing
"may be used uninitialized" warnings about some of these variables,
which is what drew my attention to this area.)  In most cases
these variables were being set as the last step within the PG_TRY
block, which might mean that we could get away without the "volatile"
marking.  But doing that seems unsafe and is definitely not per our
coding conventions.

These problems seem to have come in with 732061150, so no need
for back-patch.

8 days agoFix low-probability memory leak in XMLSERIALIZE(... INDENT).
Tom Lane [Tue, 8 Jul 2025 16:50:19 +0000 (12:50 -0400)]
Fix low-probability memory leak in XMLSERIALIZE(... INDENT).

xmltotext_with_options() did not consider the possibility that
pg_xml_init() could fail --- most likely due to OOM.  If that
happened, the already-parsed xmlDoc structure would be leaked.
Oversight in commit 483bdb2af.

Bug: #18981
Author: Dmitry Kovalenko <d.kovalenko@postgrespro.ru>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/18981-9bc3c80f107ae925@postgresql.org
Backpatch-through: 16

8 days agoFix a couple more places in docs for pg_lsn change
Álvaro Herrera [Tue, 8 Jul 2025 16:37:55 +0000 (18:37 +0200)]
Fix a couple more places in docs for pg_lsn change

Also, revert Unicode linestyle to ASCII.

Reported-by: Japin Li <japinli@hotmail.com>
Discussion: https://postgr.es/m/ME0P300MB04453A39931F95805C4205A8B64FA@ME0P300MB0445.AUSP300.PROD.OUTLOOK.COM

8 days agoChange pg_test_timing to measure in nanoseconds not microseconds.
Tom Lane [Tue, 8 Jul 2025 15:23:15 +0000 (11:23 -0400)]
Change pg_test_timing to measure in nanoseconds not microseconds.

Most of our platforms have better-than-microsecond timing resolution,
so the original definition of this program is getting less and less
useful.  Make it report nanoseconds not microseconds.  Also, add a
second output table that reports the exact observed timing durations,
up to a limit of 1024 ns; and be sure to report the largest observed
duration.

The documentation for this program included a lot of system-specific
details that now seem largely obsolete.  Move all that text to the
PG wiki, where perhaps it will be easier to maintain and update.

Also, improve the TAP test so that it actually runs a short standard
run, allowing most of the code to be exercised; its coverage before
was abysmal.

Author: Hannu Krosing <hannuk@google.com>
Co-authored-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/be0339cc-1ae1-4892-9445-8e6d8995a44d@eisentraut.org

8 days agopg_walsummary: Improve stability of test checking statistics
Michael Paquier [Tue, 8 Jul 2025 04:48:49 +0000 (13:48 +0900)]
pg_walsummary: Improve stability of test checking statistics

Per buildfarm member culicidae, the query checking for stats reported by
the WAL summarizer related to WAL reads is proving to be unstable.

Instead of a one-time query, this commit replaces the logic with a
polling query checking for the WAL read stats, making the test more
reliable on machines that could be slow with the stats reports.

This test has been introduced in f4694e0f35b2, so backpatch down to v18.

Reported-by: Alexander Lakhin <exclusion@gmail.com>
Reviewed-by: Alexander Lakhin <exclusion@gmail.com>
Discussion: https://postgr.es/m/f35ba3db-fca7-4693-bc35-6db64488e4b1@gmail.com
Backpatch-through: 18

8 days agoaio: Combine io_uring memory mappings, if supported
Andres Freund [Tue, 8 Jul 2025 01:03:16 +0000 (21:03 -0400)]
aio: Combine io_uring memory mappings, if supported

By default io_uring creates a shared memory mapping for each io_uring
instance, leading to a large number of memory mappings. Unfortunately a large
number of memory mappings slows things down, backend exit is particularly
affected.  To address that, newer kernels (6.5) support using user-provided
memory for the memory. By putting the relevant memory into shared memory we
don't need any additional mappings.

On a system with a new enough kernel and liburing, there is no discernible
overhead when doing a pgbench -S -C anymore.

Reported-by: MARK CALLAGHAN <mdcallag@gmail.com>
Reviewed-by: "Burd, Greg" <greg@burd.me>
Reviewed-by: Jim Nasby <jnasby@upgrade.com>
Discussion: https://postgr.es/m/CAFbpF8OA44_UG+RYJcWH9WjF7E3GA6gka3gvH6nsrSnEe9H0NA@mail.gmail.com
Backpatch-through: 18

8 days agoConsider explicit incremental sort for Append and MergeAppend
Richard Guo [Tue, 8 Jul 2025 01:21:44 +0000 (10:21 +0900)]
Consider explicit incremental sort for Append and MergeAppend

For an ordered Append or MergeAppend, we need to inject an explicit
sort into any subpath that is not already well enough ordered.
Currently, only explicit full sorts are considered; incremental sorts
are not yet taken into account.

In this patch, for subpaths of an ordered Append or MergeAppend, we
choose to use explicit incremental sort if it is enabled and there are
presorted keys.

The rationale is based on the assumption that incremental sort is
always faster than full sort when there are presorted keys, a premise
that has been applied in various parts of the code.  In addition, the
current cost model tends to favor incremental sort as being cheaper
than full sort in the presence of presorted keys, making it reasonable
not to consider full sort in such cases.

No backpatch as this could result in plan changes.

Author: Richard Guo <guofenglinux@gmail.com>
Reviewed-by: Andrei Lepikhov <lepihov@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/CAMbWs4_V7a2enTR+T3pOY_YZ-FU8ZsFYym2swOz4jNMqmSgyuw@mail.gmail.com

9 days agooauth: Fix kqueue detection on OpenBSD
Jacob Champion [Mon, 7 Jul 2025 20:41:55 +0000 (13:41 -0700)]
oauth: Fix kqueue detection on OpenBSD

In b0635bfda, I added an early header check to the Meson OAuth support,
which was intended to duplicate the later checks for
HAVE_SYS_[EVENT|EPOLL]_H. However, I implemented the new test via
check_header() -- which tries to compile -- rather than has_header(),
which just looks for the file's existence.

The distinction matters on OpenBSD, where <sys/event.h> can't be
compiled without including prerequisite headers, so -Dlibcurl=enabled
failed on that platform. Switch to has_header() to fix this.

Note that reviewers expressed concern about the difference between our
Autoconf feature tests (which compile headers) and our Meson feature
tests (which do not). I'm not opposed to aligning the two, but I want to
avoid making bigger changes as part of this fix.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/flat/CAOYmi+kdR218ke2zu74oTJvzYJcqV1MN5=mGAPqZQuc79HMSVA@mail.gmail.com
Backpatch-through: 18

9 days agoAdapt pg_upgrade test to pg_lsn output format difference
Álvaro Herrera [Mon, 7 Jul 2025 20:38:12 +0000 (22:38 +0200)]
Adapt pg_upgrade test to pg_lsn output format difference

Commit 2633dae2e487 added some zero padding to various LSNs output
routines so that the low word is always 8 hex digits long, for easy
human consumption.  This included the pg_lsn datatype, which breaks the
pg_upgrade test when it compares the pg_dump output of an older version.
Silence this problem by setting the pg_lsn columns to NULL before the
upgrade.

Discussion: https://postgr.es/m/202507071504.xm2r26u7lmzr@alvherre.pgsql

9 days agoRestore the ability to run pl/pgsql expression queries in parallel.
Tom Lane [Mon, 7 Jul 2025 18:33:20 +0000 (14:33 -0400)]
Restore the ability to run pl/pgsql expression queries in parallel.

pl/pgsql's notion of an "expression" is very broad, encompassing
any SQL SELECT query that returns a single column and no more than
one row.  So there are cases, for example evaluation of an aggregate
function, where the query involves significant work and it'd be useful
to run it with parallel workers.  This used to be possible, but
commits 3eea7a0c9 et al unintentionally disabled it.

The simplest fix is to make exec_eval_expr() pass maxtuples = 0
rather than 2 to exec_run_select().  This avoids the new rule that
we will never use parallelism when a nonzero "count" limit is passed
to ExecutorRun().  (Note that the pre-3eea7a0c9 behavior was indeed
unsafe, so reverting that rule is not in the cards.)  The reason
for passing 2 before was that exec_eval_expr() will throw an error
if it gets more than one returned row, so we figured that as soon
as we have two rows we know that will happen and we might as well
stop running the query.  That choice was cost-free when it was made;
but disabling parallelism is far from cost-free, so now passing 2
amounts to optimizing a failure case at the expense of useful cases.
An expression query that can return more than one row is certainly
broken.  People might now need to wait a bit longer to discover such
breakage; but hopefully few will use enormously expensive cases as
their first test of new pl/pgsql logic.

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

9 days agoRefactor some repetitive SLRU code
Álvaro Herrera [Mon, 7 Jul 2025 14:49:19 +0000 (16:49 +0200)]
Refactor some repetitive SLRU code

Functions to bootstrap and zero pages in various SLRU callers were
fairly duplicative.  We can slash almost two hundred lines with a couple
of simple helpers:

 - SimpleLruZeroAndWritePage: Does the equivalent of SimpleLruZeroPage
   followed by flushing the page to disk
 - XLogSimpleInsertInt64: Does a XLogBeginInsert followed by XLogInsert
   of a trivial record whose data is just an int64.

Author: Evgeny Voropaev <evgeny.voropaev@tantorlabs.com>
Reviewed by: Álvaro Herrera <alvherre@kurilemu.de>
Reviewed by: Andrey Borodin <x4mmm@yandex-team.ru>
Reviewed by: Aleksander Alekseev <aleksander@timescale.com>
Discussion: https://www.postgresql.org/message-id/flat/97820ce8-a1cd-407f-a02b-47368fadb14b%40tantorlabs.com

9 days agoStandardize LSN formatting by zero padding
Álvaro Herrera [Mon, 7 Jul 2025 11:57:43 +0000 (13:57 +0200)]
Standardize LSN formatting by zero padding

This commit standardizes the output format for LSNs to ensure consistent
representation across various tools and messages.  Previously, LSNs were
inconsistently printed as `%X/%X` in some contexts, while others used
zero-padding.  This often led to confusion when comparing.

To address this, the LSN format is now uniformly set to `%X/%08X`,
ensuring the lower 32-bit part is always zero-padded to eight
hexadecimal digits.

Author: Japin Li <japinli@hotmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/ME0P300MB0445CA53CA0E4B8C1879AF84B641A@ME0P300MB0445.AUSP300.PROD.OUTLOOK.COM

9 days agoIntegrate FullTransactionIds deeper into two-phase code
Michael Paquier [Mon, 7 Jul 2025 03:50:40 +0000 (12:50 +0900)]
Integrate FullTransactionIds deeper into two-phase code

This refactoring is a follow-up of the work done in 5a1dfde8334b, that
has switched 2PC file names to use FullTransactionIds when written on
disk.  This will help with the integration of a follow-up solution
related to the handling of two-phase files during recovery, to address
older defects while reading these from disk after a crash.

This change is useful in itself as it reduces the need to build the
file names from epoch numbers and TransactionIds, because we can use
directly FullTransactionIds from which the 2PC file names are guessed.
So this avoids a lot of back-and-forth between the FullTransactionIds
retrieved from the file names and how these are passed around in the
internal 2PC logic.

Note that the core of the change is the use of a FullTransactionId
instead of a TransactionId in GlobalTransactionData, that tracks 2PC
file information in shared memory.  The change in TwoPhaseCallback makes
this commit unfit for stable branches.

Noah has contributed a good chunk of this patch.  I have spent some time
on it as well while working on the issues with two-phase state files and
recovery.

Author: Noah Misch <noah@leadboat.com>
Co-Authored-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/Z5sd5O9JO7NYNK-C@paquier.xyz
Discussion: https://postgr.es/m/20250116205254.65.nmisch@google.com

9 days agoFix incompatibility with libxml2 >= 2.14
Michael Paquier [Sun, 6 Jul 2025 23:53:57 +0000 (08:53 +0900)]
Fix incompatibility with libxml2 >= 2.14

libxml2 has deprecated the members of xmlBuffer, and it is recommended
to access them with dedicated routines.  We have only one case in the
tree where this shows an impact: xml2/xpath.c where "content" was
getting directly accessed.  The rest of the code looked fine, checking
the PostgreSQL code with libxml2 close to the top of its "2.14" branch.

xmlBufferContent() exists since year 2000 based on a check of the
upstream libxml2 tree, so let's switch to it.

Like 400928b83bd2, backpatch all the way down as this can have an impact
on all the branches already released once newer versions of libxml2 get
more popular.

Reported-by: Walid Ibrahim <walidib@amazon.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/aGdSdcR4QTjEHX6s@paquier.xyz
Backpatch-through: 13

10 days agopostgres_fdw: Add Assert to estimate_path_cost_size().
Etsuro Fujita [Sun, 6 Jul 2025 08:15:00 +0000 (17:15 +0900)]
postgres_fdw: Add Assert to estimate_path_cost_size().

When estimating the cost/size of a pre-sorted path for a given upper
relation using local stats, this function dereferences the passed-in
PgFdwPathExtraData pointer without checking that it is not NULL.  But
that is not a bug as the pointer is guaranteed to be non-NULL in that
case; to avoid confusion, add an Assert to ensure that it is not NULL
before dereferencing it.

Reported-by: Ranier Vilela <ranier.vf@gmail.com>
Author: Etsuro Fujita <etsuro.fujita@gmail.com>
Reviewed-by: Ranier Vilela <ranier.vf@gmail.com>
Discussion: https://postgr.es/m/CAEudQArgiALbV1akQpeZOgim7XP05n%3DbDP1%3DTcOYLA43nRX_vA%40mail.gmail.com

12 days agoFix new pg_upgrade query not to rely on regnamespace
Álvaro Herrera [Fri, 4 Jul 2025 19:30:05 +0000 (21:30 +0200)]
Fix new pg_upgrade query not to rely on regnamespace

That was invented in 9.5, and pg_upgrade claims to support back to 9.0.
But we don't need that with a simple query change, tested by Tom Lane.

Discussion: https://postgr.es/m/202507041645.afjl5rssvrgu@alvherre.pgsql

12 days agopg_upgrade: Add missing newline in error message
Álvaro Herrera [Fri, 4 Jul 2025 16:31:35 +0000 (18:31 +0200)]
pg_upgrade: Add missing newline in error message

Minor oversight in 347758b12063

12 days agopg_upgrade: check for inconsistencies in not-null constraints w/inheritance
Álvaro Herrera [Fri, 4 Jul 2025 16:05:43 +0000 (18:05 +0200)]
pg_upgrade: check for inconsistencies in not-null constraints w/inheritance

With tables defined like this,
  CREATE TABLE ip (id int PRIMARY KEY);
  CREATE TABLE ic (id int) INHERITS (ip);
  ALTER TABLE ic ALTER id DROP NOT NULL;

pg_upgrade fails during the schema restore phase due to this error:
  ERROR: column "id" in child table must be marked NOT NULL

This can only be fixed by marking the child column as NOT NULL before
the upgrade, which could take an arbitrary amount of time (because ic's
data must be scanned).  Have pg_upgrade's check mode warn if that
condition is found, so that users know what to adjust before running the
upgrade for real.

Author: Ali Akbar <the.apaan@gmail.com>
Reviewed-by: Justin Pryzby <pryzby@telsasoft.com>
Backpatch-through: 13
Discussion: https://postgr.es/m/CACQjQLoMsE+1pyLe98pi0KvPG2jQQ94LWJ+PTiLgVRK4B=i_jg@mail.gmail.com

12 days agoamcheck: Remove unused IndexCheckableCallback typedef.
Fujii Masao [Fri, 4 Jul 2025 14:25:40 +0000 (23:25 +0900)]
amcheck: Remove unused IndexCheckableCallback typedef.

Commit d70b17636dd introduced the IndexCheckableCallback typedef for
a callback function, but it was never used. This commit removes
the unused typedef to clean up dead code.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Discussion: https://postgr.es/m/e1ea4e14-3b21-4e01-a5f2-0686883265df@oss.nttdata.com

12 days agoDisable commit timestamps during bootstrap
Michael Paquier [Fri, 4 Jul 2025 06:09:24 +0000 (15:09 +0900)]
Disable commit timestamps during bootstrap

Attempting to use commit timestamps during bootstrapping leads to an
assertion failure, that can be reached for example with an initdb -c
that enables track_commit_timestamp.  It makes little sense to register
a commit timestamp for a BootstrapTransactionId, so let's disable the
activation of the module in this case.

This problem has been independently reported once by each author of this
commit.  Each author has proposed basically the same patch, relying on
IsBootstrapProcessingMode() to skip the use of commit_ts during
bootstrap.  The test addition is a suggestion by me, and is applied down
to v16.

Author: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Author: Andy Fan <zhihuifan1213@163.com>
Reviewed-by: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/OSCPR01MB14966FF9E4C4145F37B937E52F5102@OSCPR01MB14966.jpnprd01.prod.outlook.com
Discussion: https://postgr.es/m/87plejmnpy.fsf@163.com
Backpatch-through: 13

12 days agoSpeed up truncation of temporary relations.
Fujii Masao [Fri, 4 Jul 2025 00:03:58 +0000 (09:03 +0900)]
Speed up truncation of temporary relations.

Previously, truncating a temporary relation required scanning the entire
local buffer pool once per relation fork to invalidate buffers. This could
be slow, especially with a large local buffers, as the scan was repeated
multiple times.

A similar issue with regular tables (shared buffers) was addressed in
commit 6d05086c0a7 by scanning the buffer pool only once for all forks.

This commit applies the same optimization to temporary relations,
improving truncation performance.

Author: Daniil Davydov <3danissimo@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: Maxim Orlov <orlovmg@gmail.com>
Discussion: https://postgr.es/m/CAJDiXggNqsJOH7C5co4jA8nDk8vw-=sokyh5s1_TENWnC6Ofcg@mail.gmail.com

13 days agoSimplify COALESCE() with one surviving argument.
Tom Lane [Thu, 3 Jul 2025 21:39:53 +0000 (17:39 -0400)]
Simplify COALESCE() with one surviving argument.

If, after removal of useless null-constant arguments, a CoalesceExpr
has exactly one remaining argument, we can just take that argument as
the result, without bothering to wrap a new CoalesceExpr around it.
This isn't likely to produce any great improvement in runtime per se,
but it can lead to better plans since the planner no longer has to
treat the expression as non-strict.

However, there were a few regression test cases that intentionally
wrote COALESCE(x) as a shorthand way of creating a non-strict
subexpression.  To avoid ruining the intent of those tests, write
COALESCE(x,x) instead.  (If anyone ever proposes de-duplicating
COALESCE arguments, we'll need another iteration of this arms race.
But it seems pretty unlikely that such an optimization would be
worthwhile.)

Author: Maksim Milyutin <maksim.milyutin@tantorlabs.ru>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/8e8573c3-1411-448d-877e-53258b7b2be0@tantorlabs.ru

13 days agoAdd more cross-type comparisons to contrib/btree_gin.
Tom Lane [Thu, 3 Jul 2025 20:30:38 +0000 (16:30 -0400)]
Add more cross-type comparisons to contrib/btree_gin.

Using the just-added infrastructure, extend btree_gin to support
cross-type operators in its other opclasses.  All of the cross-type
comparison operators supported by the core btree opclasses for
these datatypes are now available for btree_gin indexes as well.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Arseniy Mukhin <arseniy.mukhin.dev@gmail.com>
Discussion: https://postgr.es/m/262624.1738460652@sss.pgh.pa.us

13 days agoAdd cross-type comparisons to contrib/btree_gin.
Tom Lane [Thu, 3 Jul 2025 20:24:31 +0000 (16:24 -0400)]
Add cross-type comparisons to contrib/btree_gin.

Extend the infrastructure in btree_gin.c to permit cross-type
operators, and add the code to support them for the int2, int4,
and int8 opclasses.  (To keep this patch digestible, I left
the other datatypes for a separate patch.)  This improves the
usability of btree_gin indexes by allowing them to support the
same set of queries that a regular btree index does.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Arseniy Mukhin <arseniy.mukhin.dev@gmail.com>
Discussion: https://postgr.es/m/262624.1738460652@sss.pgh.pa.us

13 days agoBreak out xxx2yyy_opt_overflow APIs for more datetime conversions.
Tom Lane [Thu, 3 Jul 2025 20:17:08 +0000 (16:17 -0400)]
Break out xxx2yyy_opt_overflow APIs for more datetime conversions.

Previous commits invented timestamp2timestamptz_opt_overflow,
date2timestamp_opt_overflow, and date2timestamptz_opt_overflow
functions to perform non-error-throwing conversions between
datetime types.  This patch completes the set by adding
timestamp2date_opt_overflow, timestamptz2date_opt_overflow,
and timestamptz2timestamp_opt_overflow.

In addition, adjust timestamp2timestamptz_opt_overflow so that it
doesn't throw error if timestamp2tm fails, but treats that as an
overflow case.  The situation probably can't arise except with an
invalid timestamp value, and I can't think of a way that that would
happen except data corruption.  However, it's pretty silly to have a
function whose entire reason for existence is to not throw errors for
out-of-range inputs nonetheless throw an error for out-of-range input.

The new APIs are not used in this patch, but will be needed in
upcoming btree_gin changes.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Arseniy Mukhin <arseniy.mukhin.dev@gmail.com>
Discussion: https://postgr.es/m/262624.1738460652@sss.pgh.pa.us

13 days agoObtain required table lock during cross-table updates, redux.
Tom Lane [Thu, 3 Jul 2025 17:46:07 +0000 (13:46 -0400)]
Obtain required table lock during cross-table updates, redux.

Commits 8319e5cb5 et al missed the fact that ATPostAlterTypeCleanup
contains three calls to ATPostAlterTypeParse, and the other two
also need protection against passing a relid that we don't yet
have lock on.  Add similar logic to those code paths, and add
some test cases demonstrating the need for it.

In v18 and master, the test cases demonstrate that there's a
behavioral discrepancy between stored generated columns and virtual
generated columns: we disallow changing the expression of a stored
column if it's used in any composite-type columns, but not that of
a virtual column.  Since the expression isn't actually relevant to
either sort of composite-type usage, this prohibition seems
unnecessary; but changing it is a matter for separate discussion.
For now we are just documenting the existing behavior.

Reported-by: jian he <jian.universality@gmail.com>
Author: jian he <jian.universality@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: CACJufxGKJtGNRRSXfwMW9SqVOPEMdP17BJ7DsBf=tNsv9pWU9g@mail.gmail.com
Backpatch-through: 13

13 days agoAdd tab-completion for ALTER TABLE not-nulls
Álvaro Herrera [Thu, 3 Jul 2025 14:54:36 +0000 (16:54 +0200)]
Add tab-completion for ALTER TABLE not-nulls

The command is: ALTER TABLE x ADD [CONSTRAINT y] NOT NULL z

This syntax was added in 18, but I got pushback for getting commit
dbf42b84ac7b in 18 (also tab-completion for new syntax) after the
feature freeze, so I'll put this in master only for now.

Author: Álvaro Herrera <alvherre@kurilemu.de>
Reported-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://postgr.es/m/d4f14c6b-086b-463c-b15f-01c7c9728eab@oss.nttdata.com
Discussion: https://postgr.es/m/202505111448.bwbfomrymq4b@alvherre.pgsql

13 days agoRemove leftover dead code from commit_ts.h.
Fujii Masao [Thu, 3 Jul 2025 14:39:45 +0000 (23:39 +0900)]
Remove leftover dead code from commit_ts.h.

Commit 08aa89b3262 removed the COMMIT_TS_SETTS WAL record,
leaving xl_commit_ts_set and SizeOfCommitTsSet unused. However,
it missed removing these definitions. This commit cleans up
the leftover code.

Since this is a cleanup rather than a bug fix, it is applied only to
the master branch.

Author: Andy Fan <zhihuifan1213@163.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/87ecuzmkqf.fsf@163.com

13 days agoFix broken XML
Álvaro Herrera [Thu, 3 Jul 2025 14:23:22 +0000 (16:23 +0200)]
Fix broken XML

I messed this up in commit 87251e114967.

Per buildfarm member alabio, via Daniel Gustafsson.

Discussion: https://postgr.es/m/B94D82D1-7AF4-4412-AC02-82EAA6154957@yesql.se

13 days agodoc: Update outdated descriptions of wal_status in pg_replication_slots.
Fujii Masao [Thu, 3 Jul 2025 14:07:23 +0000 (23:07 +0900)]
doc: Update outdated descriptions of wal_status in pg_replication_slots.

The documentation for pg_replication_slots previously mentioned only
max_slot_wal_keep_size as a condition under which the wal_status column
could show unreserved or lost. However, since commit be87200,
replication slots can also be invalidated due to horizon or wal_level,
and since commit ac0e33136ab, idle_replication_slot_timeout can also
trigger this state.

This commit updates the description of the wal_status column to
reflect that max_slot_wal_keep_size is not the only cause of the lost state.

Back-patched to v16, where the additional invalidation cases were introduced.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Reviewed-by: Nisha Moond <nisha.moond412@gmail.com>
Discussion: https://postgr.es/m/78b34e84-2195-4f28-a151-5d204a382fdd@oss.nttdata.com
Backpatch-through: 16

13 days agoPrevent creation of duplicate not-null constraints for domains
Álvaro Herrera [Thu, 3 Jul 2025 09:46:12 +0000 (11:46 +0200)]
Prevent creation of duplicate not-null constraints for domains

This was previously harmless, but now that we create pg_constraint rows
for those, duplicates are not welcome anymore.

Backpatch to 18.

Co-authored-by: jian he <jian.universality@gmail.com>
Co-authored-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/CACJufxFSC0mcQ82bSk58sO-WJY4P-o4N6RD2M0D=DD_u_6EzdQ@mail.gmail.com

13 days agoFix bogus grammar for a CREATE CONSTRAINT TRIGGER error
Álvaro Herrera [Thu, 3 Jul 2025 09:25:39 +0000 (11:25 +0200)]
Fix bogus grammar for a CREATE CONSTRAINT TRIGGER error

If certain constraint characteristic clauses (NO INHERIT, NOT VALID, NOT
ENFORCED) are given to CREATE CONSTRAINT TRIGGER, the resulting error
message is
  ERROR:  TRIGGER constraints cannot be marked NO INHERIT
which is a bit silly, because these aren't "constraints of type
TRIGGER".  Hardcode a better error message to prevent it.  This is a
cosmetic fix for quite a fringe problem with no known complaints from
users, so no backpatch.

While at it, silently accept ENFORCED if given.

Author: Amul Sul <sulamul@gmail.com>
Reviewed-by: jian he <jian.universality@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/CAAJ_b97hd-jMTS7AjgU6TDBCzDx_KyuKxG+K-DtYmOieg+giyQ@mail.gmail.com
Discussion: https://postgr.es/m/CACJufxHSp2puxP=q8ZtUGL1F+heapnzqFBZy5ZNGUjUgwjBqTQ@mail.gmail.com

13 days agoRefactor subtype field of AlterDomainStmt
Michael Paquier [Thu, 3 Jul 2025 07:34:28 +0000 (16:34 +0900)]
Refactor subtype field of AlterDomainStmt

AlterDomainStmt.subtype used characters for its subtypes of commands,
SET|DROP DEFAULT|NOT NULL and ADD|DROP|VALIDATE CONSTRAINT, which were
hardcoded in a couple of places of the code.  The code is improved by
using an enum instead, with the same character values as the original
code.

Note that the field was documented in parsenodes.h and that it forgot to
mention 'V' (VALIDATE CONSTRAINT).

Author: Quan Zongliang <quanzongliang@yeah.net>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: wenhui qiu <qiuwenhuifx@gmail.com>
Reviewed-by: Tender Wang <tndrwang@gmail.com>
Discussion: https://postgr.es/m/41ff310b-16bd-44b9-a3ef-97e20f14b709@yeah.net

13 days agodoc: Remove incorrect note about wal_status in pg_replication_slots.
Fujii Masao [Thu, 3 Jul 2025 07:03:19 +0000 (16:03 +0900)]
doc: Remove incorrect note about wal_status in pg_replication_slots.

The documentation previously stated that the wal_status column is NULL
if restart_lsn is NULL in the pg_replication_slots view. This is incorrect,
and wal_status can be "lost" even when restart_lsn is NULL.

This commit removes the incorrect description.

Back-patched to all supported versions.

Author: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Nisha Moond <nisha.moond412@gmail.com>
Discussion: https://postgr.es/m/c9d23cdc-b5dd-455a-8ee9-f1f24d701d89@oss.nttdata.com
Backpatch-through: 13

13 days agoSupport multi-line headers in COPY FROM command.
Fujii Masao [Thu, 3 Jul 2025 06:27:26 +0000 (15:27 +0900)]
Support multi-line headers in COPY FROM command.

The COPY FROM command now accepts a non-negative integer for the HEADER option,
allowing multiple header lines to be skipped. This is useful when the input
contains multi-line headers that should be ignored during data import.

Author: Shinya Kato <shinya11.kato@gmail.com>
Co-authored-by: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Yugo Nagata <nagata@sraoss.co.jp>
Discussion: https://postgr.es/m/CAOzEurRPxfzbxqeOPF_AGnAUOYf=Wk0we+1LQomPNUNtyZGBZw@mail.gmail.com

13 days agoImprove checks for GUC recovery_target_timeline
Michael Paquier [Thu, 3 Jul 2025 02:14:20 +0000 (11:14 +0900)]
Improve checks for GUC recovery_target_timeline

Currently check_recovery_target_timeline() converts any value that is
not "current", "latest", or a valid integer to 0.  So, for example, the
following configuration added to postgresql.conf followed by a startup:
recovery_target_timeline = 'bogus'
recovery_target_timeline = '9999999999'

...  results in the following error patterns:
FATAL:  22023: recovery target timeline 0 does not exist
FATAL:  22023: recovery target timeline 1410065407 does not exist

This is confusing, because the server does not reflect the intention of
the user, and just reports incorrect data unrelated to the GUC.

The origin of the problem is that we do not perform a range check in the
GUC value passed-in for recovery_target_timeline.  This commit improves
the situation by using strtou64() and by providing stricter range
checks.  Some test cases are added for the cases of an incorrect, an
upper-bound and a lower-bound timeline value, checking the sanity of the
reports based on the contents of the server logs.

Author: David Steele <david@pgmasters.net>
Discussion: https://postgr.es/m/e5d472c7-e9be-4710-8dc4-ebe721b62cea@pgbackrest.org

13 days agoEnable use of Memoize for ANTI joins
Richard Guo [Thu, 3 Jul 2025 01:57:26 +0000 (10:57 +0900)]
Enable use of Memoize for ANTI joins

Currently, we do not support Memoize for SEMI and ANTI joins because
nested loop SEMI/ANTI joins do not scan the inner relation to
completion, which prevents Memoize from marking the cache entry as
complete.  One might argue that we could mark the cache entry as
complete after fetching the first inner tuple, but that would not be
safe: if the first inner tuple and the current outer tuple do not
satisfy the join clauses, a second inner tuple matching the parameters
would find the cache entry already marked as complete.

However, if the inner side is provably unique, this issue doesn't
arise, since there would be no second matching tuple.  That said, this
doesn't help in the case of SEMI joins, because a SEMI join with a
provably unique inner side would already have been reduced to an inner
join by reduce_unique_semijoins.

Therefore, in this patch, we check whether the inner relation is
provably unique for ANTI joins and enable the use of Memoize in such
cases.

Author: Richard Guo <guofenglinux@gmail.com>
Reviewed-by: wenhui qiu <qiuwenhuifx@gmail.com>
Reviewed-by: Andrei Lepikhov <lepihov@gmail.com>
Discussion: https://postgr.es/m/CAMbWs48FdLiMNrmJL-g6mDvoQVt0yNyJAqMkv4e2Pk-5GKCZLA@mail.gmail.com

13 days agoAdd InjectionPointList() to retrieve list of injection points
Michael Paquier [Wed, 2 Jul 2025 23:41:25 +0000 (08:41 +0900)]
Add InjectionPointList() to retrieve list of injection points

This routine has come as a useful piece to be able to know the list of
injection points currently attached in a system.  One area would be to
use it in a set-returning function, or just let out-of-core code play
with it.

This hides the internals of the shared memory array lookup holding the
information about the injection points (point name, library and function
name), allocating the result in a palloc'd List consumable by the
caller.

Reviewed-by: Jeff Davis <pgsql@j-davis.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Reviewed-by: Rahila Syed <rahilasyed90@gmail.com>
Discussion: https://postgr.es/m/Z_xYkA21KyLEHvWR@paquier.xyz
Discussion: https://postgr.es/m/aBG2rPwl3GE7m1-Q@paquier.xyz

2 weeks agoCorrectly copy the target host identification in PQcancelCreate.
Tom Lane [Wed, 2 Jul 2025 19:47:59 +0000 (15:47 -0400)]
Correctly copy the target host identification in PQcancelCreate.

PQcancelCreate failed to copy struct pg_conn_host's "type" field,
instead leaving it zero (a/k/a CHT_HOST_NAME).  This seemingly
has no great ill effects if it should have been CHT_UNIX_SOCKET
instead, but if it should have been CHT_HOST_ADDRESS then a
null-pointer dereference will occur when the cancelConn is used.

Bug: #18974
Reported-by: Maxim Boguk <maxim.boguk@gmail.com>
Author: Sergei Kornilov <sk@zsrv.org>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/18974-575f02b2168b36b3@postgresql.org
Backpatch-through: 17

2 weeks agoFix cross-version upgrade test breakage from commit fe07100e82.
Nathan Bossart [Wed, 2 Jul 2025 18:26:33 +0000 (13:26 -0500)]
Fix cross-version upgrade test breakage from commit fe07100e82.

In commit fe07100e82, I renamed a couple of functions in
test_dsm_registry to make it clear what they are testing.  However,
the buildfarm's cross-version upgrade tests run pg_upgrade with the
test modules installed, so this caused errors like:

    ERROR:  could not find function "get_val_in_shmem" in file ".../test_dsm_registry.so"

To fix, revert those renames.  I could probably get away with only
un-renaming the C symbols, but I figured I'd avoid introducing
function name mismatches.  Also, AFAICT the buildfarm's
cross-version upgrade tests do not run the test module tests
post-upgrade, else we'll need to properly version the extension.

Per buildfarm member crake.

Discussion: https://postgr.es/m/aGVuYUNW23tStUYs%40nathan

2 weeks agoMake more use of RELATION_IS_OTHER_TEMP().
Nathan Bossart [Wed, 2 Jul 2025 17:32:19 +0000 (12:32 -0500)]
Make more use of RELATION_IS_OTHER_TEMP().

A few places were open-coding it instead of using this handy macro.

Author: Junwang Zhao <zhjwpku@gmail.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://postgr.es/m/CAEG8a3LjTGJcOcxQx-SUOGoxstG4XuCWLH0ATJKKt_aBTE5K8w%40mail.gmail.com

2 weeks agoAdd GetNamedDSA() and GetNamedDSHash().
Nathan Bossart [Wed, 2 Jul 2025 16:50:52 +0000 (11:50 -0500)]
Add GetNamedDSA() and GetNamedDSHash().

Presently, the dynamic shared memory (DSM) registry only provides
GetNamedDSMSegment(), which allocates a fixed-size segment.  To use
the DSM registry for more sophisticated things like dynamic shared
memory areas (DSAs) or a hash table backed by a DSA (dshash), users
need to create a DSM segment that stores various handles and LWLock
tranche IDs and to write fairly complicated initialization code.
Furthermore, there is likely little variation in this
initialization code between libraries.

This commit introduces functions that simplify allocating a DSA or
dshash within the DSM registry.  These functions are very similar
to GetNamedDSMSegment().  Notable differences include the lack of
an initialization callback parameter and the prohibition of calling
the functions more than once for a given entry in each backend
(which should be trivially avoidable in most circumstances).  While
at it, this commit bumps the maximum DSM registry entry name length
from 63 bytes to 127 bytes.

Also note that even though one could presumably detach/destroy the
DSAs and dshashes created in the registry, such use-cases are not
yet well-supported, if for no other reason than the associated DSM
registry entries cannot be removed.  Adding such support is left as
a future exercise.

The test_dsm_registry test module contains tests for the new
functions and also serves as a complete usage example.

Reviewed-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Reviewed-by: Sami Imseih <samimseih@gmail.com>
Reviewed-by: Florents Tselai <florents.tselai@gmail.com>
Reviewed-by: Rahila Syed <rahilasyed90@gmail.com>
Discussion: https://postgr.es/m/aEC8HGy2tRQjZg_8%40nathan

2 weeks agoUpdate obsolete row compare preprocessing comments.
Peter Geoghegan [Wed, 2 Jul 2025 16:36:35 +0000 (12:36 -0400)]
Update obsolete row compare preprocessing comments.

Restore nbtree preprocessing comments describing how we mark nbtree row
compare members required to how they were prior to 2016 bugfix commit
a298a1e0.

Oversight in commit bd3f59fd, which made nbtree preprocessing revert to
the original 2006 rules, but neglected to revert these comments.

Backpatch-through: 18

2 weeks agoAllow width_bucket()'s "operand" input to be NaN.
Tom Lane [Wed, 2 Jul 2025 15:34:40 +0000 (11:34 -0400)]
Allow width_bucket()'s "operand" input to be NaN.

The array-based variant of width_bucket() has always accepted NaN
inputs, treating them as equal but larger than any non-NaN,
as we do in ordinary comparisons.  But up to now, the four-argument
variants threw errors for a NaN operand.  This is inconsistent
and unnecessary, since we can perfectly well regard NaN as falling
after the last bucket.

We do still throw error for NaN or infinity histogram-bound inputs,
since there's no way to compute sensible bucket boundaries.

Arguably this is a bug fix, but given the lack of field complaints
I'm content to fix it in master.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Dean Rasheed <dean.a.rasheed@gmail.com>
Discussion: https://postgr.es/m/2822872.1750540911@sss.pgh.pa.us