postgresql.git
7 months agoreindexdb: Skip reindexing temporary tables and indexes.
Fujii Masao [Mon, 30 Sep 2024 02:13:55 +0000 (11:13 +0900)]
reindexdb: Skip reindexing temporary tables and indexes.

Reindexing temp tables or indexes of other sessions is not allowed.
However, reindexdb in parallel mode previously listed them as
the objects to process, leading to failures.

This commit ensures reindexdb in parallel mode skips temporary tables
and indexes by adding a condition based on the relpersistence column
in pg_class to the object listing queries, preventing these issues.

Note that this commit does not affect reindexdb when temporary tables
or indexes are explicitly specified using the -t or -j options;
reindexdb in that case still does not skip them and can cause an error.

Back-patch to v13 where parallel mode was introduced in reindexdb.

Author: Fujii Masao
Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/5f37ee56-14fb-44fe-9150-9eb97e10538b@oss.nttdata.com

7 months agoSet query ID in parallel workers for vacuum, BRIN and btree
Michael Paquier [Sun, 29 Sep 2024 23:43:28 +0000 (08:43 +0900)]
Set query ID in parallel workers for vacuum, BRIN and btree

All these code paths use their own entry point when starting parallel
workers, but failed to set a query ID, even if they set a text query.
Hence, this data would be missed in pg_stat_activity for the worker
processes.  The main entry point for parallel query processing,
ParallelQueryMain(), is already doing that by saving its query ID in a
dummy PlannedStmt, but not the others.  The code is changed so as the
query ID of these queries is set in their shared state, and reported
back once the parallel workers start.

Some tests are added to show how the failures can happen for btree and
BRIN with a parallel build enforced, which are able to trigger a failure
in an assertion added by 24f520594809 in the recovery TAP test
027_stream_regress.pl where pg_stat_statements is always loaded.  In
this case, the executor path was taken because the index expression
needs to be flattened when building its IndexInfo.

Alexander Lakhin has noticed the problem in btree, and I have noticed
that the issue was more spread.  This is arguably a bug, but nobody has
complained about that until now, so no backpatch is done out of caution.
If folks would like to see a backpatch, well, let me know.

Reported-by: Alexander Lakhin
Reviewed-by: Sami Imseih
Discussion: https://postgr.es/m/cf3547c1-498a-6a61-7b01-819f902a251f@gmail.com

7 months agoRemove NULL dereference from RenameRelationInternal().
Noah Misch [Sun, 29 Sep 2024 22:54:25 +0000 (15:54 -0700)]
Remove NULL dereference from RenameRelationInternal().

Defect in last week's commit aac2c9b4fde889d13f859c233c2523345e72d32b,
per Coverity.  Reaching this would need catalog corruption.  Back-patch
to v12, like that commit.

7 months agoIn passwordFromFile, don't leak the open file after stat failures.
Tom Lane [Sun, 29 Sep 2024 17:40:03 +0000 (13:40 -0400)]
In passwordFromFile, don't leak the open file after stat failures.

Oversight in e882bcae0.  Per Coverity.

7 months agoAvoid 037_invalid_database.pl hang under debug_discard_caches.
Noah Misch [Fri, 27 Sep 2024 22:28:56 +0000 (15:28 -0700)]
Avoid 037_invalid_database.pl hang under debug_discard_caches.

Back-patch to v12 (all supported versions).

7 months agodoc: Note that CREATE MATERIALIZED VIEW restricts search_path.
Nathan Bossart [Fri, 27 Sep 2024 21:21:21 +0000 (16:21 -0500)]
doc: Note that CREATE MATERIALIZED VIEW restricts search_path.

Since v17, CREATE MATERIALIZED VIEW has set search_path to
"pg_catalog, pg_temp" while running the query.  The docs for the
other commands that restrict search_path mention it, but the page
for CREATE MATERIALIZED VIEW does not.  Fix that.

Oversight in commit 4b74ebf726.

Author: Yugo Nagata
Reviewed-by: Jeff Davis
Discussion: https://postgr.es/m/20240805160502.d2a4975802a832b1e04afb80%40sraoss.co.jp
Backpatch-through: 17

7 months agoRecalculate where-needed data accurately after a join removal.
Tom Lane [Fri, 27 Sep 2024 20:04:04 +0000 (16:04 -0400)]
Recalculate where-needed data accurately after a join removal.

Up to now, remove_rel_from_query() has done a pretty shoddy job
of updating our where-needed bitmaps (per-Var attr_needed and
per-PlaceHolderVar ph_needed relid sets).  It removed direct mentions
of the to-be-removed baserel and outer join, which is the minimum
amount of effort needed to keep the data structures self-consistent.
But it didn't account for the fact that the removed join ON clause
probably mentioned Vars of other relations, and those Vars might now
not be needed as high up in the join tree as before.  It's easy to
show cases where this results in failing to remove a lower outer join
that could also have been removed.

To fix, recalculate the where-needed bitmaps from scratch after
each successful join removal.  This sounds expensive, but it seems
to add only negligible planner runtime.  (We cheat a little bit
by preserving "relation 0" entries in the bitmaps, allowing us to
skip re-scanning the targetlist and HAVING qual.)

The submitted test case drew attention because we had successfully
optimized away the lower join prior to v16.  I suspect that that's
somewhat accidental and there are related cases that were never
optimized before and now can be.  I've not tried to come up with
one, though.

Perhaps we should back-patch this into v16 and v17 to repair the
performance regression.  However, since it took a year for anyone
to notice the problem, it can't be affecting too many people.  Let's
let the patch bake awhile in HEAD, and see if we get more complaints.

Per bug #18627 from MikaĆ«l Gourlaouen.  No back-patch for now.

Discussion: https://postgr.es/m/18627-44f950eb6a8416c2@postgresql.org

7 months agoReindent pg_verifybackup.c.
Robert Haas [Fri, 27 Sep 2024 15:14:31 +0000 (11:14 -0400)]
Reindent pg_verifybackup.c.

7 months agopg_verifybackup: Verify tar-format backups.
Robert Haas [Fri, 27 Sep 2024 12:40:24 +0000 (08:40 -0400)]
pg_verifybackup: Verify tar-format backups.

This also works for compressed tar-format backups. However, -n must be
used, because we use pg_waldump to verify WAL, and it doesn't yet know
how to verify WAL that is stored inside of a tarfile.

Amul Sul, reviewed by Sravan Kumar and by me, and revised by me.

7 months agoFix typo in pg_walsummary/nls.mk.
Fujii Masao [Fri, 27 Sep 2024 01:20:22 +0000 (10:20 +0900)]
Fix typo in pg_walsummary/nls.mk.

Author: Koki Nakamura
Discussion: https://postgr.es/m/485c613d1db8de2e8169d5afd43e7f9e@oss.nttdata.com

7 months agoFix incorrect memory access in VACUUM FULL with invalid toast indexes
Michael Paquier [Fri, 27 Sep 2024 00:40:09 +0000 (09:40 +0900)]
Fix incorrect memory access in VACUUM FULL with invalid toast indexes

An invalid toast index is skipped in reindex_relation().  These would be
remnants of a failed REINDEX CONCURRENTLY and they should never been
rebuilt as there can only be one valid toast index at a time.

REINDEX_REL_SUPPRESS_INDEX_USE, used by CLUSTER and VACUUM FULL, needs
to maintain a list of the indexes being processed.  The list of indexes
is retrieved from the relation cache, and includes invalid indexes.  The
code has missed that invalid toast indexes are ignored in
reindex_relation() as this leads to a hard failure in reindex_index(),
and they were left in the reindex pending list, making the list
inconsistent when rechecked.  The incorrect memory access was happening
when scanning pg_class for the refresh of pg_database.datfrozenxid, when
doing a scan of pg_class.

This issue exists since REINDEX CONCURRENTLY exists, where invalid toast
indexes can exist, so backpatch all the way down.

Reported-by: Alexander Lakhin
Author: Tender Wang
Discussion: https://postgr.es/m/18630-9aed99c38830657d@postgresql.org
Backpatch-through: 12

7 months agoFix catalog data of new LO privilege functions
Michael Paquier [Thu, 26 Sep 2024 22:26:29 +0000 (07:26 +0900)]
Fix catalog data of new LO privilege functions

This commit improves the catalog data in pg_proc for the three functions
for has_largeobject_privilege(), introduced in 4eada203a5a8:
- Fix their descriptions (typos and consistency).
- Reallocate OIDs to be within the 8000-9999 range as required by
a6417078c414.

Bump catalog version.

Reviewed-by: Fujii Masao
Discussion: https://postgr.es/m/[email protected]

7 months agoEnsure we have a snapshot when updating pg_index entries.
Nathan Bossart [Thu, 26 Sep 2024 20:51:23 +0000 (15:51 -0500)]
Ensure we have a snapshot when updating pg_index entries.

Creating, reindexing, and dropping an index concurrently could
entail accessing pg_index's TOAST table, which was recently added
in commit b52c4fc3c0.  These code paths start and commit their own
transactions, but they do not always set an active snapshot.  This
rightfully leads to assertion failures and ERRORs when trying to
access pg_index's TOAST table, such as the following:

ERROR:  cannot fetch toast data without an active snapshot

To fix, push an active snapshot just before each section of code
that might require accessing pg_index's TOAST table, and pop it
shortly afterwards.

Reported-by: Alexander Lakhin
Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/a97d7401-e7c9-f771-6a00-037379f0a8bb%40gmail.com

7 months agoImprove style of pg_upgrade task callback functions.
Nathan Bossart [Thu, 26 Sep 2024 18:54:37 +0000 (13:54 -0500)]
Improve style of pg_upgrade task callback functions.

I wanted to avoid adjusting this code too much when converting
these tasks to use the new parallelization framework (see commit
40e2e5e92b), which is why this is being done as a follow-up commit.
These stylistic adjustments result in fewer lines of code and fewer
levels of indentation in some places.

While at it, add names to the UpgradeTaskSlotState enum and the
UpgradeTaskSlot struct.  I'm not aware of any established project
policy in this area, but let's at least be consistent within the
same file.

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

7 months agoModernize to_char's Roman-numeral code, fixing overflow problems.
Tom Lane [Thu, 26 Sep 2024 15:02:31 +0000 (11:02 -0400)]
Modernize to_char's Roman-numeral code, fixing overflow problems.

int_to_roman() only accepts plain "int" input, which is fine since
we're going to produce '###############' for any value above 3999
anyway.  However, the numeric and int8 variants of to_char() would
throw an error if the given input exceeded the integer range, while
the float-input variants invoked undefined-per-C-standard behavior.
Fix things so that you uniformly get '###############' for out of
range input.

Also add test cases covering this code, plus the equally-untested
EEEE, V, and PL format codes.

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

7 months agoDoc: InitPlans aren't parallel-restricted any more.
Tom Lane [Thu, 26 Sep 2024 14:37:51 +0000 (10:37 -0400)]
Doc: InitPlans aren't parallel-restricted any more.

Commit e08d74ca1 removed that restriction, but missed updating
the documentation about it.  Noted by Egor Rogov.

Discussion: https://postgr.es/m/cdc8f87b-a378-4e22-6d29-40ae32dd97d1@postgrespro.ru

7 months agoDoc: Add a note in the upgrade of logical replication clusters.
Amit Kapila [Thu, 26 Sep 2024 10:44:07 +0000 (16:14 +0530)]
Doc: Add a note in the upgrade of logical replication clusters.

The steps used to upgrade the cluster first upgraded the publisher node
but ideally, any node could be upgraded first.

Author: Vignesh C
Discussion: https://postgr.es/m/CALDaNm1_iDO6srWzntqTr0ZDVkk2whVhNKEWAvtgZBfSmuBeZQ@mail.gmail.com
Discussion: https://postgr.es/m/CALDaNm3Y-M+kAqr_mf=_C1kNwAB-cS6S5hTHnKMEqDw4sGEh4Q@mail.gmail.com

7 months agoUpdate oid for pg_wal_replay_wait() procedure
Alexander Korotkov [Thu, 26 Sep 2024 08:48:23 +0000 (11:48 +0300)]
Update oid for pg_wal_replay_wait() procedure

Use an oid from 8000-9999 range, as required by 98eab30b93d5.

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/ZvUY6bfTwB0GsyzP%40paquier.xyz

7 months agoRemove extra whitespace in pg_upgrade status message.
Nathan Bossart [Wed, 25 Sep 2024 16:18:56 +0000 (11:18 -0500)]
Remove extra whitespace in pg_upgrade status message.

There's no need to add another level of indentation to this status
message.  pg_log() will put it in the right place.

Oversight in commit 347758b120.

Reviewed-by: Daniel Gustafsson
Discussion: https://postgr.es/m/ZunW7XHLd2uTts4f%40nathan
Backpatch-through: 17

7 months agoTurn 'if' condition around to avoid Svace complaint
Alvaro Herrera [Wed, 25 Sep 2024 14:42:02 +0000 (16:42 +0200)]
Turn 'if' condition around to avoid Svace complaint

The unwritten assumption of this code is that both events->head and
events->tail are NULL together (an empty list) or they aren't.  So the
code was testing events->head for nullness and using that as a cue to
deference events->tail, which annoys the Svace static code analyzer.
We can silence it by testing events->tail member instead, and add an
assertion about events->head to ensure it's all consistent.

This code is very old and as far as we know, there's never been a bug
report related to this, so there's no need to backpatch.

This was found by the ALT Linux Team using Svace.

Author: Alexander Kuznetsov <[email protected]>
Discussion: https://postgr.es/m/6d0323c3-3f5d-4137-af73-98a5ab90e77c@altlinux.org

7 months agovacuumdb: Skip temporary tables in query to build list of relations
Michael Paquier [Wed, 25 Sep 2024 05:43:16 +0000 (14:43 +0900)]
vacuumdb: Skip temporary tables in query to build list of relations

Running vacuumdb with a non-superuser while another user has created a
temporary table would lead to a mid-flight permission failure,
interrupting the operation.  vacuum_rel() skips temporary relations of
other backends, and it makes no sense for vacuumdb to know about these
relations, so let's switch it to ignore temporary relations entirely.

Adding a qual in the query based on relpersistence simplifies the
generation of its WHERE clause in vacuum_one_database(), per se the
removal of "has_where".

Author: VaibhaveS, Michael Paquier
Reviewed-by: Fujii Masao
Discussion: https://postgr.es/m/CAM_eQjwfAR=y3G1fGyS1U9FTmc+FyJm9amNfY2QCZBnDDbNPZg@mail.gmail.com
Backpatch-through: 12

7 months agoDoc: Add the steps for upgrading the logical replication cluster.
Amit Kapila [Wed, 25 Sep 2024 04:36:10 +0000 (10:06 +0530)]
Doc: Add the steps for upgrading the logical replication cluster.

Author: Vignesh C
Reviewed-by: Peter Smith, Amit Kapila, Hayato Kuroda, Bharath Rupireddy
Discussion: https://postgr.es/m/CALDaNm1_iDO6srWzntqTr0ZDVkk2whVhNKEWAvtgZBfSmuBeZQ@mail.gmail.com

7 months agopg_stat_statements: Expand tests for SET statements
Michael Paquier [Wed, 25 Sep 2024 01:04:44 +0000 (10:04 +0900)]
pg_stat_statements: Expand tests for SET statements

There are many grammar flavors that depend on the parse node
VariableSetStmt.  This closes the gap in pg_stat_statements by providing
test coverage for what should be a large majority of them, improving more
the work begun in de2aca288569.  This will be used to ease the
evaluation of a path towards more normalization of SET queries with
query jumbling.

Note that SET NAMES (grammar from the standard, synonym of SET
client_encoding) is omitted on purpose, this could use UTF8 with a
conditional script where UTF8 is supported, but that does not seem worth
the maintenance cost for the sake of these tests.

The author has submitted most of these in a TAP test (filled in any
holes I could spot), still queries in a SQL file of pg_stat_statements
is able to achieve the same goal while being easier to look at when
testing normalization patterns.

Author: Greg Sabino Mullane, Michael Paquier
Discussion: https://postgr.es/m/CAKAnmmJtJY2jzQN91=2QAD2eAJAA-Per61eyO48-TyxEg-q0Rg@mail.gmail.com

7 months agoFor inplace update durability, make heap_update() callers wait.
Noah Misch [Tue, 24 Sep 2024 22:25:18 +0000 (15:25 -0700)]
For inplace update durability, make heap_update() callers wait.

The previous commit fixed some ways of losing an inplace update.  It
remained possible to lose one when a backend working toward a
heap_update() copied a tuple into memory just before inplace update of
that tuple.  In catalogs eligible for inplace update, use LOCKTAG_TUPLE
to govern admission to the steps of copying an old tuple, modifying it,
and issuing heap_update().  This includes MERGE commands.  To avoid
changing most of the pg_class DDL, don't require LOCKTAG_TUPLE when
holding a relation lock sufficient to exclude inplace updaters.
Back-patch to v12 (all supported versions).  In v13 and v12, "UPDATE
pg_class" or "UPDATE pg_database" can still lose an inplace update.  The
v14+ UPDATE fix needs commit 86dc90056dfdbd9d1b891718d2e5614e3e432f35,
and it wasn't worth reimplementing that fix without such infrastructure.

Reviewed by Nitin Motiani and (in earlier versions) Heikki Linnakangas.

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

7 months agoFix data loss at inplace update after heap_update().
Noah Misch [Tue, 24 Sep 2024 22:25:18 +0000 (15:25 -0700)]
Fix data loss at inplace update after heap_update().

As previously-added tests demonstrated, heap_inplace_update() could
instead update an unrelated tuple of the same catalog.  It could lose
the update.  Losing relhasindex=t was a source of index corruption.
Inplace-updating commands like VACUUM will now wait for heap_update()
commands like GRANT TABLE and GRANT DATABASE.  That isn't ideal, but a
long-running GRANT already hurts VACUUM progress more just by keeping an
XID running.  The VACUUM will behave like a DELETE or UPDATE waiting for
the uncommitted change.

For implementation details, start at the systable_inplace_update_begin()
header comment and README.tuplock.  Back-patch to v12 (all supported
versions).  In back branches, retain a deprecated heap_inplace_update(),
for extensions.

Reported by Smolkin Grigory.  Reviewed by Nitin Motiani, (in earlier
versions) Heikki Linnakangas, and (in earlier versions) Alexander
Lakhin.

Discussion: https://postgr.es/m/CAMp+ueZQz3yDk7qg42hk6-9gxniYbp-=bG2mgqecErqR5gGGOA@mail.gmail.com

7 months agoWarn if LOCKTAG_TUPLE is held at commit, under debug_assertions.
Noah Misch [Tue, 24 Sep 2024 22:25:18 +0000 (15:25 -0700)]
Warn if LOCKTAG_TUPLE is held at commit, under debug_assertions.

The current use always releases this locktag.  A planned use will
continue that intent.  It will involve more areas of code, making unlock
omissions easier.  Warn under debug_assertions, like we do for various
resource leaks.  Back-patch to v12 (all supported versions), the plan
for the commit of the new use.

Reviewed by Heikki Linnakangas.

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

7 months agoAllow length=-1 for NUL-terminated input to pg_strncoll(), etc.
Jeff Davis [Tue, 24 Sep 2024 22:15:03 +0000 (15:15 -0700)]
Allow length=-1 for NUL-terminated input to pg_strncoll(), etc.

Like ICU, allow a length of -1 to be specified for NUL-terminated
arguments to pg_strncoll(), pg_strnxfrm(), and pg_strnxfrm_prefix().

Simplifies the code and comments.

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

7 months agoFix psql describe commands' handling of ACL columns for old servers.
Tom Lane [Tue, 24 Sep 2024 21:21:38 +0000 (17:21 -0400)]
Fix psql describe commands' handling of ACL columns for old servers.

Commit d1379ebf4 carelessly broke printACLColumn for pre-9.4 servers,
by using the cardinality() function which we introduced in 9.4.
We expect psql's describe-related commands to work back to 9.2, so
this is bad.  Use the longstanding array_length() function instead.

Per report from Christoph Berg.  Back-patch to v17.

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

7 months agoTighten up make_libc_collator() and make_icu_collator().
Jeff Davis [Tue, 24 Sep 2024 19:01:45 +0000 (12:01 -0700)]
Tighten up make_libc_collator() and make_icu_collator().

Ensure that error paths within these functions do not leak a collator,
and return the result rather than using an out parameter. (Error paths
in the caller may still result in a leaked collator, which will be
addressed separately.)

In make_libc_collator(), if the first newlocale() succeeds and the
second one fails, close the first locale_t object.

The function make_icu_collator() doesn't have any external callers, so
change it to be static.

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

7 months agoAdd further excludes to headerscheck
Peter Eisentraut [Tue, 24 Sep 2024 18:41:47 +0000 (20:41 +0200)]
Add further excludes to headerscheck

Some header files under contrib/isn/ are not meant to be included
independently, and they fail -Wmissing-variable-declarations when
doing so.

Reported-by: Thomas Munro <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CA%2BhUKG%2BYVt5MBD-w0HyHpsGb4U8RNge3DvAbDmOFy_epGhZ2Mg%40mail.gmail.com#aba3226c6dd493923bd6ce95d25a2d77

7 months agoNeaten up our choices of SQLSTATEs for XML-related errors.
Tom Lane [Tue, 24 Sep 2024 16:59:43 +0000 (12:59 -0400)]
Neaten up our choices of SQLSTATEs for XML-related errors.

When our XML-handling modules were first written, the SQL standard
lacked any error codes that were particularly intended for XML
error conditions.  Unsurprisingly, this led to some rather random
choices of errcodes in those modules.  Now the standard has a whole
SQLSTATE class, "Class 10 - XQuery Error", with a reasonably large
selection of relevant-looking errcodes.

In this patch I've chosen one fairly generic code defined by the
standard, 10608 = invalid_argument_for_xquery, and used it where
it seemed appropriate.  I've also made an effort to replace
ERRCODE_INTERNAL_ERROR everywhere it was not clearly reporting
a coding problem; in particular, many of the existing uses look
like they can fairly be reported as ERRCODE_OUT_OF_MEMORY.

It might be interesting to try to map libxml2's error codes into
the standard's new collection, but I've not undertaken that here.

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

7 months agoUpdate obsolete nbtree array preprocessing comments.
Peter Geoghegan [Tue, 24 Sep 2024 16:58:55 +0000 (12:58 -0400)]
Update obsolete nbtree array preprocessing comments.

The array->scan_key references fixed up at the end of preprocessing
start out as offsets into the arrayKeyData[] array (the array returned
by _bt_preprocess_array_keys at the start of preprocessing that involves
array scan keys).  Offsets into the arrayKeyData[] array are no longer
guaranteed to be valid offsets into our original scan->keyData[] input
scan key array, but comments describing the array->scan_key references
still talked about scan->keyData[].  Update those comments.

Oversight in commit b5249741.

7 months agoAdd ONLY support for VACUUM and ANALYZE
David Rowley [Tue, 24 Sep 2024 06:03:40 +0000 (18:03 +1200)]
Add ONLY support for VACUUM and ANALYZE

Since autovacuum does not trigger an ANALYZE for partitioned tables,
users must perform these manually.  However, performing a manual ANALYZE
on a partitioned table would always result in recursively analyzing each
partition and that could be undesirable as autovacuum takes care of that.
For partitioned tables that contain a large number of partitions, having
to analyze each partition could take an unreasonably long time, especially
so for tables with a large number of columns.

Here we allow the ONLY keyword to prefix the name of the table to allow
users to have ANALYZE skip processing partitions.  This option can also
be used with VACUUM, but there is no work to do if VACUUM ONLY is used on
a partitioned table.

This commit also changes the behavior of VACUUM and ANALYZE for
inheritance parents.  Previously inheritance child tables would not be
processed when operating on the parent.  Now, by default we *do* operate
on the child tables.  ONLY can be used to obtain the old behavior.
The release notes should note this as an incompatibility.  The default
behavior has not changed for partitioned tables as these always
recursively processed the partitions.

Author: Michael Harris <[email protected]>
Discussion: https://postgr.es/m/CADofcAWATx_haD=QkSxHbnTsAe6+e0Aw8Eh4H8cXyogGvn_kOg@mail.gmail.com
Discussion: https://postgr.es/m/CADofcAXVbD0yGp_EaC9chmzsOoSai3jcfBCnyva3j0RRdRvMVA@mail.gmail.com
Reviewed-by: Jelte Fennema-Nio <[email protected]>
Reviewed-by: Melih Mutlu <[email protected]>
Reviewed-by: Atsushi Torikoshi <[email protected]>
Reviewed-by: jian he <[email protected]>
Reviewed-by: David Rowley <[email protected]>
7 months agoRemove ATT_TABLE for ALTER TABLE ... ATTACH/DETACH
Michael Paquier [Mon, 23 Sep 2024 23:59:08 +0000 (08:59 +0900)]
Remove ATT_TABLE for ALTER TABLE ... ATTACH/DETACH

Attempting these commands for a non-partitioned table would result in a
failure when creating the relation in transformPartitionCmd().  This
gives the possibility to throw an error earlier with a much better error
message, thanks to d69a3f4d70b7.

The extra test cases are from me.  Note that FINALIZE uses a different
subcommand and it had no coverage for its failure path with
non-partitioned tables.

Author: Ćlvaro Herrera, Michael Paquier
Reviewed-by: Nathan Bossart
Discussion: https://postgr.es/m/202409190803[email protected]

7 months agojsonapi: fix memory leakage during OOM error recovery.
Tom Lane [Mon, 23 Sep 2024 16:30:51 +0000 (12:30 -0400)]
jsonapi: fix memory leakage during OOM error recovery.

Coverity pointed out that inc_lex_level() would leak memory
(not to mention corrupt the pstack data structure) if some
but not all of its three REALLOC's failed.  To fix, store
successfully-updated pointers back into the pstack struct
immediately.

Oversight in 0785d1b8b, so no need for back-patch.

7 months agoFix asserts in fast-path locking code
Tomas Vondra [Mon, 23 Sep 2024 09:37:12 +0000 (11:37 +0200)]
Fix asserts in fast-path locking code

Commit c4d5cb71d229 introduced a couple asserts in the fast-path locking
code, upsetting Coverity.

The assert in InitProcGlobal() is clearly wrong, as it assigns instead
of checking the value. This is harmless, but doesn't check anything.

The asserts in FAST_PATH_ macros are written as if for signed values,
but the macros are only called for unsigned ones. That makes the check
for (val >= 0) useless. Checks written as ((uint32) x < max) work for
both signed and unsigned values. Negative values should wrap to values
greater than INT32_MAX.

Per Coverity, report by Tom Lane.

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

7 months agoAdd memory/disk usage for more executor nodes.
Tatsuo Ishii [Mon, 23 Sep 2024 07:34:24 +0000 (16:34 +0900)]
Add memory/disk usage for more executor nodes.

This commit is similar to 95d6e9af07, expanding the idea to CTE scan,
table function scan and recursive union scan nodes so that the maximum
tuplestore memory or disk usage is shown with EXPLAIN ANALYZE command.

Also adjust show_storage_info() so that it accepts storage type and
storage size arguments instead of Tuplestorestate. This allows the
node types to share the formatting code using show_storage_info(). Due
to this show_material_info() and show_windowagg_info() are also
modified.

Reviewed-by: David Rowley
Discussion: https://postgr.es/m/20240918.211246.1127161704188186085.ishii%40postgresql.org

7 months agoRemove pg_authid's TOAST table.
Nathan Bossart [Sat, 21 Sep 2024 20:17:46 +0000 (15:17 -0500)]
Remove pg_authid's TOAST table.

pg_authid's only varlena column is rolpassword, which unfortunately
cannot be de-TOASTed during authentication because we haven't
selected a database yet and cannot read pg_class.  By removing
pg_authid's TOAST table, attempts to set password hashes that
require out-of-line storage will fail with a "row is too big"
error instead.  We may want to provide a more user-friendly error
in the future, but for now let's just remove the useless TOAST
table.

Bumps catversion.

Reported-by: Alexander Lakhin
Reviewed-by: Tom Lane, Michael Paquier
Discussion: https://postgr.es/m/89e8649c-eb74-db25-7945-6d6b23992394%40gmail.com

7 months agoIncrease the number of fast-path lock slots
Tomas Vondra [Sat, 21 Sep 2024 18:06:49 +0000 (20:06 +0200)]
Increase the number of fast-path lock slots

Replace the fixed-size array of fast-path locks with arrays, sized on
startup based on max_locks_per_transaction. This allows using fast-path
locking for workloads that need more locks.

The fast-path locking introduced in 9.2 allowed each backend to acquire
a small number (16) of weak relation locks cheaply. If a backend needs
to hold more locks, it has to insert them into the shared lock table.
This is considerably more expensive, and may be subject to contention
(especially on many-core systems).

The limit of 16 fast-path locks was always rather low, because we have
to lock all relations - not just tables, but also indexes, views, etc.
For planning we need to lock all relations that might be used in the
plan, not just those that actually get used in the final plan. So even
with rather simple queries and schemas, we often need significantly more
than 16 locks.

As partitioning gets used more widely, and the number of partitions
increases, this limit is trivial to hit. Complex queries may easily use
hundreds or even thousands of locks. For workloads doing a lot of I/O
this is not noticeable, but for workloads accessing only data in RAM,
the access to the shared lock table may be a serious issue.

This commit removes the hard-coded limit of the number of fast-path
locks. Instead, the size of the fast-path arrays is calculated at
startup, and can be set much higher than the original 16-lock limit.
The overall fast-path locking protocol remains unchanged.

The variable-sized fast-path arrays can no longer be part of PGPROC, but
are allocated as a separate chunk of shared memory and then references
from the PGPROC entries.

The fast-path slots are organized as a 16-way set associative cache. You
can imagine it as a hash table of 16-slot "groups". Each relation is
mapped to exactly one group using hash(relid), and the group is then
processed using linear search, just like the original fast-path cache.
With only 16 entries this is cheap, with good locality.

Treating this as a simple hash table with open addressing would not be
efficient, especially once the hash table gets almost full. The usual
remedy is to grow the table, but we can't do that here easily. The
access would also be more random, with worse locality.

The fast-path arrays are sized using the max_locks_per_transaction GUC.
We try to have enough capacity for the number of locks specified in the
GUC, using the traditional 2^n formula, with an upper limit of 1024 lock
groups (i.e. 16k locks). The default value of max_locks_per_transaction
is 64, which means those instances will have 64 fast-path slots.

The main purpose of the max_locks_per_transaction GUC is to size the
shared lock table. It is often set to the "average" number of locks
needed by backends, with some backends using significantly more locks.
This should not be a major issue, however. Some backens may have to
insert locks into the shared lock table, but there can't be too many of
them, limiting the contention.

The only solution is to increase the GUC, even if the shared lock table
already has sufficient capacity. That is not free, especially in terms
of memory usage (the shared lock table entries are fairly large). It
should only happen on machines with plenty of memory, though.

In the future we may consider a separate GUC for the number of fast-path
slots, but let's try without one first.

Reviewed-by: Robert Haas, Jakub Wartak
Discussion: https://postgr.es/m/510b887e-c0ce-4a0c-a17a-2c6abb8d9a5c@enterprisedb.com

7 months agoRefactor handling of nbtree array redundancies.
Peter Geoghegan [Sat, 21 Sep 2024 17:25:49 +0000 (13:25 -0400)]
Refactor handling of nbtree array redundancies.

Teach _bt_preprocess_array_keys to eliminate redundant array equality
scan keys directly, rather than just marking them as redundant.  Its
_bt_preprocess_keys caller is no longer required to ignore input scan
keys that were marked redundant in this way.  Oversights like the one
fixed by commit f22e17f7 are no longer possible.

The new scheme also makes it easier for _bt_preprocess_keys to output a
so.keyData[] scan key array with _more_ scan keys than it was passed in
its scan.keyData[] input scan key array.  An upcoming patch that adds
skip scan optimizations to nbtree will take advantage of this.

In passing, remove and rename certain _bt_preprocess_keys variables to
make the difference between our input scan key array and our output scan
key array clearer.

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

7 months agoImprove Asserts checking relation matching in parallel scans.
Tom Lane [Fri, 20 Sep 2024 20:37:55 +0000 (16:37 -0400)]
Improve Asserts checking relation matching in parallel scans.

table_beginscan_parallel and index_beginscan_parallel contain
Asserts checking that the relation a worker will use in
a parallel scan is the same one the leader intended.  However,
they were checking for relation OID match, which was not strong
enough to detect the mismatch problem fixed in 126ec0bc7.
What would be strong enough is to compare relfilenodes instead.
Arguably, that's a saner definition anyway, since a scan surely
operates on a physical relation not a logical one.  Hence,
store and compare RelFileLocators not relation OIDs.  Also
ensure that index_beginscan_parallel checks the index identity
not just the table identity.

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

7 months agoAlphabetize #include directives in pg_checksums.c.
Nathan Bossart [Fri, 20 Sep 2024 20:18:42 +0000 (15:18 -0500)]
Alphabetize #include directives in pg_checksums.c.

Author: Michael Banck
Discussion: https://postgr.es/m/66edaed0.050a0220.32a9ba.42c8%40mx.google.com

7 months agoDoc: explain how to test ADMIN privilege with pg_has_role().
Tom Lane [Fri, 20 Sep 2024 19:56:34 +0000 (15:56 -0400)]
Doc: explain how to test ADMIN privilege with pg_has_role().

This has always been possible, but the syntax is a bit obscure,
and our user-facing docs were not very helpful.  Spell it out
more clearly.

Per complaint from Dominique Devienne.  Back-patch to
all supported branches.

Discussion: https://postgr.es/m/CAFCRh-8JNEy+dV4SXFOrWca50u+d=--TO4cq=+ac1oBtfJy4AA@mail.gmail.com

7 months agoFix nbtree pgstats accounting with parallel scans.
Peter Geoghegan [Fri, 20 Sep 2024 18:06:32 +0000 (14:06 -0400)]
Fix nbtree pgstats accounting with parallel scans.

Commit 5bf748b8, which enhanced nbtree ScalarArrayOp execution, made
parallel index scans work with the new design for arrays via explicit
scheduling of primitive index scans.  Under this scheme a parallel index
scan with array keys will perform the same number of index descents as
an equivalent serial index scan (barring corner cases where an
individual parallel worker discovers that it can advance the scan's
array keys without anybody needing to perform another descent of the
index to get to the relevant page on the leaf level).

Despite all this, the pgstats accounting wasn't updated; it continued to
increment the total number of index scans for the rel once per _bt_first
call, no matter the details.  As a result, the number of (primitive)
index scans could be over-counted during parallel scans.

To fix, delay incrementing the count of index scans until after we've
established that another descent of the index (using either _bt_search
or _bt_endpoint) is required.  That way pg_stat_user_tables.idx_scan
always advances in the same way, regardless of whether or not the scan
makes use of parallelism.

Oversight in commit 5bf748b8, which enhanced nbtree ScalarArrayOp
execution.

Author: Peter Geoghegan <[email protected]>
Reviewed-By: Tomas Vondra <[email protected]>
Discussion: https://postgr.es/m/CAH2-Wz=E7XrkvscBN0U6V81NK3Q-dQOmivvbEsjG-zwEfDdFpg@mail.gmail.com
Discussion: https://postgr.es/m/CAH2-WzkRqvaqR2CTNqTZP0z6FuL4-3ED6eQB0yx38XBNj1v-4Q@mail.gmail.com
Backpatch: 17-, where nbtree SAOP execution was enhanced.

7 months agoAdd parameter "connstr" to PostgreSQL::Test::Cluster::background_psql
Michael Paquier [Fri, 20 Sep 2024 00:49:43 +0000 (09:49 +0900)]
Add parameter "connstr" to PostgreSQL::Test::Cluster::background_psql

Like for Cluster::psql, this can be handy to force the use of a
connection string with some values overriden, like a "host".

Author: Aidar Imamov
Discussion: https://postgr.es/m/ecacb079efc533aed3c234cbcb5b07b6@postgrespro.ru

7 months agoRestore relmapper state early enough in parallel workers.
Tom Lane [Fri, 20 Sep 2024 00:58:17 +0000 (20:58 -0400)]
Restore relmapper state early enough in parallel workers.

We need to do RestoreRelationMap before loading catalog-derived
state, else the worker may end up with catalog relcache entries
containing stale relfilenode data.  Move up RestoreReindexState
too, on the principle that that should also happen before we
do much of any catalog access.

I think ideally these things would happen even before InitPostgres,
but there are various problems standing in the way of that, notably
that the relmapper thinks "active" mappings should be discarded at
transaction end.  The implication of this is that InitPostgres and
RestoreLibraryState will see the same catalog state as an independent
backend would see, which is probably fine; at least, it's been like
that all along.

Per report from Justin Pryzby.  There is a case to be made that
this should be back-patched.  But given the lack of complaints
before 6e086fa2e and the short amount of time remaining before
17.0 wraps, I'll just put it in HEAD for now.

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

7 months agopsql: Add tests for repeated calls of \bind[_named]
Michael Paquier [Thu, 19 Sep 2024 23:59:20 +0000 (08:59 +0900)]
psql: Add tests for repeated calls of \bind[_named]

The implementation assumes that on multiple calls of these meta-commands
the last one wins.  Multiple \g calls in-between mean multiple
executions.

There were no tests to check these properties, hence let's add
something.

Author: Jelte Fennema-Nio, Michael Paquier
Discussion: https://postgr.es/m/CAGECzQSTE7CoM=Gst56Xj8pOvjaPr09+7jjtWqTC40pGETyAuA@mail.gmail.com

7 months agodoc PG relnotes: remove warning about commit links in PDF build
Bruce Momjian [Thu, 19 Sep 2024 22:05:22 +0000 (18:05 -0400)]
doc PG relnotes:  remove warning about commit links in PDF build

Make paragraph empty instead of removing it.

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

Backpatch-through: 12

7 months agodoc PG relnotes: document "Unresolved ID reference found" cause
Bruce Momjian [Thu, 19 Sep 2024 16:01:59 +0000 (12:01 -0400)]
doc PG relnotes:  document "Unresolved ID reference found" cause

Backpatch-through: 12

7 months agodoc PG relnotes: rename commit link paragraph for clarity
Bruce Momjian [Thu, 19 Sep 2024 13:47:22 +0000 (09:47 -0400)]
doc PG relnotes:  rename commit link paragraph for clarity

FYI, during PDF builds, this link type generates a "Unresolved ID
reference found" warning because it is suppressed from the PDF output.

Backpatch-through: 12

7 months agoImprove Perl script which adds commit links to release notes
Bruce Momjian [Thu, 19 Sep 2024 12:45:33 +0000 (08:45 -0400)]
Improve Perl script which adds commit links to release notes

Reported-by: Andrew Dunstan
Discussion: https://postgr.es/m/b2465837-56df-4794-a0b5-5e6ed44ed870@dunslane.net

Author: Andrew Dunstan

Backpatch-through: 12

7 months agoAdd UpgradeTaskProcessCB to typedefs.list
Alexander Korotkov [Thu, 19 Sep 2024 11:34:52 +0000 (14:34 +0300)]
Add UpgradeTaskProcessCB to typedefs.list

While it doesn't directly influence indentation right now, add it for
uniformity.

7 months agoFix order of includes in src/bin/pg_upgrade/info.c
Alexander Korotkov [Thu, 19 Sep 2024 11:34:00 +0000 (14:34 +0300)]
Fix order of includes in src/bin/pg_upgrade/info.c

7 months agoMove pg_wal_replay_wait() to xlogfuncs.c
Alexander Korotkov [Thu, 19 Sep 2024 11:26:03 +0000 (14:26 +0300)]
Move pg_wal_replay_wait() to xlogfuncs.c

This commit moves pg_wal_replay_wait() procedure to be a neighbor of
WAL-related functions in xlogfuncs.c.  The implementation of LSN waiting
continues to reside in the same place.

By proposal from Michael Paquier.

Reported-by: Peter Eisentraut
Discussion: https://postgr.es/m/18c0fa64-0475-415e-a1bd-665d922c5201%40eisentraut.org

7 months agopsql: Clean up more aggressively state of \bind[_named], \parse and \close
Michael Paquier [Thu, 19 Sep 2024 06:39:01 +0000 (15:39 +0900)]
psql: Clean up more aggressively state of \bind[_named], \parse and \close

This fixes a couple of issues with the psql meta-commands mentioned
above when called repeatedly:
- The statement name is reset for each call.  If a command errors out,
its send_mode would still be set, causing an incorrect path to be taken
when processing a query.  For \bind_named, this could trigger an
assertion failure as a statement name is always expected for this
meta-command.  This issue has been introduced by d55322b0da60.
- The memory allocated for bind parameters can be leaked.  This is a bug
enlarged by d55322b0da60 that exists since 5b66de3433e2, as it is also
possible to leak memory with \bind in v16 and v17.  This requires a fix
that will be done on the affected branches separately.  This issue is
taken care of here for HEAD.

This patch tightens the cleanup of the state used for the extended
protocol meta-commands (bind parameters, send mode, statement name) by
doing it before running each meta-command on top of doing it once a
query has been processed, avoiding any leaks and the inconsistencies
when mixing calls, by refactoring the cleanup in a single routine used
in all the code paths where this step is required.

Reported-by: Alexander Lakhin
Author: Anthonin Bonnefoy
Discussion: https://postgr.es/m/2e5b89af-a351-ff0a-000c-037ac28314ab@gmail.com

7 months agoIntroduce ATT_PARTITIONED_TABLE in tablecmds.c
Michael Paquier [Thu, 19 Sep 2024 03:22:56 +0000 (12:22 +0900)]
Introduce ATT_PARTITIONED_TABLE in tablecmds.c

Partitioned tables and normal tables have been relying on ATT_TABLE in
ATSimplePermissions() to produce error messages that depend on the
relation's relkind, because both relkinds currently support the same set
of ALTER TABLE subcommands.

A patch to restrict SET LOGGED/UNLOGGED for partitioned tables is under
discussion, and introducing ATT_PARTITIONED_TABLE makes subcommand
restrictions for partitioned tables easier to deal with, so let's add
one.  There is no functional change.

Author: Michael Paquier
Reviewed-by: Nathan Bossart
Discussion: https://postgr.es/m/[email protected]

7 months agoOptimize tuplestore usage for WITH RECURSIVE CTEs
David Rowley [Thu, 19 Sep 2024 03:20:35 +0000 (15:20 +1200)]
Optimize tuplestore usage for WITH RECURSIVE CTEs

nodeRecursiveunion.c makes use of two tuplestores and, until now, would
delete and recreate one of these tuplestores after every recursive
iteration.

Here we adjust that behavior and instead reuse one of the existing
tuplestores and just empty it of all tuples using tuplestore_clear().

This saves some free/malloc roundtrips and has shown a 25-30% performance
improvement for queries that perform very little work between recursive
iterations.

This also paves the way to add some EXPLAIN ANALYZE telemetry output for
recursive common table expressions, similar to what was done in 1eff8279d
and 95d6e9af0.  Previously calling tuplestore_end() would have caused
the maximum storage space used to be lost.

Reviewed-by: Tatsuo Ishii
Discussion: https://postgr.es/m/CAApHDvr9yW0YRiK8A2J7nvyT8g17YzbSfOviEWrghazKZbHbig@mail.gmail.com

7 months agodoc PG relnotes: add paragraph explaining the section symbol
Bruce Momjian [Wed, 18 Sep 2024 21:13:19 +0000 (17:13 -0400)]
doc PG relnotes:  add paragraph explaining the section symbol

And suppress the symbol in print mode, where the section symbol does not
appear.

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

Backpatch-through: 12

7 months agodoc PG relnotes: no relnote footnotes for commit links in PDF
Bruce Momjian [Wed, 18 Sep 2024 20:34:52 +0000 (16:34 -0400)]
doc PG relnotes: no relnote footnotes for commit links in PDF

In print output, there are too many commit links for footnotes in the
release notes to be useful.

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

Backpatch-through: 12

7 months agoAdd TOAST table to pg_index.
Nathan Bossart [Wed, 18 Sep 2024 19:42:57 +0000 (14:42 -0500)]
Add TOAST table to pg_index.

This change allows pg_index rows to use out-of-line storage for the
"indexprs" and "indpred" columns, which enables use-cases such as
very large index expressions.

This system catalog was previously not given a TOAST table due to a
fear of circularity issues (see commit 96cdeae07f).  Testing has
not revealed any such problems, and it seems unlikely that the
entries for system indexes could ever need out-of-line storage.  In
any case, it is still early in the v18 development cycle, so
committing this now will hopefully increase the chances of finding
any unexpected problems prior to release.

Bumps catversion.

Reported-by: Jonathan Katz
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/b611015f-b423-458c-aa2d-be0e655cc1b4%40postgresql.org

7 months agodocs: Improve the description of num_timed column in pg_stat_checkpointer.
Fujii Masao [Wed, 18 Sep 2024 17:14:10 +0000 (02:14 +0900)]
docs: Improve the description of num_timed column in pg_stat_checkpointer.

The previous documentation stated that num_timed reflects the number of
scheduled checkpoints performed. However, checkpoints may be skipped
if the server has been idle, and num_timed counts both skipped and completed
checkpoints. This commit clarifies the description to make it clear that
the counter includes both skipped and completed checkpoints.

Back-patch to v17 where pg_stat_checkpointer was added.

Author: Fujii Masao
Reviewed-by: Alexander Korotkov
Discussion: https://postgr.es/m/9ea77f40-818d-4841-9dee-158ac8f6e690@oss.nttdata.com

7 months agoAdd some sanity checks in executor for query ID reporting
Michael Paquier [Wed, 18 Sep 2024 05:43:37 +0000 (14:43 +0900)]
Add some sanity checks in executor for query ID reporting

This commit adds three sanity checks in code paths of the executor where
it is possible to use hooks, checking that a query ID is reported in
pg_stat_activity if compute_query_id is enabled:
- ExecutorRun()
- ExecutorFinish()
- ExecutorEnd()

This causes the test in pg_stat_statements added in 933848d16dc9 to
complain immediately in ExecutorRun().  The idea behind this commit is
to help extensions to detect if they are missing query ID reports when a
query goes through the executor.  Perhaps this will prove to be a bad
idea, but let's see where this experience goes in v18 and newer
versions.

Reviewed-by: Sami Imseih
Discussion: https://postgr.es/m/[email protected]

7 months agopostgres_fdw: Extend postgres_fdw_get_connections to return user name.
Fujii Masao [Wed, 18 Sep 2024 03:51:48 +0000 (12:51 +0900)]
postgres_fdw: Extend postgres_fdw_get_connections to return user name.

This commit adds a "user_name" output column to
the postgres_fdw_get_connections function, returning the name
of the local user mapped to the foreign server for each connection.
If a public mapping is used, it returns "public."

This helps identify postgres_fdw connections more easily,
such as determining which connections are invalid, closed,
or used within the current transaction.

No extension version bump is needed, as commit c297a47c5f
already handled it for v18~.

Author: Hayato Kuroda
Reviewed-by: Fujii Masao
Discussion: https://postgr.es/m/b492a935-6c7e-8c08-e485-3c1d64d7d10f@oss.nttdata.com

7 months agoExtend PgStat_HashKey.objid from 4 to 8 bytes
Michael Paquier [Wed, 18 Sep 2024 03:44:15 +0000 (12:44 +0900)]
Extend PgStat_HashKey.objid from 4 to 8 bytes

This opens the possibility to define keys for more types of statistics
kinds in PgStat_HashKey, the first case being 8-byte query IDs for
statistics like pg_stat_statements.

This increases the size of PgStat_HashKey from 12 to 16 bytes, while
PgStatShared_HashEntry, entry stored in the dshash for pgstats, keeps
the same size due to alignment.

xl_xact_stats_item, that tracks the stats items to drop in commit WAL
records, is increased from 12 to 16 bytes.  Note that individual chunks
in commit WAL records should be multiples of sizeof(int), hence 8-byte
object IDs are stored as two uint32, based on a suggestion from Heikki
Linnakangas.

While on it, the field of PgStat_HashKey is renamed from "objoid" to
"objid", as for some stats kinds this field does not refer to OIDs but
just IDs, like for replication slot stats.

This commit bumps the following format variables:
- PGSTAT_FILE_FORMAT_ID, as PgStat_HashKey is written to the stats file
for non-serialized stats kinds in the dshash table.
- XLOG_PAGE_MAGIC for the changes in xl_xact_stats_item.
- Catalog version, for the SQL function pg_stat_have_stats().

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

7 months agoDon't enter parallel mode when holding interrupts.
Noah Misch [Wed, 18 Sep 2024 02:53:11 +0000 (19:53 -0700)]
Don't enter parallel mode when holding interrupts.

Doing so caused the leader to hang in wait_event=ParallelFinish, which
required an immediate shutdown to resolve.  Back-patch to v12 (all
supported versions).

Francesco Degrassi

Discussion: https://postgr.es/m/CAC-SaSzHUKT=vZJ8MPxYdC_URPfax+yoA1hKTcF4ROz_Q6z0_Q@mail.gmail.com

7 months agoAdd missing query ID reporting in extended query protocol
Michael Paquier [Wed, 18 Sep 2024 00:59:09 +0000 (09:59 +0900)]
Add missing query ID reporting in extended query protocol

This commit adds query ID reports for two code paths when processing
extended query protocol messages:
- When receiving a bind message, setting it to the first Query retrieved
from a cached cache.
- When receiving an execute message, setting it to the first PlannedStmt
stored in a portal.

An advantage of this method is that this is able to cover all the types
of portals handled in the extended query protocol, particularly these
two when the report done in ExecutorStart() is not enough (neither is an
addition in ExecutorRun(), actually, for the second point):
- Multiple execute messages, with multiple ExecutorRun().
- Portal with execute/fetch messages, like a query with a RETURNING
clause and a fetch size that stores the tuples in a first execute
message going though ExecutorStart() and ExecuteRun(), followed by one
or more execute messages doing only fetches from the tuplestore created
in the first message.  This corresponds to the case where
execute_is_fetch is set, for example.

Note that the query ID reporting done in ExecutorStart() is still
necessary, as an EXECUTE requires it.  Query ID reporting is optimistic
and more calls to pgstat_report_query_id() don't matter as the first
report takes priority except if the report is forced.  The comment in
ExecutorStart() is adjusted to reflect better the reality with the
extended query protocol.

The test added in pg_stat_statements is a courtesy of Robert Haas.  This
uses psql's \bind metacommand, hence this part is backpatched down to
v16.

Reported-by: Kaido Vaikla, Erik Wienhold
Author: Sami Imseih
Reviewed-by: Jian He, Andrei Lepikhov, Michael Paquier
Discussion: https://postgr.es/m/CA+427g8DiW3aZ6pOpVgkPbqK97ouBdf18VLiHFesea2jUk3XoQ@mail.gmail.com
Discussion: https://postgr.es/m/CA+TgmoZxtnf_jZ=VqBSyaU8hfUkkwoJCJ6ufy4LGpXaunKrjrg@mail.gmail.com
Discussion: https://postgr.es/m/1391613709.939460.1684777418070@office.mailbox.org
Backpatch-through: 14

7 months agoAllow ReadStream to be consumed as raw block numbers.
Thomas Munro [Tue, 17 Sep 2024 21:20:59 +0000 (09:20 +1200)]
Allow ReadStream to be consumed as raw block numbers.

Commits 041b9680 and 6377e12a changed the interface of
scan_analyze_next_block() to take a ReadStream instead of a BlockNumber
and a BufferAccessStrategy, and to return a value to indicate when the
stream has run out of blocks.

This caused integration problems for at least one known extension that
uses specially encoded BlockNumber values that map to different
underlying storage, because acquire_sample_rows() sets up the stream so
that read_stream_next_buffer() reads blocks from the main fork of the
relation's SMgrRelation.

Provide read_stream_next_block(), as a way for such an extension to
access the stream of raw BlockNumbers directly and forward them to its
own ReadBuffer() calls after decoding, as it could in earlier releases.
The new function returns the BlockNumber and BufferAccessStrategy that
were previously passed directly to scan_analyze_next_block().
Alternatively, an extension could wrap the stream of BlockNumbers in
another ReadStream with a callback that performs any decoding required
to arrive at real storage manager BlockNumber values, so that it could
benefit from the I/O combining and concurrency provided by
read_stream.c.

Another class of table access method that does nothing in
scan_analyze_next_block() because it is not block-oriented could use
this function to control the number of block sampling loops.  It could
match the previous behavior with "return read_stream_next_block(stream,
&bas) != InvalidBlockNumber".

Ongoing work is expected to provide better ANALYZE support for table
access methods that don't behave like heapam with respect to storage
blocks, but that will be for future releases.

Back-patch to 17.

Reported-by: Mats Kindahl <[email protected]>
Reviewed-by: Mats Kindahl <[email protected]>
Discussion: https://postgr.es/m/CA%2B14425%2BCcm07ocG97Fp%2BFrD9xUXqmBKFvecp0p%2BgV2YYR258Q%40mail.gmail.com

7 months agoRepair pg_upgrade for identity sequences with non-default persistence.
Tom Lane [Tue, 17 Sep 2024 19:53:26 +0000 (15:53 -0400)]
Repair pg_upgrade for identity sequences with non-default persistence.

Since we introduced unlogged sequences in v15, identity sequences
have defaulted to having the same persistence as their owning table.
However, it is possible to change that with ALTER SEQUENCE, and
pg_dump tries to preserve the logged-ness of sequences when it doesn't
match (as indeed it wouldn't for an unlogged table from before v15).

The fly in the ointment is that ALTER SEQUENCE SET [UN]LOGGED fails
in binary-upgrade mode, because it needs to assign a new relfilenode
which we cannot permit in that mode.  Thus, trying to pg_upgrade a
database containing a mismatching identity sequence failed.

To fix, add syntax to ADD/ALTER COLUMN GENERATED AS IDENTITY to allow
the sequence's persistence to be set correctly at creation, and use
that instead of ALTER SEQUENCE SET [UN]LOGGED in pg_dump.  (I tried to
make SET [UN]LOGGED work without any pg_dump modifications, but that
seems too fragile to be a desirable answer.  This way should be
markedly faster anyhow.)

In passing, document the previously-undocumented SEQUENCE NAME option
that pg_dump also relies on for identity sequences; I see no value
in trying to pretend it doesn't exist.

Per bug #18618 from Anthony Hsu.
Back-patch to v15 where we invented this stuff.

Discussion: https://postgr.es/m/18618-d4eb26d669ed110a@postgresql.org

7 months agoEnsure standby promotion point in 043_wal_replay_wait.pl
Alexander Korotkov [Tue, 17 Sep 2024 19:51:06 +0000 (22:51 +0300)]
Ensure standby promotion point in 043_wal_replay_wait.pl

This commit ensures standby will be promoted at least at the primary insert
LSN we have just observed.  We use pg_switch_wal() to force the insert LSN
to be written then wait for standby to catchup.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/1d7b08f2-64a2-77fb-c666-c9a74c68eeda%40gmail.com

7 months agoMinor cleanup related to pg_wal_replay_wait() procedure
Alexander Korotkov [Tue, 17 Sep 2024 19:50:43 +0000 (22:50 +0300)]
Minor cleanup related to pg_wal_replay_wait() procedure

 * Rename $node_standby1 to $node_standby in 043_wal_replay_wait.pl as there
   is only one standby.
 * Remove useless debug printing in 043_wal_replay_wait.pl.
 * Fix typo in one check description in 043_wal_replay_wait.pl.
 * Fix some wording in comments and documentation.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/1d7b08f2-64a2-77fb-c666-c9a74c68eeda%40gmail.com
Reviewed-by: Alexander Lakhin
7 months agoAvoid parallel nbtree index scan hangs with SAOPs.
Peter Geoghegan [Tue, 17 Sep 2024 15:10:35 +0000 (11:10 -0400)]
Avoid parallel nbtree index scan hangs with SAOPs.

Commit 5bf748b8, which enhanced nbtree ScalarArrayOp execution, made
parallel index scans work with the new design for arrays via explicit
scheduling of primitive index scans.  A backend that successfully
scheduled the scan's next primitive index scan saved its backend local
array keys in shared memory.  Any backend could pick up the scheduled
primitive scan within _bt_first.  This scheme decouples scheduling a
primitive scan from starting the scan (by performing another descent of
the index via a _bt_search call from _bt_first) to make things robust.

The scheme had a deadlock hazard, at least when the leader process
participated in the scan.  _bt_parallel_seize had a code path that made
backends that were not in an immediate position to start a scheduled
primitive index scan wait for some other backend to do so instead.
Under the right circumstances, the leader process could wait here
forever: the leader would wait for any other backend to start the
primitive scan, while every worker was busy waiting on the leader to
consume tuples from the scan's tuple queue.

To fix, don't wait for a scheduled primitive index scan to be started by
some other eligible backend from within _bt_parallel_seize (when the
calling backend isn't in a position to do so itself).  Return false
instead, while recording that the scan has a scheduled primitive index
scan in backend local state.  This leaves the backend in the same state
as the existing case where a backend schedules (or tries to schedule)
another primitive index scan from within _bt_advance_array_keys, before
calling _bt_parallel_seize.  _bt_parallel_seize already handles that
case by returning false without waiting, and without unsetting the
backend local state.  Leaving the backend in this state enables it to
start a previously scheduled primitive index scan once it gets back to
_bt_first.

Oversight in commit 5bf748b8, which enhanced nbtree ScalarArrayOp
execution.

Matthias van de Meent, with tweaks by me.

Author: Matthias van de Meent <[email protected]>
Reported-By: Tomas Vondra <[email protected]>
Reviewed-By: Peter Geoghegan <[email protected]>
Discussion: https://postgr.es/m/CAH2-WzmMGaPa32u9x_FvEbPTUkP5e95i=QxR8054nvCRydP-sw@mail.gmail.com
Backpatch: 17-, where nbtree SAOP execution was enhanced.

7 months agoAdd temporal FOREIGN KEY contraints
Peter Eisentraut [Tue, 17 Sep 2024 08:41:07 +0000 (10:41 +0200)]
Add temporal FOREIGN KEY contraints

Add PERIOD clause to foreign key constraint definitions.  This is
supported for range and multirange types.  Temporal foreign keys check
for range containment instead of equality.

This feature matches the behavior of the SQL standard temporal foreign
keys, but it works on PostgreSQL's native ranges instead of SQL's
"periods", which don't exist in PostgreSQL (yet).

Reference actions ON {UPDATE,DELETE} {CASCADE,SET NULL,SET DEFAULT}
are not supported yet.

(previously committed as 34768ee3616, reverted by 8aee330af55; this is
essentially unchanged from those)

Author: Paul A. Jungwirth <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: jian he <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CA+renyUApHgSZF9-nd-a0+OPGharLQLO=mDHcY4_qQ0+noCUVg@mail.gmail.com

7 months agoAdd temporal PRIMARY KEY and UNIQUE constraints
Peter Eisentraut [Tue, 17 Sep 2024 08:36:09 +0000 (10:36 +0200)]
Add temporal PRIMARY KEY and UNIQUE constraints

Add WITHOUT OVERLAPS clause to PRIMARY KEY and UNIQUE constraints.
These are backed by GiST indexes instead of B-tree indexes, since they
are essentially exclusion constraints with = for the scalar parts of
the key and && for the temporal part.

(previously committed as 46a0cd4cefb, reverted by 46a0cd4cefb; the new
part is this:)

Because 'empty' && 'empty' is false, the temporal PK/UQ constraint
allowed duplicates, which is confusing to users and breaks internal
expectations.  For instance, when GROUP BY checks functional
dependencies on the PK, it allows selecting other columns from the
table, but in the presence of duplicate keys you could get the value
from any of their rows.  So we need to forbid empties.

This all means that at the moment we can only support ranges and
multiranges for temporal PK/UQs, unlike the original patch (above).
Documentation and tests for this are added.  But this could
conceivably be extended by introducing some more general support for
the notion of "empty" for other types.

Author: Paul A. Jungwirth <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: jian he <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CA+renyUApHgSZF9-nd-a0+OPGharLQLO=mDHcY4_qQ0+noCUVg@mail.gmail.com

7 months agoAdd stratnum GiST support function
Peter Eisentraut [Tue, 17 Sep 2024 08:19:26 +0000 (10:19 +0200)]
Add stratnum GiST support function

This is support function 12 for the GiST AM and translates
"well-known" RT*StrategyNumber values into whatever strategy number is
used by the opclass (since no particular numbers are actually
required).  We will use this to support temporal PRIMARY
KEY/UNIQUE/FOREIGN KEY/FOR PORTION OF functionality.

This commit adds two implementations, one for internal GiST opclasses
(just an identity function) and another for btree_gist opclasses.  It
updates btree_gist from 1.7 to 1.8, adding the support function for
all its opclasses.

(previously committed as 6db4598fcb8, reverted by 8aee330af55; this is
essentially unchanged from those)

Author: Paul A. Jungwirth <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: jian he <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CA+renyUApHgSZF9-nd-a0+OPGharLQLO=mDHcY4_qQ0+noCUVg@mail.gmail.com

7 months agoAdd memory/disk usage for Window aggregate nodes in EXPLAIN.
Tatsuo Ishii [Tue, 17 Sep 2024 05:38:53 +0000 (14:38 +0900)]
Add memory/disk usage for Window aggregate nodes in EXPLAIN.

This commit is similar to 1eff8279d and expands the idea to Window
aggregate nodes so that users can know how much memory or disk the
tuplestore used.

This commit uses newly introduced tuplestore_get_stats() to inquire this
information and add some additional output in EXPLAIN ANALYZE to
display the information for the Window aggregate node.

Reviewed-by: David Rowley, Ashutosh Bapat, Maxim Orlov, Jian He
Discussion: https://postgr.es/m/20240706.202254.89740021795421286.ishii%40postgresql.org

7 months agoFix redefinition of typedef.
Nathan Bossart [Mon, 16 Sep 2024 21:33:50 +0000 (16:33 -0500)]
Fix redefinition of typedef.

Per buildfarm members sifaka and longfin, clang with
-Wtypedef-redefinition warns of a duplicate typedef unless building
with C11.

Oversight in commit 40e2e5e92b.

7 months agopg_upgrade: Parallelize encoding conversion check.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize encoding conversion check.

This commit makes use of the new task framework in pg_upgrade to
parallelize the check for incompatible user-defined encoding
conversions, i.e., those defined on servers older than v14.  This
step will now process multiple databases concurrently when
pg_upgrade's --jobs option is provided a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize WITH OIDS check.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize WITH OIDS check.

This commit makes use of the new task framework in pg_upgrade to
parallelize the check for tables declared WITH OIDS.  This step
will now process multiple databases concurrently when pg_upgrade's
--jobs option is provided a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize incompatible polymorphics check.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize incompatible polymorphics check.

This commit makes use of the new task framework in pg_upgrade to
parallelize the check for usage of incompatible polymorphic
functions, i.e., those with arguments of type anyarray/anyelement
rather than the newer anycompatible variants.  This step will now
process multiple databases concurrently when pg_upgrade's --jobs
option is provided a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize postfix operator check.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize postfix operator check.

This commit makes use of the new task framework in pg_upgrade to
parallelize the check for user-defined postfix operators.  This
step will now process multiple databases concurrently when
pg_upgrade's --jobs option is provided a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize contrib/isn check.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize contrib/isn check.

This commit makes use of the new task framework in pg_upgrade to
parallelize the check for contrib/isn functions that rely on the
bigint data type.  This step will now process multiple databases
concurrently when pg_upgrade's --jobs option is provided a value
greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize data type checks.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize data type checks.

This commit makes use of the new task framework in pg_upgrade to
parallelize the checks for incompatible data types, i.e., data
types whose on-disk format has changed, data types that have been
removed, etc.  This step will now process multiple databases
concurrently when pg_upgrade's --jobs option is provided a value
greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize retrieving extension updates.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize retrieving extension updates.

This commit makes use of the new task framework in pg_upgrade to
parallelize retrieving the set of extensions that should be updated
with the ALTER EXTENSION command after upgrade.  This step will now
process multiple databases concurrently when pg_upgrade's --jobs
option is provided a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize retrieving loadable libraries.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize retrieving loadable libraries.

This commit makes use of the new task framework in pg_upgrade to
parallelize retrieving the names of all libraries referenced by
non-built-in C functions.  This step will now process multiple
databases concurrently when pg_upgrade's --jobs option is provided
a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize subscription check.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize subscription check.

This commit makes use of the new task framework in pg_upgrade to
parallelize the part of check_old_cluster_subscription_state() that
verifies each of the subscribed tables is in the 'i' (initialize)
or 'r' (ready) state.  This check will now process multiple
databases concurrently when pg_upgrade's --jobs option is provided
a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agopg_upgrade: Parallelize retrieving relation information.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
pg_upgrade: Parallelize retrieving relation information.

This commit makes use of the new task framework in pg_upgrade to
parallelize retrieving relation and logical slot information.  This
step will now process multiple databases concurrently when
pg_upgrade's --jobs option is provided a value greater than 1.

Reviewed-by: Daniel Gustafsson, Ilya Gladyshev
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agoIntroduce framework for parallelizing various pg_upgrade tasks.
Nathan Bossart [Mon, 16 Sep 2024 21:10:33 +0000 (16:10 -0500)]
Introduce framework for parallelizing various pg_upgrade tasks.

A number of pg_upgrade steps require connecting to every database
in the cluster and running the same query in each one.  When there
are many databases, these steps are particularly time-consuming,
especially since they are performed sequentially, i.e., we connect
to a database, run the query, and process the results before moving
on to the next database.

This commit introduces a new framework that makes it easy to
parallelize most of these once-in-each-database tasks by processing
multiple databases concurrently.  This framework manages a set of
slots that follow a simple state machine, and it uses libpq's
asynchronous APIs to establish the connections and run the queries.
The --jobs option is used to determine the number of slots to use.
To use this new task framework, callers simply need to provide the
query and a callback function to process its results, and the
framework takes care of the rest.  A more complete description is
provided at the top of the new task.c file.

None of the eligible once-in-each-database tasks are converted to
use this new framework in this commit.  That will be done via
several follow-up commits.

Reviewed-by: Jeff Davis, Robert Haas, Daniel Gustafsson, Ilya Gladyshev, Corey Huinker
Discussion: https://postgr.es/m/20240516211638.GA1688936%40nathanxps13

7 months agodoc PG relnotes: fix SGML markup for new commit links
Bruce Momjian [Mon, 16 Sep 2024 18:23:39 +0000 (14:23 -0400)]
doc PG relnotes:  fix SGML markup for new commit links

Backpatch-through: 12

7 months agoscripts: add Perl script to add links to release notes
Bruce Momjian [Mon, 16 Sep 2024 17:26:37 +0000 (13:26 -0400)]
scripts:  add Perl script to add links to release notes

Reported-by: jian he
Discussion: https://postgr.es/m/[email protected]

Backpatch-through: 12

7 months agoPerl scripts: revert 43ce181059d
Bruce Momjian [Mon, 16 Sep 2024 01:25:00 +0000 (21:25 -0400)]
Perl scripts:  revert 43ce181059d

Small improvement not worth the code churn.

Reported-by: Andrew Dunstan
Discussion: https://postgr.es/m/42f2242a-422b-4aa3-8d60-d67b229c4a52@dunslane.net

Backpatch-through: master

7 months agoReplace usages of xmlXPathCompile() with xmlXPathCtxtCompile().
Tom Lane [Sun, 15 Sep 2024 17:33:09 +0000 (13:33 -0400)]
Replace usages of xmlXPathCompile() with xmlXPathCtxtCompile().

In existing releases of libxml2, xmlXPathCompile can be driven
to stack overflow because it fails to protect itself against
too-deeply-nested input.  While there is an upstream fix as of
yesterday, it will take years for that to propagate into all
shipping versions.  In the meantime, we can protect our own
usages basically for free by calling xmlXPathCtxtCompile instead.

(The actual bug is that libxml2 keeps its nesting counter in the
xmlXPathContext, and its parsing code was willing to just skip
counting nesting levels if it didn't have a context.  So if we supply
a context, all is well.  It seems odd actually that it works at all
to not supply a context, because this means that XPath parsing does
not have access to XML namespace info.  Apparently libxml2 never
checks namespaces until runtime?  Anyway, this seems like good
future-proofing even if its only immediate effect is to dodge a bug.)

Sadly, this hack only offers protection with libxml2 2.9.11 and newer.
Before that there are multiple similar problems, so if you are
processing untrusted XML it behooves you to get a newer version.
But we have some pretty old libxml2 in the buildfarm, so it seems
impractical to add a regression test to verify this fix.

Per bug #18617 from Jingzhou Fu.  Back-patch to all supported
versions.

Discussion: https://postgr.es/m/18617-1cee4d2ed1f4e7ae@postgresql.org
Discussion: https://gitlab.gnome.org/GNOME/libxml2/-/issues/799

7 months agoPerl scripts: eliminate "Useless interpolation" warnings
Bruce Momjian [Sun, 15 Sep 2024 14:55:37 +0000 (10:55 -0400)]
Perl scripts:  eliminate "Useless interpolation" warnings

Eliminate warnings of Perl Critic from src/tools.

Backpatch-through: master

7 months agoRun regression tests with timezone America/Los_Angeles.
Tom Lane [Sat, 14 Sep 2024 21:55:02 +0000 (17:55 -0400)]
Run regression tests with timezone America/Los_Angeles.

Historically we've used timezone "PST8PDT", but the recent release
2024b of tzdb changes the definition of that zone in a way that
breaks many test cases concerned with dates before 1970.  Although
we've not yet adopted 2024b into our own tree, this is already
problematic for people using --with-system-tzdata if their platform
has already adopted 2024b.  To work with both older and newer
versions of tzdb, switch to using "America/Los_Angeles", accepting
the ensuing changes in regression test results.

Back-patch to all supported branches.

Per report and patch from Wolfgang Walther.

Discussion: https://postgr.es/m/0a997455-5aba-4cf2-a354-d26d8bcbfae6@technowledgy.de

7 months agoAdd commit 7229ebe011df to .git-blame-ignore-revs.
Alvaro Herrera [Sat, 14 Sep 2024 18:17:30 +0000 (20:17 +0200)]
Add commit 7229ebe011df to .git-blame-ignore-revs.

7 months agoRemove obsolete comment in pg_stat_statements.
Tom Lane [Sat, 14 Sep 2024 15:42:31 +0000 (11:42 -0400)]
Remove obsolete comment in pg_stat_statements.

Commit 76db9cb63 removed the use of multiple nesting counters,
but missed one comment describing that arrangement.

Back-patch to v17 where 76db9cb63 came in, just to avoid confusion.

Julien Rouhaud

Discussion: https://postgr.es/m/gfcwh3zjxc2vygltapgo7g6yacdor5s4ynr234b6v2ohhuvt7m@gr42joxalenw

7 months agoImprove meson's detection of perl build flags
Andrew Dunstan [Sat, 14 Sep 2024 14:26:25 +0000 (10:26 -0400)]
Improve meson's detection of perl build flags

The current method of detecting perl build flags breaks if the path to
perl contains a space. This change makes two improvements. First,
instead of getting a list of ldflags and ccdlflags and then trying to
filter those out of the reported ldopts, we tell perl to suppress
reporting those in the first instance. Second, it tells perl to parse
those and output them, one per line. Thus any space on the option in a
file name, for example, is preserved.

Issue reported off-list by Muralikrishna Bandaru

Discussion: https://postgr.es/01117f88-f465-bf6c-9362-083bd72ca305@dunslane.net

Backpatch to release 16.

7 months agoOnly define NO_THREAD_SAFE_LOCALE for MSVC plperl when required
Andrew Dunstan [Sat, 14 Sep 2024 12:37:08 +0000 (08:37 -0400)]
Only define NO_THREAD_SAFE_LOCALE for MSVC plperl when required

Latest versions of Strawberry Perl define USE_THREAD_SAFE_LOCALE, and we
therefore get a handshake error when building against such instances.
The solution is to perform a test to see if USE_THREAD_SAFE_LOCALE is
defined and only define NO_THREAD_SAFE_LOCALE if it isn't.

Backpatch the meson.build fix back to release 16 and apply the same
logic to Mkvcbuild.pm in releases 12 through 16.

Original report of the issue from Muralikrishna Bandaru.

7 months agoAllow _h_indexbuild() to be interrupted.
Tom Lane [Fri, 13 Sep 2024 20:16:47 +0000 (16:16 -0400)]
Allow _h_indexbuild() to be interrupted.

When we are building a hash index that is large enough to need
pre-sorting (larger than either maintenance_work_mem or NBuffers),
the initial sorting phase is interruptible, but the insertion
phase wasn't.  Add the missing CHECK_FOR_INTERRUPTS().

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

Pavel Borisov

Discussion: https://postgr.es/m/18616-acbb9e5caf41e964@postgresql.org

7 months agoAdd commit 2b03cfeea4 to .git-blame-ignore-revs.
Nathan Bossart [Fri, 13 Sep 2024 18:06:06 +0000 (13:06 -0500)]
Add commit 2b03cfeea4 to .git-blame-ignore-revs.

7 months agoFix contrib/pageinspect's test for sequences.
Nathan Bossart [Fri, 13 Sep 2024 15:16:40 +0000 (10:16 -0500)]
Fix contrib/pageinspect's test for sequences.

I managed to break this test in two different ways in commit
05036a3155.

First, the output of the new call to tuple_data_split() on the test
sequence is dependent on endianness.  This is fixed by setting a
special start value for the test sequence that produces the same
output regardless of the endianness of the machine.

Second, on versions older than v15, the new test case fails under
"force_parallel_mode = regress" with the following error:

ERROR:  cannot access temporary tables during a parallel operation

This is because pageinspect's disk-accessing functions are
incorrectly marked PARALLEL SAFE on versions older than v15 (see
commit aeaaf520f4 for details).  This one is fixed by changing the
test sequence to be permanent.  The only reason it was previously
marked temporary was to avoid needing a DROP SEQUENCE command at
the end of the test.  Unlike some other tests in this file, the use
of a permanent sequence here shouldn't result in any test
instability like what was fixed by commit e2933a6e11.

Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/ZuOKOut5hhDlf_bP%40nathan
Backpatch-through: 12