postgresql.git
10 months agoSQL/JSON: Prevent ON EMPTY for EXISTS columns in JSON_TABLE()
Amit Langote [Fri, 28 Jun 2024 04:59:13 +0000 (13:59 +0900)]
SQL/JSON: Prevent ON EMPTY for EXISTS columns in JSON_TABLE()

Due to an oversight in de3600452b61, the ON EMPTY clause was
incorrectly allowed in the EXISTS column. Fix the grammar to prevent
this.

Discussion: https://postgr.es/m/CA%2BHiwqHh3YDXTpccgAo4CdfV9Mhy%2Bmg%3Doh6t8rfM5uLW1BJN4g%40mail.gmail.com

10 months agoUpdate modules/injection_points/.gitignore
Michael Paquier [Fri, 28 Jun 2024 04:41:39 +0000 (13:41 +0900)]
Update modules/injection_points/.gitignore

Thinko in c35f419d6efb, where an isolation test has been added to the
module.

10 months agoFix comments in heaptuple.c
Michael Paquier [Fri, 28 Jun 2024 04:30:47 +0000 (13:30 +0900)]
Fix comments in heaptuple.c

Since e27f4ee0a701, fastgetattr() and heap_getattr() are not macros, but
inlined functions.

Author: Junwang Zhao
Reviewed-by: Stepan Neretin
Discussion: https://postgr.es/m/CAEG8a3JS-JKWWyOcM7BU=vPqFXa3W7mZSHnvc3CBqx=tC+3SCA@mail.gmail.com

10 months agoImprove locking around InjectionPointRun()
Michael Paquier [Fri, 28 Jun 2024 03:31:29 +0000 (12:31 +0900)]
Improve locking around InjectionPointRun()

As coded, an injection point could be loaded into the local cache
without the LWLock InjectionPointLock taken, hence a point detached and
re-attached concurrently of a point running calling InjectionPointRun()
may finish by loading a callback it did no set initially.  Based on all
the cases discussed until now on the lists, it is fine to delay the lock
release until the callback is run, so let's do that.

While on it, remove a useless LWLockRelease() called before an error in
InjectionPointAttach().

Per discussion with Heikki Linnakangas and Noah Misch.

Discussion: https://postgr.es/m/e1ffb822-054e-4006-ac06-50532767f75b@iki.fi

10 months agoRemove comment about xl_heap_inplace "AT END OF STRUCT".
Noah Misch [Fri, 28 Jun 2024 02:21:06 +0000 (19:21 -0700)]
Remove comment about xl_heap_inplace "AT END OF STRUCT".

Commit 2c03216d831160bedd72d45f712601b6f7d03f1c moved the tuple data
from there to the buffer-0 data.  Back-patch to v12 (all supported
versions), the plan for the next change to this struct.

Discussion: https://postgr.es/m/20240523000548[email protected]

10 months agoCope with inplace update making catcache stale during TOAST fetch.
Noah Misch [Fri, 28 Jun 2024 02:21:06 +0000 (19:21 -0700)]
Cope with inplace update making catcache stale during TOAST fetch.

This extends ad98fb14226ae6456fbaed7990ee7591cbe5efd2 to invals of
inplace updates.  Trouble requires an inplace update of a catalog having
a TOAST table, so only pg_database was at risk.  (The other catalog on
which core code performs inplace updates, pg_class, has no TOAST table.)
Trouble would require something like the inplace-inval.spec test.
Consider GRANT ... ON DATABASE fetching a stale row from cache and
discarding a datfrozenxid update that vac_truncate_clog() has already
relied upon.  Back-patch to v12 (all supported versions).

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240114201411[email protected]
Discussion: https://postgr.es/m/20240512232923[email protected]

10 months agoAccessExclusiveLock new relations just after assigning the OID.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
AccessExclusiveLock new relations just after assigning the OID.

This has no user-visible, important consequences, since other sessions'
catalog scans can't find the relation until we commit.  However, this
unblocks introducing a rule about locks required to heap_update() a
pg_class row.  CREATE TABLE has been acquiring this lock eventually, but
it can heap_update() pg_class.relchecks earlier.  create_toast_table()
has been acquiring only ShareLock.  Back-patch to v12 (all supported
versions), the plan for the commit relying on the new rule.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240611024525[email protected]

10 months agoLock before setting relhassubclass on RELKIND_PARTITIONED_INDEX.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Lock before setting relhassubclass on RELKIND_PARTITIONED_INDEX.

Commit 5b562644fec696977df4a82790064e8287927891 added a comment that
SetRelationHasSubclass() callers must hold this lock.  When commit
17f206fbc824d2b4b14480199ca9ff7dea417eda extended use of this column to
partitioned indexes, it didn't take the lock.  As the latter commit
message mentioned, we currently never reset a partitioned index to
relhassubclass=f.  That largely avoids harm from the lock omission.  The
cause for fixing this now is to unblock introducing a rule about locks
required to heap_update() a pg_class row.  This might cause more
deadlocks.  It gives minor user-visible benefits:

- If an ALTER INDEX SET TABLESPACE runs concurrently with ALTER TABLE
  ATTACH PARTITION or CREATE PARTITION OF, one transaction blocks
  instead of failing with "tuple concurrently updated".  (Many cases of
  DDL concurrency still fail that way.)

- Match ALTER INDEX ATTACH PARTITION in choosing to lock the index.

While not user-visible today, we'll need this if we ever make something
set the flag to false for a partitioned index, like ANALYZE does today
for tables.  Back-patch to v12 (all supported versions), the plan for
the commit relying on the new rule.  In back branches, add
LockOrStrongerHeldByMe() instead of adding a LockHeldByMe() parameter.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240611024525[email protected]

10 months agoLock owned sequences during ALTER TABLE SET { LOGGED | UNLOGGED }.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Lock owned sequences during ALTER TABLE SET { LOGGED | UNLOGGED }.

These commands already make the persistence of owned sequences follow
owned table persistence changes.  They didn't lock those sequences.
They lost the effect of nextval() calls that other sessions make after
the ALTER TABLE command, before the ALTER TABLE transaction commits.
Fix by acquiring the same lock that ALTER SEQUENCE SET { LOGGED |
UNLOGGED } acquires.  This might cause more deadlocks.  Back-patch to
v15, where commit 344d62fb9a978a72cf8347f0369b9ee643fd0b31 introduced
unlogged sequences.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240611024525[email protected]

10 months agoExpand comments and add an assertion in nodeModifyTable.c.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Expand comments and add an assertion in nodeModifyTable.c.

Most comments concern RELKIND_VIEW.  One addresses the ExecUpdate()
"tupleid" parameter.  A later commit will rely on these facts, but they
hold already.  Back-patch to v12 (all supported versions), the plan for
that commit.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

10 months agoAdd an injection_points isolation test suite.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Add an injection_points isolation test suite.

Make the isolation harness recognize injection_points wait events as a
type of blocked state.  Test an extant inplace-update bug.

Reviewed by Robert Haas and Michael Paquier.

Discussion: https://postgr.es/m/20240512232923[email protected]

10 months agoCreate waitfuncs.c for pg_isolation_test_session_is_blocked().
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Create waitfuncs.c for pg_isolation_test_session_is_blocked().

The next commit makes the function inspect an additional non-lock
contention source, so it no longer fits in lockfuncs.c.

Reviewed by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

10 months agoAdd wait event type "InjectionPoint", a custom type like "Extension".
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Add wait event type "InjectionPoint", a custom type like "Extension".

Both injection points and customization of type "Extension" are new in
v17, so this just changes a detail of an unreleased feature.

Reported by Robert Haas.  Reviewed by Michael Paquier.

Discussion: https://postgr.es/m/CA+TgmobfMU5pdXP36D5iAwxV5WKE_vuDLtp_1QyH+H5jMMt21g@mail.gmail.com

10 months agoImprove test coverage for changes to inplace-updated catalogs.
Noah Misch [Fri, 28 Jun 2024 02:21:05 +0000 (19:21 -0700)]
Improve test coverage for changes to inplace-updated catalogs.

This covers both regular and inplace changes, since bugs arise at their
intersection.  Where marked, these witness extant bugs.  Back-patch to
v12 (all supported versions).

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

10 months agoMake TAP todo_start effects the same under Meson and prove_check.
Noah Misch [Fri, 28 Jun 2024 02:21:04 +0000 (19:21 -0700)]
Make TAP todo_start effects the same under Meson and prove_check.

This could have caused spurious failures only on SPARC Linux, because
today's only todo_start tests for that platform.  Back-patch to v16,
where Meson support first appeared.

Reviewed by Robert Haas.

Discussion: https://postgr.es/m/20240512232923[email protected]

10 months agoSQL/JSON: Document behavior when input document is not jsonb
Amit Langote [Fri, 28 Jun 2024 00:42:13 +0000 (09:42 +0900)]
SQL/JSON: Document behavior when input document is not jsonb

The input document to functions JSON_EXISTS(), JSON_QUERY(),
JSON_VALUE(), and JSON_TABLE() can be specified as character or
UTF8-encoded bytea strings. These are automatically converted to
jsonb with an implicit cast before being passed to the jsonpath
machinery.

In the current implementation, errors that occur when parsing the
specified string into a valid JSON document are thrown
unconditionally. This means they are not subject to the explicit or
implicit ON ERROR clause of those functions, which is a standard-
conforming behavior.  Add a note to the documentation to mention
that.

Reported-by: Markus Winand
Discussion: https://postgr.es/m/F7DD1442-265C-4220-A603-CB0DEB77E91D%40winand.at

10 months agoAvoid crashing when a JIT-inlined backend function throws an error.
Tom Lane [Thu, 27 Jun 2024 18:43:59 +0000 (14:43 -0400)]
Avoid crashing when a JIT-inlined backend function throws an error.

errfinish() assumes that the __FUNC__ and __FILE__ arguments it's
passed are compile-time constant strings that can just be pointed
to rather than physically copied.  However, it's possible for LLVM
to generate code in which those pointers point into a dynamically
loaded code segment.  If that segment gets unloaded before we're
done with the ErrorData struct, we have dangling pointers that
will lead to SIGSEGV.  In simple cases that won't happen, because we
won't unload LLVM code before end of transaction.  But it's possible
to happen if the error is thrown within end-of-transaction code run by
_SPI_commit or _SPI_rollback, because since commit 2e517818f those
functions clean up by ending the transaction and starting a new one.

Rather than fixing this by adding pstrdup() overhead to every
elog/ereport sequence, let's fix it by copying the risky pointers
in CopyErrorData().  That solves it for _SPI_commit/_SPI_rollback
because they use that function to preserve the error data across
the transaction end/restart sequence; and it seems likely that
any other code doing something similar would need to do that too.

I'm suspicious that this behavior amounts to an LLVM bug (or a
bug in our use of it?), because it implies that string constant
references that should be pointer-equal according to a naive
understanding of C semantics will sometimes not be equal.
However, even if it is a bug and someday gets fixed, we'll have
to cope with the current behavior for a long time to come.

Report and patch by me.  Back-patch to all supported branches.

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

10 months agoFix MVCC bug with prepared xact with subxacts on standby
Heikki Linnakangas [Thu, 27 Jun 2024 18:06:32 +0000 (21:06 +0300)]
Fix MVCC bug with prepared xact with subxacts on standby

We did not recover the subtransaction IDs of prepared transactions
when starting a hot standby from a shutdown checkpoint. As a result,
such subtransactions were considered as aborted, rather than
in-progress. That would lead to hint bits being set incorrectly, and
the subtransactions suddenly becoming visible to old snapshots when
the prepared transaction was committed.

To fix, update pg_subtrans with prepared transactions's subxids when
starting hot standby from a shutdown checkpoint. The snapshots taken
from that state need to be marked as "suboverflowed", so that we also
check the pg_subtrans.

Backport to all supported versions.

Discussion: https://www.postgresql.org/message-id/6b852e98-2d49-4ca1-9e95-db419a2696e0@iki.fi

10 months agotests: Trim newline from result returned by BackgroundPsql->query
Heikki Linnakangas [Thu, 27 Jun 2024 18:06:27 +0000 (21:06 +0300)]
tests: Trim newline from result returned by BackgroundPsql->query

This went unnoticed, because only a few existing callers of
BackgroundPsql->query used the result, and the ones that did were not
bothered by an extra newline. I noticed because I was about to add a
new test that checks the result.

Backport to all supported versions, since I just backported the
BackgroundPsql facility to all supported versions too.

10 months agoFix thinkos in comments
Alvaro Herrera [Thu, 27 Jun 2024 17:51:47 +0000 (19:51 +0200)]
Fix thinkos in comments

The first one was noticed by Tender Wang and introduced with
8aba9322511f; the other one was newly introduced with dbca3469ebf8.

10 months agoDrop the temporary tuple slots allocated by pgoutput.
Amit Kapila [Thu, 27 Jun 2024 06:05:00 +0000 (11:35 +0530)]
Drop the temporary tuple slots allocated by pgoutput.

In pgoutput, when converting the child table's tuple format to match the
parent table's, we temporarily create a new slot to store the converted
tuple. However, we missed to drop such temporary slots, leading to
resource leakage.

Reported-by: Bowen Shi
Author: Hou Zhijie
Reviewed-by: Amit Kapila
Backpatch-through: 15
Discussion: https://postgr.es/m/CAM_vCudv8dc3sjWiPkXx5F2b27UV7_YRKRbtSCcE-pv=cVACGA@mail.gmail.com

10 months agoFix overflow with pgstats DSA reference count
Michael Paquier [Thu, 27 Jun 2024 00:44:47 +0000 (09:44 +0900)]
Fix overflow with pgstats DSA reference count

When pgstats is initialized for a backend, it uses dsa_attach_in_place()
without a "segment" provided.  Hence, no callback is registered to
automatically release the DSA attached once a backend exits.  Not doing
any cleanup causes the reference count of the pgstats DSA to
continuously increment, at some point overflowing it (the more the
number of connections, the faster it is to reach this state).  Once the
reference count overflows and then gets back to 0, new backends are not
able to attach to the pgstats DSA, failing startup.

This issue is resolved by adding in the pgstats shutdown hook a call to
dsa_release_in_place(), ensuring that the DSA attached at backend
startup is correctly released, keeping the reference count at bay.

The author of this patch has been able to see this issue on a server
with a long uptime and a high connection turnover.

Issue introduced by 5891c7a8ed8f, so backpatch down to 15.

Author: Anthonin Bonnefoy
Discussion: https://postgr.es/m/CAO6_XqqJbJBL=M7Ym13TcB4Xnq58vRa2jcC+gwEPBgbAda6B1Q@mail.gmail.com
Backpatch-through: 15

10 months agoFix bugs in MultiXact truncation
Heikki Linnakangas [Fri, 21 Jun 2024 15:31:15 +0000 (18:31 +0300)]
Fix bugs in MultiXact truncation

1. TruncateMultiXact() performs the SLRU truncations in a critical
section. Deleting the SLRU segments calls ForwardSyncRequest(), which
will try to compact the request queue if it's full
(CompactCheckpointerRequestQueue()). That in turn allocates memory,
which is not allowed in a critical section. Backtrace:

    TRAP: failed Assert("CritSectionCount == 0 || (context)->allowInCritSection"), File: "../src/backend/utils/mmgr/mcxt.c", Line: 1353, PID: 920981
    postgres: autovacuum worker template0(ExceptionalCondition+0x6e)[0x560a501e866e]
    postgres: autovacuum worker template0(+0x5dce3d)[0x560a50217e3d]
    postgres: autovacuum worker template0(ForwardSyncRequest+0x8e)[0x560a4ffec95e]
    postgres: autovacuum worker template0(RegisterSyncRequest+0x2b)[0x560a50091eeb]
    postgres: autovacuum worker template0(+0x187b0a)[0x560a4fdc2b0a]
    postgres: autovacuum worker template0(SlruDeleteSegment+0x101)[0x560a4fdc2ab1]
    postgres: autovacuum worker template0(TruncateMultiXact+0x2fb)[0x560a4fdbde1b]
    postgres: autovacuum worker template0(vac_update_datfrozenxid+0x4b3)[0x560a4febd2f3]
    postgres: autovacuum worker template0(+0x3adf66)[0x560a4ffe8f66]
    postgres: autovacuum worker template0(AutoVacWorkerMain+0x3ed)[0x560a4ffe7c2d]
    postgres: autovacuum worker template0(+0x3b1ead)[0x560a4ffecead]
    postgres: autovacuum worker template0(+0x3b620e)[0x560a4fff120e]
    postgres: autovacuum worker template0(+0x3b3fbb)[0x560a4ffeefbb]
    postgres: autovacuum worker template0(+0x2f724e)[0x560a4ff3224e]
    /lib/x86_64-linux-gnu/libc.so.6(+0x27c8a)[0x7f62cc642c8a]
    /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x85)[0x7f62cc642d45]
    postgres: autovacuum worker template0(_start+0x21)[0x560a4fd16f31]

To fix, bail out in CompactCheckpointerRequestQueue() without doing
anything, if it's called in a critical section. That covers the above
call path, as well as any other similar cases where
RegisterSyncRequest might be called in a critical section.

2. After fixing that, another problem became apparent: Autovacuum
process doing that truncation can deadlock with the checkpointer
process. TruncateMultiXact() sets "MyProc->delayChkptFlags |=
DELAY_CHKPT_START". If the sync request queue is full and cannot be
compacted, the process will repeatedly sleep and retry, until there is
room in the queue. However, if the checkpointer is trying to start a
checkpoint at the same time, and is waiting for the DELAY_CHKPT_START
processes to finish, the queue will never shrink.

More concretely, the autovacuum process is stuck here:

    #0  0x00007fc934926dc3 in epoll_wait () from /lib/x86_64-linux-gnu/libc.so.6
    #1  0x000056220b24348b in WaitEventSetWaitBlock (set=0x56220c2e4b50, occurred_events=0x7ffe7856d040, nevents=1, cur_timeout=<optimized out>) at ../src/backend/storage/ipc/latch.c:1570
    #2  WaitEventSetWait (set=0x56220c2e4b50, timeout=timeout@entry=10, occurred_events=<optimized out>, occurred_events@entry=0x7ffe7856d040, nevents=nevents@entry=1,
        wait_event_info=wait_event_info@entry=150994949) at ../src/backend/storage/ipc/latch.c:1516
    #3  0x000056220b243224 in WaitLatch (latch=<optimized out>, latch@entry=0x0, wakeEvents=wakeEvents@entry=40, timeout=timeout@entry=10, wait_event_info=wait_event_info@entry=150994949)
        at ../src/backend/storage/ipc/latch.c:538
    #4  0x000056220b26cf46 in RegisterSyncRequest (ftag=ftag@entry=0x7ffe7856d0a0, type=type@entry=SYNC_FORGET_REQUEST, retryOnError=true) at ../src/backend/storage/sync/sync.c:614
    #5  0x000056220af9db0a in SlruInternalDeleteSegment (ctl=ctl@entry=0x56220b7beb60 <MultiXactMemberCtlData>, segno=segno@entry=11350) at ../src/backend/access/transam/slru.c:1495
    #6  0x000056220af9dab1 in SlruDeleteSegment (ctl=ctl@entry=0x56220b7beb60 <MultiXactMemberCtlData>, segno=segno@entry=11350) at ../src/backend/access/transam/slru.c:1566
    #7  0x000056220af98e1b in PerformMembersTruncation (oldestOffset=<optimized out>, newOldestOffset=<optimized out>) at ../src/backend/access/transam/multixact.c:3006
    #8  TruncateMultiXact (newOldestMulti=newOldestMulti@entry=3221225472, newOldestMultiDB=newOldestMultiDB@entry=4) at ../src/backend/access/transam/multixact.c:3201
    #9  0x000056220b098303 in vac_truncate_clog (frozenXID=749, minMulti=<optimized out>, lastSaneFrozenXid=749, lastSaneMinMulti=3221225472) at ../src/backend/commands/vacuum.c:1917
    #10 vac_update_datfrozenxid () at ../src/backend/commands/vacuum.c:1760
    #11 0x000056220b1c3f76 in do_autovacuum () at ../src/backend/postmaster/autovacuum.c:2550
    #12 0x000056220b1c2c3d in AutoVacWorkerMain (startup_data=<optimized out>, startup_data_len=<optimized out>) at ../src/backend/postmaster/autovacuum.c:1569

and the checkpointer is stuck here:

    #0  0x00007fc9348ebf93 in clock_nanosleep () from /lib/x86_64-linux-gnu/libc.so.6
    #1  0x00007fc9348fe353 in nanosleep () from /lib/x86_64-linux-gnu/libc.so.6
    #2  0x000056220b40ecb4 in pg_usleep (microsec=microsec@entry=10000) at ../src/port/pgsleep.c:50
    #3  0x000056220afb43c3 in CreateCheckPoint (flags=flags@entry=108) at ../src/backend/access/transam/xlog.c:7098
    #4  0x000056220b1c6e86 in CheckpointerMain (startup_data=<optimized out>, startup_data_len=<optimized out>) at ../src/backend/postmaster/checkpointer.c:464

To fix, add AbsorbSyncRequests() to the loops where the checkpointer
waits for DELAY_CHKPT_START or DELAY_CHKPT_COMPLETE operations to
finish.

Backpatch to v14. Before that, SLRU deletion didn't call
RegisterSyncRequest, which avoided this failure. I'm not sure if there
are other similar scenarios on older versions, but we haven't had
any such reports.

Discussion: https://www.postgresql.org/message-id/ccc66933-31c1-4f6a-bf4b-45fef0d4f22e@iki.fi

10 months agodoc PG 17 relnotes: fix system catalog name mistake
Bruce Momjian [Wed, 26 Jun 2024 19:08:06 +0000 (15:08 -0400)]
doc PG 17 relnotes:  fix system catalog name mistake

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwYgkaOuao4DXuQwhbg+vyu4Xb5TGpuDNDOfMa0AftyweQ@mail.gmail.com

Backpatch-through: master

10 months agodoc PG 17 relnotes: add item about pg_collation column renames
Bruce Momjian [Wed, 26 Jun 2024 17:13:46 +0000 (13:13 -0400)]
doc PG 17 relnotes:  add item about pg_collation column renames

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwYRw30QaWrSsL57k3L_=zdQ4JTgY9pGnnhm42B7fGJX1A@mail.gmail.com

Backpatch-through: master

10 months agoUse PqMsg_* macros in fe-auth.c.
Nathan Bossart [Wed, 26 Jun 2024 16:25:38 +0000 (11:25 -0500)]
Use PqMsg_* macros in fe-auth.c.

Commit f4b54e1ed9, which introduced macros for protocol characters,
missed updating a few places in fe-auth.c.

Author: Jelte Fennema-Nio
Discussion: https://postgr.es/m/CAGECzQSoPHtZ4xe0raJ6FYSEiPPS%2BYWXBhOGo%2BY1YecLgknF3g%40mail.gmail.com

10 months agoFix nbtree array unsatisfied inequality check.
Peter Geoghegan [Wed, 26 Jun 2024 14:45:52 +0000 (10:45 -0400)]
Fix nbtree array unsatisfied inequality check.

_bt_advance_array_keys didn't take sufficient care at the point where it
decides whether to start a new primitive index scan based on a call to
_bt_check_compare against finaltup (a call with the scan direction
flipped around).  The final decision was conditioned on rules about how
the scan key offset sktrig that initially triggered array advancement
(passed to _bt_advance_array_keys from its _bt_checkkeys caller)
compared to the offset set by its own _bt_check_compare finaltup call.
This approach was faulty, in that it allowed _bt_advance_array_keys to
incorrectly start a new primitive index scan, that landed on the same
leaf page (on assert-enabled builds it led to an assertion failure).

In general, scans with array keys are expected to never have to read the
same leaf page more than once (barring cases involving cursors, and
cases where the scan restores a marked position for the inner side of a
merge join).  This principle was established by commit 5bf748b8.

To fix, make the final decision based on whether the scan key offset set
by the _bt_check_compare finaltup call is an offset to an inequality
strategy scan key.  An unsatisfied required inequality strategy scan key
indicates that all of the scan's required equality strategy scan keys
must also be satisfied by finaltup (not just by caller's tuple), and
that there is a decent chance that _bt_first will be able to reposition
the scan to a position many leaf pages ahead of the current leaf page.

Oversight in commit 5bf748b8.

Discussion: https://postgr.es/m/CAH2-Wz=DyHbcg7o6zXqzyiin8WE8vzk4tvU8Lrnh-a=EAvO0TQ@mail.gmail.com

10 months agoFix partition pruning setup during DETACH CONCURRENTLY
Alvaro Herrera [Wed, 26 Jun 2024 11:40:26 +0000 (13:40 +0200)]
Fix partition pruning setup during DETACH CONCURRENTLY

When detaching partition in concurrent mode, it's possible for partition
descriptors to not match the set that was recently seen when the plan
was made, causing an assertion failure or (in production builds) failure
to construct a working plan.  The case that was reported involves
prepared statements, but I think it may be possible to hit this bug
without that too.

The problem is that CreatePartitionPruneState is constructing a
PartitionPruneState under the assumption that new partitions can be
added, but never removed, but it turns out that this isn't true: a
prepared statement gets replanned when the DETACH CONCURRENTLY session
sends out its invalidation message, but if the invalidation message
arrives after ExecInitAppend started, we would build a partition
descriptor without the partition, and then CreatePartitionPruneState
would refuse to work with it.

CreatePartitionPruneState already contains code to deal with the new
descriptor having more partitions than before (and behaving for the
extra partitions as if they had been pruned), but doesn't have code to
deal with less partitions than before, and it is naïve about the case
where the number of partitions is the same.  We could simply add that a
new stanza for less partitions than before, and in simple testing it
works to do that; but it's possible to press the test scripts even
further and hit the case where one partition is added and a partition is
removed quickly enough that we see the same number of partitions, but
they don't actually match, causing hangs during execution.

To cope with both these problems, we now memcmp() the arrays of
partition OIDs, and do a more elaborate mapping (relying on the fact
that both OID arrays are in partition-bounds order) if they're not
identical.

This fix was already pushed in backbranches earlier.

Reported-by: yajun Hu <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Discussion: https://postgr.es/m/18377-e0324601cfebdfe5@postgresql.org

10 months agoImprove comment in gram.y.
Tom Lane [Tue, 25 Jun 2024 21:53:41 +0000 (17:53 -0400)]
Improve comment in gram.y.

"As so-and-so" isn't bad English, but it has a faintly archaic
whiff to it, and confuses some non-native speakers.  Write
"Like so-and-so" instead.

Per complaint from Tatsuo Ishii.

Discussion: https://postgr.es/m/20240623.130154.1867056921698616251[email protected]

10 months agoStamp 17beta2. REL_17_BETA2
Joe Conway [Mon, 24 Jun 2024 21:24:14 +0000 (17:24 -0400)]
Stamp 17beta2.

10 months agoRevert "Fix partition pruning setup during DETACH CONCURRENTLY"
Alvaro Herrera [Mon, 24 Jun 2024 15:20:21 +0000 (17:20 +0200)]
Revert "Fix partition pruning setup during DETACH CONCURRENTLY"

This reverts commit 27162a64b386; this branch is in code freeze due to a
nearing release.  We can commit again after the release is out.

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

10 months agoFix partition pruning setup during DETACH CONCURRENTLY
Alvaro Herrera [Mon, 24 Jun 2024 13:56:32 +0000 (15:56 +0200)]
Fix partition pruning setup during DETACH CONCURRENTLY

When detaching partition in concurrent mode, it's possible for partition
descriptors to not match the set that was recently seen when the plan
was made, causing an assertion failure or (in production builds) failure
to construct a working plan.  The case that was reported involves
prepared statements, but I think it may be possible to hit this bug
without that too.

The problem is that CreatePartitionPruneState is constructing a
PartitionPruneState under the assumption that new partitions can be
added, but never removed, but it turns out that this isn't true: a
prepared statement gets replanned when the DETACH CONCURRENTLY session
sends out its invalidation message, but if the invalidation message
arrives after ExecInitAppend started, we would build a partition
descriptor without the partition, and then CreatePartitionPruneState
would refuse to work with it.

CreatePartitionPruneState already contains code to deal with the new
descriptor having more partitions than before (and behaving for the
extra partitions as if they had been pruned), but doesn't have code to
deal with less partitions than before, and it is naïve about the case
where the number of partitions is the same.  We could simply add that a
new stanza for less partitions than before, and in simple testing it
works to do that; but it's possible to press the test scripts even
further and hit the case where one partition is added and a partition is
removed quickly enough that we see the same number of partitions, but
they don't actually match, causing hangs during execution.

To cope with both these problems, we now memcmp() the arrays of
partition OIDs, and do a more elaborate mapping (relying on the fact
that both OID arrays are in partition-bounds order) if they're not
identical.

Backpatch to 14, where DETACH CONCURRENTLY appeared.

Reported-by: yajun Hu <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Discussion: https://postgr.es/m/18377-e0324601cfebdfe5@postgresql.org

10 months agoTranslation updates
Peter Eisentraut [Mon, 24 Jun 2024 11:11:27 +0000 (13:11 +0200)]
Translation updates

Source-Git-URL: https://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 4409d73e450606ff15b428303d706f1d15c1f597

10 months agoRemove extra comment at TableAmRoutine.scan_analyze_next_block
Alexander Korotkov [Sat, 22 Jun 2024 13:13:08 +0000 (16:13 +0300)]
Remove extra comment at TableAmRoutine.scan_analyze_next_block

The extra comment was accidentally copied here by 6377e12a from
heapam_scan_analyze_next_block().

Reported-by: Matthias van de Meent
Discussion: https://postgr.es/m/CAEze2WjC5PiweG-4oe0hB_Zr59iF3tRE1gURm8w4Cg5b6JEBGw%40mail.gmail.com

10 months agodoc PG 17 relnotes: wording improvements, add links, merge item
Bruce Momjian [Fri, 21 Jun 2024 16:08:14 +0000 (12:08 -0400)]
doc PG 17 relnotes:  wording improvements, add links, merge item

Backpatch-through: master

10 months agoFix relcache invalidation when relfilelocator is updated
Heikki Linnakangas [Fri, 21 Jun 2024 14:13:10 +0000 (17:13 +0300)]
Fix relcache invalidation when relfilelocator is updated

In commit af0e7deb4a, I removed a call to RelationCloseSmgr(), because
the dangling SMgrRelation was no longer an issue. However, we still
need the call when the relation's relfilelocator changes, so that the
new relfilelocator takes effect immediately.

Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://www.postgresql.org/message-id/987b1c8c-8c91-4847-ca0e-879f421680ff%40gmail.com

10 months agodoc PG 17 relnotes: add link to enable_group_by_reordering GUC
Bruce Momjian [Fri, 21 Jun 2024 14:11:12 +0000 (10:11 -0400)]
doc PG 17 relnotes:  add link to enable_group_by_reordering GUC

Backpatch-through: master

10 months agoAdd doc entry for the new GUC paramenter enable_group_by_reordering
Alexander Korotkov [Fri, 21 Jun 2024 12:39:13 +0000 (15:39 +0300)]
Add doc entry for the new GUC paramenter enable_group_by_reordering

0452b461bc4 adds alternative orderings of group-by keys during the query
optimization. This new feature is controlled by the new GUC parameter
enable_group_by_reordering, which accidentally came without the documentation.
This commit adds the missing documentation for that GUC.

Reported-by: Bruce Momjian
Discussion: https://postgr.es/m/ZnDx2FYlba_OafQd%40momjian.us
Author: Andrei Lepikhov
Reviewed-by: Pavel Borisov, Alexander Korotkov
10 months agoPrevent access of uninitialized memory in radix tree nodes
John Naylor [Fri, 21 Jun 2024 07:59:11 +0000 (14:59 +0700)]
Prevent access of uninitialized memory in radix tree nodes

RT_NODE_16_SEARCH_EQ() performs comparisions using vector registers
on x64-64 and aarch64. We apply a mask to the resulting bitfield
to eliminate irrelevant bits that may be set. This ensures correct
behavior, but Valgrind complains of the partially-uninitialised
values. So far the warnings have only occurred on aarch64, which
explains why this hasn't been seen earlier.

To fix this warning, initialize the whole fixed-sized part of the nodes
upon allocation, rather than just do the minimum initialization to
function correctly. The initialization for node48 is a bit different
in that the 256-byte slot index array must be populated with "invalid
index" rather than zero. Experimentation has shown that compilers
tend to emit code that uselessly memsets that array twice. To avoid
pessimizing this path, swap the order of the slot_idxs[] and isset[]
arrays so we can initialize with two non-overlapping memset calls.

Reported by Tomas Vondra
Analysis and patch by Tom Lane, reviewed by Masahiko Sawada. I
investigated the behavior of memset calls to overlapping regions,
leading to the above tweaks to node48 as discussed in the thread.

Discussion: https://postgr.es/m/120c63ad-3d12-415f-a7bf-3da451c31bf6%40enterprisedb.com

10 months agopg_combinebackup: Error message improvements
Peter Eisentraut [Fri, 21 Jun 2024 07:40:44 +0000 (09:40 +0200)]
pg_combinebackup: Error message improvements

Make the wordings of some file-related error messages more like those
used in other files.

10 months agoRemove redundant newlines from error messages
Peter Eisentraut [Fri, 21 Jun 2024 07:29:34 +0000 (09:29 +0200)]
Remove redundant newlines from error messages

10 months agoFix make build on MinGW
Peter Eisentraut [Fri, 21 Jun 2024 06:17:23 +0000 (08:17 +0200)]
Fix make build on MinGW

Revert a couple of the simplifications done in commit 721856ff24b
because platforms without ln -s, where LN_S='cp -pR', such as MinGW,
required the specific previous incantations.

Reported-by: Noah Misch <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240616193448[email protected]

10 months agoparse_manifest: Use const char *
Peter Eisentraut [Fri, 21 Jun 2024 05:50:02 +0000 (07:50 +0200)]
parse_manifest: Use const char *

This adapts the manifest parsing code to take advantage of the
const-ified jsonapi.

Reviewed-by: Andrew Dunstan <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/f732b014-f614-4600-a437-dba5a2c3738b%40eisentraut.org

10 months agojsonapi: Use const char *
Peter Eisentraut [Fri, 21 Jun 2024 05:50:02 +0000 (07:50 +0200)]
jsonapi: Use const char *

Apply const qualifiers to char * arguments and fields throughout the
jsonapi.  This allows the top-level APIs such as
pg_parse_json_incremental() to declare their input argument as const.
It also reduces the number of unconstify() calls.

Reviewed-by: Andrew Dunstan <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/f732b014-f614-4600-a437-dba5a2c3738b%40eisentraut.org

10 months agojsonapi: Use size_t
Peter Eisentraut [Fri, 21 Jun 2024 05:50:02 +0000 (07:50 +0200)]
jsonapi: Use size_t

Use size_t instead of int for object sizes in the jsonapi.  This makes
the API better self-documenting.

Reviewed-by: Andrew Dunstan <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/f732b014-f614-4600-a437-dba5a2c3738b%40eisentraut.org

10 months agoDoc: Generated columns are skipped for logical replication.
Amit Kapila [Fri, 21 Jun 2024 04:25:25 +0000 (09:55 +0530)]
Doc: Generated columns are skipped for logical replication.

Add a note in docs that generated columns are skipped for logical
replication.

Author: Peter Smith
Reviewed-by: Peter Eisentraut
Backpatch-through: 12
Discussion: https://postgr.es/m/CAHut+PuXb1GLQztQkoWzYjSwkAZZ0dgCJaAHyJtZF3kmtcL=kA@mail.gmail.com

10 months agodoc PG 17 relnotes: remove mention of undocumented GUC
Bruce Momjian [Thu, 20 Jun 2024 23:53:01 +0000 (19:53 -0400)]
doc PG 17 relnotes:  remove mention of undocumented GUC

GUC is trace_connection_negotiation.  If it is undocumented, we should
not mention it in the release notes.

Backpatch-through: master

10 months agoDon't throw an error if a queued AFTER trigger no longer exists.
Tom Lane [Thu, 20 Jun 2024 18:21:36 +0000 (14:21 -0400)]
Don't throw an error if a queued AFTER trigger no longer exists.

afterTriggerInvokeEvents and AfterTriggerExecute have always
treated it as an error if the trigger OID mentioned in a queued
after-trigger event can't be found.  However, that fails to
account for the edge case where the trigger's been dropped in
the current transaction since queueing the event.  There seems
no very good reason to disallow that case, so instead silently
do nothing if the trigger OID can't be found.

This does give up a little bit of bug-detection ability, but I don't
recall that these error messages have ever actually revealed a bug,
so it seems mostly theoretical.  Alternatives such as marking
pending events DONE at the time of dropping a trigger would be
complicated and perhaps introduce bugs of their own.

Per bug #18517 from Alexander Lakhin.  Back-patch to all
supported branches.

Discussion: https://postgr.es/m/18517-af2d19882240902c@postgresql.org

10 months agopg_combinebackup: Fix small mistake in --help output
Peter Eisentraut [Thu, 20 Jun 2024 09:49:01 +0000 (11:49 +0200)]
pg_combinebackup: Fix small mistake in --help output

It was not showing that the --output option takes an argument.

10 months agopg_createsubscriber: Indent --help output correctly
Peter Eisentraut [Thu, 20 Jun 2024 09:42:40 +0000 (11:42 +0200)]
pg_createsubscriber: Indent --help output correctly

It was using 1 space indent instead of the 2 spaces used everywhere
else.

10 months agopg_dump: Fix weird error message composition
Peter Eisentraut [Thu, 20 Jun 2024 09:36:38 +0000 (11:36 +0200)]
pg_dump: Fix weird error message composition

The previous way could make it look like "stdin" was the actual input
file name.  Write it as two separate messages instead.

10 months agoFix redundancy in error messages
Peter Eisentraut [Thu, 20 Jun 2024 09:17:21 +0000 (11:17 +0200)]
Fix redundancy in error messages

pg_log_error() already prints the program name, so we don't need to
print it again inside the message.

10 months agoUnify some error messages
Peter Eisentraut [Thu, 20 Jun 2024 09:10:26 +0000 (11:10 +0200)]
Unify some error messages

10 months agomeson: Fix import library name in Windows
Peter Eisentraut [Thu, 20 Jun 2024 06:09:28 +0000 (08:09 +0200)]
meson: Fix import library name in Windows

This changes the import library name from 'postgres.exe.lib' to
'postgres.lib', which is what it was with the old MSVC build system.
Extension builds use that name.

Bug: #18513
Reported-by: Muralikrishna Bandaru <[email protected]>
10 months agoFix comment in pg_upgrade.h.
Nathan Bossart [Wed, 19 Jun 2024 21:12:18 +0000 (16:12 -0500)]
Fix comment in pg_upgrade.h.

Contrary to what the comment for the "check" struct member claims,
'pg_upgrade --check' performs only the checks and does not ask the
user for permission to make changes.

Reviewed-by: Daniel Gustafsson
Discussion: https://postgr.es/m/ZnHk7ci5IuTWVc_c%40nathan

10 months agoSQL/JSON: Correctly enforce the default ON EMPTY behavior
Amit Langote [Wed, 19 Jun 2024 06:22:59 +0000 (15:22 +0900)]
SQL/JSON: Correctly enforce the default ON EMPTY behavior

Currently, when the ON EMPTY clause is not present, the ON ERROR
clause (implicit or explicit) dictates the behavior when jsonpath
evaluation in ExecEvalJsonExprPath() results in an empty sequence.
That is an oversight in the commit 6185c9737c.

This commit fixes things so that a NULL is returned instead in that
case which is the default behavior when the ON EMPTY clause is not
present.

Reported-by: Markus Winand
Discussion: https://postgr.es/m/F7DD1442-265C-4220-A603-CB0DEB77E91D%40winand.at

10 months agoSQL/JSON: Correct jsonpath variable name matching
Amit Langote [Wed, 19 Jun 2024 06:22:06 +0000 (15:22 +0900)]
SQL/JSON: Correct jsonpath variable name matching

Previously, GetJsonPathVar() allowed a jsonpath expression to
reference any prefix of a PASSING variable's name. For example, the
following query would incorrectly work:

SELECT JSON_QUERY(context_item, jsonpath '$xy' PASSING val AS xyz);

The fix ensures that the length of the variable name mentioned in a
jsonpath expression matches exactly with the name of the PASSING
variable before comparing the strings using strncmp().

Reported-by: Alvaro Herrera (off-list)
Discussion: https://postgr.es/m/CA+HiwqFGkLWMvELBH6E4SQ45qUHthgcRH6gCJL20OsYDRtFx_w@mail.gmail.com

10 months agodoc PG 17 relnotes: properly wrap SGML text
Bruce Momjian [Wed, 19 Jun 2024 02:41:49 +0000 (22:41 -0400)]
doc PG 17 relnotes:  properly wrap SGML text

Backpatch-through: master

10 months agodoc PG 17 relnotes: add links to documentation sections
Bruce Momjian [Wed, 19 Jun 2024 02:09:41 +0000 (22:09 -0400)]
doc PG 17 relnotes:  add links to documentation sections

Also slightly improve markup instructions.  Indentation is still needed.

Backpatch-through: master

10 months agoFix possible Assert failure in cost_memoize_rescan
David Rowley [Tue, 18 Jun 2024 22:20:24 +0000 (10:20 +1200)]
Fix possible Assert failure in cost_memoize_rescan

In cost_memoize_rescan(), when calculating the hit_ratio using the calls
and ndistinct estimations, if the value that was set in
MemoizePath.calls had not been processed through clamp_row_est(), then it
was possible that it was set to some non-integer value which could result
in ndistinct being 1 higher than calls due to estimate_num_groups()
performing clamp_row_est() on its input_rows.  This could result in
hit_ratio values slightly below 0.0, which would cause an Assert failure.

The value of MemoizePath.calls comes from the final parameter in the
create_memoize_path() function, of which we only have one true caller of.
That caller passes outer_path->rows.  All the core code I looked at
always seems to call clamp_row_est() on the Path.rows, so there might
have been no issues with any core Paths causing troubles here.  The bug
report was about a CustomPath with a non-clamped row estimated.

The misbehavior as a result of this seems to be mostly limited to the
Assert() failing.  Aside from that, it seems the Memoize costs would
just come out slightly higher than they should have, which is likely
fairly harmless.

Reported-by: Kohei KaiGai <[email protected]>
Discussion: https://postgr.es/m/CAOP8fzZnTU+N64UYJYogb1hN-5hFP+PwTb3m_cnGAD7EsQwrKw@mail.gmail.com
Reviewed-by: Richard Guo
Backpatch-through: 14, where Memoize was introduced

10 months agoFix incorrect punctuation in error message
Peter Eisentraut [Tue, 18 Jun 2024 12:53:11 +0000 (14:53 +0200)]
Fix incorrect punctuation in error message

10 months agoFix typo in 029_stats_restart.pl
Michael Paquier [Tue, 18 Jun 2024 03:51:36 +0000 (12:51 +0900)]
Fix typo in 029_stats_restart.pl

Oversight in 16acf7f1aaea, where the test has been introduced.  Issue
noticed while scanning this area of the tree.

10 months agodoc PG 17 relnotes: update to current
Bruce Momjian [Mon, 17 Jun 2024 19:05:05 +0000 (15:05 -0400)]
doc PG 17 relnotes:  update to current

Backpatch-through: master

10 months agodoc PG 17 relnotes: Fix sslnegotation typo
Andres Freund [Mon, 17 Jun 2024 18:53:07 +0000 (11:53 -0700)]
doc PG 17 relnotes: Fix sslnegotation typo

I was confused with copy-pasting the parameter name didn't work...

10 months agoFix insertion of SP-GiST REDIRECT tuples during REINDEX CONCURRENTLY.
Tom Lane [Mon, 17 Jun 2024 18:30:59 +0000 (14:30 -0400)]
Fix insertion of SP-GiST REDIRECT tuples during REINDEX CONCURRENTLY.

Reconstruction of an SP-GiST index by REINDEX CONCURRENTLY may
insert some REDIRECT tuples.  This will typically happen in
a transaction that lacks an XID, which leads either to assertion
failure in spgFormDeadTuple or to insertion of a REDIRECT tuple
with zero xid.  The latter's not good either, since eventually
VACUUM will apply GlobalVisTestIsRemovableXid() to the zero xid,
resulting in either an assertion failure or a garbage answer.

In practice, since REINDEX CONCURRENTLY locks out index scans
till it's done, it doesn't matter whether it inserts REDIRECTs
or PLACEHOLDERs; and likewise it doesn't matter how soon VACUUM
reduces such a REDIRECT to a PLACEHOLDER.  So in non-assert builds
there's no observable problem here, other than perhaps a little
index bloat.  But it's not behaving as intended.

To fix, remove the failing Assert in spgFormDeadTuple, acknowledging
that we might sometimes insert a zero XID; and guard VACUUM's
GlobalVisTestIsRemovableXid() call with a test for valid XID,
ensuring that we'll reduce such a REDIRECT the first time VACUUM
sees it.  (Versions before v14 use TransactionIdPrecedes here,
which won't fail on zero xid, so they really have no bug at all
in non-assert builds.)

Another solution could be to not create REDIRECTs at all during
REINDEX CONCURRENTLY, making the relevant code paths treat that
case like index build (which likewise knows that no concurrent
index scans can be happening).  That would allow restoring the
Assert in spgFormDeadTuple, but we'd still need the VACUUM change
because redirection tuples with zero xid may be out there already.
But there doesn't seem to be a nice way for spginsert() to tell that
it's being called in REINDEX CONCURRENTLY without some API changes,
so we'll leave that as a possible future improvement.

In HEAD, also rename the SpGistState.myXid field to redirectXid,
which seems less misleading (since it might not in fact be our
transaction's XID) and is certainly less uninformatively generic.

Per bug #18499 from Alexander Lakhin.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18499-8a519c280f956480@postgresql.org

10 months agoRemove recordExtensionInitPriv[Worker]'s ownerId argument.
Tom Lane [Mon, 17 Jun 2024 17:00:53 +0000 (13:00 -0400)]
Remove recordExtensionInitPriv[Worker]'s ownerId argument.

In the wake of the previous commit, we're not doing anything
with that argument.  Hence, revert the portions of 534287403
that added that argument and taught the callers to pass it.
Passing the ownerId requires additional syscache lookups in
some code paths, which'd be fine if we were doing anything
useful with the info, but it seems inadvisable if we're not.

Committed separately since there's some thought that we might
want to un-revert this in future, in case it's decided that
storing the original owner ID explicitly in pg_init_privs
is worth doing.

Discussion: https://postgr.es/m/CAMT0RQSVgv48G5GArUvOVhottWqZLrvC5wBzBa4HrUdXe9VRXw@mail.gmail.com

10 months agoImprove tracking of role dependencies of pg_init_privs entries.
Tom Lane [Mon, 17 Jun 2024 16:55:10 +0000 (12:55 -0400)]
Improve tracking of role dependencies of pg_init_privs entries.

Commit 534287403 invented SHARED_DEPENDENCY_INITACL entries in
pg_shdepend, but installed them only for non-owner roles mentioned
in a pg_init_privs entry.  This turns out to be the wrong thing,
because there is nothing to cue REASSIGN OWNED to go and update
pg_init_privs entries when the object's ownership is reassigned.
That leads to leaving dangling entries in pg_init_privs, as
reported by Hannu Krosing.  Instead, install INITACL entries for
all roles mentioned in pg_init_privs entries (except pinned roles),
and change ALTER OWNER to not touch them, just as it doesn't
touch pg_init_privs entries.

REASSIGN OWNED will now substitute the new owner OID for the old
in pg_init_privs entries.  This feels like perhaps not quite the
right thing, since pg_init_privs ought to be a historical record
of the state of affairs just after CREATE EXTENSION.  However,
it's hard to see what else to do, if we don't want to disallow
dropping the object's original owner.  In any case this is
better than the previous do-nothing behavior, and we're unlikely
to come up with a superior solution in time for v17.

While here, tighten up some coding rules about how ACLs in
pg_init_privs should never be null or empty.  There's not any
obvious reason to allow that, and perhaps asserting that it's
not so will catch some bugs.  (We were previously inconsistent
on the point, with some code paths taking care not to store
empty ACLs and others not.)

This leaves recordExtensionInitPrivWorker not doing anything
with its ownerId argument, but we'll deal with that separately.

catversion bump forced because of change of expected contents
of pg_shdepend when pg_init_privs entries exist.

Discussion: https://postgr.es/m/CAMT0RQSVgv48G5GArUvOVhottWqZLrvC5wBzBa4HrUdXe9VRXw@mail.gmail.com

10 months agoTeach jsonpath string() to unwrap in lax mode
Andrew Dunstan [Mon, 17 Jun 2024 14:31:29 +0000 (10:31 -0400)]
Teach jsonpath string() to unwrap in lax mode

This was an ommission in commit 66ea94e, and brings it into compliance
with both other methods and the standard.

Per complaint from David Wheeler.

Author: David Wheeler, Jeevan Chalke
Reviewed-by: Chapman Flack
Discussion: https://postgr.es/m/A64AE04F-4410-42B7-A141-7A7349260F4D@justatheory.com

10 months agopg_createsubscriber: Remove failover replication slots on subscriber
Peter Eisentraut [Mon, 17 Jun 2024 10:12:49 +0000 (12:12 +0200)]
pg_createsubscriber: Remove failover replication slots on subscriber

After running pg_createsubscriber, these replication slots have no use
on subscriber, so drop them.

Author: Euler Taveira <[email protected]>
Reviewed-by: Hayato Kuroda <[email protected]>
Discussion: https://www.postgresql.org/message-id/776c5cac-5ef5-4001-b1bc-5b698bc0c62a%40app.fastmail.com

10 months agopg_createsubscriber: Remove replication slot check on primary
Peter Eisentraut [Mon, 17 Jun 2024 08:48:17 +0000 (10:48 +0200)]
pg_createsubscriber: Remove replication slot check on primary

It used to check if the replication slot exists and is active on
primary.  This check might fail on slow hosts because the replication
slot might not be active at the time of this check.

The current code obtains the replication slot name from the
primary_slot_name on standby and assumes the replication slot exists
and is active on primary.  If it doesn't exist, this tool will log an
error and continue.

Author: Euler Taveira <[email protected]>
Reviewed-by: Hayato Kuroda <[email protected]>
Discussion: https://www.postgresql.org/message-id/776c5cac-5ef5-4001-b1bc-5b698bc0c62a%40app.fastmail.com

10 months agopg_createsubscriber: Only --recovery-timeout controls the end of recovery process
Peter Eisentraut [Mon, 17 Jun 2024 07:42:51 +0000 (09:42 +0200)]
pg_createsubscriber: Only --recovery-timeout controls the end of recovery process

It used to check if the target server is connected to the primary
server (send required WAL) to rapidly react when the process won't
succeed.  This code is not enough to guarantee that the recovery
process will complete.  There is a window between the walreceiver
shutdown and the pg_is_in_recovery() returns false that can reach
NUM_CONN_ATTEMPTS attempts and fails.

Instead, rely only on the --recovery-timeout option to give up the
process after the specified number of seconds.

This should help with buildfarm failures on slow machines.

Author: Euler Taveira <[email protected]>
Reviewed-by: Hayato Kuroda <[email protected]>
Discussion: https://www.postgresql.org/message-id/776c5cac-5ef5-4001-b1bc-5b698bc0c62a%40app.fastmail.com

10 months agoMake regress function make_tuple_indirect() able to handle plain attributes
Michael Paquier [Mon, 17 Jun 2024 05:26:27 +0000 (14:26 +0900)]
Make regress function make_tuple_indirect() able to handle plain attributes

The function has been introduced in 368202501539 to test at a low level
the new kinds of external toast datums, and would fail on OOM when
dealing with a plain storage attribute.  The existing tests of
indirect_toast do not test this case, still the error generated was
confusing.

Author: Alexander Lakhin
Discussion: https://postgr.es/m/250a21e5-d677-6b2a-2692-cd4233785e37@gmail.com

10 months agodoc: Mention modules/injection_points as example for injection points
Michael Paquier [Mon, 17 Jun 2024 04:49:40 +0000 (13:49 +0900)]
doc: Mention modules/injection_points as example for injection points

This should have been added in 49cd2b93d7db, that introduced the module.

Reported-by: Jian He
Discussion: https://postgr.es/m/CACJufxF+Vfj2Oz2kBR5v1bjHeZxvs63cLogm70v9Uto1Rqiieg@mail.gmail.com

10 months agoAdd Windows file version information to test_json_parser programs.
Noah Misch [Sun, 16 Jun 2024 19:29:30 +0000 (12:29 -0700)]
Add Windows file version information to test_json_parser programs.

10 months agoRemove use of %z in sscanf.
Noah Misch [Sun, 16 Jun 2024 19:29:25 +0000 (12:29 -0700)]
Remove use of %z in sscanf.

As in 9d7ded0f4277f5c0063eca8e871a34e2355a8371, it causes warnings on
some MinGW compilers.

10 months agoConvert confusing macros in multixact.c to static inline functions
Heikki Linnakangas [Sun, 16 Jun 2024 17:47:07 +0000 (20:47 +0300)]
Convert confusing macros in multixact.c to static inline functions

The macros were confused about the argument data types. All the
arguments were called 'xid', and some of the macros included casts to
TransactionId, even though the arguments were actually either
MultiXactIds or MultiXactOffsets. It compiles to the same thing,
because TransactionId, MultiXactId and MultiXactOffset are all
typedefs of uint32, but it was highly misleading.

Author: Maxim Orlov <[email protected]>
Discussion: https://www.postgresql.org/message-id/CACG%3DezbLUG-OD1osAW3OchOMxZtdxHh2itYR9Zhh-a13wEBEQw%40mail.gmail.com
Discussion: https://www.postgresql.org/message-id/ff143b24-a093-40da-9833-d36b83726bdf%40iki.fi

10 months agodoc: fix typo in create role manual.
Tatsuo Ishii [Sun, 16 Jun 2024 07:21:46 +0000 (16:21 +0900)]
doc: fix typo in create role manual.

There was a small mistake in the create role manual.

Author: Satoru Koizumi
Reviewed-by: David G. Johnston
Discussion: https://postgr.es/m/flat/20240616.112523.1208348667552014162.t-ishii%40sranhm.sra.co.jp
Backpatch-through: 16

10 months agoClean out column-level pg_init_privs entries when dropping tables.
Tom Lane [Fri, 14 Jun 2024 20:20:35 +0000 (16:20 -0400)]
Clean out column-level pg_init_privs entries when dropping tables.

DeleteInitPrivs did not get the memo about how, when dropping a
whole object (with subid == 0), you should drop entries relating
to its sub-objects too.  This is visible in the test_pg_dump test
case if one drops the extension at the end: the entry for
GRANT SELECT(col1) ON regress_pg_dump_table TO public;
was still present in pg_init_privs afterwards, although it was
pointing to a dangling table OID.

Noted while fooling with a fix for REASSIGN OWNED for pg_init_privs
entries.  This bug is aboriginal in the pg_init_privs feature
though, and there seems no reason not to back-patch the fix.

10 months agoFix misc_sanity test to accept SHARED_DEPENDENCY_INITACL entries.
Tom Lane [Fri, 14 Jun 2024 19:29:09 +0000 (15:29 -0400)]
Fix misc_sanity test to accept SHARED_DEPENDENCY_INITACL entries.

Oversight in 534287403.  We missed this up to now because the
core regression tests create no such entries (at least up to
this test), so the only way to see the failure is to do
"make installcheck" in an installation where some other DB
has such entries.  I happened to do that just now ...

10 months agoReintroduce dead tuple counter in pg_stat_progress_vacuum.
Masahiko Sawada [Fri, 14 Jun 2024 01:08:15 +0000 (10:08 +0900)]
Reintroduce dead tuple counter in pg_stat_progress_vacuum.

Commit 667e65aac3 changed both num_dead_tuples and max_dead_tuples
columns to dead_tuple_bytes and max_dead_tuple_bytes columns,
respectively. But as per discussion, the number of dead tuples
collected still provides meaningful insights for users.

This commit reintroduces the column for the count of dead tuples,
renamed as num_dead_item_ids. It avoids confusion with the number of
dead tuples removed by VACUUM, which includes dead heap-only tuples
but excludes any pre-existing LP_DEAD items left behind by
opportunistic pruning.

Bump catalog version.

Reviewed-by: Peter Geoghegan, Álvaro Herrera, Andrey Borodin
Discussion: https://postgr.es/m/CAD21AoBL5sJE9TRWPyv%2Bw7k5Ee5QAJqDJEDJBUdAaCzGWAdvZw%40mail.gmail.com

10 months agoFix parsing of ignored operators in websearch_to_tsquery().
Tom Lane [Fri, 14 Jun 2024 00:34:42 +0000 (20:34 -0400)]
Fix parsing of ignored operators in websearch_to_tsquery().

The manual says clearly that punctuation in the input of
websearch_to_tsquery() is ignored, except for the special cases
of dashes and quotes.  However, this failed for cases like
"(foo bar) or something", or in general an ISOPERATOR character
in front of the "or".  We'd switch back to WAITOPERAND state,
then ignore the operator character while remaining in that state,
and then reach the "or" in WAITOPERAND state which (intentionally)
makes us treat it as data.

The fix is simple enough: if we see an ISOPERATOR character while in
WAITOPERATOR state, we have to skip it while staying in that state.
(We don't need to worry about other punctuation characters: those will
be consumed as though they were words, but then rejected by lexizing.)

In v14 and up (since commit eb086056f) we can simplify the code a bit
more too, because there is no longer a reason for the WAITOPERAND
state to distinguish between quoted and unquoted operands.

Per bug #18479 from Manos Emmanouilidis.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18479-d9b46e2fc242c33e@postgresql.org

10 months agodoc: Fix description WAL summarizer in glossary
Michael Paquier [Fri, 14 Jun 2024 00:28:11 +0000 (09:28 +0900)]
doc: Fix description WAL summarizer in glossary

The WAL summarizer is an auxiliary process.

Oversight in 7b1dbf0a8d1d.

Author: Masahiro Ikeda
Discussion: https://postgr.es/m/d3a5a4278fd8d9e7a47c6aa4db9e9a39@oss.nttdata.com

10 months agodoc: Fix description WAL writer in glossary
Michael Paquier [Fri, 14 Jun 2024 00:26:32 +0000 (09:26 +0900)]
doc: Fix description WAL writer in glossary

The WAL writer is an auxiliary process, but its description in the
glossary did not match that.

This is inexact since d3014fff4cd4.

Author: Masahiro Ikeda
Discussion: https://postgr.es/m/d3a5a4278fd8d9e7a47c6aa4db9e9a39@oss.nttdata.com
Backpatch-through: 15

10 months agoImprove the granularity of PQsocketPoll's timeout parameter.
Tom Lane [Thu, 13 Jun 2024 19:14:32 +0000 (15:14 -0400)]
Improve the granularity of PQsocketPoll's timeout parameter.

Commit f5e4dedfa exposed libpq's internal function PQsocketPoll
without a lot of thought about whether that was an API we really
wanted to chisel in stone.  The main problem with it is the use of
time_t to specify the timeout.  While we do want an absolute time
so that a loop around PQsocketPoll doesn't have problems with
timeout slippage, time_t has only 1-second resolution.  That's
already problematic for libpq's own internal usage --- for example,
pqConnectDBComplete has long had a kluge to treat "connect_timeout=1"
as 2 seconds so that it doesn't accidentally round to nearly zero.
And it's even less likely to be satisfactory for external callers.
Hence, let's change this while we still can.

The best idea seems to be to use an int64 count of microseconds since
the epoch --- basically the same thing as the backend's TimestampTz,
but let's use the standard Unix epoch (1970-01-01) since that's more
likely for clients to be easy to calculate.  Millisecond resolution
would be plenty for foreseeable uses, but maybe the day will come that
we're glad we used microseconds.

Also, since time(2) isn't especially helpful for computing timeouts
defined this way, introduce a new function PQgetCurrentTimeUSec
to get the current time in this form.

Remove the hack in pqConnectDBComplete, so that "connect_timeout=1"
now means what you'd expect.

We can also remove the "#include <time.h>" that f5e4dedfa added to
libpq-fe.h, since there's no longer a need for time_t in that header.
It seems better for v17 not to enlarge libpq-fe.h's include footprint
from what it's historically been, anyway.

I also failed to resist the temptation to do some wordsmithing
on PQsocketPoll's documentation.

Patch by me, per complaint from Dominique Devienne.

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

10 months agoWhen replanning a plpgsql "simple expression", check it's still simple.
Tom Lane [Thu, 13 Jun 2024 17:37:46 +0000 (13:37 -0400)]
When replanning a plpgsql "simple expression", check it's still simple.

The previous coding here assumed that we didn't need to recheck any
of the querytree tests made in exec_simple_check_plan().  I think
we supposed that those properties were fully determined by the
syntax of the source text and hence couldn't change.  That is true
for most of them, but at least hasTargetSRFs and hasAggs can change
by dint of forcibly dropping an originally-referenced function and
recreating it with new properties.  That leads to "unexpected plan
node type" or similar failures.

These tests are pretty cheap compared to the cost of replanning, so
rather than sweat over exactly which properties need to be rechecked,
let's just recheck them all.  Hence, factor out those tests into a new
function exec_is_simple_query(), and rearrange callers as needed.

A second problem in the same area was that if we failed during
replanning or during exec_save_simple_expr(), we'd potentially
leave behind now-dangling pointers to the old simple expression,
potentially resulting in crashes later.  To fix, clear those pointers
before replanning.

The v12 code looks quite different in this area but still has the
bug about needing to recheck query simplicity.  I chose to back-patch
all of the plpgsql_simple.sql test script, which formerly didn't exist
in this branch.

Per bug #18497 from Nikita Kalinin.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18497-fe93b6da82ce31d4@postgresql.org

10 months agoClamp result of MultiXactMemberFreezeThreshold
Heikki Linnakangas [Thu, 13 Jun 2024 16:01:30 +0000 (19:01 +0300)]
Clamp result of MultiXactMemberFreezeThreshold

The purpose of the function is to reduce the effective
autovacuum_multixact_freeze_max_age if the multixact members SLRU is
approaching wraparound, to make multixid freezing more aggressive.
The returned value should therefore never be greater than plain
autovacuum_multixact_freeze_max_age.

Reviewed-by: Robert Haas
Discussion: https://www.postgresql.org/message-id/85fb354c-f89f-4d47-b3a2-3cbd461c90a3@iki.fi
Backpatch-through: 12, all supported versions

10 months agoSkip some permissions checks on Cygwin
Andrew Dunstan [Thu, 13 Jun 2024 11:38:48 +0000 (07:38 -0400)]
Skip some permissions checks on Cygwin

These are checks that are already skipped on other Windows systems.

Backpatch to all live branches, as appropriate.

10 months agoAdd postgres_inc to meson check for Python.h
Andrew Dunstan [Thu, 13 Jun 2024 11:30:10 +0000 (07:30 -0400)]
Add postgres_inc to meson check for Python.h

Required for Cygwin.

Backpatch to release 16.

10 months agoFix documentation of initdb --show option
Peter Eisentraut [Thu, 13 Jun 2024 09:52:35 +0000 (11:52 +0200)]
Fix documentation of initdb --show option

It wasn't in the documentation at all (even though we document all the
other debugging-like options).  Also, change the --help output to show
that it exits after showing, similar to other options.

10 months agoAdd missing source files to nls.mk
Peter Eisentraut [Thu, 13 Jun 2024 08:17:36 +0000 (10:17 +0200)]
Add missing source files to nls.mk

Files in common/ and fe_utils/ that contain translatable strings need
to be listed in the nls.mk files of the programs that use them.  (Not
great, but that's the way it works for now.)  This usually requires
some manual analysis which is done about once during each major
release beta period.  This time, I wrote a hackish script that figures
some of this out more automatically, so this update is a bit larger as
it also includes some files that were missed in the past.

10 months agolibpq: Some message style normalization
Peter Eisentraut [Thu, 13 Jun 2024 05:10:35 +0000 (07:10 +0200)]
libpq: Some message style normalization

10 months agoHarmonize pg_bsd_indent parameter names.
Peter Geoghegan [Wed, 12 Jun 2024 22:04:10 +0000 (18:04 -0400)]
Harmonize pg_bsd_indent parameter names.

Make sure that function declarations use names that exactly match the
corresponding names from function definitions in pg_bsd_indent.

This commit was written with help from clang-tidy, by mechanically
applying the same rules as similar clean-up commits.

Discussion: https://postgr.es/m/CAH2-WzkaBS8w-vCbG5M5Bx7XikC0WhNLJV_+Z_YAWW9Kef6OBQ@mail.gmail.com

10 months agoHarmonize function parameter names for Postgres 17.
Peter Geoghegan [Wed, 12 Jun 2024 21:01:51 +0000 (17:01 -0400)]
Harmonize function parameter names for Postgres 17.

Make sure that function declarations use names that exactly match the
corresponding names from function definitions in a few places.  These
inconsistencies were all introduced during Postgres 17 development.

pg_bsd_indent still has a couple of similar inconsistencies, which I
(pgeoghegan) have left untouched for now.

This commit was written with help from clang-tidy, by mechanically
applying the same rules as similar clean-up commits (the earliest such
commit was commit 035ce1fe).

10 months agolibpq: Add missing gettext markers
Peter Eisentraut [Wed, 12 Jun 2024 13:31:31 +0000 (15:31 +0200)]
libpq: Add missing gettext markers

Follow-up to 87d2801d4b: That commit restored some lost error
messages, but they ended up in a place where xgettext wouldn't find
them.  Rather than elevating ENCRYPTION_NEGOTIATION_FAILED() to a
gettext trigger, it's easiest for now to put in some explicit
libpq_gettext() calls in the couple of call sites.

10 months agolibpq: Remove a gettext marker
Peter Eisentraut [Wed, 12 Jun 2024 06:43:43 +0000 (08:43 +0200)]
libpq: Remove a gettext marker

This one error message is just a workaround for a missing OpenSSL
error string.  But OpenSSL does not have gettext support, so we don't
need to provide it in our workaround either.  That way, the
user-facing behavior is consistent whether the user has a fixed
OpenSSL or not.

10 months agoFix typo in error message
Peter Eisentraut [Wed, 12 Jun 2024 02:48:39 +0000 (04:48 +0200)]
Fix typo in error message

10 months agoFix segmentation fault in test_tidstore.
Masahiko Sawada [Wed, 12 Jun 2024 00:56:13 +0000 (09:56 +0900)]
Fix segmentation fault in test_tidstore.

The do_set_block_offsets() and other functions accessing the tidstore
did not check if the tidstore was NULL. This led to a segmentation
fault when these functions are called without calling the
test_create().

This commit adds NULL checks in relevant functions of test_tidstore to
raise an error instead if the tidstore is not initialized.

Bug: #18483
Reported-by: Alexander Kozhemyakin
Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/18483-30bfff42de238000%40postgresql.org

10 months agoFix infer_arbiter_indexes() to not assume resultRelation is 1.
Tom Lane [Tue, 11 Jun 2024 21:57:46 +0000 (17:57 -0400)]
Fix infer_arbiter_indexes() to not assume resultRelation is 1.

infer_arbiter_indexes failed to renumber varnos in index expressions
or predicates that it got from the catalogs.  This escaped detection
up to now because the stored varnos in such trees will be 1, and an
INSERT's result relation is usually the first rangetable entry,
so that that was fine.  However, in cases such as inserting through
an updatable view, it's not fine, leading to failure to match the
expressions to the query with ensuing "there is no unique or exclusion
constraint matching the ON CONFLICT specification" errors.

Fix by copy-and-paste from get_relation_info().

Per bug #18502 from Michael Wang.  Back-patch to all supported
versions.

Discussion: https://postgr.es/m/18502-545b53f5b81e54e0@postgresql.org

10 months agoFix creation of partition descriptor during concurrent detach
Alvaro Herrera [Tue, 11 Jun 2024 09:38:45 +0000 (11:38 +0200)]
Fix creation of partition descriptor during concurrent detach

When a partition is being detached in concurrent mode, it is possible
for find_inheritance_children_extended() to return that partition in the
list, and immediately after that receive an invalidation message that
sets its relpartbound to NULL just before we read it.  (This can happen
because table_open() reads invalidation messages.)  Currently we raise
an error
  ERROR:  missing relpartbound for relation %u
about the situation, but that's bogus because the table is no longer a
partition, so we shouldn't be complaining about it.  A better reaction
is to retry the find_inheritance_children_extended call to get a new
list, which will no longer have the partition being detached.

Noticed while investigating bug #18377.

Backpatch to 14, where DETACH CONCURRENTLY appeared.

Discussion: https://postgr.es/m/202405201616[email protected]

10 months agoFix an assert in CheckPointReplicationSlots().
Amit Kapila [Tue, 11 Jun 2024 05:21:34 +0000 (10:51 +0530)]
Fix an assert in CheckPointReplicationSlots().

Commit e0b2eed047 assumed that the confirmed_flush LSN can't go backward.
However, it is possible that confirmed_flush LSN can go backward
temporarily when the client acknowledges a prior value of flush location.
This can happen when the client (subscriber in this case) acknowledges an
LSN it doesn't have to do anything for (say for DDLs) and thus didn't
store persistently. After restart, the client sends the prior value of
flush LSN which it had stored persistently and the server updates the
confirmed_flush LSN with that value.

The fix is to remove the assumption and not allow the prior value of
confirmed_flush LSN to be flushed to the disk.

Author: Vignesh C
Reviewed-by: Amit Kapila, Shlok Kyal
Discussion: https://postgr.es/m/CALDaNm3hgow2+oEov5jBk4iYP5eQrUCF1yZtW7+dV3J__p4KLQ@mail.gmail.com