postgresql.git
10 months agoDoc: mention executor memory usage for enable_partitionwise* GUCs
David Rowley [Wed, 31 Jul 2024 13:26:16 +0000 (01:26 +1200)]
Doc: mention executor memory usage for enable_partitionwise* GUCs

Prior to this commit, the docs for enable_partitionwise_aggregate and
enable_partitionwise_join mentioned the additional overheads enabling
these causes for the query planner, but they mentioned nothing about the
possible surge in work_mem-consuming executor nodes that could end up in
the final plan.  Dimitrios reported the OOM killer intervened on his
query as a result of using enable_partitionwise_aggregate=on.

Here we adjust the docs to mention the possible increase in the number of
work_mem-consuming executor nodes that can appear in the final plan as a
result of enabling these GUCs.

Reported-by: Dimitrios Apostolou
Reviewed-by: Ashutosh Bapat
Discussion: https://postgr.es/m/3603c380-d094-136e-e333-610914fb3e80%40gmx.net
Discussion: https://postgr.es/m/CAApHDvoZ0_yqwPFEpb6h261L76BUpmh5GxBQq0LeRzQ5Jh3zzg@mail.gmail.com
Backpatch-through: 12, oldest supported version

10 months agoRelax check for return value from second call of pg_strnxfrm().
Jeff Davis [Tue, 30 Jul 2024 23:23:20 +0000 (16:23 -0700)]
Relax check for return value from second call of pg_strnxfrm().

strxfrm() is not guaranteed to return the exact number of bytes needed
to store the result; it may return a higher value.

Discussion: https://postgr.es/m/32f85d88d1f64395abfe5a10dd97a62a4d3474ce[email protected]
Reviewed-by: Heikki Linnakangas
Backpatch-through: 16

10 months agoPreserve tz when converting to jsonb timestamptz
Andrew Dunstan [Tue, 30 Jul 2024 11:57:16 +0000 (07:57 -0400)]
Preserve tz when converting to jsonb timestamptz

This removes an inconsistency in the treatment of different datatypes by
the jsonpath timestamp_tz() function. Conversions from data types that
are not timestamp-aware, such as date and timestamp, are now treated
consistently with conversion from those that are such as timestamptz.

Author: David Wheeler
Reviewed-by: Junwang Zhao and Jeevan Chalke
Discussion: https://postgr.es/m/7DE080CE-6D8C-4794-9BD1-7D9699172FAB%40justatheory.com

Backpatch to release 17.

10 months agopg_createsubscriber: Remove obsolete comment
Peter Eisentraut [Tue, 30 Jul 2024 10:21:20 +0000 (12:21 +0200)]
pg_createsubscriber: Remove obsolete comment

This comment should have been removed by commit b9639138262.  There is
no replication slot check on the primary anymore.

Author: Euler Taveira <[email protected]>
Discussion: https://www.postgresql.org/message-id/697d692f-f9d3-41f6-9f0e-29a4fb18e544@app.fastmail.com

10 months agoStabilize xid_wraparound tests
Andrew Dunstan [Tue, 30 Jul 2024 10:17:48 +0000 (06:17 -0400)]
Stabilize xid_wraparound tests

The tests had a race condition if autovacuum was set to off. Instead we
create all the tables we are interested in with autovacuum disabled, so
they are only ever touched when in danger of wraparound.

Discussion: https://postgr.es/m/3e2cbd24-f45e-4b2b-ba83-8149214f0a4d@dunslane.net

Masahiko Sawada (slightly tweaked by me)

Backpatch to release 17 where these tests were introduced.

10 months agopg_createsubscriber: Fix an unpredictable recovery wait time.
Amit Kapila [Tue, 30 Jul 2024 08:47:30 +0000 (14:17 +0530)]
pg_createsubscriber: Fix an unpredictable recovery wait time.

The problem is that the tool is using the LSN returned by
pg_create_logical_replication_slot() as recovery_target_lsn. This LSN is
ahead of the current WAL position and the recovery waits until the
publisher writes a WAL record to reach the target and ends the recovery.
On idle systems, this wait time is unpredictable and could lead to failure
in promoting the subscriber. To avoid that, insert a harmless WAL record.

Reported-by: Alexander Lakhin and Tom Lane
Diagnosed-by: Hayato Kuroda
Author: Euler Taveira
Reviewed-by: Hayato Kuroda, Amit Kapila
Backpatch-through: 17
Discussion: https://postgr.es/m/2377319.1719766794%40sss.pgh.pa.us
Discussion: https://postgr.es/m/CA+TgmoYcY+Wb67NAwaHT7MvxCSeV86oSc+va9hHKaasE42ukyw@mail.gmail.com

10 months agoSQL/JSON: Fix casting for integer EXISTS columns in JSON_TABLE
Amit Langote [Tue, 30 Jul 2024 01:12:23 +0000 (10:12 +0900)]
SQL/JSON: Fix casting for integer EXISTS columns in JSON_TABLE

The current method of coercing the boolean result value of
JsonPathExists() to the target type specified for an EXISTS column,
which is to call the type's input function via json_populate_type(),
leads to an error when the target type is integer, because the
integer input function doesn't recognize boolean literal values as
valid.

Instead use the boolean-to-integer cast function for coercion in that
case so that using integer or domains thereof as type for EXISTS
columns works. Note that coercion for ON ERROR values TRUE and FALSE
already works like that because the parser creates a cast expression
including the cast function, but the coercion of the actual result
value is not handled by the parser.

Tests by Jian He.

Reported-by: Jian He <[email protected]>
Author: Jian He <[email protected]>
Author: Amit Langote <[email protected]>
Discussion: https://postgr.es/m/CACJufxEo4sUjKCYtda0_qt9tazqqKPmF1cqhW9KBOUeJFqQd2g@mail.gmail.com
Backpatch-through: 17

10 months agoSQL/JSON: Some fixes to JsonBehavior expression casting
Amit Langote [Tue, 30 Jul 2024 01:37:56 +0000 (10:37 +0900)]
SQL/JSON: Some fixes to JsonBehavior expression casting

1. Remove the special case handling when casting the JsonBehavior
   expressions to types with typmod, like 86d33987 did for the casting
   of SQL/JSON constructor functions.

2. Fix casting for fixed-length character and bit string types by
   using assignment-level casts.  This is again similar to what
   86d33987 did, but for ON ERROR / EMPTY expressions.

3. Use runtime coercion for the boolean ON ERROR constants so that
   using fixed-length character string types, for example, for an
   EXISTS column doesn't cause a "value too long for type
   character(n)" when the parser tries to coerce the default ON ERROR
   value "false" to that type, that is, even when clause is not
   specified.

4. Simplify the conditions of when to use runtime coercion vs
   creating the cast expression in the parser itself.  jsonb-valued
   expressions are now always coerced at runtime and boolean
   expressions too if the target type is a string type for the
   reasons mentioned above.

New tests are from a patch that Jian He posted.  Outputs of some
existing tests change because the coercion now happens at runtime
instead of at parse time.

Reported-by: Jian He <[email protected]>
Author: Jian He <[email protected]>
Author: Amit Langote <[email protected]>
Discussion: https://postgr.es/m/CACJufxEo4sUjKCYtda0_qt9tazqqKPmF1cqhW9KBOUeJFqQd2g@mail.gmail.com
Backpatch-through: 17

10 months agoDetach syslogger from shared memory
Heikki Linnakangas [Mon, 29 Jul 2024 19:21:34 +0000 (22:21 +0300)]
Detach syslogger from shared memory

Commit aafc05de1b removed the calls to detach from shared memory from
syslogger startup. That was not intentional, so put them back.

Author: Rui Zhao
Reviewed-by: Aleksander Alekseev
Backpatch-through: 17
Discussion: https://www.postgresql.org/message-id/11505016-8cf3-4691-b996-7faed99b7877[email protected]

10 months agoCount individual SQL commands in pg_restore's --transaction-size mode.
Tom Lane [Mon, 29 Jul 2024 16:17:24 +0000 (12:17 -0400)]
Count individual SQL commands in pg_restore's --transaction-size mode.

The initial implementation in commit 959b38d77 counted one action
per TOC entry (except for some special cases for multi-blob BLOBS
entries).  This assumes that TOC entries are all about equally
complex, but it turns out that that assumption doesn't hold up very
well in binary-upgrade mode.  For example, even after the previous
commit I was able to cause backend bloat with tables having many
inherited constraints.  There may be other cases too.  (Since no
serious problems have been reported with --single-transaction mode,
we can conclude that the backend copes well with psql's regular
restore scripts; but before 959b38d77 we never ran binary-upgrade
restores with multi-command transactions.)

To fix, count multi-command TOC entries as N actions, allowing the
transaction size to be scaled down when we hit a complex TOC entry.
Rather than add a SQL parser to pg_restore, approximate "multi
command" by counting semicolons in the TOC entry's defn string.
This will be fooled by semicolons appearing in string literals ---
but the error is in the conservative direction, so it doesn't seem
worth working harder.  The biggest risk is with function/procedure
TOC entries, but we can just explicitly skip those.

(This is undoubtedly a hack, and maybe someday we'll be able to
revert it after fixing the backend's bloat issues or rethinking
what pg_dump emits in binary upgrade mode.  But that surely isn't
a project for v17.)

Thanks to Alexander Korotkov for the let's-count-semicolons idea.

Per report from Justin Pryzby.  Back-patch to v17 where txn_size mode
was introduced.

Discussion: https://postgr.es/m/ZqEND4ZcTDBmcv31@pryzbyj2023

10 months agoReduce number of commands dumpTableSchema emits for binary upgrade.
Tom Lane [Mon, 29 Jul 2024 15:53:49 +0000 (11:53 -0400)]
Reduce number of commands dumpTableSchema emits for binary upgrade.

Avoid issuing a separate SQL UPDATE command for each column when
directly manipulating pg_attribute contents in binary upgrade mode.
With the separate updates, we triggered a relcache invalidation with
each update.  For a table with N columns, that causes O(N^2) relcache
bloat in txn_size mode because the table's newly-created relcache
entry can't be flushed till end of transaction.  Reducing the number
of commands should make it marginally faster as well as avoiding that
problem.

While at it, likewise avoid issuing a separate UPDATE on pg_constraint
for each inherited constraint.  This is less exciting, first because
inherited (non-partitioned) constraints are relatively rare, and
second because the backend has a good deal of trouble anyway with
restoring tables containing many such constraints, due to
MergeConstraintsIntoExisting being horribly inefficient.  But it seems
more consistent to do it this way here too, and it surely can't hurt.

In passing, fix one place in dumpTableSchema that failed to use ONLY
in ALTER TABLE.  That's not a live bug, but it's inconsistent.
Also avoid silently casting away const from string literals.

Per report from Justin Pryzby.  Back-patch to v17 where txn_size mode
was introduced.

Discussion: https://postgr.es/m/ZqEND4ZcTDBmcv31@pryzbyj2023

10 months agoFix incorrect return value for pg_size_pretty(bigint)
David Rowley [Sun, 28 Jul 2024 10:23:32 +0000 (22:23 +1200)]
Fix incorrect return value for pg_size_pretty(bigint)

pg_size_pretty(bigint) would return the value in bytes rather than PB
for the smallest-most bigint value.  This happened due to an incorrect
assumption that the absolute value of -9223372036854775808 could be
stored inside a signed 64-bit type.

Here we fix that by instead storing that value in an unsigned 64-bit type.

This bug does exist in versions prior to 15 but the code there is
sufficiently different and the bug seems sufficiently non-critical that
it does not seem worth risking backpatching further.

Author: Joseph Koshakow <[email protected]>
Discussion: https://postgr.es/m/CAAvxfHdTsMZPWEHUrZ=h3cky9Ccc3Mtx2whUHygY+ABP-mCmUw@mail.gmail.com
Backpatch-through: 15

10 months agolibpq: Use strerror_r instead of strerror
Peter Eisentraut [Sun, 28 Jul 2024 07:12:00 +0000 (09:12 +0200)]
libpq: Use strerror_r instead of strerror

Commit 453c4687377 introduced a use of strerror() into libpq, but that
is not thread-safe.  Fix by using strerror_r() instead.

In passing, update some of the code comments added by 453c4687377, as
we have learned more about the reason for the change in OpenSSL that
started this.

Reviewed-by: Daniel Gustafsson <[email protected]>
Discussion: Discussion: https://postgr.es/m/b6fb018b-f05c-4afd-abd3-318c649faf18@highgo.ca

10 months agodoc PG 17 relnotes: add "()" to PQsocketPoll mention
Bruce Momjian [Sun, 28 Jul 2024 08:10:11 +0000 (04:10 -0400)]
doc PG 17 relnotes:  add "()" to PQsocketPoll mention

Backpatch-through: 17 only

10 months agoSupport falling back to non-preferred readline implementation with meson
Heikki Linnakangas [Sat, 27 Jul 2024 10:53:16 +0000 (13:53 +0300)]
Support falling back to non-preferred readline implementation with meson

To build with -Dreadline=enabled one can use either readline or
libedit. The -Dlibedit_preferred flag is supposed to control the order
of names to lookup.  This works fine when either both libraries are
present or -Dreadline is set to auto. However, explicitly enabling
readline with only libedit present, but not setting libedit_preferred,
or alternatively enabling readline with only readline present, but
setting libedit_preferred, too, are both broken. This is because
cc.find_library will throw an error for a not found dependency as soon
as the first required dependency is checked, thus it's impossible to
fallback to the alternative.

Here we only check the second of the two dependencies for
requiredness, thus we only fail when none of the two can be found.

Author: Wolfgang Walther
Reviewed-by: Nazir Bilal Yavuz, Alvaro Herrera, Peter Eisentraut
Reviewed-by: Tristan Partin
Discussion: https://www.postgresql.org/message-id/ca8f37e1-a2c3-40e2-91f6-59c3d3652ad4@technowledgy.de
Backpatch: 16-, where meson support was added

10 months agoSupport absolute bindir/libdir in regression tests with meson
Heikki Linnakangas [Sat, 27 Jul 2024 10:53:14 +0000 (13:53 +0300)]
Support absolute bindir/libdir in regression tests with meson

Passing an absolute bindir/libdir will install the binaries and
libraries to <build>/tmp_install/<bindir> and
<build>/tmp_install/<libdir> respectively.

This path is correctly passed to the regression test suite via
configure/make, but not via meson, yet. This is because the "/"
operator in the following expression throws away the whole left side
when the right side is an absolute path:

    test_install_location / get_option('libdir')

This was already correctly handled for dir_prefix, which is likely
absolute as well. This patch handles both bindir and libdir in the
same way - prefixing absolute paths with the tmp_install path
correctly.

Author: Wolfgang Walther
Reviewed-by: Nazir Bilal Yavuz, Alvaro Herrera, Peter Eisentraut
Reviewed-by: Tristan Partin
Discussion: https://www.postgresql.org/message-id/ca8f37e1-a2c3-40e2-91f6-59c3d3652ad4@technowledgy.de
Backpatch: 16-, where meson support was added

10 months agoFallback to clang in PATH with meson
Heikki Linnakangas [Sat, 27 Jul 2024 10:53:11 +0000 (13:53 +0300)]
Fallback to clang in PATH with meson

Some distributions put clang into a different path than the llvm
binary path.

For example, this is the case on NixOS / nixpkgs, which failed to find
clang with meson before this patch.

Author: Wolfgang Walther
Reviewed-by: Nazir Bilal Yavuz, Alvaro Herrera, Peter Eisentraut
Reviewed-by: Tristan Partin
Discussion: https://www.postgresql.org/message-id/ca8f37e1-a2c3-40e2-91f6-59c3d3652ad4@technowledgy.de
Backpatch: 16-, where meson support was added

10 months agoFallback to uuid for ossp-uuid with meson
Heikki Linnakangas [Sat, 27 Jul 2024 10:53:08 +0000 (13:53 +0300)]
Fallback to uuid for ossp-uuid with meson

The upstream name for the ossp-uuid package / pkg-config file is
"uuid". Many distributions change this to be "ossp-uuid" to not
conflict with e2fsprogs.

This lookup fails on distributions which don't change this name, for
example NixOS / nixpkgs. Both "ossp-uuid" and "uuid" are also checked
in configure.ac.

Author: Wolfgang Walther
Reviewed-by: Nazir Bilal Yavuz, Alvaro Herrera, Peter Eisentraut
Reviewed-by: Tristan Partin
Discussion: https://www.postgresql.org/message-id/ca8f37e1-a2c3-40e2-91f6-59c3d3652ad4@technowledgy.de
Backpatch: 16-, where meson support was added

10 months agoFix more holes with SLRU code in need of int64 for segment numbers
Michael Paquier [Fri, 26 Jul 2024 22:16:59 +0000 (07:16 +0900)]
Fix more holes with SLRU code in need of int64 for segment numbers

This is a continuation of 3937cadfd438, taking care of more areas I have
managed to miss previously.

Reported-by: Noah Misch
Reviewed-by: Noah Misch
Discussion: https://postgr.es/m/20240724130059[email protected]
Backpatch-through: 17

10 months agoWait for WAL summarization to catch up before creating .partial file.
Robert Haas [Fri, 26 Jul 2024 18:50:21 +0000 (14:50 -0400)]
Wait for WAL summarization to catch up before creating .partial file.

When a standby is promoted, CleanupAfterArchiveRecovery() may decide
to rename the final WAL file from the old timeline by adding ".partial"
to the name. If WAL summarization is enabled and this file is renamed
before its partial contents are summarized, WAL summarization breaks:
the summarizer gets stuck at that point in the WAL stream and just
errors out.

To fix that, first make the startup process wait for WAL summarization
to catch up before renaming the file. Generally, this should be quick,
and if it's not, the user can shut off summarize_wal and try again.
To make this fix work, also teach the WAL summarizer that after a
promotion has occurred, no more WAL can appear on the previous
timeline: previously, the WAL summarizer wouldn't switch to the new
timeline until we actually started writing WAL there, but that meant
that when the startup process was waiting for the WAL summarizer, it
was waiting for an action that the summarizer wasn't yet prepared to
take.

In the process of fixing these bugs, I realized that the logic to wait
for WAL summarization to catch up was spread out in a way that made
it difficult to reuse properly, so this code refactors things to make
it easier.

Finally, add a test case that would have caught this bug and the
previously-fixed bug that WAL summarization sometimes needs to back up
when the timeline changes.

Discussion: https://postgr.es/m/CA+TgmoZGEsZodXC4f=XZNkAeyuDmWTSkpkjCEOcF19Am0mt_OA@mail.gmail.com

10 months agoFix indentation.
Robert Haas [Fri, 26 Jul 2024 15:58:52 +0000 (11:58 -0400)]
Fix indentation.

10 months agoFix macro placement in pg_config.h.in
Daniel Gustafsson [Fri, 26 Jul 2024 14:25:56 +0000 (16:25 +0200)]
Fix macro placement in pg_config.h.in

Commit 274bbced85383e831dde accidentally placed the pg_config.h.in
for SSL_CTX_set_num_tickets on the wrong line wrt where autoheader
places it.  Fix by re-arranging and backpatch to the same level as
the original commit.

Reported-by: Marina Polyakova <[email protected]>
Discussion: https://postgr.es/m/48cebe8c3eaf308bae253b1dbf4e4a75@postgrespro.ru
Backpatch-through: v12

10 months agoAllow WAL summarization to back up when timeline changes.
Robert Haas [Fri, 26 Jul 2024 13:50:31 +0000 (09:50 -0400)]
Allow WAL summarization to back up when timeline changes.

The old code believed that it was not possible to switch timelines
without first replaying all of the WAL from the old timeline, but
that turns out to be false, as demonstrated by an example from Fujii
Masao. As a result, it assumed that summarization would always
continue from the LSN where summarization previously ended. But in
fact, when a timeline switch occurs without replaying all the WAL
from the previous timeline, we can need to back up to an earlier
LSN. Adjust accordingly.

Discussion: https://postgr.es/m/CA+TgmoZGEsZodXC4f=XZNkAeyuDmWTSkpkjCEOcF19Am0mt_OA@mail.gmail.com

10 months agopg_createsubscriber: Message style improvements
Peter Eisentraut [Fri, 26 Jul 2024 12:45:13 +0000 (14:45 +0200)]
pg_createsubscriber: Message style improvements

Refactor some messages, improve quoting.

10 months agoFix using injection points at backend startup in EXEC_BACKEND mode
Heikki Linnakangas [Fri, 26 Jul 2024 11:55:04 +0000 (14:55 +0300)]
Fix using injection points at backend startup in EXEC_BACKEND mode

Commit 86db52a506 changed the locking of injection points to use only
atomic ops and spinlocks, to make it possible to define injection
points in processes that don't have a PGPROC entry (yet). However, it
didn't work in EXEC_BACKEND mode, because the pointer to shared memory
area was not initialized until the process "attaches" to all the
shared memory structs. To fix, pass the pointer to the child process
along with other global variables that need to be set up early.

Backpatch-through: 17

10 months agoFix fallback behavior when server sends an ERROR early at startup
Heikki Linnakangas [Fri, 26 Jul 2024 11:52:08 +0000 (14:52 +0300)]
Fix fallback behavior when server sends an ERROR early at startup

With sslmode=prefer, the desired behavior is to completely fail the
connection attempt, *not* fall back to a plaintext connection, if the
server responds to the SSLRequest with an error ('E') response instead
of rejecting SSL with an 'N' response. This was broken in commit
05fd30c0e7.

Reported-by: Jacob Champion
Reviewed-by: Michael Paquier
Discussion: https://www.postgresql.org/message-id/CAOYmi%2Bnwvu21mJ4DYKUa98HdfM_KZJi7B1MhyXtnsyOO-PB6Ww%40mail.gmail.com
Backpatch-through: 17

10 months agoDisable all TLS session tickets
Daniel Gustafsson [Fri, 26 Jul 2024 09:09:45 +0000 (11:09 +0200)]
Disable all TLS session tickets

OpenSSL supports two types of session tickets for TLSv1.3, stateless
and stateful. The option we've used only turns off stateless tickets
leaving stateful tickets active. Use the new API introduced in 1.1.1
to disable all types of tickets.

Backpatch to all supported versions.

Reviewed-by: Heikki Linnakangas <[email protected]>
Reported-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/20240617173803[email protected]
Backpatch-through: v12

10 months agoSQL/JSON: Remove useless code in ExecInitJsonExpr()
Amit Langote [Fri, 26 Jul 2024 07:37:59 +0000 (16:37 +0900)]
SQL/JSON: Remove useless code in ExecInitJsonExpr()

The code was for adding an unconditional JUMP to the next step,
which is unnecessary processing.

Reported-by: Jian He <[email protected]>
Discussion: https://postgr.es/m/CACJufxEo4sUjKCYtda0_qt9tazqqKPmF1cqhW9KBOUeJFqQd2g@mail.gmail.com
Backpatch-through: 17

10 months agoSQL/JSON: Respect OMIT QUOTES when RETURNING domains over jsonb
Amit Langote [Fri, 26 Jul 2024 07:08:13 +0000 (16:08 +0900)]
SQL/JSON: Respect OMIT QUOTES when RETURNING domains over jsonb

populate_domain() didn't take into account the omit_quotes flag passed
down to json_populate_type() by ExecEvalJsonCoercion() and that led
to incorrect behavior when the RETURNING type is a domain over
jsonb.  Fix that by passing the flag by adding a new function
parameter to populate_domain().

Reported-by: Jian He <[email protected]>
Discussion: https://postgr.es/m/CACJufxEo4sUjKCYtda0_qt9tazqqKPmF1cqhW9KBOUeJFqQd2g@mail.gmail.com
Backpatch-through: 17

10 months agoSQL/JSON: Improve error-handling of JsonBehavior expressions
Amit Langote [Fri, 26 Jul 2024 07:00:16 +0000 (16:00 +0900)]
SQL/JSON: Improve error-handling of JsonBehavior expressions

Instead of returning a NULL when the JsonBehavior expression value
could not be coerced to the RETURNING type, throw the error message
informing the user that it is the JsonBehavior expression that caused
the error with the actual coercion error message shown in its DETAIL
line.

Discussion: https://postgr.es/m/CACJufxEo4sUjKCYtda0_qt9tazqqKPmF1cqhW9KBOUeJFqQd2g@mail.gmail.com
Backpatch-through: 17

10 months agoSQL/JSON: Fix error-handling of some JsonBehavior expressions
Amit Langote [Fri, 26 Jul 2024 06:59:27 +0000 (15:59 +0900)]
SQL/JSON: Fix error-handling of some JsonBehavior expressions

To ensure that the errors of executing a JsonBehavior expression that
is coerced in the parser are caught instead of being thrown directly,
pass ErrorSaveContext to ExecInitExprRec() when initializing it.
Also, add a EEOP_JSONEXPR_COERCION_FINISH step to handle the errors
that are caught that way.

Discussion: https://postgr.es/m/CACJufxEo4sUjKCYtda0_qt9tazqqKPmF1cqhW9KBOUeJFqQd2g@mail.gmail.com
Backpatch-through: 17

10 months agoDoc: fix misleading syntax synopses for targetlists.
Tom Lane [Thu, 25 Jul 2024 23:52:08 +0000 (19:52 -0400)]
Doc: fix misleading syntax synopses for targetlists.

In the syntax synopses for SELECT, INSERT, UPDATE, etc,
SELECT ... and RETURNING ... targetlists were missing { ... }
braces around an OR (|) operator.  That allows misinterpretation
which could lead to confusion.

David G. Johnston, per gripe from [email protected].

Discussion: https://postgr.es/m/172193970148.915373.2403176471224676074@wrigleys.postgresql.org

10 months agoDocument restrictions regarding incremental backups and standbys.
Robert Haas [Thu, 25 Jul 2024 19:45:06 +0000 (15:45 -0400)]
Document restrictions regarding incremental backups and standbys.

If you try to take an incremental backup on a standby and there hasn't
been much system activity, it might fail. Document why this happens.
Also add a hint to the error message you get, to make it more likely
that users will understand what has gone wrong.

Laurenz Albe and Robert Haas

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

10 months agopg_createsubscriber: Message improvements
Peter Eisentraut [Thu, 25 Jul 2024 13:25:42 +0000 (15:25 +0200)]
pg_createsubscriber: Message improvements

Objects are typically "in" a database, not "on".

10 months agoRemove useless unconstify() call
Peter Eisentraut [Thu, 25 Jul 2024 09:38:05 +0000 (11:38 +0200)]
Remove useless unconstify() call

This should have been part of 67c0ef9752 but was apparently forgotten
there.

10 months agoci: Pin MacPorts version to 2.9.3.
Thomas Munro [Thu, 25 Jul 2024 02:46:01 +0000 (14:46 +1200)]
ci: Pin MacPorts version to 2.9.3.

Commit d01ce180 invented a new way to find the latest MacPorts version.
By bad luck, a new beta release has just been published, and it seems
to lack some packages we need.  Go back to searching for this specific
version for now.  We still search with a pattern so that we can find the
package for the running version of macOS, but for now we always look for
2.9.3.  The code to do that had been anticipated already in a commented
out line, I just didn't expect to have to use it so soon...

Also include the whole MacPorts installation script in the cache key, so
that changes to the script cause a fresh installation.  This should make
it a bit easier to reason about the effect of changes on cached state in
github accounts using CI, when we make adjustments.

Back-patch to 15, like d01ce180.

Discussion: https://postgr.es/m/CA%2BhUKGLqJdv6RcwyZ_0H7khxtLTNJyuK%2BvDFzv3uwYbn8hKH6A%40mail.gmail.com

10 months agoci: Upgrade macOS version from 13 to 14.
Thomas Munro [Wed, 24 Jul 2024 23:26:48 +0000 (11:26 +1200)]
ci: Upgrade macOS version from 13 to 14.

1.  Previously we were using ghcr.io/cirruslabs/macos-XXX-base:latest
images, but Cirrus has started ignoring that and using a particular
image, currently ghcr.io/cirruslabs/macos-runner:sonoma, for github
accounts using free CI resources (as opposed to dedicated runner
machines, as cfbot uses).  Let's just ask for that image anyway, to stay
in sync.

2.  Instead of hard-coding a MacPorts installation URL, deduce it from
the running macOS version and the available releases.  This removes the
need to keep the ci_macports_packages.sh in sync with .cirrus.task.yml,
and to advance the MacPorts version from time to time.

3.  Change the cache key we use to cache the whole macports installation
across builds to include the OS major version, to trigger a fresh
installation when appropriate.

Back-patch to 15 where CI began.

Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CA%2BhUKGLqJdv6RcwyZ_0H7khxtLTNJyuK%2BvDFzv3uwYbn8hKH6A%40mail.gmail.com

10 months agopg_upgrade: Retrieve subscription count more efficiently.
Nathan Bossart [Wed, 24 Jul 2024 16:30:33 +0000 (11:30 -0500)]
pg_upgrade: Retrieve subscription count more efficiently.

Presently, pg_upgrade obtains the number of subscriptions in the
to-be-upgraded cluster by first querying pg_subscription in every
database for the number of subscriptions in only that database.
Then, in count_old_cluster_subscriptions(), it adds all the values
collected in the first step.  This is expensive, especially when
there are many databases.

Fortunately, there is a better way to retrieve the subscription
count.  Since pg_subscription is a shared catalog, we only need to
connect to a single database and query it once.  This commit
modifies pg_upgrade to use that approach, which also allows us to
trim several lines of code.  In passing, move the call to
get_db_subscription_count(), which has been renamed to
get_subscription_count(), from get_db_rel_and_slot_infos() to the
dedicated >= v17 section in check_and_dump_old_cluster().

We may be able to make similar improvements to
get_old_cluster_logical_slot_infos(), but that is left as a future
exercise.

Reviewed-by: Michael Paquier, Amit Kapila
Discussion: https://postgr.es/m/ZprQJv_TxccN3tkr%40nathan
Backpatch-through: 17

10 months agoFix a missing article in the documentation
Alvaro Herrera [Wed, 24 Jul 2024 12:13:55 +0000 (14:13 +0200)]
Fix a missing article in the documentation

Per complaint from Grant Gryczan.

It's a very old typo; backpatch all the way back.

Author: Laurenz Albe <[email protected]>
Discussion: https://postgr.es/m/172179789219.915368.16590585529628354757@wrigleys.postgresql.org

10 months agoReset relhassubclass upon attaching table as a partition
Alvaro Herrera [Wed, 24 Jul 2024 10:38:18 +0000 (12:38 +0200)]
Reset relhassubclass upon attaching table as a partition

We don't allow inheritance parents as partitions, and have checks to
prevent this; but if a table _was_ in the past an inheritance parents
and all their children are removed, the pg_class.relhassubclass flag
may remain set, which confuses the partition pruning code (most
obviously, it results in an assertion failure; in production builds it
may be worse.)

Fix by resetting relhassubclass on attach.

Backpatch to all supported versions.

Reported-by: Alexander Lakhin <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/18550-d5e047e9a897a889@postgresql.org

10 months agoDoc: Fix the mistakes in the subscription's failover option.
Amit Kapila [Wed, 24 Jul 2024 10:00:58 +0000 (15:30 +0530)]
Doc: Fix the mistakes in the subscription's failover option.

The documentation incorrectly stated that users could not alter the
subscription's failover option when the two-phase commit is enabled.

The steps to confirm that the standby server is ready for failover were
incorrect.

Author: Shveta Malik, Hou Zhijie
Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/OS0PR01MB571657B72F8D75BD858DCCE394AD2@OS0PR01MB5716.jpnprd01.prod.outlook.com
Discussion: https://postgr.es/m/CAJpy0uBBk+OZXXqQ00Gai09XR+mDi2=9sMBYY0F+BedoFivaMA@mail.gmail.com

10 months agoDetect integer overflow in array_set_slice().
Nathan Bossart [Wed, 24 Jul 2024 02:59:02 +0000 (21:59 -0500)]
Detect integer overflow in array_set_slice().

When provided an empty initial array, array_set_slice() fails to
check for overflow when computing the new array's dimensions.
While such overflows are ordinarily caught by ArrayGetNItems(),
commands with the following form are accepted:

INSERT INTO t (i[-2147483648:2147483647]) VALUES ('{}');

To fix, perform the hazardous computations using overflow-detecting
arithmetic routines.  As with commit 18b585155a, the added test
cases generate errors that include a platform-dependent value, so
we again use psql's VERBOSITY parameter to suppress printing the
message text.

Reported-by: Alexander Lakhin
Author: Joseph Koshakow
Reviewed-by: Jian He
Discussion: https://postgr.es/m/31ad2cd1-db94-bdb3-f91a-65ffdb4bef95%40gmail.com
Backpatch-through: 12

10 months agoUse more consistently int64 for page numbers in SLRU-related code
Michael Paquier [Tue, 23 Jul 2024 08:59:20 +0000 (17:59 +0900)]
Use more consistently int64 for page numbers in SLRU-related code

clog.c, async.c and predicate.c included some SLRU page numbers still
handled as 4-byte integers, while int64 should be used for this purpose.

These holes have been introduced in 4ed8f0913bfd, that has introduced
the use of 8-byte integers for SLRU page numbers, still forgot about the
code paths updated by this commit.

Reported-by: Noah Misch
Author: Aleksander Alekseev, Michael Paquier
Discussion: https://postgr.es/m/20240626002747[email protected]
Backpatch-through: 17

10 months agoImprove comments in slru.{c,h} about segment name format
Michael Paquier [Tue, 23 Jul 2024 07:55:09 +0000 (16:55 +0900)]
Improve comments in slru.{c,h} about segment name format

slru.h described incorrectly how SLRU segment names are formatted
depending on the segment number and if long or short segment names are
used.  This commit closes the gap with a better description, fitting
with the reality.

Reported-by: Noah Misch
Author: Aleksander Alekseev
Discussion: https://postgr.es/m/20240626002747[email protected]
Backpatch-through: 17

10 months agoDoc: improve description of plpgsql's FETCH and MOVE commands.
Tom Lane [Mon, 22 Jul 2024 23:43:12 +0000 (19:43 -0400)]
Doc: improve description of plpgsql's FETCH and MOVE commands.

We were not being clear about which variants of the "direction"
clause are permitted in MOVE.  Also, the text seemed to be
written with only the FETCH/MOVE NEXT case in mind, so it
didn't apply very well to other variants.

Also, document that "MOVE count IN cursor" only works if count
is a constant.  This is not the whole truth, because some other
cases such as a parenthesized expression will also work, but
we want to push people to use "MOVE FORWARD count" instead.
The constant case is enough to cover what we allow in plain SQL,
and that seems sufficient to claim support for.

Update a comment in pl_gram.y claiming that we don't document
that point.

Per gripe from Philipp Salvisberg.

Discussion: https://postgr.es/m/172155553388.702.7932496598218792085@wrigleys.postgresql.org

10 months agoRevert "Test that vacuum removes tuples older than OldestXmin"
Melanie Plageman [Mon, 22 Jul 2024 20:32:43 +0000 (16:32 -0400)]
Revert "Test that vacuum removes tuples older than OldestXmin"

This reverts commit 80c34692e8e674e3b2f150f248ef2002ae2ac3a7.

This test proved to be unstable on the buildfarm, timing out before the
standby could catch up on 32-bit machines where more rows were required
and failing to reliably trigger multiple index vacuum rounds on 64-bit
machines where fewer rows should be required.

Because the instability is only known to be present on versions of
Postgres with TIDStore used for dead TID storage by vacuum, this is only
being reverted on master and REL_17_STABLE.

As having this coverage may be valuable, there is a discussion on the
thread of possible ways to stabilize the test. If that happens, a fixed
test can be committed again.

Backpatch-through: 17
Reported-by: Tom Lane
Discussion: https://postgr.es/m/614152.1721580711%40sss.pgh.pa.us

10 months agoInitialize wal_level in the initial checkpoint record.
Robert Haas [Mon, 22 Jul 2024 19:32:43 +0000 (15:32 -0400)]
Initialize wal_level in the initial checkpoint record.

As per Coverity and Tom Lane, commit 402b586d0 (back-patched to v17
as 2b5819e2b) forgot to initialize this new structure member in this
code path.

10 months agoAdd missing call to ConditionVariableCancelSleep().
Robert Haas [Wed, 17 Jul 2024 18:53:00 +0000 (14:53 -0400)]
Add missing call to ConditionVariableCancelSleep().

After calling ConditionVariableSleep() or ConditionVariableTimedSleep()
one or more times, code is supposed to call ConditionVariableCancelSleep()
to remove itself from the waitlist. This code neglected to do so.
As far as I know, that had no observable consequences, but let's make
the code correct.

Discussion: http://postgr.es/m/CA+TgmoYW8eR+KN6zhVH0sin7QH6AvENqw_bkN-bB4yLYKAnsew@mail.gmail.com

10 months agopostgres_fdw: Split out the query_cancel test to its own file
Alvaro Herrera [Mon, 22 Jul 2024 10:49:57 +0000 (12:49 +0200)]
postgres_fdw: Split out the query_cancel test to its own file

This allows us to skip it in Cygwin, where it's reportedly flaky because
of platform bugs or something.

Backpatch to 17, where the test was introduced by commit 2466d6654f85.

Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://postgr.es/m/e4d0cb33-6be5-e4d5-ae49-9eac3ff2b005@gmail.com

10 months agomeson: Add dependency lookups via names used by cmake
Andres Freund [Sat, 20 Jul 2024 20:51:08 +0000 (13:51 -0700)]
meson: Add dependency lookups via names used by cmake

Particularly on windows it's useful to look up dependencies via cmake, instead
of pkg-config. Meson supports doing so. Unfortunately the dependency names
used by various projects often differs between their pkg-config and cmake
files.

This would look a lot neater if we could rely on meson >= 0.60.0...

Reviewed-by: Tristan Partin <[email protected]>
Discussion: https://postgr.es/m/20240709065101[email protected]
Backpatch: 16-, where meson support was added

10 months agomeson: Add support for detecting ossp-uuid without pkg-config
Andres Freund [Sat, 20 Jul 2024 20:51:08 +0000 (13:51 -0700)]
meson: Add support for detecting ossp-uuid without pkg-config

This is necessary as ossp-uuid on windows installs neither a pkg-config nor a
cmake dependency information. Nor is there another supported uuid
implementation available on windows.

Reported-by: Dave Page <[email protected]>
Reviewed-by: Tristan Partin <[email protected]>
Discussion: https://postgr.es/m/20240709065101[email protected]
Backpatch: 16-, where meson support was added

10 months agomeson: Add support for detecting gss without pkg-config
Andres Freund [Sat, 20 Jul 2024 20:51:08 +0000 (13:51 -0700)]
meson: Add support for detecting gss without pkg-config

This is required as MIT Kerberos does provide neither pkg-config nor cmake
dependency information on windows.

Reported-by: Dave Page <[email protected]>
Reviewed-by: Tristan Partin <[email protected]>
Discussion: https://postgr.es/m/20240709065101[email protected]
Backpatch: 16-, where meson support was added

10 months agomeson: Add missing argument to gssapi.h check
Andres Freund [Sat, 20 Jul 2024 20:51:08 +0000 (13:51 -0700)]
meson: Add missing argument to gssapi.h check

These were missing since the initial introduction of the meson based build, in
e6927270cd18. As-is this is unlikely to cause an issue, but a future commit
will add support for detecting gssapi without use of dependency(), which could
fail due to this.

Discussion: https://postgr.es/m/20240708225659[email protected]
Backpatch: 16-, where the meson based build was added

10 months agoCorrectly check updatability of columns targeted by INSERT...DEFAULT.
Tom Lane [Sat, 20 Jul 2024 17:40:15 +0000 (13:40 -0400)]
Correctly check updatability of columns targeted by INSERT...DEFAULT.

If a view has some updatable and some non-updatable columns, we failed
to verify updatability of any columns for which an INSERT or UPDATE
on the view explicitly specifies a DEFAULT item (unless the view has
a declared default for that column, which is rare anyway, and one
would almost certainly not write one for a non-updatable column).
This would lead to an unexpected "attribute number N not found in
view targetlist" error rather than the intended error.

Per bug #18546 from Alexander Lakhin.  This bug is old, so back-patch
to all supported branches.

Discussion: https://postgr.es/m/18546-84a292e759a9361d@postgresql.org

10 months agoAdd overflow checks to money type.
Nathan Bossart [Fri, 19 Jul 2024 16:52:32 +0000 (11:52 -0500)]
Add overflow checks to money type.

None of the arithmetic functions for the the money type handle
overflow.  This commit introduces several helper functions with
overflow checking and makes use of them in the money type's
arithmetic functions.

Fixes bug #18240.

Reported-by: Alexander Lakhin
Author: Joseph Koshakow
Discussion: https://postgr.es/m/18240-c5da758d7dc1ecf0%40postgresql.org
Discussion: https://postgr.es/m/CAAvxfHdBPOyEGS7s%2Bxf4iaW0-cgiq25jpYdWBqQqvLtLe_t6tw%40mail.gmail.com
Backpatch-through: 12

10 months agoTest that vacuum removes tuples older than OldestXmin
Melanie Plageman [Fri, 19 Jul 2024 14:40:42 +0000 (10:40 -0400)]
Test that vacuum removes tuples older than OldestXmin

If vacuum fails to prune a tuple killed before OldestXmin, it will
decide to freeze its xmax and later error out in pre-freeze checks.

Add a test reproducing this scenario to the recovery suite which creates
a table on a primary, updates the table to generate dead tuples for
vacuum, and then, during the vacuum, uses a replica to force
GlobalVisState->maybe_needed on the primary to move backwards and
precede the value of OldestXmin set at the beginning of vacuuming the
table.

This commit is separate from the fix in case there are test stability
issues.

Author: Melanie Plageman
Reviewed-by: Peter Geoghegan
Discussion: https://postgr.es/m/CAAKRu_apNU2MPBK96V%2BbXjTq0RiZ-%3DA4ZTaysakpx9jxbq1dbQ%40mail.gmail.com

10 months agoEnsure vacuum removes all visibly dead tuples older than OldestXmin
Melanie Plageman [Fri, 19 Jul 2024 14:40:39 +0000 (10:40 -0400)]
Ensure vacuum removes all visibly dead tuples older than OldestXmin

If vacuum fails to remove a tuple with xmax older than
VacuumCutoffs->OldestXmin and younger than GlobalVisState->maybe_needed,
it may attempt to freeze the tuple's xmax and then ERROR out in
pre-freeze checks with "cannot freeze committed xmax".

Fix this by having vacuum always remove tuples older than OldestXmin.

It is possible for GlobalVisState->maybe_needed to precede OldestXmin if
maybe_needed is forced to go backward while vacuum is running. This can
happen if a disconnected standby with a running transaction older than
VacuumCutoffs->OldestXmin reconnects to the primary after vacuum
initially calculates GlobalVisState and OldestXmin.

In back branches starting with 14, the first version using
GlobalVisState, failing to remove tuples older than OldestXmin during
pruning caused vacuum to infinitely loop in lazy_scan_prune(), as
investigated on this [1] thread. After 1ccc1e05ae removed the retry loop
in lazy_scan_prune() and stopped comparing tuples to OldestXmin, the
hang could no longer happen, but we could still attempt to freeze dead
tuples with xmax older than OldestXmin -- resulting in an ERROR.

Fix this by always removing dead tuples with xmax older than
VacuumCutoffs->OldestXmin. This is okay because the standby won't replay
the tuple removal until the tuple is removable. Thus, the worst that can
happen is a recovery conflict.

[1] https://postgr.es/m/20240415173913.4zyyrwaftujxthf2%40awork3.anarazel.de#1b216b7768b5bd577a3d3d51bd5aadee

Back-patch through 14

Author: Melanie Plageman
Reviewed-by: Peter Geoghegan, Robert Haas, Andres Freund, Heikki Linnakangas, and Noah Misch
Discussion: https://postgr.es/m/CAAKRu_bDD7oq9ZwB2OJqub5BovMG6UjEYsoK2LVttadjEqyRGg%40mail.gmail.com

10 months agoMove resowner from common JitContext to LLVM specific
Heikki Linnakangas [Fri, 19 Jul 2024 07:27:06 +0000 (10:27 +0300)]
Move resowner from common JitContext to LLVM specific

Only the LLVM specific code uses it since resource owners were made
extensible in commit b8bff07daa85c837a2747b4d35cd5a27e73fb7b2. This is
new in v17, so backpatch there to keep the branches from diverging
just yet.

Author: Andreas Karlsson <[email protected]>
Discussion: https://www.postgresql.org/message-id/fd3a2a00-6605-4e30-a118-48418b478e6e@proxel.se

10 months agopostgres_fdw: Avoid "cursor can only scan forward" error.
Etsuro Fujita [Fri, 19 Jul 2024 04:15:01 +0000 (13:15 +0900)]
postgres_fdw: Avoid "cursor can only scan forward" error.

Commit d844cd75a disallowed rewind in a non-scrollable cursor to resolve
anomalies arising from such a cursor operation.  However, this failed to
take into account the assumption in postgres_fdw that when rescanning a
foreign relation, it can rewind the cursor created for scanning the
foreign relation without specifying the SCROLL option, regardless of its
scrollability, causing this error when it tried to do such a rewind in a
non-scrollable cursor.  Fix by modifying postgres_fdw to instead
recreate the cursor, regardless of its scrollability, when rescanning
the foreign relation.  (If we had a way to check its scrollability, we
could improve this by rewinding it if it is scrollable and recreating it
if not, but we do not have it, so this commit modifies it to recreate it
in any case.)

Per bug #17889 from Eric Cyr.  Devrim Gunduz also reported this problem.
Back-patch to v15 where that commit enforced the prohibition.

Reviewed by Tom Lane.

Discussion: https://postgr.es/m/17889-e8c39a251d258dda%40postgresql.org
Discussion: https://postgr.es/m/b415ac3255f8352d1ea921cf3b7ba39e0587768a.camel%40gunduz.org

10 months agoPropagate query IDs of utility statements in functions
Michael Paquier [Fri, 19 Jul 2024 01:21:21 +0000 (10:21 +0900)]
Propagate query IDs of utility statements in functions

For utility statements defined within a function, the query tree is
copied to a PlannedStmt as utility commands do not require planning.
However, the query ID was missing from the information passed down.

This leads to plugins relying on the query ID like pg_stat_statements to
not be able to track utility statements within function calls.  Tests
are added to check this behavior, depending on pg_stat_statements.track.

This is an old bug.  Now, query IDs for utilities are compiled using
their parsed trees rather than the query string since v16
(3db72ebcbe20), leading to less bloat with utilities, so backpatch down
only to this version.

Author: Anthonin Bonnefoy
Discussion: https://postgr.es/m/CAO6_XqrGp-uwBqi3vBPLuRULKkddjC7R5QZCgsFren=8E+m2Sg@mail.gmail.com
Backpatch-through: 16

10 months agoDo not summarize WAL if generated with wal_level=minimal.
Robert Haas [Thu, 18 Jul 2024 16:09:48 +0000 (12:09 -0400)]
Do not summarize WAL if generated with wal_level=minimal.

To do this, we must include the wal_level in the first WAL record
covered by each summary file; so add wal_level to struct Checkpoint
and the payload of XLOG_CHECKPOINT_REDO and XLOG_END_OF_RECOVERY.

This, in turn, requires bumping XLOG_PAGE_MAGIC and, since the
Checkpoint is also stored in the control file, also
PG_CONTROL_VERSION. It's not great to do that so late in the release
cycle, but the alternative seems to ship v17 without robust
protections against this scenario, which could result in corrupted
incremental backups.

A side effect of this patch is that, when a server with
wal_level=replica is started with summarize_wal=on for the first time,
summarization will no longer begin with the oldest WAL that still
exists in pg_wal, but rather from the first checkpoint after that.
This change should be harmless, because a WAL summary for a partial
checkpoint cycle can never make an incremental backup possible when
it would otherwise not have been.

Report by Fujii Masao. Patch by me. Review and/or testing by Jakub
Wartak and Fujii Masao.

Discussion: http://postgr.es/m/6e30082e-041b-4e31-9633-95a66de76f5d@oss.nttdata.com

10 months agoDoc: fix minor syntax error in example.
Tom Lane [Wed, 17 Jul 2024 19:17:52 +0000 (15:17 -0400)]
Doc: fix minor syntax error in example.

The CREATE TABLE option is GENERATED BY DEFAULT *AS* IDENTITY.

Per bug #18543 from OndÅ™ej Navrátil.  Seems to have crept in
in a37bb7c13, so back-patch to v17 where that was added.

Discussion: https://postgr.es/m/18543-93c721689f9928e8@postgresql.org

10 months agoUse PqMsg_* macros in more places.
Nathan Bossart [Wed, 17 Jul 2024 15:51:00 +0000 (10:51 -0500)]
Use PqMsg_* macros in more places.

Commit f4b54e1ed9, which introduced macros for protocol characters,
missed updating a few places.  It also did not introduce macros for
messages sent from parallel workers to their leader processes.
This commit adds a new section in protocol.h for those.

Author: Aleksander Alekseev
Discussion: https://postgr.es/m/CAJ7c6TNTd09AZq8tGaHS3LDyH_CCnpv0oOz2wN1dGe8zekxrdQ%40mail.gmail.com
Backpatch-through: 17

10 months agoAvoid error in recovery test if history file is not yet present
Andrew Dunstan [Wed, 17 Jul 2024 14:35:50 +0000 (10:35 -0400)]
Avoid error in recovery test if history file is not yet present

Error was detected when testing use of libpq sessions instead of psql
for polling queries.

Discussion: https://postgr.es/m/e86b6d2d-20d8-4ac9-9a98-165fff7db886@dunslane.net

Backpatch to all live branches

10 months agoSQL/JSON: Rethink c2d93c3802b
Amit Langote [Wed, 17 Jul 2024 08:10:57 +0000 (17:10 +0900)]
SQL/JSON: Rethink c2d93c3802b

This essentially reverts c2d93c3802b except tests. The problem with
c2d93c3802b was that it only changed the casting behavior for types
with typmod, and had coding issues noted in the post-commit review.

This commit changes coerceJsonFuncExpr() to use assignment-level casts
instead of explicit casts to coerce the result of JSON constructor
functions to the specified or the default RETURNING type.  Using
assignment-level casts fixes the problem that using explicit casts was
leading to the wrong typmod / length coercion behavior -- truncating
results longer than the specified length instead of erroring out --
which c2d93c3802b aimed to solve.

That restricts the set of allowed target types to string types, the
same set that's currently allowed.

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

10 months agoWhen creating materialized views, use REFRESH to load data.
Jeff Davis [Tue, 16 Jul 2024 22:41:22 +0000 (15:41 -0700)]
When creating materialized views, use REFRESH to load data.

Previously, CREATE MATERIALIZED VIEW ... WITH DATA populated the MV
the same way as CREATE TABLE ... AS.

Instead, reuse the REFRESH logic, which locks down security-restricted
operations and restricts the search_path. This reduces the chance that
a subsequent refresh will fail.

Reported-by: Noah Misch
Backpatch-through: 17
Discussion: https://postgr.es/m/20240630222344[email protected]

10 months agoSQL/JSON: Fix a paragraph in JSON_TABLE documentation
Amit Langote [Tue, 16 Jul 2024 05:11:10 +0000 (14:11 +0900)]
SQL/JSON: Fix a paragraph in JSON_TABLE documentation

Using <replaceable>text</replaceable> inside parantheses is not a
common or good style, so rephrase a sentence to avoid that style.
Also rephrase the text in that paragraph a bit while at it.

Reported-by: Marcos Pegoraro <[email protected]>
Author: Jian He <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/CAB-JLwZqH3Yec6Kz-4-+pa0ZG9QJBsxjJZwYcMZYzEDR_fXnKw@mail.gmail.com

10 months agoFix bad indentation introduced in 43cd30bcd1c
Andres Freund [Mon, 15 Jul 2024 22:17:37 +0000 (15:17 -0700)]
Fix bad indentation introduced in 43cd30bcd1c

Oops.

Reported-by: Nathan Bossart <[email protected]>
Discussion: https://postgr.es/m/ZpVZB9rH5tHllO75@nathan
Backpatch: 12-, like 43cd30bcd1c

10 months agoAdd missing RestrictSearchPath() calls.
Jeff Davis [Mon, 15 Jul 2024 19:08:00 +0000 (12:08 -0700)]
Add missing RestrictSearchPath() calls.

Reported-by: Noah Misch
Backpatch-through: 17
Discussion: https://postgr.es/m/20240630222344[email protected]

10 months agoci: Upgrade to Debian Bookworm
Andres Freund [Mon, 15 Jul 2024 16:26:01 +0000 (09:26 -0700)]
ci: Upgrade to Debian Bookworm

Bullseye is getting long in the tooth, upgrade to the current stable version.

Backpatch to all versions with CI support, we don't want to generate CI images
for multiple Debian versions.

Author: Nazir Bilal Yavuz <[email protected]>
Discussion: https://postgr.es/m/CAN55FZ0fY5EFHXLKCO_%3Dp4pwFmHRoVom_qSE_7B48gpchfAqzw%40mail.gmail.com
Backpatch: 15-, where CI was added

10 months agoFix type confusion in guc_var_compare()
Andres Freund [Mon, 15 Jul 2024 16:26:01 +0000 (09:26 -0700)]
Fix type confusion in guc_var_compare()

Before this change guc_var_compare() cast the input arguments to
const struct config_generic *.  That's not quite right however, as the input
on one side is often just a char * on one side.

Instead just use char *, the first field in config_generic.

This fixes a -Warray-bounds warning with some versions of gcc. While the
warning is only known to be triggered for <= 15, the issue the warning points
out seems real, so apply the fix everywhere.

Author: Nazir Bilal Yavuz <[email protected]>
Reported-by: Erik Rijkers <[email protected]>
Suggested-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/a74a1a0d-0fd2-3649-5224-4f754e8f91aa%40xs4all.nl

10 months agoDoc: minor improvements for plpgsql "Transaction Management" section.
Tom Lane [Mon, 15 Jul 2024 15:59:43 +0000 (11:59 -0400)]
Doc: minor improvements for plpgsql "Transaction Management" section.

Point out that savepoint commands cannot be issued in PL/pgSQL,
and suggest that exception blocks can usually be used instead.

Add a caveat to the discussion of cursor loops vs. transactions,
pointing out that any locks taken by the cursor query will be lost
at COMMIT.  This is implicit in what's already said, but the existing
text leaves the distinct impression that the auto-hold behavior is
transparent, which it's not really.

Per a couple of recent complaints (one unsigned, and one in bug #18531
from Dzmitry Jachnik).  Back-patch to v17, just so this makes it into
current docs in less than a year-and-a-half.

Discussion: https://postgr.es/m/172076354433.736586.14347210271966220018@wrigleys.postgresql.org
Discussion: https://postgr.es/m/18531-c6dddd33b8555fd2@postgresql.org

10 months agoUse atomics to avoid locking in InjectionPointRun()
Heikki Linnakangas [Mon, 15 Jul 2024 07:21:16 +0000 (10:21 +0300)]
Use atomics to avoid locking in InjectionPointRun()

This allows using injection points without having a PGPROC, like early
at backend startup, or in the postmaster.

The injection points facility is new in v17, so backpatch there.

Reviewed-by: Michael Paquier <[email protected]>
Disussion: https://www.postgresql.org/message-id/4317a7f7-8d24-435e-9e49-29b72a3dc418@iki.fi

10 months agoFix unstable tests in partition_merge.sql and partition_split.sql.
Fujii Masao [Mon, 15 Jul 2024 05:09:30 +0000 (14:09 +0900)]
Fix unstable tests in partition_merge.sql and partition_split.sql.

The tests added by commit c086896625 were unstable due to
missing schema names when checking pg_tables and pg_indexes.

Backpatch to v17.

Reported by buildfarm.

10 months agoFix tablespace handling in MERGE/SPLIT partition commands.
Fujii Masao [Mon, 15 Jul 2024 04:11:51 +0000 (13:11 +0900)]
Fix tablespace handling in MERGE/SPLIT partition commands.

As commit ca4103025d stated, new partitions without a specified tablespace
should inherit the parent relation's tablespace. However, previously,
ALTER TABLE MERGE PARTITIONS and ALTER TABLE SPLIT PARTITION commands
always created new partitions in the default tablespace, ignoring
the parent's tablespace. This commit ensures new partitions inherit
the parent's tablespace.

Backpatch to v17 where these commands were introduced.

Author: Fujii Masao
Reviewed-by: Masahiko Sawada
Discussion: https://postgr.es/m/abaf390b-3320-40a5-8815-ef476db5cfe7@oss.nttdata.com

10 months agoAvoid unhelpful internal error for incorrect recursive-WITH queries.
Tom Lane [Sun, 14 Jul 2024 17:49:46 +0000 (13:49 -0400)]
Avoid unhelpful internal error for incorrect recursive-WITH queries.

checkWellFormedRecursion would issue "missing recursive reference"
if a WITH RECURSIVE query contained a single self-reference but
that self-reference was inside a top-level WITH, ORDER BY, LIMIT,
etc, rather than inside the second arm of the UNION as expected.
We already intended to throw more-on-point errors for such cases,
but those error checks must be done before examining the UNION arm
in order to have the desired results.  So this patch need only
move some code (and improve the comments).

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

Discussion: https://postgr.es/m/18536-0a342ec07901203e@postgresql.org

10 months agoUse correct collate.windows.win1252.out
Andrew Dunstan [Sat, 13 Jul 2024 20:19:10 +0000 (16:19 -0400)]
Use correct collate.windows.win1252.out

I inadvertently missed backporting this to Release 17 from commit 291c420747

per offlist reminder from Alexander Lakhin.

10 months agoFix new assertion for MERGE view_name ... DO NOTHING.
Noah Misch [Sat, 13 Jul 2024 15:09:33 +0000 (08:09 -0700)]
Fix new assertion for MERGE view_name ... DO NOTHING.

Such queries don't expand automatically updatable views, and ModifyTable
uses the wholerow attribute unconditionally.  The user-visible behavior
is fine, so change to more-specific assertions.  Commit
d5f788b41dc2cbdde6e7694c70dda54d829a5ed5 added the wrong assertion.
Back-patch to v17, where commit 5f2e179bd31e5f5803005101eb12a8d7bf8db8f3
introduced MERGE view_name.

Reported by Alexander Lakhin.

Discussion: https://postgr.es/m/e4b40a88-c134-6926-3196-bc4501cb87a2@gmail.com

10 months agoDon't lose partitioned table reltuples=0 after relhassubclass=f.
Noah Misch [Sat, 13 Jul 2024 15:09:33 +0000 (08:09 -0700)]
Don't lose partitioned table reltuples=0 after relhassubclass=f.

ANALYZE sets relhassubclass=f when a partitioned table no longer has
partitions.  An ANALYZE doing that proceeded to apply the inplace update
of pg_class.reltuples to the old pg_class tuple instead of the new
tuple, losing that reltuples=0 change if the ANALYZE committed.
Non-partitioning inheritance trees were unaffected.  Back-patch to v14,
where commit 375aed36ad83f0e021e9bdd3a0034c0c992c66dc introduced
maintenance of partitioned table pg_class.reltuples.

Reported by Alexander Lakhin.

Discussion: https://postgr.es/m/a295b499-dcab-6a99-c06e-01cf60593344@gmail.com

10 months agoMake sure to run pg_isready on correct port
Andrew Dunstan [Fri, 12 Jul 2024 22:29:15 +0000 (18:29 -0400)]
Make sure to run pg_isready on correct port

The current code can have pg_isready unexpectedly succeed if there is a
server running on the default port. To avoid this we delay running the
test until after a node has been created but before it starts, and then
use that node's port, so we are fairly sure there is nothing running on
the port.

Backpatch to all live branches.

10 months agoFix lost Windows socket EOF events.
Thomas Munro [Sat, 13 Jul 2024 02:59:46 +0000 (14:59 +1200)]
Fix lost Windows socket EOF events.

Winsock only signals an FD_CLOSE event once if the other end of the
socket shuts down gracefully.  Because each WaitLatchOrSocket() call
constructs and destroys a new event handle every time, with unlucky
timing we can lose it and hang.  We get away with this only if the other
end disconnects non-gracefully, because FD_CLOSE is repeatedly signaled
in that case.

To fix this design flaw in our Windows socket support fundamentally,
we'd probably need to rearchitect it so that a single event handle
exists for the lifetime of a socket, or switch to completely different
multiplexing or async I/O APIs.  That's going to be a bigger job
and probably wouldn't be back-patchable.

This brute force kludge closes the race by explicitly polling with
MSG_PEEK before sleeping.

Back-patch to all supported releases.  This should hopefully clear up
some random build farm and CI hang failures reported over the years.  It
might also allow us to try using graceful shutdown in more places again
(reverted in commit 29992a6) to fix instability in the transmission of
FATAL error messages, but that isn't done by this commit.

Reported-by: Tom Lane <[email protected]>
Tested-by: Alexander Lakhin <[email protected]>
Discussion: https://postgr.es/m/176008.1715492071%40sss.pgh.pa.us

10 months agoAdd ORDER BY to new test query
Alvaro Herrera [Fri, 12 Jul 2024 11:44:19 +0000 (13:44 +0200)]
Add ORDER BY to new test query

Per buildfarm.

10 months agoFix ALTER TABLE DETACH for inconsistent indexes
Alvaro Herrera [Fri, 12 Jul 2024 10:54:01 +0000 (12:54 +0200)]
Fix ALTER TABLE DETACH for inconsistent indexes

When a partitioned table has an index that doesn't support a constraint,
but a partition has an equivalent index that does, then a DETACH
operation would misbehave: a crash in assertion-enabled systems (because
we fail to find the constraint in the parent that we expect to), or a
broken coninhcount value (-1) in production systems (because we blindly
believe that we've successfully detached the parent).

While we should reject an ATTACH of a partition with such an index, we
have failed to do so in existing releases, so adding an error in stable
releases might break the (unlikely) existing applications that rely on
this behavior.  At this point I don't even want to reject them in
master, because it'd break pg_upgrade if such databases exist, and there
would be no easy way to fix existing databases without expensive index
rebuilds.

(Later on we could add ALTER TABLE ... ADD CONSTRAINT USING INDEX to
partitioned tables, which would allow the user to fix such patterns.  At
that point we could add more restrictions to prevent the problem from
its root.)

Also, add a test case that leaves one table in this condition, so that
we can verify that pg_upgrade continues to work if we later decide to
change the policy on the master branch.

Backpatch to all supported branches.

Co-authored-by: Tender Wang <[email protected]>
Reported-by: Alexander Lakhin <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Reviewed-by: Michael Paquier <[email protected]>
Discussion: https://postgr.es/m/18500-62948b6fe5522f56@postgresql.org

10 months agoFix unstable test in 040_pg_createsubscriber.
Amit Kapila [Fri, 12 Jul 2024 04:05:46 +0000 (09:35 +0530)]
Fix unstable test in 040_pg_createsubscriber.

The slot synchronization failed because the local slot's (created during
slot synchronization) catalog_xmin on standby is ahead of remote slot.
This happens because the INSERT before slot synchronization results in the
generation of a new xid that could be replicated to the standby. Now
before the xmin of the physical slot on the primary catches up via
hot_standby_feedback, the test has created a logical slot that got some
prior value of catalog_xmin.

To fix this we could try to ensure that the physical slot's catalog_xmin
is caught up to latest value before creating a logical slot but we took a
simpler path to move the INSERT after synchronizing the logical slot.

Reported-by: Alexander Lakhin as per buildfarm
Diagnosed-by: Amit Kapila, Hou Zhijie, Alexander Lakhin
Author: Hou Zhijie
Backpatch-through: 17
Discussion: https://postgr.es/m/bde6ac67-69cc-c104-5ab6-dd4f5deadf24@gmail.com

10 months agoFix possibility of logical decoding partial transaction changes.
Masahiko Sawada [Thu, 11 Jul 2024 13:48:21 +0000 (22:48 +0900)]
Fix possibility of logical decoding partial transaction changes.

When creating and initializing a logical slot, the restart_lsn is set
to the latest WAL insertion point (or the latest replay point on
standbys). Subsequently, WAL records are decoded from that point to
find the start point for extracting changes in the
DecodingContextFindStartpoint() function. Since the initial
restart_lsn could be in the middle of a transaction, the start point
must be a consistent point where we won't see the data for partial
transactions.

Previously, when not building a full snapshot, serialized snapshots
were restored, and the SnapBuild jumps to the consistent state even
while finding the start point. Consequently, the slot's restart_lsn
and confirmed_flush could be set to the middle of a transaction. This
could lead to various unexpected consequences. Specifically, there
were reports of logical decoding decoding partial transactions, and
assertion failures occurred because only subtransactions were decoded
without decoding their top-level transaction until decoding the commit
record.

To resolve this issue, the changes prevent restoring the serialized
snapshot and jumping to the consistent state while finding the start
point.

On v17 and HEAD, a flag indicating whether snapshot restores should be
skipped has been added to the SnapBuild struct, and SNAPBUILD_VERSION
has been bumpded.

On backbranches, the flag is stored in the LogicalDecodingContext
instead, preserving on-disk compatibility.

Backpatch to all supported versions.

Reported-by: Drew Callahan
Reviewed-by: Amit Kapila, Hayato Kuroda
Discussion: https://postgr.es/m/2444AA15-D21B-4CCE-8052-52C7C2DAFE5C%40amazon.com
Backpatch-through: 12

10 months agoMake our back branches compatible with libxml2 2.13.x.
Tom Lane [Thu, 11 Jul 2024 00:15:52 +0000 (20:15 -0400)]
Make our back branches compatible with libxml2 2.13.x.

This back-patches HEAD commits 066e8ac6e6082b3d5de7192486d,
and 896cd266f into supported branches.  Changes:

* Use xmlAddChildList not xmlAddChild in XMLSERIALIZE
(affects v16 and up only).  This was a flat-out coding mistake
that we got away with due to lax checking in previous versions
of xmlAddChild.

* Use xmlParseInNodeContext not xmlParseBalancedChunkMemory.
This is to dodge a bug in xmlParseBalancedChunkMemory in libxm2
releases 2.13.0-2.13.2.  While that bug is now fixed upstream and
will probably never be seen in any production-oriented distro, it is
currently a problem on some more-bleeding-edge-friendly platforms.

* Suppress "chunk is not well balanced" errors from libxml2,
unless it is the only error.  This eliminates an error-reporting
discrepancy between 2.13 and older releases.  This error is
almost always redundant with previous errors, if not flat-out
inappropriate, which is why 2.13 changed the behavior and why
nobody's likely to miss it.

Erik Wienhold and Tom Lane, per report from Frank Streitzig.

Discussion: https://postgr.es/m/trinity-b0161630-d230-4598-9ebc-7a23acdb37cb-1720186432160@3c-app-gmx-bap25
Discussion: https://postgr.es/m/trinity-361ba18b-541a-4fe7-bc63-655ae3a7d599-1720259822452@3c-app-gmx-bs01

10 months agoUse diff's --strip-trailing-cr flag where appropriate on Windows
Andrew Dunstan [Wed, 10 Jul 2024 13:53:47 +0000 (09:53 -0400)]
Use diff's --strip-trailing-cr flag where appropriate on Windows

Test result files might be checked out using Unix or Windows style line
endings, depening on git flags, so on Windows we use the
--strip-trailing-cr flag to tell diff to ignore line endings
differences.

The flag is added to the diff invocation for the test_json_parser module
tests and the pg_bsd_indent tests. in pg_regress.c we replace the
current use of the "-w" flag, which ignore all white space differences,
with this one which only ignores line end differences.

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

10 months agodoc: Update track_io_timing documentation to mention pg_stat_io.
Fujii Masao [Wed, 10 Jul 2024 06:56:07 +0000 (15:56 +0900)]
doc: Update track_io_timing documentation to mention pg_stat_io.

The I/O timing information collected when track_io_timing is
enabled is now documented to appear in the pg_stat_io view,
which was previously not mentioned.

This commit also enhances the description of track_io_timing
to clarify that it monitors not only block read and write
but also block extend and fsync operations. Additionally,
the description of track_wal_io_timing has been improved
to mention both WAL write and WAL fsync monitoring.

Backpatch to v16 where pg_stat_io was added.

Author: Hajime Matsunaga
Reviewed-by: Melanie Plageman, Nazir Bilal Yavuz, Fujii Masao
Discussion: https://postgr.es/m/TYWPR01MB10742EE4A6F34C33061429D38A4D52@TYWPR01MB10742.jpnprd01.prod.outlook.com

10 months agoPrevent CRLF conversion of inputs in json_parser test module
Andrew Dunstan [Tue, 9 Jul 2024 21:29:48 +0000 (17:29 -0400)]
Prevent CRLF conversion of inputs in json_parser test module

Do this by opening the file in PG_BINARY_R mode. This prevents us from
getting wrong byte count from stat().

Per complaint from Andres Freund

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

Backpatch to rlease 17 where this code was introduced

10 months agoFix missing invalidations for search_path cache.
Jeff Davis [Tue, 9 Jul 2024 18:27:10 +0000 (11:27 -0700)]
Fix missing invalidations for search_path cache.

Reported-by: Noah Misch
Discussion: https://postgr.es/m/20240630223047[email protected]
Backpatch-through: 17

10 months agoSQL/JSON: Various improvements to SQL/JSON query function docs
Amit Langote [Tue, 9 Jul 2024 07:12:22 +0000 (16:12 +0900)]
SQL/JSON: Various improvements to SQL/JSON query function docs

1. Remove the keyword SELECT from the examples to be consistent
with the examples of other JSON-related functions listed on the
same page.

2. Add <synopsis> tags around the functions' syntax definition

3. Capitalize function names in the syntax synopsis and the examples

4. Use <itemizedlist> lists for dividing the descriptions of
   individual functions into bullet points

5. Significantly rewrite the description of wrapper clauses of
   JSON_QUERY

6. Significantly rewrite the descriptions of ON ERROR / EMPTY
   clauses of JSON_QUERY() and JSON_VALUE() functions

7. Add a note about how JSON_VALUE() and JSON_QUERY() differ when
   returning a JSON null result

8. Move the description of the PASSING clause from the descriptions
   of individual functions into the top paragraph

And other miscellaneous text improvements, typo fixes.

Suggested-by: Thom Brown <[email protected]>
Suggested-by: David G. Johnston <[email protected]>
Reviewed-by: Jian He <[email protected]>
Reviewed-by: Erik Rijkers <[email protected]>
Discussion: https://postgr.es/m/CAA-aLv7Dfy9BMrhUZ1skcg=OdqysWKzObS7XiDXdotJNF0E44Q@mail.gmail.com
Discussion: https://postgr.es/m/CAKFQuwZNxNHuPk44zDF7z8qZec1Aof10aA9tWvBU5CMhEKEd8A@mail.gmail.com

10 months agoFix limit block handling in pg_wal_summary_contents().
Fujii Masao [Tue, 9 Jul 2024 00:26:54 +0000 (09:26 +0900)]
Fix limit block handling in pg_wal_summary_contents().

Previously, pg_wal_summary_contents() had two issues,
causing discrepancies between pg_wal_summary_contents()
and the pg_walsummary command on the same WAL summary file:

(1) It did not emit the limit block when that's the only data for
     a particular relation fork.
(2) It emitted the same limit block multiple times if the list of
     block numbers was long enough.

This commit fixes these issues.

Backpatch to v17 where pg_wal_summary_contents() was added.

Author: Fujii Masao
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/90980ee6-2da6-42f6-a7b0-b7bae62ae279@oss.nttdata.com

10 months agoSymlink pg_replslot robustly on Windows in pg_basebackup test
Andrew Dunstan [Mon, 8 Jul 2024 17:46:21 +0000 (13:46 -0400)]
Symlink pg_replslot robustly on Windows in pg_basebackup test

This reverts commit e9f15bc9. Instead of a hacky solution that didn't
work on Windows, we avoid trying to move the directory possibly across
drives, and instead remove it and recreate it in the new location.

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

Backpatch to release 14 like the previous patch.

10 months agoChoose ports for test servers less likely to result in conflicts
Andrew Dunstan [Mon, 8 Jul 2024 15:18:06 +0000 (11:18 -0400)]
Choose ports for test servers less likely to result in conflicts

If we choose ports in the range typically used for ephemeral ports there
is a danger of encountering a port conflict due to a race condition
between the time we choose the port in a range below that typically used
to allocate ephemeral ports, but higher than the range typically used by
well known services.

Author: Jelte Fenema-Nio, with some editing by me.

Discussion: https://postgr.es/m/d6ee8761-39d1-0033-1afb-d5a57ee056f2@gmail.com

Backpatch to all live branches (12 and up)

10 months agoForce nodes for SSL tests to start in TCP mode
Andrew Dunstan [Mon, 8 Jul 2024 09:51:26 +0000 (05:51 -0400)]
Force nodes for SSL tests to start in TCP mode

Currently they are started in unix socket mode in ost cases, and then
converted to run in TCP mode. This can result in port collisions, and
there is no virtue in startng in unix socket mode, so start as we will
be going on.

Discussion: https://postgr.es/m/d6ee8761-39d1-0033-1afb-d5a57ee056f2@gmail.com

Backpatch to all live branches (12 and up).

10 months agoFix scale clamping in numeric round() and trunc().
Dean Rasheed [Mon, 8 Jul 2024 16:51:23 +0000 (17:51 +0100)]
Fix scale clamping in numeric round() and trunc().

The numeric round() and trunc() functions clamp the scale argument to
the range between +/- NUMERIC_MAX_RESULT_SCALE (2000), which is much
smaller than the actual allowed range of type numeric. As a result,
they return incorrect results when asked to round/truncate more than
2000 digits before or after the decimal point.

Fix by using the correct upper and lower scale limits based on the
actual allowed (and documented) range of type numeric.

While at it, use the new NUMERIC_WEIGHT_MAX constant instead of
SHRT_MAX in all other overflow checks, and fix a comment thinko in
power_var() introduced by e54a758d24 -- the minimum value of
ln_dweight is -NUMERIC_DSCALE_MAX (-16383), not -SHRT_MAX, though this
doesn't affect the point being made in the comment, that the resulting
local_rscale value may exceed NUMERIC_MAX_DISPLAY_SCALE (1000).

Back-patch to all supported branches.

Dean Rasheed, reviewed by Joel Jacobson.

Discussion: https://postgr.es/m/CAEZATCXB%2BrDTuMjhK5ZxcouufigSc-X4tGJCBTMpZ3n%3DxxQuhg%40mail.gmail.com

10 months agoTypo fix
Amit Langote [Mon, 8 Jul 2024 13:11:57 +0000 (22:11 +0900)]
Typo fix

Reported-by: Junwang Zhao <[email protected]>
Discussion: https://postgr.es/m/CAEG8a3KPi=LayiTwJ11ikF7bcqnZUrcj8NgX0V8nO1mQKZ9GfQ@mail.gmail.com
Backpatch-through: 17

10 months agoFix outdated comment after removal of direct SSL fallback
Heikki Linnakangas [Mon, 8 Jul 2024 09:44:45 +0000 (12:44 +0300)]
Fix outdated comment after removal of direct SSL fallback

The option to fall back from direct SSL to negotiated SSL or a
plaintext connection was removed in commit fb5718f35f.

Discussion: https://www.postgresql.org/message-id/c82ad227-e049-4e18-8898-475a748b5a5a@iki.fi

10 months agoFix right-anti-joins when the inner relation is proven unique
Richard Guo [Mon, 8 Jul 2024 01:17:12 +0000 (10:17 +0900)]
Fix right-anti-joins when the inner relation is proven unique

For an inner_unique join, we always assume that the executor will stop
scanning for matches after the first match.  Therefore, for a mergejoin
that is inner_unique and whose mergeclauses are sufficient to identify a
match, we set the skip_mark_restore flag to true, indicating that the
executor need not do mark/restore calls.  However, merge-right-anti-join
did not get this memo and continues scanning the inner side for matches
after the first match.  If there are duplicates in the outer scan, we
may incorrectly skip matching some inner tuples, which can lead to wrong
results.

Here we fix this issue by ensuring that merge-right-anti-join also
advances to next outer tuple after the first match in inner_unique
cases.  This also saves cycles by avoiding unnecessary scanning of inner
tuples after the first match.

Although hash-right-anti-join does not suffer from this wrong results
issue, we apply the same change to it as well, to help save cycles for
the same reason.

Per bug #18522 from Antti Lampinen, and bug #18526 from Feliphe Pozzer.
Back-patch to v16 where right-anti-join was introduced.

Author: Richard Guo
Discussion: https://postgr.es/m/18522-c7a8956126afdfd0@postgresql.org

10 months agoRe-enable autoruns for for cmd.exe on Windows
Michael Paquier [Mon, 8 Jul 2024 00:35:10 +0000 (09:35 +0900)]
Re-enable autoruns for for cmd.exe on Windows

This acts as a revert of b83747a8a65b and 9886744a361b.  As pointed out
by Noah, HEAD and REL_17_STABLE are in a weird state where the code
paths adding /D would limit the spawn of child processes, but we still
have code paths where the spawn of more than one child process would be
possible.

Let's remove these /D switches for now, to bring back the code into a
state consistent with how autorun is configured on a Windows host.

Reported-by: Noah Misch
Discussion: https://postgr.es/m/20240630021211[email protected]
Backpatch-through: 17