postgresql.git
6 months agoUpdate header comment for lookup_type_cache()
Alexander Korotkov [Thu, 24 Oct 2024 11:34:16 +0000 (14:34 +0300)]
Update header comment for lookup_type_cache()

Describe the way we handle concurrent invalidation messages.

Discussion: https://postgr.es/m/CAPpHfdsQhwUrnB3of862j9RgHoJM--eRbifvBMvtQxpC57dxCA%40mail.gmail.com
Reviewed-by: Andrei Lepikhov, Artur Zakirov, Pavel Borisov
6 months agoTrack more precisely query locations for nested statements
Michael Paquier [Thu, 24 Oct 2024 00:28:51 +0000 (09:28 +0900)]
Track more precisely query locations for nested statements

Previously, a Query generated through the transform phase would have
unset stmt_location, tracking the starting point of a query string.

Extensions relying on the statement location to extract its relevant
parts in the source text string would fallback to use the whole
statement instead, leading to confusing results like in
pg_stat_statements for queries relying on nested queries, like:
- EXPLAIN, with top-level and nested query using the same query string,
and a query ID coming from the nested query when the non-top-level
entry.
- Multi-statements, with only partial portions of queries being
normalized.
- COPY TO with a query, SELECT or DMLs.

This patch improves things by keeping track of the statement locations
and propagate it to Query during transform, allowing PGSS to only show
the relevant part of the query for nested query.  This leads to less
bloat in entries for non-top-level entries, as queries can now be
grouped within the same (toplevel, queryid) duos in pg_stat_statements.
The result gives a stricter one-one mapping between query IDs and its
query strings.

The regression tests introduced in 45e0ba30fc40 produce differences
reflecting the new logic.

Author: Anthonin Bonnefoy
Reviewed-by: Michael Paquier, Jian He
Discussion: https://postgr.es/m/CAO6_XqqM6S9bQ2qd=75W+yKATwoazxSNhv5sjW06fjGAtHbTUA@mail.gmail.com

6 months agoImprove pg_set_attribute_stats() error message.
Jeff Davis [Wed, 23 Oct 2024 23:11:45 +0000 (16:11 -0700)]
Improve pg_set_attribute_stats() error message.

Previously, an invalid attribute name was caught, but the error
message was unhelpful.

6 months agoFix typo in tidstore.h.
Masahiko Sawada [Wed, 23 Oct 2024 22:37:00 +0000 (15:37 -0700)]
Fix typo in tidstore.h.

An oversight in commit f6bef362c.

Reviewed-by: David Rowley
Discussion: https://postgr.es/m/CAD21AoB8MJ5OHtpUw1UEGf7spioFmP3PNH44KNx6Yb3FiZSwKA%40mail.gmail.com

6 months agoAnother documentation fixup.
Jeff Davis [Wed, 23 Oct 2024 17:28:31 +0000 (10:28 -0700)]
Another documentation fixup.

Reported-by: Erik Rijkers
6 months agoFix compiler warning.
Jeff Davis [Wed, 23 Oct 2024 17:24:17 +0000 (10:24 -0700)]
Fix compiler warning.

Some buildfarm members complained about an always-true test in the
SOFT_ERROR_OCCURRED macro. Fix by reading the field directly rather
than using the macro.

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

6 months agoDocumentation fixup.
Jeff Davis [Wed, 23 Oct 2024 16:43:06 +0000 (09:43 -0700)]
Documentation fixup.

Wrong return type for pg_clear_attribute_stats().

Author: Noriyoshi Shinoda
Discussion: https://postgr.es/m/DM4PR84MB17347944F27A552F0CCDF84CEE4C2@DM4PR84MB1734.NAMPRD84.PROD.OUTLOOK.COM

6 months agoFix incorrect struct reference in comment
Daniel Gustafsson [Wed, 23 Oct 2024 14:13:28 +0000 (16:13 +0200)]
Fix incorrect struct reference in comment

SASL frontend mechanisms are implemented with pg_fe_sasl_mech and
not the _be_ variant which is the backend implementation. Spotted
while reading adjacent code.

6 months agoMake SASL max message length configurable
Daniel Gustafsson [Wed, 23 Oct 2024 14:10:27 +0000 (16:10 +0200)]
Make SASL max message length configurable

The proposed OAUTHBEARER SASL mechanism will need to allow larger
messages in the exchange, since tokens are sent directly by the
client.  Move this limit into the pg_be_sasl_mech struct so that
it can be changed per-mechanism.

Author: Jacob Champion <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Discussion: https://postgr.es/m/CAOYmi+nqX_5=Se0W0Ynrr55Fha3CMzwv_R9P3rkpHb=1kG7ZTQ@mail.gmail.com

6 months agodoc: Fix INSERT statement syntax for identity columns
Daniel Gustafsson [Wed, 23 Oct 2024 12:58:17 +0000 (14:58 +0200)]
doc: Fix INSERT statement syntax for identity columns

The INSERT statements in the examples were erroneously using
VALUE instead of VALUES. Backpatch to v17 where the examples
were added through a37bb7c1399.

Reported-by: [email protected]
Discussion: https://postgr.es/m/172958472112.696.6075270400394560263@wrigleys.postgresql.org
Backpatch-through: 17

6 months agoRemove unnecessary word in a comment
Amit Langote [Wed, 23 Oct 2024 08:54:48 +0000 (17:54 +0900)]
Remove unnecessary word in a comment

Relations opened by the executor are only closed once in
ExecCloseRangeTableRelations(), so the word "again" in the comment
for ExecGetRangeTableRelation() is misleading and unnecessary.

Discussion: https://postgr.es/m/CA+HiwqHnw-zR+u060i3jp4ky5UR0CjByRFQz50oZ05de7wUg=Q@mail.gmail.com
Backpatch-through: 12

6 months agoecpg: Fix out-of-bound read in DecodeDateTime()
Michael Paquier [Tue, 22 Oct 2024 23:33:54 +0000 (08:33 +0900)]
ecpg: Fix out-of-bound read in DecodeDateTime()

It was possible for the code to read out-of-bound data from the
"day_tab" table with some crafted input data.  Let's treat these as
invalid input as the month number is incorrect.

A test is added to test this case with a check on the errno returned by
the decoding routine.  A test close to the new one added in this commit
was testing for a failure, but did not look at the errno generated, so
let's use this commit to also change it, adding a check on the errno
returned by DecodeDateTime().

Like the other test scripts, dt_test should likely be expanded to
include more checks based on the errnos generated in these code paths.
This is left as future work.

This issue exists since 2e6f97560a83, so backpatch all the way down.

Reported-by: Pavel Nekrasov
Author: Bruce Momjian, Pavel Nekrasov
Discussion: https://postgr.es/m/18614-6bbe00117352309e@postgresql.org
Backpatch-through: 12

6 months agoAdd functions pg_set_attribute_stats() and pg_clear_attribute_stats().
Jeff Davis [Tue, 22 Oct 2024 22:06:55 +0000 (15:06 -0700)]
Add functions pg_set_attribute_stats() and pg_clear_attribute_stats().

Enable manipulation of attribute statistics. Only superficial
validation is performed, so it's possible to add nonsense, and it's up
to the planner (or other users of statistics) to behave reasonably in
that case.

Bump catalog version.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=eErgzn7ECDpwFcptJKOk9SxZEk5Pot4d94eVTZsvj3gw@mail.gmail.com

6 months agoChange pg_*_relation_stats() functions to return type to void.
Jeff Davis [Tue, 22 Oct 2024 19:48:01 +0000 (12:48 -0700)]
Change pg_*_relation_stats() functions to return type to void.

These functions will either raise an ERROR or run to normal
completion, so no return value is necessary.

Bump catalog version.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=cBF8rnphuTyHFi3KYzB9ByDgx57HwK9Rz2yp7S+Om87w@mail.gmail.com

6 months agoImprove reporting of errors in extension script files.
Tom Lane [Tue, 22 Oct 2024 15:31:45 +0000 (11:31 -0400)]
Improve reporting of errors in extension script files.

Previously, CREATE/ALTER EXTENSION gave basically no useful
context about errors reported while executing script files.
I think the idea was that you could run the same commands
manually to see the error, but that's often quite inconvenient.
Let's improve that.

If we get an error during raw parsing, we won't have a current
statement identified by a RawStmt node, but we should always get
a syntax error position.  Show the portion of the script from
the last semicolon-newline before the error position to the first
one after it.  There are cases where this might show only a
fragment of a statement, but that should be uncommon, and it
seems better than showing the whole script file.

Without an error cursor, if we have gotten past raw parsing (which
we probably have), we can report just the current SQL statement as
an item of error context.

In any case also report the script file name as error context,
since it might not be entirely obvious which of a series of
update scripts failed.  We can also show an approximate script
line number in case whatever we printed of the query isn't
sufficiently identifiable.

The error-context code path is already exercised by some
test_extensions test cases, but add tests for the syntax-error
path.

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

6 months agoImprove parser's reporting of statement start locations.
Tom Lane [Tue, 22 Oct 2024 15:26:05 +0000 (11:26 -0400)]
Improve parser's reporting of statement start locations.

Up to now, the parser's reporting of a statement's stmt_location
included any preceding whitespace or comments.  This isn't really
desirable but was done to avoid accounting honestly for nonterminals
that reduce to empty.  It causes problems for pg_stat_statements,
which partially compensates by manually stripping whitespace, but
is not bright enough to strip /*-style comments.  There will be
more problems with an upcoming patch to improve reporting of errors
in extension scripts, so it's time to do something about this.

The thing we have to do to make it work right is to adjust
YYLLOC_DEFAULT to scan the inputs of each production to find the
first one that has a valid location (i.e., did not reduce to
empty).  In theory this adds a little bit of per-reduction overhead,
but in practice it's negligible.  I checked by measuring the time
to run raw_parser() on the contents of information_schema.sql, and
there was basically no change.

Having done that, we can rely on any nonterminal that didn't reduce
to completely empty to have a correct starting location, and we don't
need the kluges the stmtmulti production formerly used.

This should have a side benefit of allowing parse error reports to
include an error position in some cases where they formerly failed to
do so, due to trying to report the position of an empty nonterminal.
I did not go looking for an example though.  The one previously known
case where that could happen (OptSchemaEltList) no longer needs the
kluge it had; but I rather doubt that that was the only case.

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

6 months agoecpg: Refactor ecpg_log() to skip unnecessary calls to ECPGget_sqlca().
Fujii Masao [Tue, 22 Oct 2024 14:56:37 +0000 (23:56 +0900)]
ecpg: Refactor ecpg_log() to skip unnecessary calls to ECPGget_sqlca().

Previously, ecpg_log() always called ECPGget_sqlca() to retrieve sqlca,
even though it was only needed for debug logging. This commit updates
ecpg_log() to call ECPGget_sqlca() only when debug logging is enabled.

Author: Yuto Sasaki
Reviewed-by: Alvaro Herrera, Tom Lane, Fujii Masao
Discussion: https://postgr.es/m/TY2PR01MB3628A85689649BABC9A1C6C3C1782@TY2PR01MB3628.jpnprd01.prod.outlook.com

6 months agoRestructure foreign key handling code for ATTACH/DETACH
Álvaro Herrera [Tue, 22 Oct 2024 14:01:18 +0000 (16:01 +0200)]
Restructure foreign key handling code for ATTACH/DETACH

... to fix bugs when the referenced table is partitioned.

The catalog representation we chose for foreign keys connecting
partitioned tables (in commit f56f8f8da6af) is inconvenient, in the
sense that a standalone table has a different way to represent the
constraint when referencing a partitioned table, than when the same
table becomes a partition (and vice versa).  Because of this, we need to
create additional catalog rows on detach (pg_constraint and pg_trigger),
and remove them on attach.  We were doing some of those things, but not
all of them, leading to missing catalog rows in certain cases.

The worst problem seems to be that we are missing action triggers after
detaching a partition, which means that you could update/delete rows
from the referenced partitioned table that still had referencing rows on
that table, the server failing to throw the required errors.

!!!
Note that this means existing databases with FKs that reference
partitioned tables might have rows that break relational integrity, on
tables that were once partitions on the referencing side of the FK.

Another possible problem is that trying to reattach a table
that had been detached would fail indicating that internal triggers
cannot be found, which from the user's point of view is nonsensical.

In branches 15 and above, we fix this by creating a new helper function
addFkConstraint() which is in charge of creating a standalone
pg_constraint row, and repurposing addFkRecurseReferencing() and
addFkRecurseReferenced() so that they're only the recursive routine for
each side of the FK, and they call addFkConstraint() to create
pg_constraint at each partitioning level and add the necessary triggers.
These new routines can be used during partition creation, partition
attach and detach, and foreign key creation.  This reduces redundant
code and simplifies the flow.

In branches 14 and 13, we have a much simpler fix that consists on
simply removing the constraint on detach.  The reason is that those
branches are missing commit f4566345cf40, which reworked the way this
works in a way that we didn't consider back-patchable at the time.

We opted to leave branch 12 alone, because it's different from branch 13
enough that the fix doesn't apply; and because it is going in EOL mode
very soon, patching it now might be worse since there's no way to undo
the damage if it goes wrong.

Existing databases might need to be repaired.

In the future we might want to rethink the catalog representation to
avoid this problem, but for now the code seems to do what's required to
make the constraints operate correctly.

Co-authored-by: Jehan-Guillaume de Rorthais <[email protected]>
Co-authored-by: Tender Wang <[email protected]>
Co-authored-by: Alvaro Herrera <[email protected]>
Reported-by: Guillaume Lelarge <[email protected]>
Reported-by: Jehan-Guillaume de Rorthais <[email protected]>
Reported-by: Thomas Baehler (SBB CFF FFS) <[email protected]>
Discussion: https://postgr.es/m/20230420144344.40744130@karst
Discussion: https://postgr.es/m/20230705233028.2f554f73@karst
Discussion: https://postgr.es/m/GVAP278MB02787E7134FD691861635A8BC9032@GVAP278MB0278.CHEP278.PROD.OUTLOOK.COM
Discussion: https://postgr.es/m/18541-628a61bc267cd2d3@postgresql.org

6 months agoMake all Perl warnings fatal in 043_wal_replay_wait.pl
Alexander Korotkov [Tue, 22 Oct 2024 10:25:10 +0000 (13:25 +0300)]
Make all Perl warnings fatal in 043_wal_replay_wait.pl

This file was committed after c5385929593, but accidentally missed changing
all warnings into fatal errors.

Reported-by: Anton Voloshin
Discussion: https://postgr.es/m/aa8a55d5-554a-4027-a491-1b0ca7c85f7a%40postgrespro.ru

6 months agoFix C23 compiler warning
Peter Eisentraut [Tue, 22 Oct 2024 06:12:43 +0000 (08:12 +0200)]
Fix C23 compiler warning

The approach of declaring a function pointer with an empty argument
list and hoping that the compiler will not complain about casting it
to another type no longer works with C23, because foo() is now
equivalent to foo(void).

We don't need to do this here.  With a few struct forward declarations
we can supply a correct argument list without having to pull in
another header file.

(This is the only new warning with C23.  Together with the previous
fix a67a49648d9, this makes the whole code compile cleanly under C23.)

Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/95c6a9bf-d306-43d8-b880-664ef08f2944%40eisentraut.org

6 months agopg_stat_statements: Add tests for nested queries with level tracking
Michael Paquier [Tue, 22 Oct 2024 04:05:51 +0000 (13:05 +0900)]
pg_stat_statements: Add tests for nested queries with level tracking

There have never been any regression tests in PGSS for various query
patterns for nested queries combined with level tracking, like:
- Multi-statements.
- CREATE TABLE AS
- CREATE/REFRESH MATERIALIZED VIEW
- DECLARE CURSOR
- EXPLAIN, with a subset of the above supported.
- COPY.

All the tests added here track historical, sometimes confusing, existing
behaviors.  For example, EXPLAIN stores two PGSS entries with the same
top-level query string but two different query IDs as one is calculated
for the top-level EXPLAIN (this part is right) and a second one for the
inner query in the EXPLAIN (this part is not right).

A couple of patches are under discussion to improve the situation, and
all the tests added here will prove useful to evaluate the changes
discussed.

Author: Anthonin Bonnefoy
Reviewed-by: Michael Paquier, Jian He
Discussion: https://postgr.es/m/CAO6_XqqM6S9bQ2qd=75W+yKATwoazxSNhv5sjW06fjGAtHbTUA@mail.gmail.com

6 months agoFix wrong assertion and poor error messages in "COPY (query) TO".
Tom Lane [Mon, 21 Oct 2024 19:08:22 +0000 (15:08 -0400)]
Fix wrong assertion and poor error messages in "COPY (query) TO".

If the query is rewritten into a NOTIFY command by a DO INSTEAD
rule, we'd get an assertion failure, or in non-assert builds
issue a rather confusing error message.  Improve that.

Also fix a longstanding grammar mistake in a nearby error message.

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

Tender Wang and Tom Lane

Discussion: https://postgr.es/m/18664-ffd0ebc2386598df@postgresql.org

6 months agoUpdate outdated comment on WAL-logged locks with invalid XID
Heikki Linnakangas [Mon, 21 Oct 2024 11:28:43 +0000 (14:28 +0300)]
Update outdated comment on WAL-logged locks with invalid XID

We haven't generated those for a long time.

Discussion: https://www.postgresql.org/message-id/b439edfc-c5e5-43a9-802d-4cb51ec20646@iki.fi

6 months agoFix race condition in committing a serializable transaction
Heikki Linnakangas [Mon, 21 Oct 2024 06:49:21 +0000 (09:49 +0300)]
Fix race condition in committing a serializable transaction

The finished transaction list can contain XIDs that are older than the
serializable global xmin. It's a short-lived state;
ClearOldPredicateLocks() removes any such transactions from the list,
and it's called whenever the global xmin advances. But if another
backend calls SummarizeOldestCommittedSxact() in that window, it will
call SerialAdd() on an XID that's older than the global xmin, or if
there are no more transactions running, when global xmin is
invalid. That trips the assertion in SerialAdd().

Fixes bug #18658 reported by Andrew Bille. Thanks to Alexander Lakhin
for analysis. Backpatch to all versions.

Discussion: https://www.postgresql.org/message-id/18658-7dab125ec688c70b%40postgresql.org

6 months agoFix grammar of a comment in bufmgr.c
Michael Paquier [Mon, 21 Oct 2024 02:25:29 +0000 (11:25 +0900)]
Fix grammar of a comment in bufmgr.c

Author: Junwang Zhao
Discussion: https://postgr.es/m/CAEG8a3L5YjxXCjx0LhkwHdDGsNgpFGEqH7SqtXRPNP+dwFMVZQ@mail.gmail.com

6 months agoinjection_points: Add basic isolation test
Michael Paquier [Mon, 21 Oct 2024 02:10:51 +0000 (11:10 +0900)]
injection_points: Add basic isolation test

This test can act as a template when implementing an isolation test with
injection points, and tracks in a much simpler way some of the behaviors
implied in the existing isolation test "inplace" that has been added in
c35f419d6efb.  Particularly, a detach does not affect a backend wait; a
wait needs to be interrupted by a wakeup.

Reviewed-by: Bertrand Drouvot
Discussion: https://postgr.es/m/[email protected]

6 months agoNote that index_name in ALTER INDEX ATTACH PARTITION can be schema-qualified
Álvaro Herrera [Sun, 20 Oct 2024 13:36:20 +0000 (15:36 +0200)]
Note that index_name in ALTER INDEX ATTACH PARTITION can be schema-qualified

Missed in 8b08f7d4820f; backpatch to all supported branches.

Reported-by: [email protected]
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/172924785099.698.15236991344616673753@wrigleys.postgresql.org

6 months agoSQL/JSON: Fix some oversights in commit b6e1157e7
Amit Langote [Sun, 20 Oct 2024 03:20:55 +0000 (12:20 +0900)]
SQL/JSON: Fix some oversights in commit b6e1157e7

The decision in b6e1157e7 to ignore raw_expr when evaluating a
JsonValueExpr was incorrect.  While its value is not ultimately
used (since formatted_expr's value is), failing to initialize it
can lead to problems, for instance,  when the expression tree in
raw_expr contains Aggref nodes, which must be initialized to
ensure the parent Agg node works correctly.

Also, optimize eval_const_expressions_mutator()'s handling of
JsonValueExpr a bit.  Currently, when formatted_expr cannot be folded
into a constant, we end up processing it twice -- once directly in
eval_const_expressions_mutator() and again recursively via
ece_generic_processing().  This recursive processing is required to
handle raw_expr. To avoid the redundant processing of formatted_expr,
we now  process raw_expr directly in eval_const_expressions_mutator().

Finally, update the comment of JsonValueExpr to describe the roles of
raw_expr and formatted_expr more clearly.

Bug: #18657
Reported-by: Alexander Lakhin <[email protected]>
Diagnosed-by: Fabio R. Sluzala <[email protected]>
Diagnosed-by: Tender Wang <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/18657-1b90ccce2b16bdb8@postgresql.org
Backpatch-through: 16

6 months agoFix comment about pg_authid.
Tom Lane [Sat, 19 Oct 2024 15:44:14 +0000 (11:44 -0400)]
Fix comment about pg_authid.

pg_shadow is not "publicly readable".  (pg_group is, but there seems
no need to make that distinction here.)  Seems to be a thinko dating
clear back to 7762619e9.

Antonin Houska

Discussion: https://postgr.es/m/31926.1729252247@antos

6 months agoDisable autovacuum for tables in stats import tests.
Jeff Davis [Fri, 18 Oct 2024 17:57:46 +0000 (10:57 -0700)]
Disable autovacuum for tables in stats import tests.

While we haven't observed any test instability, it seems like a good
idea to disable autovacuum during the stats import tests.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=fajh1Lpcyr_XsMmq-9Z=SGk-u+_Zeac7Pt0RAN3uiVCg@mail.gmail.com

6 months agoAllow pg_set_relation_stats() to set relpages to -1.
Jeff Davis [Fri, 18 Oct 2024 17:44:15 +0000 (10:44 -0700)]
Allow pg_set_relation_stats() to set relpages to -1.

While the default value for relpages is 0, if a partitioned table with
at least one child has been analyzed, then the partititoned table will
have a relpages value of -1.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=fajh1Lpcyr_XsMmq-9Z=SGk-u+_Zeac7Pt0RAN3uiVCg@mail.gmail.com

6 months agoOptimize nbtree backwards scans.
Peter Geoghegan [Fri, 18 Oct 2024 15:25:32 +0000 (11:25 -0400)]
Optimize nbtree backwards scans.

Make nbtree backwards scans optimistically access the next page to be
read to the left by following a prevPage block number that's now stashed
in currPos when the leaf page is first read.  This approach matches the
one taken during forward scans, which follow a symmetric nextPage block
number from currPos.  We stash both a prevPage and a nextPage, since the
scan direction might change (when fetching from a scrollable cursor).

Backwards scans will no longer need to lock the same page twice, except
in rare cases where the scan detects a concurrent page split (or page
deletion).  Testing has shown this optimization to be particularly
effective during parallel index-only backwards scans: ~12% reductions in
query execution time are quite possible.

We're much better off being optimistic; concurrent left sibling page
splits are rare in general.  It's possible that we'll need to lock more
pages than the pessimistic approach would have, but only when there are
_multiple_ concurrent splits of the left sibling page we now start at.
If there's just a single concurrent left sibling page split, the new
approach to scanning backwards will at least break even relative to the
old one (we'll acquire the same number of leaf page locks as before).

The optimization from this commit has long been contemplated by comments
added by commit 2ed5b87f96, which changed the rules for locking/pinning
during nbtree index scans.  The approach that that commit introduced to
leaf level link traversal when scanning forwards is now more or less
applied all the time, regardless of the direction we're scanning in.

Following uniform conventions around sibling link traversal is simpler.
The only real remaining difference between our forward and backwards
handling is that our backwards handling must still detect and recover
from any concurrent left sibling splits (and concurrent page deletions),
as documented in the nbtree README.  That is structured as a single,
isolated extra step that takes place in _bt_readnextpage.

Also use this opportunity to further simplify the functions that deal
with reading pages and traversing sibling links on the leaf level, and
to document their preconditions and postconditions (with respect to
things like buffer locks, buffer pins, and seizing the parallel scan).

This enhancement completely supersedes the one recently added by commit
3f44959f.

Author: Matthias van de Meent <[email protected]>
Author: Peter Geoghegan <[email protected]>
Discussion: https://postgr.es/m/CAEze2WgpBGRgTTxTWVPXc9+PB6fc1a7t+VyGXHzfnrFXcQVxnA@mail.gmail.com
Discussion: https://postgr.es/m/CAH2-WzkBTuFv7W2+84jJT8mWZLXVL0GHq2hMUTn6c9Vw=eYrCw@mail.gmail.com

6 months agoAdjust documentation for configuring Linux huge pages.
Nathan Bossart [Fri, 18 Oct 2024 15:20:15 +0000 (10:20 -0500)]
Adjust documentation for configuring Linux huge pages.

The present wording about viewing shared_memory_size_in_huge_pages
seems to suggest that the parameter cannot be viewed after startup
at all, whereas the intent is to make it clear that you can't use
"postgres -C" to view this parameter while the server is running.
This commit rephrases this section to remove the ambiguity.

Author: Seino Yuki
Reviewed-by: Michael Paquier, David G. Johnston, Fujii Masao
Discussion: https://postgr.es/m/420584fd274f9ec4f337da55ffb3b790%40oss.nttdata.com
Backpatch-through: 15

6 months agoFix memory leaks from incorrect strsep() uses
Peter Eisentraut [Fri, 18 Oct 2024 09:28:54 +0000 (11:28 +0200)]
Fix memory leaks from incorrect strsep() uses

Commit 5d2e1cc117b introduced some strsep() uses, but it did the
memory management wrong in some cases.  We need to keep a separate
pointer to the allocate memory so that we can free it later, because
strsep() advances the pointer we pass to it, and it at the end it
will be NULL, so any free() calls won't do anything.

(This fixes two of the four places changed in commit 5d2e1cc117b.  The
other two don't have this problem.)

Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/79692bf9-17d3-41e6-b9c9-fc8c3944222a@eisentraut.org

6 months agoFix strsep() use for SCRAM secrets parsing
Peter Eisentraut [Fri, 18 Oct 2024 09:06:41 +0000 (11:06 +0200)]
Fix strsep() use for SCRAM secrets parsing

The previous code (from commit 5d2e1cc117b) did not detect end of
string correctly, so it would fail to error out if fewer than the
expected number of fields were present, which could then later lead to
a crash when NULL string pointers are accessed.

Reported-by: Alexander Lakhin <[email protected]>
Reported-by: Ranier Vilela <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/79692bf9-17d3-41e6-b9c9-fc8c3944222a@eisentraut.org

6 months agoRemove unused code for unlogged materialized views.
Fujii Masao [Fri, 18 Oct 2024 08:18:57 +0000 (17:18 +0900)]
Remove unused code for unlogged materialized views.

Commit 3bf3ab8c56 initially introduced support for unlogged
materialized views, but this was later disallowed by commit 3223b25ff7.
Additionally, commit d25f519107 added more code for handling
unlogged materialized views. This commit cleans up all unused
code related to them.

If unlogged materialized views had been supported in any official
release, psql would need to retain code to handle them for compatibility
with older servers. However, since they were never included in
an official release, this code is no longer necessary.

Author: Pixian Shi
Reviewed-by: Yugo Nagata, Fujii Masao
Discussion: https://postgr.es/m/CAAccyYKRZ=OvAvgowiSH+OELbStLP=p2Ht=R3CgT=OaNSH5DAA@mail.gmail.com

6 months agoFix description of PostgreSQL::Test::Cluster::wait_for_event()
Michael Paquier [Fri, 18 Oct 2024 04:49:58 +0000 (13:49 +0900)]
Fix description of PostgreSQL::Test::Cluster::wait_for_event()

The arguments of the function were listed in an incorrect order in the
description of the routine.  This information can be seen with perldoc.

Issue spotted while working on this area of the code.

Backpatch-through: 17

6 months agoImprove ThrowErrorData() comments for use with soft errors.
Jeff Davis [Thu, 17 Oct 2024 21:56:44 +0000 (14:56 -0700)]
Improve ThrowErrorData() comments for use with soft errors.

Reviewed-by: Corey Huinker
Discussion: https://postgr.es/m/901ab7cf01957f92ea8b30b6feeb0eacfb7505fc[email protected]

6 months agoecpg: fix more minor mishandling of bad input in preprocessor.
Tom Lane [Thu, 17 Oct 2024 19:28:32 +0000 (15:28 -0400)]
ecpg: fix more minor mishandling of bad input in preprocessor.

Don't get confused by an unmatched right brace in the input.
(Previously, this led to discarding information about file-level
variables and then possibly crashing.)

Detect, rather than crash on, an attempt to index into a non-array
variable.

As before, in the absence of field complaints I'm not too
excited about back-patching these.

Per valgrind testing by Alexander Lakhin.

Discussion: https://postgr.es/m/a239aec2-6c79-5fc9-9272-cea41158a360@gmail.com

6 months agoFix extreme skew detection in Parallel Hash Join.
Thomas Munro [Thu, 17 Oct 2024 02:52:24 +0000 (15:52 +1300)]
Fix extreme skew detection in Parallel Hash Join.

After repartitioning the inner side of a hash join that would have
exceeded the allowed size, we check if all the tuples from a parent
partition moved to one child partition.  That is evidence that it
contains duplicate keys and later attempts to repartition will also
fail, so we should give up trying to limit memory (for lack of a better
fallback strategy).

A thinko prevented the check from working correctly in partition 0 (the
one that is partially loaded into memory already).  After
repartitioning, we should check for extreme skew if the *parent*
partition's space_exhausted flag was set, not the child partition's.
The consequence was repeated futile repartitioning until per-partition
data exceeded various limits including "ERROR: invalid DSA memory alloc
request size 1811939328", OS allocation failure, or temporary disk space
errors.  (We could also do something about some of those symptoms, but
that's material for separate patches.)

This problem only became likely when PostgreSQL 16 introduced support
for Parallel Hash Right/Full Join, allowing NULL keys into the hash
table.  Repartitioning always leaves NULL in partition 0, no matter how
many times you do it, because the hash value is all zero bits.  That's
unlikely for other hashed values, but they might still have caused
wasted extra effort before giving up.

Back-patch to all supported releases.

Reported-by: Craig Milhiser <[email protected]>
Reviewed-by: Andrei Lepikhov <[email protected]>
Discussion: https://postgr.es/m/CA%2BwnhO1OfgXbmXgC4fv_uu%3DOxcDQuHvfoQ4k0DFeB0Qqd-X-rQ%40mail.gmail.com

6 months agoRemove superfluous forward declaration
Peter Eisentraut [Thu, 17 Oct 2024 06:57:56 +0000 (08:57 +0200)]
Remove superfluous forward declaration

The need for this was removed by commit dc9c3b0ff21.

6 months agoFix whitespace
Peter Eisentraut [Thu, 17 Oct 2024 06:42:58 +0000 (08:42 +0200)]
Fix whitespace

6 months agoFix unnecessary casts of copyObject() result
Peter Eisentraut [Thu, 17 Oct 2024 06:36:14 +0000 (08:36 +0200)]
Fix unnecessary casts of copyObject() result

The result is already of the correct type, so these casts don't do
anything.

Reviewed-by: Nathan Bossart <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/637eeea8-5663-460b-a114-39572c0f6c6e%40eisentraut.org

6 months agoImprove node type forward reference
Peter Eisentraut [Thu, 17 Oct 2024 06:36:14 +0000 (08:36 +0200)]
Improve node type forward reference

Instead of using Node *, we can use an incomplete struct.  That way,
everything has the correct type and fewer casts are required.  This
technique is already used elsewhere in node type definitions.

Reviewed-by: Nathan Bossart <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/637eeea8-5663-460b-a114-39572c0f6c6e%40eisentraut.org

6 months agojsonapi: fully initialize dummy lexer
Peter Eisentraut [Thu, 17 Oct 2024 06:23:46 +0000 (08:23 +0200)]
jsonapi: fully initialize dummy lexer

Valgrind reports that checks on lex->inc_state are undefined for the
"dummy lexer" used for incremental parsing, since it's only partially
initialized on the stack. This was introduced in 0785d1b8b2.
Zero-initialize the whole struct.

Author: Jacob Champion <[email protected]>
Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://www.postgresql.org/message-id/CAOYmi+n9QWr4gsAADZc6qFQjFViXQYVk=gBy_EvxuqsgPJcb_g@mail.gmail.com

6 months agoFix unusual include style
Peter Eisentraut [Thu, 17 Oct 2024 06:14:45 +0000 (08:14 +0200)]
Fix unusual include style

Project-internal header files should be included using " ", not < >.

6 months agoDon't store intermediate hash values in ExprState->resvalue
David Rowley [Thu, 17 Oct 2024 01:25:08 +0000 (14:25 +1300)]
Don't store intermediate hash values in ExprState->resvalue

adf97c156 made it so ExprStates could support hashing and changed Hash
Join to use that instead of manually extracting Datums from tuples and
hashing them one column at a time.

When hashing multiple columns or expressions, the code added in that
commit stored the intermediate hash value in the ExprState's resvalue
field.  That was a mistake as steps may be injected into the ExprState
between each hashing step that look at or overwrite the stored
intermediate hash value.  EEOP_PARAM_SET is an example of such a step.

Here we fix this by adding a new dedicated field for storing
intermediate hash values and adjust the code so that all apart from the
final hashing step store their result in the intermediate field.

In passing, rename a variable so that it's more aligned to the
surrounding code and also so a few lines stay within the 80 char margin.

Reported-by: Andres Freund
Reviewed-by: Alena Rybakina <[email protected]>
Discussion: https://postgr.es/m/CAApHDvqo9eenEFXND5zZ9JxO_k4eTA4jKMGxSyjdTrsmYvnmZw@mail.gmail.com

6 months agoFix validation of COPY FORCE_NOT_NULL/FORCE_NULL for the all-column cases
Michael Paquier [Wed, 16 Oct 2024 23:44:50 +0000 (08:44 +0900)]
Fix validation of COPY FORCE_NOT_NULL/FORCE_NULL for the all-column cases

This commit adds missing checks for COPY FORCE_NOT_NULL and FORCE_NULL
when applied to all columns via "*".  These options now correctly
require CSV mode and are disallowed in COPY TO, making their behavior
consistent with FORCE_QUOTE.

Some regression tests are added to verify the correct behavior for the
all-columns case, including FORCE_QUOTE, which was not tested.

Backpatch down to 17, where support for the all-column grammar with
FORCE_NOT_NULL and FORCE_NULL has been added.

Author: Joel Jacobson
Reviewed-by: Zhang Mingli
Discussion: https://postgr.es/m/65030d1d-5f90-4fa4-92eb-f5f50389858e@app.fastmail.com
Backpatch-through: 17

6 months agoRewrite some regression queries for option checks with COPY
Michael Paquier [Wed, 16 Oct 2024 22:21:35 +0000 (07:21 +0900)]
Rewrite some regression queries for option checks with COPY

Some queries in copy2 are there to check various option combinations,
and used "stdin" or "stdout" incompatible with the COPY TO or FROM
clauses combined with them, which was confusing.  This commit rewrites
these queries to use a compatible grammar.

The coverage of the tests is unchanged.  Like the original commit
451d1164b9d0, backpatch down to 16 where these have been introduced.  A
follow-up commit will rely on this area of the tests for a bug fix.

Author: Joel Jacobson
Reviewed-by: Zhang Mingli
Discussion: https://postgr.es/m/65030d1d-5f90-4fa4-92eb-f5f50389858e@app.fastmail.com
Backpatch-through: 16

6 months agonbtree: fix read page recheck typo.
Peter Geoghegan [Wed, 16 Oct 2024 21:38:38 +0000 (17:38 -0400)]
nbtree: fix read page recheck typo.

Oversight in commit 79fa7b3b.

6 months agoFurther refine _SPI_execute_plan's rule for atomic execution.
Tom Lane [Wed, 16 Oct 2024 21:36:29 +0000 (17:36 -0400)]
Further refine _SPI_execute_plan's rule for atomic execution.

Commit 2dc1deaea turns out to have been still a brick shy of a load,
because CALL statements executing within a plpgsql exception block
could still pass the wrong snapshot to stable functions within the
CALL's argument list.  That happened because standard_ProcessUtility
forces isAtomicContext to true if IsTransactionBlock is true, which
it always will be inside a subtransaction.  Then ExecuteCallStmt
would think it does not need to push a new snapshot --- but
_SPI_execute_plan didn't do so either, since it thought it was in
nonatomic mode.

The best fix for this seems to be for _SPI_execute_plan to operate
in atomic execution mode if IsSubTransaction() is true, even when the
SPI context as a whole is non-atomic.  This makes _SPI_execute_plan
have the same rules about when non-atomic execution is allowed as
_SPI_commit/_SPI_rollback have about when COMMIT/ROLLBACK are allowed,
which seems appropriately symmetric.  (If anyone ever tries to allow
COMMIT/ROLLBACK inside a subtransaction, this would all need to be
rethought ... but I'm unconvinced that such a thing could be logically
consistent at all.)

For further consistency, also check IsSubTransaction() in
SPI_inside_nonatomic_context.  That does not matter for its
one present-day caller StartTransaction, which can't be reached
inside a subtransaction.  But if any other callers ever arise,
they'd presumably want this definition.

Per bug #18656 from Alexander Alehin.  Back-patch to all
supported branches, like previous fixes in this area.

Discussion: https://postgr.es/m/18656-cade1780866ef66c@postgresql.org

6 months agoWhitespace fixup from generated unicode tables.
Jeff Davis [Wed, 16 Oct 2024 19:21:13 +0000 (12:21 -0700)]
Whitespace fixup from generated unicode tables.

When running the 'update-unicode' build target, generate files that
conform to pgindent whitespace rules.

6 months agoFix #include order from e839c8ecc9.
Jeff Davis [Wed, 16 Oct 2024 19:09:16 +0000 (12:09 -0700)]
Fix #include order from e839c8ecc9.

Reported-by: Alexander Korotkov
Discussion: https://postgr.es/m/CAPpHfduAiGSsvUc614Z-JOnyQffcMeJncWMF2HnUL8wFy4fuWA@mail.gmail.com

6 months agoReduce memory block size for decoded tuple storage to 8kB.
Masahiko Sawada [Wed, 16 Oct 2024 19:08:05 +0000 (12:08 -0700)]
Reduce memory block size for decoded tuple storage to 8kB.

Commit a4ccc1cef introduced the Generation Context and modified the
logical decoding process to use a Generation Context with a fixed
block size of 8MB for storing tuple data decoded during logical
decoding (i.e., rb->tup_context). Several reports have indicated that
the logical decoding process can be terminated due to
out-of-memory (OOM) situations caused by excessive memory usage in
rb->tup_context.

This issue can occur when decoding a workload involving several
concurrent transactions, including a long-running transaction that
modifies tuples. By design, the Generation Context does not free a
memory block until all chunks within that block are
released. Consequently, if tuples modified by the long-running
transaction are stored across multiple memory blocks, these blocks
remain allocated until the long-running transaction completes, leading
to substantial memory fragmentation. The memory usage during logical
decoding, tracked by rb->size, does not account for memory
fragmentation, resulting in potentially much higher memory consumption
than the value of the logical_decoding_work_mem parameter.

Various improvement strategies were discussed in the relevant
thread. This change reduces the block size of the Generation Context
used in rb->tup_context from 8MB to 8kB. This modification
significantly decreases the likelihood of substantial memory
fragmentation occurring and is relatively straightforward to
backport. Performance testing across multiple platforms has confirmed
that this change will not introduce any performance degradation that
would impact actual operation.

Backport to all supported branches.

Reported-by: Alex Richman, Michael Guissine, Avi Weinberg
Reviewed-by: Amit Kapila, Fujii Masao, David Rowley
Tested-by: Hayato Kuroda, Shlok Kyal
Discussion: https://postgr.es/m/CAD21AoBTY1LATZUmvSXEssvq07qDZufV4AF-OHh9VD2pC0VY2A%40mail.gmail.com
Backpatch-through: 12

6 months agoecpg: fix some minor mishandling of bad input in preprocessor.
Tom Lane [Wed, 16 Oct 2024 16:24:57 +0000 (12:24 -0400)]
ecpg: fix some minor mishandling of bad input in preprocessor.

Avoid null-pointer crash when considering a cursor declaration
that's outside any C function (a case which is useless anyway).

Ensure a cursor for a prepared statement is marked as initially
not open.  At worst, if we chanced to get not-already-zeroed memory
from malloc(), this oversight would result in failing to issue a
"cursor "foo" has been declared but not opened" warning that would
have been appropriate.

Avoid running off the end of the buffer when there are mismatched
square brackets following a variable name.  This could lead to
SIGSEGV after reaching the end of memory.

Given the lack of field complaints, none of these seem to be worth
back-patching, but let's clean them up in HEAD.

Per valgrind testing by Alexander Lakhin.

Discussion: https://postgr.es/m/5f5bcecd-d7ec-b8c0-6c92-d1a7c6e0f639@gmail.com

6 months agoNormalize nbtree truncated high key array behavior.
Peter Geoghegan [Wed, 16 Oct 2024 16:17:49 +0000 (12:17 -0400)]
Normalize nbtree truncated high key array behavior.

Commit 5bf748b8 taught nbtree ScalarArrayOp index scans to decide when
and how to start the next primitive index scan based on physical index
characteristics.  This included rules for deciding whether to start a
new primitive index scan (or whether to move onto the right sibling leaf
page instead) that specifically consider truncated lower-order columns
(-inf columns) from leaf page high keys.

These omitted columns were treated as satisfying the scan's required
scan keys, though only for scan keys marked required in the current scan
direction (forward).  Scan keys that didn't get this behavior (those
marked required in the backwards direction only) usually didn't give the
scan reasonable cause to reposition itself to a later leaf page (via
another descent of the index in _bt_first), but _bt_advance_array_keys
would nevertheless always give up by forcing another call to _bt_first.

_bt_advance_array_keys was unwilling to allow the scan to continue onto
the next leaf page, to reconsider whether we really should start another
primitive scan based on the details of the sibling page's tuples.  This
didn't match its behavior with similar cases involving keys required in
the current scan direction (forward), which seems unprincipled.  It led
to an excessive number of primitive scans/index descents for queries
with a higher-order = array scan key (with dense, contiguous values)
mixed with a lower-order required > or >= scan key.

Bring > and >= strategy scan keys in line with other required scan key
types: treat truncated -inf scan keys as having satisfied scan keys
required in either scan direction (forwards and backwards alike) during
array advancement.  That way affected scans can continue to the right
sibling leaf page.  Advancement must now schedule an explicit recheck of
the right sibling page's high key in cases involving > or >= scan keys.
The recheck gives the scan a way to back out and start another primitive
index scan (we can't just rely on _bt_checkkeys with > or >= scan keys).

This work can be considered a stand alone optimization on top of the
work from commit 5bf748b8.  But it was written in preparation for an
upcoming patch that will add skip scan to nbtree.  In practice scans
that use "skip arrays" will tend to be much more sensitive to any
implementation deficiencies in this area.

Author: Peter Geoghegan <[email protected]>
Reviewed-By: Tomas Vondra <[email protected]>
Discussion: https://postgr.es/m/CAH2-Wz=9A_UtM7HzUThSkQ+BcrQsQZuNhWOvQWK06PRkEp=SKQ@mail.gmail.com

6 months agoFix typo in comment of transformJsonAggConstructor()
Amit Langote [Wed, 16 Oct 2024 09:11:53 +0000 (18:11 +0900)]
Fix typo in comment of transformJsonAggConstructor()

An oversight of 3a8a1f3254b.

Reported-by: Tender Wang <[email protected]>
Author: Tender Wang <[email protected]>
Backpatch-through: 16

6 months agoinitdb: Change default to using data checksums.
Peter Eisentraut [Wed, 16 Oct 2024 06:45:09 +0000 (08:45 +0200)]
initdb: Change default to using data checksums.

Checksums are now on by default.  They can be disabled by the
previously added option --no-data-checksums.

Author: Greg Sabino Mullane <[email protected]>
Reviewed-by: Nathan Bossart <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CAKAnmmKwiMHik5AHmBEdf5vqzbOBbcwEPHo4-PioWeAbzwcTOQ@mail.gmail.com

6 months agodoc: Fix initdb option xreflabels
Peter Eisentraut [Wed, 16 Oct 2024 06:28:12 +0000 (08:28 +0200)]
doc: Fix initdb option xreflabels

Generally, we don't want any overriding xreflabels in the options
list, so that we can link to options and the link renders as the
option name.  The -g option did this differently and config.sgml made
use of that for a link.  The new --no-data-checksums option (commit
983a588e0b8) apparently copied this pattern, but that seems like the
wrong direction, as a future patch revealed.

To fix, remove the two xreflabels and rewrite the link in config.sgml
with an explicit link text.

6 months agoAdd type cast to foreach_internal's loop variable.
Nathan Bossart [Tue, 15 Oct 2024 21:20:49 +0000 (16:20 -0500)]
Add type cast to foreach_internal's loop variable.

C++ requires explicitly casting void pointers to the appropriate
pointer type, which means the foreach_ptr macro cannot be used in
C++ code without this change.

Author: Jelte Fennema-Nio
Reviewed-by: Bruce Momjian
Discussion: https://postgr.es/m/CAGECzQSYG3QfHrc-rOk2KbnB9iJOd7Qu-Xii1s-GTA%3D3JFt49Q%40mail.gmail.com
Backpatch-through: 17

6 months agoMove clause_sides_match_join() into restrictinfo.h
David Rowley [Tue, 15 Oct 2024 08:14:21 +0000 (21:14 +1300)]
Move clause_sides_match_join() into restrictinfo.h

Two near-identical copies of clause_sides_match_join() existed in
joinpath.c and analyzejoins.c.  Deduplicate this by moving the function
into restrictinfo.h.

It isn't quite clear that keeping the inline property of this function
is worthwhile, but this commit is just an exercise in code
deduplication.  More effort would be required to determine if the inline
property is worth keeping.

Author: James Hunter <[email protected]>
Discussion: https://postgr.es/m/CAJVSvF7Nm_9kgMLOch4c-5fbh3MYg%3D9BdnDx3Dv7Fcb64zr64Q%40mail.gmail.com

6 months agoAdd contrib/pg_logicalinspect.
Masahiko Sawada [Tue, 15 Oct 2024 00:22:02 +0000 (17:22 -0700)]
Add contrib/pg_logicalinspect.

This module provides SQL functions that allow to inspect logical
decoding components.

It currently allows to inspect the contents of serialized logical
snapshots of a running database cluster, which is useful for debugging
or educational purposes.

Author: Bertrand Drouvot
Reviewed-by: Amit Kapila, Shveta Malik, Peter Smith, Peter Eisentraut
Reviewed-by: David G. Johnston
Discussion: https://postgr.es/m/ZscuZ92uGh3wm4tW%40ip-10-97-1-34.eu-west-3.compute.internal

6 months agoMove SnapBuild and SnapBuildOnDisk structs to snapshot_internal.h.
Masahiko Sawada [Tue, 15 Oct 2024 00:19:33 +0000 (17:19 -0700)]
Move SnapBuild and SnapBuildOnDisk structs to snapshot_internal.h.

This commit moves the definitions of the SnapBuild and SnapBuildOnDisk
structs, related to logical snapshots, to the snapshot_internal.h
file. This change allows external tools, such as
pg_logicalinspect (with an upcoming patch), to access and utilize the
contents of logical snapshots.

Author: Bertrand Drouvot
Reviewed-by: Amit Kapila, Shveta Malik, Peter Smith
Discussion: https://postgr.es/m/ZscuZ92uGh3wm4tW%40ip-10-97-1-34.eu-west-3.compute.internal

6 months agoecpg: invent a saner syntax for ecpg.addons entries.
Tom Lane [Mon, 14 Oct 2024 20:13:48 +0000 (16:13 -0400)]
ecpg: invent a saner syntax for ecpg.addons entries.

Put the rule type at the start not the end, and put spaces
between the constitutent token names instead of smashing them
into an illegible mess.  This has no functional impact but
I think it makes the rules a great deal more readable.

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

6 months agoAdd commit 7f7474a8e4 to .git-blame-ignore-revs.
Nathan Bossart [Mon, 14 Oct 2024 20:09:39 +0000 (15:09 -0500)]
Add commit 7f7474a8e4 to .git-blame-ignore-revs.

6 months agoecpg: add cross-checks to parse.pl for usage of internal tables.
Tom Lane [Mon, 14 Oct 2024 19:59:13 +0000 (15:59 -0400)]
ecpg: add cross-checks to parse.pl for usage of internal tables.

parse.pl contains several constant tables that describe tweaks
to be made to the backend grammar.  In the same spirit as
00b0e7204, add cross-checks that each table entry is used at
least once (or exactly once if that's appropriate).  This should
help catch cases where adjustments to the backend grammar cause
a table entry not to match as expected.

Per suggestion from Michael Paquier.

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

6 months agoMove libc-specific code from pg_locale.c into pg_locale_libc.c.
Jeff Davis [Mon, 14 Oct 2024 19:22:13 +0000 (12:22 -0700)]
Move libc-specific code from pg_locale.c into pg_locale_libc.c.

Move implementation of pg_locale_t code for libc collations into
pg_locale_libc.c. Other locale-related code, such as
pg_perm_setlocale(), remains in pg_locale.c for now.

Discussion: https://postgr.es/m/flat/2830211e1b6e6a2e26d845780b03e125281ea17b[email protected]

6 months agoecpg: avoid breaking the IDENT precedence level in two.
Tom Lane [Mon, 14 Oct 2024 19:41:42 +0000 (15:41 -0400)]
ecpg: avoid breaking the IDENT precedence level in two.

Careless string hacking caused parse.pl to transform gram.y's
declaration

%nonassoc    IDENT PARTITION RANGE ROWS ...

into

%nonassoc IDENT
%nonassoc CSTRING PARTITION RANGE ROWS ...

It turns out that this has no semantic impact, because the
generated preproc.c is exactly the same either way (if you
inject a blank line to keep line numbers the same).

Nonetheless, given the great emphasis that the commentary in
gram.y places on keeping those other keywords at the same
precedence level as IDENT, this seems like foolishly risking ecpg
behaving differently from the core parser.  Adjust the code so
that CSTRING is added to the precedence line without breaking it
into two lines.

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

6 months agoMove ICU-specific code from pg_locale.c into pg_locale_icu.c.
Jeff Davis [Mon, 14 Oct 2024 19:13:20 +0000 (12:13 -0700)]
Move ICU-specific code from pg_locale.c into pg_locale_icu.c.

Discussion: https://postgr.es/m/flat/2830211e1b6e6a2e26d845780b03e125281ea17b[email protected]

6 months agoecpg: improve preprocessor's memory management.
Tom Lane [Mon, 14 Oct 2024 17:55:08 +0000 (13:55 -0400)]
ecpg: improve preprocessor's memory management.

Invent a notion of "local" storage that will automatically be
reclaimed at the end of each statement.  Use this for location
strings as well as other visibly short-lived data within the parser.

Also, make cat_str and make_str return local storage and not free
their inputs, which allows dispensing with a whole lot of retail
mm_strdup calls.  We do have to add some new ones in places where
a local-lifetime string needs to be added to a longer-lived data
structure, but on balance there are a lot less mm_strdup calls than
before.

In hopes of flushing out places where changes were necessary,
I changed YYLTYPE from "char *" to "const char *", which forced
const-ification of various function arguments that probably
should've been like that all along.

This still leaks somewhat more memory than v17, but that will be
cleaned up in future commits.

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

6 months agoecpg: move some functions into a new file ecpg/preproc/util.c.
Tom Lane [Mon, 14 Oct 2024 17:47:59 +0000 (13:47 -0400)]
ecpg: move some functions into a new file ecpg/preproc/util.c.

mm_alloc and mm_strdup were in type.c, which seems a completely
random choice.  No doubt the original author thought two small
functions didn't deserve their own file.  But I'm about to add
some more memory-management stuff beside them, so let's put them
in a less surprising place.  This seems like a better home for
mmerror, mmfatal, and the cat_str/make_str family, too.

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

6 months agoecpg: re-implement preprocessor's string management.
Tom Lane [Mon, 14 Oct 2024 17:44:42 +0000 (13:44 -0400)]
ecpg: re-implement preprocessor's string management.

Most productions in the preprocessor grammar construct strings
representing SQL or C statements or fragments thereof.  Instead
of returning these as <str> results of the productions, return
them as "location" values, taking advantage of Bison's flexibility
about what a location is.  We aren't really giving up anything
thereby, since ecpg's error reports have always just given line
numbers, and that's tracked separately.  The advantage of this
is that a single instance of the YYLLOC_DEFAULT macro can
perform all the work needed by the vast majority of productions,
including all the ones made automatically by parse.pl.  This
avoids having large numbers of effectively-identical productions,
which tickles an optimization inefficiency in recent versions of
clang.  (This patch reduces the compilation time for preproc.o
by more than 100-fold with clang 16, and is visibly helpful with
gcc too.)  The compiled parser is noticeably smaller as well.

A disadvantage of this approach is that YYLLOC_DEFAULT is applied
before running the production's semantic action (if any).  This
means it cannot use the method favored by cat_str() of free'ing
all the input strings; if the action needs to look at the input
strings, it'd be looking at dangling storage.  As this stands,
therefore, it leaks memory like a sieve.  This is already a big
patch though, and fixing the memory management seems like a
separable problem, so let's leave that for the next step.
(This does remove some free() calls that I'd have had to touch
anyway, in the expectation that the next step will manage
memory reclamation quite differently.)

Most of the changes here are mindless substitution of "@N" for
"$N" in grammar rules; see the changes to README.parser for
an explanation.

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

6 months agoecpg: major cleanup, simplification, and documentation of parse.pl.
Tom Lane [Mon, 14 Oct 2024 17:37:33 +0000 (13:37 -0400)]
ecpg: major cleanup, simplification, and documentation of parse.pl.

Remove a lot of cruft, clean up and document what's left.
This produces the same preproc.y output as before, except for
fewer blank lines.  (It's not like we're making any attempt to
match the layout of gram.y, so I removed the one bit of logic
that seemed to have that in mind.)

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

6 months agoecpg: remove check_rules.pl.
Tom Lane [Mon, 14 Oct 2024 17:33:41 +0000 (13:33 -0400)]
ecpg: remove check_rules.pl.

As noted in the previous commit, check_rules.pl is now entirely
redundant with checks made by parse.pl, or would be if it weren't
for the places where it's wrong.  It's a waste of build cycles
and maintenance effort, so remove it.

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

6 months agoecpg: clean up documentation of parse.pl, and add more input checking.
Tom Lane [Mon, 14 Oct 2024 17:29:36 +0000 (13:29 -0400)]
ecpg: clean up documentation of parse.pl, and add more input checking.

README.parser is the user's manual, such as it is, for parse.pl.
It's rather poorly written if you ask me; so try to improve it.
(More could be written here, but this at least covers the same
info in a more organized fashion.)

Also, the single solitary line of usage info in parse.pl itself
was a lie.  Replace.

Add some error checks that the ecpg.addons entries meet the syntax
rules set forth in README.parser.  One of them didn't, but
accidentally worked anyway because the logic in include_addon is
such that 'block' is the default behavior.

Also add a cross-check that each ecpg.addons entry is matched exactly
once in the backend grammar.  This exposed that there are two dead
entries there --- they are dead because the %replace_types table in
parse.pl causes their nonterminals to be ignored altogether.
Removing them doesn't change the generated preproc.y file.

(This implies that check_rules.pl is completely worthless and should
be nuked: it adds build cycles and maintenance effort while failing
to reliably accomplish its one job of detecting dead rules.  I'll
do that separately.)

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

6 months agoRemove obsolete comment in reorderbuffer.h.
Masahiko Sawada [Mon, 14 Oct 2024 16:53:05 +0000 (09:53 -0700)]
Remove obsolete comment in reorderbuffer.h.

Commit 9fab40ad32e changed ReorderBuffer to use Slab Context for
allocating ReorderBufferTXN entries instead of using a caching
mechanism. The txn->node is no longer used as an element of the list
of preallocated ReorderBufferTXNs.

Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/CAD21AoB1CTnX66Ji3zTCnjoPVC9OzYe0B6LygUHcxEB2RV-hFw%40mail.gmail.com

6 months agoUse construct_array_builtin for FLOAT8OID instead of construct_array.
Masahiko Sawada [Mon, 14 Oct 2024 16:49:29 +0000 (09:49 -0700)]
Use construct_array_builtin for FLOAT8OID instead of construct_array.

Commit d746021de1 introduced construct_array_builtin() for built-in
data types, but forgot some replacements linked to FLOAT8OID.

Author: Bertrand Drouvot
Reviewed-by: Peter Eisentraut
Discussion: https://postgr.es/m/CAD21AoCERkwmttY44dqUw%3Dm_9QCctu7W%2Bp6B7w_VqxRJA1Qq_Q%40mail.gmail.com

6 months agoTrack scan reversals in MergeJoin
Peter Eisentraut [Mon, 14 Oct 2024 13:36:18 +0000 (15:36 +0200)]
Track scan reversals in MergeJoin

The MergeJoin struct was tracking "mergeStrategies", which were an
array of btree strategy numbers, purely for the purpose of comparing
it later against btree strategies to determine if the scan direction
was forward or reverse.  Change that.  Instead, track
"mergeReversals", an array of bool, to indicate the same without an
unfortunate assumption that a strategy number refers specifically to a
btree strategy.

Author: Mark Dilger <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/E72EAA49-354D-4C2E-8EB9-255197F55330@enterprisedb.com

6 months agoTrack sort direction in SortGroupClause
Peter Eisentraut [Mon, 14 Oct 2024 13:36:02 +0000 (15:36 +0200)]
Track sort direction in SortGroupClause

Functions make_pathkey_from_sortop() and transformWindowDefinitions(),
which receive a SortGroupClause, were determining the sort order
(ascending vs. descending) by comparing that structure's operator
strategy to BTLessStrategyNumber, but could just as easily have gotten
it from the SortGroupClause object, if it had such a field, so add
one.  This reduces the number of places that hardcode the assumption
that the strategy refers specifically to a btree strategy, rather than
some other index AM's operators.

Author: Mark Dilger <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/E72EAA49-354D-4C2E-8EB9-255197F55330@enterprisedb.com

6 months agoAllow TAP tests to force checksums off when calling init()
Peter Eisentraut [Mon, 14 Oct 2024 08:57:54 +0000 (10:57 +0200)]
Allow TAP tests to force checksums off when calling init()

TAP tests can write

    $node->init(no_data_checksums => 1);

to initialize a cluster explicitly without checksums.  Currently, this
is the default, but this change allows running all tests with
checksums enabled, like

    PG_TEST_INITDB_EXTRA_OPTS=--data-checksums meson test ...

And this also prepares the tests for when we switch the default to
checksums enabled.

The pg_checksums tests need to disable checksums so it can test its
own functionality of enabling checksums.  The amcheck/pg_amcheck tests
need to disable checksums because they manually introduce corruption
that they want to detect, but with checksums enabled, the checksum
verification will fail before they even get to their work.

Author: Greg Sabino Mullane <[email protected]>
Reviewed-by: Nathan Bossart <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CAKAnmmKwiMHik5AHmBEdf5vqzbOBbcwEPHo4-PioWeAbzwcTOQ@mail.gmail.com

6 months agoRun pgperltidy on newly-added test code
Peter Eisentraut [Mon, 14 Oct 2024 09:07:04 +0000 (11:07 +0200)]
Run pgperltidy on newly-added test code

From commit 85ec945b78 (but apparently not caught by 05d1b9b5c2).

6 months agodoc: Add anchors for COPY format descriptions
Daniel Gustafsson [Mon, 14 Oct 2024 08:15:33 +0000 (10:15 +0200)]
doc: Add anchors for COPY format descriptions

When answering support questions online it's helpful to be able to
refer to the specific format by using an anchored link.

Author: Dagfinn Ilmari Mannsåker <[email protected]>
Discussion: https://postgr.es/m/[email protected]

6 months agoRemove traces of BeOS.
Peter Eisentraut [Mon, 14 Oct 2024 06:02:38 +0000 (08:02 +0200)]
Remove traces of BeOS.

Commit 15abc7788e6 tolerated namespace pollution from BeOS system
headers.  Commit 44f902122 de-supported BeOS.  Since that stuff didn't
make it into the Meson build system, synchronize by removing from
configure.

Author: Thomas Munro <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Reviewed-by: Japin Li <[email protected]>
Reviewed-by: Tom Lane <[email protected]> (the idea, not the patch)
Discussion: https://postgr.es/m/ME3P282MB3166F9D1F71F787929C0C7E7B6312%40ME3P282MB3166.AUSP282.PROD.OUTLOOK.COM

6 months agopsql: Fix \watch when using interval values less than 1ms
Michael Paquier [Mon, 14 Oct 2024 03:27:51 +0000 (12:27 +0900)]
psql: Fix \watch when using interval values less than 1ms

Attempting to use an interval of time less than 1ms would cause \watch
to hang.  This was confusing, so let's change the logic so as an
interval lower than 1ms behaves the same as 0.

Comments are added to mention that the internals of do_watch() had
better rely on "sleep_ms", the interval value in milliseconds.  While on
it, this commit adds a test to check the behavior of interval values
less than 1ms.

\watch hanging for interval values less than 1ms existed before
6f9ee74d45aa, that has changed the code to support an interval value of
0.

Reported-by: Heikki Linnakangas
Author: Andrey M. Borodin, Michael Paquier
Discussion: https://postgr.es/m/88445e0e-3156-4b9d-afae-9a1a7b1631f6@iki.fi
Backpatch-through: 16

6 months agoFixup for pg_set_relation_stats().
Jeff Davis [Sun, 13 Oct 2024 20:44:23 +0000 (13:44 -0700)]
Fixup for pg_set_relation_stats().

Reported-by: Noriyoshi Shinoda
Discussion: https://postgr.es/m/DM4PR84MB17345E2DFF28A5557B7CBC3CEE7A2@DM4PR84MB1734.NAMPRD84.PROD.OUTLOOK.COM

6 months agoUse MAX_PARALLEL_WORKER_LIMIT for max_parallel_maintenance_workers
Michael Paquier [Sun, 13 Oct 2024 02:20:30 +0000 (11:20 +0900)]
Use MAX_PARALLEL_WORKER_LIMIT for max_parallel_maintenance_workers

max_parallel_maintenance_workers has been introduced in 9da0cc35284b,
and used a hardcoded limit of 1024 rather than this variable.

max_parallel_workers and max_parallel_workers_per_gather already used
MAX_PARALLEL_WORKER_LIMIT (1024) as their upper-bound since
6599c9ac3340.

Author: Matthias van de Meent
Reviewed-by: Zhang Mingli
Discussion: https://postgr.es/m/CAEze2WiCiJD+8Wig_wGPyn4vgdPjbnYXy2Rw+9KYi6izTMuP=w@mail.gmail.com

6 months agoCorrectly identify which EC members are computable at a plan node.
Tom Lane [Sat, 12 Oct 2024 18:56:08 +0000 (14:56 -0400)]
Correctly identify which EC members are computable at a plan node.

find_computable_ec_member() had the wrong mental model of what
its primary caller prepare_sort_from_pathkeys() would do with
the selected EquivalenceClass member expression.  We will not
compute the EC expression in a plan node atop the one returning
the passed-in targetlist; rather, the EC expression will be
computed as an additional column of that targetlist.  So any
Var or quasi-Var used in the given tlist is also available to the
EC expression.  In simple cases this makes no difference because
the given tlist is just a list of Vars or quasi-Vars --- but if
we are considering an appendrel member produced by flattening
a UNION ALL, the tlist may contain expressions, resulting in
failure to match and a "could not find pathkey item to sort"
error.

To fix, we can flatten both the tlist and the EC members with
pull_var_clause(), and then just check for subset-ness, so
that the code is actually shorter than before.

While this bug is quite old, the present patch only works back to
v13.  We could possibly make it work in v12 by back-patching parts
of 375398244.  On the whole though I don't like the risk/reward
ratio of that idea.  v12's final release is next month, meaning
there would be no chance to correct matters if the patch causes a
regression.  Since this failure has escaped notice for 14 years,
it's likely nobody will hit it in the field with v12.

Per bug #18652 from Alexander Lakhin.

Andrei Lepikhov and Tom Lane

Discussion: https://postgr.es/m/18652-deaa782ebcca85d1@postgresql.org

6 months agoFix missed case for builtin collation provider.
Jeff Davis [Fri, 11 Oct 2024 23:57:48 +0000 (16:57 -0700)]
Fix missed case for builtin collation provider.

A missed check for the builtin collation provider could result in
falling through to call isalpha().

This does not appear to have practical consequences because it only
happens for characters in the ASCII range. Regardless, the builtin
provider should not be calling libc functions, so backpatch.

Discussion: https://postgr.es/m/1bd5a0a5192f82c22ee7527e825b18ab0028b2c7[email protected]
Backpatch-through: 17

6 months agoCreate functions pg_set_relation_stats, pg_clear_relation_stats.
Jeff Davis [Fri, 11 Oct 2024 23:55:11 +0000 (16:55 -0700)]
Create functions pg_set_relation_stats, pg_clear_relation_stats.

These functions are used to tweak statistics on any relation, provided
that the user has MAINTAIN privilege on the relation, or is the database
owner.

Bump catalog version.

Author: Corey Huinker
Discussion: https://postgr.es/m/CADkLM=eErgzn7ECDpwFcptJKOk9SxZEk5Pot4d94eVTZsvj3gw@mail.gmail.com

6 months agoAvoid mixing custom and OpenSSL BIO functions
Daniel Gustafsson [Fri, 11 Oct 2024 19:58:58 +0000 (21:58 +0200)]
Avoid mixing custom and OpenSSL BIO functions

PostgreSQL has for a long time mixed two BIO implementations, which can
lead to subtle bugs and inconsistencies. This cleans up our BIO by just
just setting up the methods we need. This patch does not introduce any
functionality changes.

The following methods are no longer defined due to not being needed:

  - gets: Not used by libssl
  - puts: Not used by libssl
  - create: Sets up state not used by libpq
  - destroy: Not used since libpq use BIO_NOCLOSE, if it was used it close
             the socket from underneath libpq
  - callback_ctrl: Not implemented by sockets

The following methods are defined for our BIO:

  - read: Used for reading arbitrary length data from the BIO. No change
          in functionality from the previous implementation.
  - write: Used for writing arbitrary length data to the BIO. No change
           in functionality from the previous implementation.
  - ctrl: Used for processing ctrl messages in the BIO (similar to ioctl).
          The only ctrl message which matters is BIO_CTRL_FLUSH used for
          writing out buffered data (or signal EOF and that no more data
          will be written). BIO_CTRL_FLUSH is mandatory to implement and
          is implemented as a no-op since there is no intermediate buffer
          to flush.
          BIO_CTRL_EOF is the out-of-band method for signalling EOF to
          read_ex based BIO's. Our BIO is not read_ex based but someone
          could accidentally call BIO_CTRL_EOF on us so implement mainly
          for completeness sake.

As the implementation is no longer related to BIO_s_socket or calling
SSL_set_fd, methods have been renamed to reference the PGconn and Port
types instead.

This also reverts back to using BIO_set_data, with our fallback, as a small
optimization as BIO_set_app_data require the ex_data mechanism in OpenSSL.

Author: David Benjamin <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Discussion: https://postgr.es/m/CAF8qwaCZ97AZWXtg_y359SpOHe+HdJ+p0poLCpJYSUxL-8Eo8A@mail.gmail.com

6 months agoAdd pg_ls_summariesdir().
Nathan Bossart [Fri, 11 Oct 2024 16:02:09 +0000 (11:02 -0500)]
Add pg_ls_summariesdir().

This function returns the name, size, and last modification time of
each regular file in pg_wal/summaries.  This allows administrators
to grant privileges to view the contents of this directory without
granting privileges on pg_ls_dir(), which allows listing the
contents of many other directories.  This commit also gives the
pg_monitor predefined role EXECUTE privileges on the new
pg_ls_summariesdir() function.

Bumps catversion.

Author: Yushi Ogiwara
Reviewed-by: Michael Paquier, Fujii Masao
Discussion: https://postgr.es/m/a0a3af15a9b9daa107739eb45aa9a9bc%40oss.nttdata.com

6 months agoMark consume_xids test functions VOLATILE and PARALLEL UNSAFE
Heikki Linnakangas [Fri, 11 Oct 2024 08:09:09 +0000 (11:09 +0300)]
Mark consume_xids test functions VOLATILE and PARALLEL UNSAFE

Both functions advance the transaction ID, which modifies the system
state. Thus, they should be marked as VOLATILE.

Additionally, they call the AssignTransactionId function, which cannot
be invoked in parallel mode, so they should be marked as PARALLEL
UNSAFE.

Author: Yushi Ogiwara <[email protected]>
Discussion: https://www.postgresql.org/message-id/18f01e4fd46448f88c7a1363050a9955@oss.nttdata.com

6 months agoFix typo in connection limits test
Daniel Gustafsson [Fri, 11 Oct 2024 08:04:23 +0000 (10:04 +0200)]
Fix typo in connection limits test

Spotted while doing post-commit review.

6 months agoUse deconstruct_array_builtin instead of deconstruct_array
Álvaro Herrera [Fri, 11 Oct 2024 07:54:18 +0000 (09:54 +0200)]
Use deconstruct_array_builtin instead of deconstruct_array

Commit 062a84442424 introduced use of deconstruct_array when
deconstruct_array_builtin can be used instead.  Do that to save some
code.

Author: Bertrand Drouvot <[email protected]>
Discussion: https://postgr.es/m/[email protected]

6 months agopgbench: Improve result outputs related to failed transactions.
Tatsuo Ishii [Fri, 11 Oct 2024 04:40:23 +0000 (13:40 +0900)]
pgbench: Improve result outputs related to failed transactions.

Previously, per-script statistics were never output when all
transactions failed due to serialization or deadlock errors.  However,
it is reasonable to report such information if there are ones even
when there are no successful transaction since these failed
transactions are now objects to be reported.

Meanwhile, if the total number of successful, skipped, and failed
transactions is zero, we don't have to report the number of failed
transactions as similar to the number of skipped transactions, which
avoids to print "NaN%" in lines on failed transaction reports.

Also, the number of transactions in per-script results now includes
skipped and failed transactions. It prevents to print "total of NaN%"
when any transactions are not successfully processed. The number of
transactions actually processed per-script and TPS based on it are now
output explicitly in a separate line.

Author: Yugo Nagata
Reviewed-by: Tatsuo Ishii
Discussion: https://postgr.es/m/20240921003544.2436ef8da9c5c8cb963c651b%40sraoss.co.jp

6 months agoAdjust EXPLAIN's output for disabled nodes
David Rowley [Fri, 11 Oct 2024 04:19:59 +0000 (17:19 +1300)]
Adjust EXPLAIN's output for disabled nodes

c01743aa4 added EXPLAIN output to display the plan node's disabled_node
count whenever that count is above 0.  Seemingly, there weren't many
people who liked that output as each parent of a disabled node would
also have a "Disabled Nodes" output due to the way disabled_nodes is
accumulated towards the root plan node.  It was often hard and sometimes
impossible to figure out which nodes were disabled from looking at
EXPLAIN.  You might think it would be possible to manually add up the
numbers from the "Disabled Nodes" output of a given node's children to
figure out if that node has a higher disabled_nodes count than its
children, but that wouldn't have worked for Append and Merge Append nodes
if some disabled child nodes were run-time pruned during init plan.  Those
children are not displayed in EXPLAIN.

Here we attempt to improve this output by only showing "Disabled: true"
against only the nodes which are explicitly disabled themselves.  That
seems to be the output that's desired by the most people who voiced
their opinion.  This is done by summing up the disabled_nodes of the
given node's children and checking if that number is less than the
disabled_nodes of the current node.

This commit also fixes a bug in make_sort() which was neglecting to set
the Sort's disabled_nodes field.  This should have copied what was done
in cost_sort(), but it hadn't been updated.  With the new output, the
choice to not maintain that field properly was clearly wrong as the
disabled-ness of the node was attributed to the Sort's parent instead.

Reviewed-by: Laurenz Albe, Alena Rybakina
Discussion: https://postgr.es/m/9e4ad616bebb103ec2084bf6f724cfc739e7fabb[email protected]

6 months agoDon't hard-code the input file name in gen_tabcomplete.pl's output.
Tom Lane [Thu, 10 Oct 2024 21:02:08 +0000 (17:02 -0400)]
Don't hard-code the input file name in gen_tabcomplete.pl's output.

Use $ARGV[0], that is the specified input file name, in #line
directives generated by gen_tabcomplete.pl.  This makes code
coverage reports work properly in the meson build system (where
the input file name will be a relative path).

Also fix up brain fade in the meson build rule for tab-complete.c:
we only need to write the input file name once not twice.

Jacob Champion (some cosmetic adjustments by me)

Discussion: https://postgr.es/m/CAOYmi+=+oWAoi8pqnH0MJQqsSn4ddzqDhqRQJvyiN2aJSWvw2w@mail.gmail.com

6 months agoAvoid possible segfault in psql's tab completion.
Tom Lane [Thu, 10 Oct 2024 20:17:38 +0000 (16:17 -0400)]
Avoid possible segfault in psql's tab completion.

Fix oversight in bd1276a3c: the "words_after_create" stanza in
psql_completion() requires previous_words_count > 0, since it uses
prev_wd.  This condition was formerly assured by the if-else chain
above it, but no more.  If there were no previous words then we'd
dereference an uninitialized pointer, possibly causing a segfault.

Report and patch by Anthonin Bonnefoy.

Discussion: https://postgr.es/m/CAO6_XqrSRE7c_i+D7Hm07K3+6S0jTAmMr60RY41XzaA29Ae5uA@mail.gmail.com

6 months agoUnbreak overflow test for attinhcount/coninhcount
Álvaro Herrera [Thu, 10 Oct 2024 15:41:01 +0000 (17:41 +0200)]
Unbreak overflow test for attinhcount/coninhcount

Commit 90189eefc1e1 narrowed pg_attribute.attinhcount and
pg_constraint.coninhcount from 32 to 16 bits, but kept other related
structs with 32-bit wide fields: ColumnDef and CookedConstraint contain
an int 'inhcount' field which is itself checked for overflow on
increments, but there's no check that the values aren't above INT16_MAX
before assigning to the catalog columns.  This means that a creative
user can get a inconsistent table definition and override some
protections.

Fix it by changing those other structs to also use int16.

Also, modernize style by using pg_add_s16_overflow for overflow testing
instead of checking for negative values.

We also have Constraint.inhcount, which is here removed completely.
This was added by commit b0e96f311985 and not removed by its revert at
6f8bb7c1e961.  It is not needed by the upcoming not-null constraints
patch.

This is mostly academic, so we agreed not to backpatch to avoid ABI
problems.

Bump catversion because of the changes to parse nodes.

Co-authored-by: Álvaro Herrera <[email protected]>
Co-authored-by: 何建 (jian he) <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/202410081611[email protected]

6 months agoImprove descriptions of some pg_stat_checkpoints functions in pg_proc.dat.
Fujii Masao [Thu, 10 Oct 2024 15:12:29 +0000 (00:12 +0900)]
Improve descriptions of some pg_stat_checkpoints functions in pg_proc.dat.

Previously, the descriptions of pg_stat_get_checkpointer_num_requested(),
pg_stat_get_checkpointer_restartpoints_requested(),
and pg_stat_get_checkpointer_restartpoints_performed() in pg_proc.dat
referred to "backend". This was misleading because these functions report
the number of checkpoints or restartpoints requested or performed
by other than backends as well.

This commit removes "backend" from these descriptions to avoid confusion.

Bump catalog version.

Idea from Anton A. Melnikov
Author: Fujii Masao
Reviewed-by: Anton A. Melnikov
Discussion: https://postgr.es/m/8e5f353f-8b31-4a8e-9cfa-c037f22b4aee@postgrespro.ru