postgresql.git
13 months agoIntroduce a non-recursive JSON parser
Andrew Dunstan [Mon, 11 Mar 2024 03:10:14 +0000 (23:10 -0400)]
Introduce a non-recursive JSON parser

This parser uses an explicit prediction stack, unlike the present
recursive descent parser where the parser state is represented on the
call stack. This difference makes the new parser suitable for use in
incremental parsing of huge JSON documents that cannot be conveniently
handled piece-wise by the recursive descent parser. One potential use
for this will be in parsing large backup manifests associated with
incremental backups.

Because this parser is somewhat slower than the recursive descent
parser, it  is not replacing that parser, but is an additional parser
available to callers.

For testing purposes, if the build is done with -DFORCE_JSON_PSTACK, all
JSON parsing is done with the non-recursive parser, in which case only
trivial regression differences in error messages should be observed.

Author: Andrew Dunstan
Reviewed-By: Jacob Champion
Discussion: https://postgr.es/m/7b0a51d6-0d9d-7366-3a1a-f74397a02f55@dunslane.net

13 months agoSilence meson warning
Peter Eisentraut [Thu, 4 Apr 2024 09:22:07 +0000 (11:22 +0200)]
Silence meson warning

Commit 619bc23a1a introduced

    WARNING: Project targets '>=0.54' but uses feature introduced in '0.55.0': Passing executable/found program object to script parameter of add_dist_script

Work around that by wrapping the offending line in a meson version check.

Author: Tristan Partin <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/D096Q3NFFVH1.1T5RE4MOO9ZFH%40neon.tech

13 months agopostgres_fdw: Remove useless ternary expression.
Etsuro Fujita [Thu, 4 Apr 2024 08:55:00 +0000 (17:55 +0900)]
postgres_fdw: Remove useless ternary expression.

There is no case where we would call pgfdw_exec_cleanup_query or
pgfdw_exec_cleanup_query_{begin,end} with a NULL query string, so this
expression is pointless; remove it and instead add to the latter
functions an assertion ensuring the given query string is not NULL.

Thinko in commit 815d61fcd.

Discussion: https://postgr.es/m/CAPmGK14mm%2B%3DUjyjoWj_Hu7c%2BQqX-058RFfF%2BqOkcMZ_Nj52v-A%40mail.gmail.com

13 months agoSecondary refactor of heap scanning functions
David Rowley [Thu, 4 Apr 2024 06:22:45 +0000 (19:22 +1300)]
Secondary refactor of heap scanning functions

Similar to 44086b097, refactor heap scanning functions to be more
suitable for the read stream API.

Author: Melanie Plageman
Discussion: https://postgr.es/m/CAAKRu_YtXJiYKQvb5JsA2SkwrsizYLugs4sSOZh3EAjKUg=gEQ@mail.gmail.com

13 months agoCoordinate emit_log_hook and all log destinations to share the same timeval
Michael Paquier [Thu, 4 Apr 2024 05:15:22 +0000 (14:15 +0900)]
Coordinate emit_log_hook and all log destinations to share the same timeval

This would cause the timestamp values used by emit_log_hook and all the
other log destinations to differ, because the timestamps are reset
before sending the logs to the server and after calling the hook.

This change matters for emit_log_hook when generating log information
with 'n' or 'm' in log_line_prefix through log_status_format(), or when
doing direct calls to get_formatted_log_time() like in the JSON or CSV
log formats.

While on it, this commit fixes a couple of comments related to the
formatted timestamps where the JSON was not mentioned.  Oversight in
dc686681e079, that I have noticed while reviewing this patch.

Author: Kambam Vinay, Michael Paquier
Discussion: https://postgr.es/m/CANiRfmsK36A0i8mnQtzaxhSm3CUCimPwJPp4WQNq53OdSNkgWg@mail.gmail.com

13 months agoPreliminary refactor of heap scanning functions
David Rowley [Thu, 4 Apr 2024 03:41:13 +0000 (16:41 +1300)]
Preliminary refactor of heap scanning functions

To allow the use of the read stream API added in b5a9b18cd for
sequential scans on heap tables, here we make some adjustments to make
that change less invasive and perhaps make the code easier to follow in
the process.

Here heapgetpage() gets broken into two functions:

1) The part which reads the block has now been moved into a function
   named heapfetchbuf().
2) The part which performed pruning and populated the scan's
   rs_vistuples[] array is now moved into a new function named
   heap_prepare_pagescan().

The functionality provided by heap_prepare_pagescan() was only ever
required by SO_ALLOW_PAGEMODE scans, so the branching that was
previously done in heapgetpage() is no longer needed as we simply just
don't call heap_prepare_pagescan() from heapgettup() in the refactored
code.

Author: Melanie Plageman
Discussion: https://postgr.es/m/CAAKRu_YtXJiYKQvb5JsA2SkwrsizYLugs4sSOZh3EAjKUg=gEQ@mail.gmail.com

13 months agopg_regress: Save errno in emit_tap_output_v() and switch to %m
Michael Paquier [Thu, 4 Apr 2024 02:33:07 +0000 (11:33 +0900)]
pg_regress: Save errno in emit_tap_output_v() and switch to %m

emit_tap_output_v() includes some fprintf() calls for some output
related to the TAP protocol, that may clobber errno and break %m.  This
commit makes the logging of pg_regress smarter by saving errno before
restoring it in vfprintf() where the input strings are used, removing
the need for strerror().  All logs are switched to %m rather than
strerror(), shaving some code.

This was not a problem until now as pg_regress.c did not use %m, but the
change is simple enough that we have no reason to not support this
placeholder, and that will avoid future mistakes if new logs that
include %m are added.

Author: Dagfinn Ilmari Mannsåker
Reviewed-by: Peter Eisentraunt, Michael Paquier
Discussion: https://postgr.es/m/[email protected]

13 months agoCREATE INDEX: do not update stats during binary upgrade.
Jeff Davis [Wed, 3 Apr 2024 23:12:45 +0000 (16:12 -0700)]
CREATE INDEX: do not update stats during binary upgrade.

During binary upgrade, indexes are created before the data is moved
into place, so it will always be zero.

This is not currently a major problem, but will be when we try to
preserve statistics during upgrade.

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

13 months agoInvent SERIALIZE option for EXPLAIN.
Tom Lane [Wed, 3 Apr 2024 21:41:54 +0000 (17:41 -0400)]
Invent SERIALIZE option for EXPLAIN.

EXPLAIN (ANALYZE, SERIALIZE) allows collection of statistics about
the volume of data emitted by a query, as well as the time taken
to convert the data to the on-the-wire format.  Previously there
was no way to investigate this without actually sending the data
to the client, in which case network transmission costs might
swamp what you wanted to see.  In particular this feature allows
investigating the costs of de-TOASTing compressed or out-of-line
data during formatting.

Stepan Rutz and Matthias van de Meent,
reviewed by Tomas Vondra and myself

Discussion: https://postgr.es/m/ca0adb0e-fa4e-c37e-1cd7-91170b18cae1@gmx.de

13 months agoFix the parameters order for TableAmRoutine.relation_copy_for_cluster()
Alexander Korotkov [Wed, 3 Apr 2024 18:29:18 +0000 (21:29 +0300)]
Fix the parameters order for TableAmRoutine.relation_copy_for_cluster()

Specify OldTable first, NewTable second as used by
table_relation_copy_for_cluster() and as implemented in
heapam_relation_copy_for_cluster().

Backpatch to PostgreSQL 12, where TableAmRoutine was introduced.

Discussion: https://postgr.es/m/ME3P282MB3166860D4911AE82F92DF7C5B63F2%40ME3P282MB3166.AUSP282.PROD.OUTLOOK.COM
Author: Japin Li
Reviewed-by: Pavel Borisov
Backpatch-through: 12

13 months agodocs: Demote "Monitoring Disk Usage" from chapter to section.
Robert Haas [Wed, 3 Apr 2024 20:09:41 +0000 (16:09 -0400)]
docs: Demote "Monitoring Disk Usage" from chapter to section.

This chapter is very short, and the immediately preceding chapter is
called "Monitoring Database Activity". So, instead of having a
separate chapter for this, make it the last section of the preceding
chapter instead.

Discussion: http://postgr.es/m/CA+Tgmob7_uoYuS2=rVwpVXaRwP-UXz+++saYTC-BCZ42QzSNKQ@mail.gmail.com

13 months agoSplit XLogCtl->LogwrtResult into separate struct members
Alvaro Herrera [Wed, 3 Apr 2024 17:55:11 +0000 (19:55 +0200)]
Split XLogCtl->LogwrtResult into separate struct members

After this change we have XLogCtl->logWriteResult and ->logFlushResult.
There's no functional change, other than the fact that the assignment
from shared memory to local is no longer done via struct assignment, but
instead using a macro that copies each member separately.

The current representation is inconvenient going forward; notably, we
would like to add a new member "Copy" (to keep track of the last
position copied into WAL buffers), so the symmetry between the values in
shared memory vs. those in local would be lost.

This also gives us freedom to later change the concurrency model for the
values in shared memory: we can make them use atomics instead of relying
on the info_lck spinlock.

Reviewed-by: Bharath Rupireddy <[email protected]>
Discussion: https://postgr.es/m/202404031119[email protected]

13 months agoInline pg_popcount() for small buffers.
Nathan Bossart [Wed, 3 Apr 2024 17:22:02 +0000 (12:22 -0500)]
Inline pg_popcount() for small buffers.

If there aren't many bytes to process, the function call overhead
of the optimized implementation isn't worth taking, so instead we
inline a loop that consults pg_number_of_ones in that case.  If
there are many bytes to process, we accept the function call
overhead because the optimized versions are likely to be faster.
The threshold at which we use the optimized implementation is set
to the smallest amount of data required to use special popcount
instructions.

Reviewed-by: Alvaro Herrera, Tom Lane
Discussion: https://postgr.es/m/20240402155301.GA2750455%40nathanxps13

13 months agoCombine freezing and pruning steps in VACUUM
Heikki Linnakangas [Wed, 3 Apr 2024 16:32:28 +0000 (19:32 +0300)]
Combine freezing and pruning steps in VACUUM

Execute both freezing and pruning of tuples in the same
heap_page_prune() function, now called heap_page_prune_and_freeze(),
and emit a single WAL record containing all changes. That reduces the
overall amount of WAL generated.

This moves the freezing logic from vacuumlazy.c to the
heap_page_prune_and_freeze() function. The main difference in the
coding is that in vacuumlazy.c, we looked at the tuples after the
pruning had already happened, but in heap_page_prune_and_freeze() we
operate on the tuples before pruning. The heap_prepare_freeze_tuple()
function is now invoked after we have determined that a tuple is not
going to be pruned away.

VACUUM no longer needs to loop through the items on the page after
pruning. heap_page_prune_and_freeze() does all the work. It now
returns the list of dead offsets, including existing LP_DEAD items, to
the caller. Similarly it's now responsible for tracking 'all_visible',
'all_frozen', and 'hastup' on the caller's behalf.

Author: Melanie Plageman <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240330055710.kqg6ii2cdojsxgje@liskov

13 months agoRefactor how heap_prune_chain() updates prunable_xid
Heikki Linnakangas [Wed, 3 Apr 2024 16:32:21 +0000 (19:32 +0300)]
Refactor how heap_prune_chain() updates prunable_xid

In preparation of freezing and counting tuples which are not
candidates for pruning, split heap_prune_record_unchanged() into
multiple functions, depending the kind of line pointer. That's not too
interesting right now, but makes the next commit smaller.

Recording the lowest soon-to-be prunable xid is one of the actions we
take for unchanged LP_NORMAL item pointers but not for others, so move
that to the new heap_prune_record_unchanged_lp_normal() function. The
next commit will add more actions to these functions.

Author: Melanie Plageman <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240330055710.kqg6ii2cdojsxgje@liskov

13 months agoFix zeroing of pg_serial page without SLRU bank lock
Alvaro Herrera [Wed, 3 Apr 2024 15:49:44 +0000 (17:49 +0200)]
Fix zeroing of pg_serial page without SLRU bank lock

Bug in commit 53c2a97a9266: we failed to acquire the correct SLRU bank
lock when iterating to zero-out intermediate pages in predicate.c.
Rewrite the code block so that we follow the locking protocol correctly.

Also update an outdated comment in the same file -- SerialSLRULock
exists no more.

Reported-by: Alexander Lakhin <[email protected]>
Reviewed-by: Dilip Kumar <[email protected]>
Discussion: https://postgr.es/m/2a25eaf4-a3a4-5fd1-6241-9d7c73142085@gmail.com

13 months agoUse the pairing heap instead of a flat array for LSN replay waiters
Alexander Korotkov [Wed, 3 Apr 2024 15:15:17 +0000 (18:15 +0300)]
Use the pairing heap instead of a flat array for LSN replay waiters

06c418e163 introduced pg_wal_replay_wait() procedure allowing to wait for
the particular LSN to be replayed on standby.  The waiters were stored in
the flat array.  Even though scanning small arrays is fast, that might be a
problem at scale (a lot of waiting processes).

This commit replaces the flat shared memory array with the pairing heap,
which holds the waiter with the least LSN at the top.  This gives us O(log N)
complexity for both inserting and removing waiters.

Reported-by: Alvaro Herrera
Discussion: https://postgr.es/m/202404030658.hhj3vfxeyhft%40alvherre.pgsql

13 months agoDrop global objects after completed test
Daniel Gustafsson [Wed, 3 Apr 2024 11:33:25 +0000 (13:33 +0200)]
Drop global objects after completed test

Project policy is to not leave global objects behind after a regress
test run.  This was found as a result of the development of a patch
to make pg_regress detect such leftovers automatically, which in the
end was withdrawn due to issues with parallel runs.

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

13 months agoEnsure that the sync slots reach a consistent state after promotion without losing...
Amit Kapila [Wed, 3 Apr 2024 08:34:59 +0000 (14:04 +0530)]
Ensure that the sync slots reach a consistent state after promotion without losing data.

We were directly copying the LSN locations while syncing the slots on the
standby. Now, it is possible that at some particular restart_lsn there are
some running xacts, which means if we start reading the WAL from that
location after promotion, we won't reach a consistent snapshot state at
that point. However, on the primary, we would have already been in a
consistent snapshot state at that restart_lsn so we would have just
serialized the existing snapshot.

To avoid this problem we will use the advance_slot functionality unless
the snapshot already exists at the synced restart_lsn location. This will
help us to ensure that snapbuilder/slot statuses are updated properly
without generating any changes. Note that the synced slot will remain as
RS_TEMPORARY till the decoding from corresponding restart_lsn can reach a
consistent snapshot state after which they will be marked as
RS_PERSISTENT.

Per buildfarm

Author: Hou Zhijie
Reviewed-by: Bertrand Drouvot, Shveta Malik, Bharath Rupireddy, Amit Kapila
Discussion: https://postgr.es/m/OS0PR01MB5716B3942AE49F3F725ACA92943B2@OS0PR01MB5716.jpnprd01.prod.outlook.com

13 months agoMinor improvements for waitlsn.c
Alexander Korotkov [Wed, 3 Apr 2024 08:23:21 +0000 (11:23 +0300)]
Minor improvements for waitlsn.c

 * Remove extra includes
 * Fill 'cur' in addLSNWaiter() before taking the spinlock
 * Initialize 'endtime' with zero in WaitForLSN() to avoid compiler warning

Reported-by: Alvaro Herrera, Masahiko Sawada, Daniel Gustafsson
Discussion: https://postgr.es/m/202404030658.hhj3vfxeyhft%40alvherre.pgsql
Discussion: https://postgr.es/m/CAD21AoAx7irptnPH1OkkkNh9E0M6X-phfX7sYZfwoMsc1qV1sQ%40mail.gmail.com

13 months agoFix indentation from cafe1056558f
Daniel Gustafsson [Wed, 3 Apr 2024 07:44:47 +0000 (09:44 +0200)]
Fix indentation from cafe1056558f

Per buildfarm animal koel

13 months agoAdd error codes to some PANIC/FATAL errors reports
Daniel Gustafsson [Wed, 3 Apr 2024 07:19:25 +0000 (09:19 +0200)]
Add error codes to some PANIC/FATAL errors reports

This adds errcodes to a set of PANIC and FATAL errors in xlog.c
and relcache.c,  which previously had no errcode at all set, in
order to make fleetwide analysis of errorlogs easier. There are
many more ereport/elogs left which could benefit from having an
errcode but this at least makes a dent in the issue.

Author: Nazir Bilal Yavuz <[email protected]>
Discussion: https://postgr.es/m/CAN55FZ1k8LgLEqncPGmz_fWnrobV6bjABOTH4tOWta6xNcPQig@mail.gmail.com

13 months agoAdd built-in ERROR handling for archive callbacks.
Nathan Bossart [Wed, 3 Apr 2024 03:28:11 +0000 (22:28 -0500)]
Add built-in ERROR handling for archive callbacks.

Presently, the archiver process restarts when an archive callback
ERRORs.  To avoid this, archive module authors can use sigsetjmp(),
manage a memory context, etc., but that requires a lot of extra
code that will likely look roughly the same between modules.  This
commit adds basic archive callback ERROR handling to pgarch.c so
that module authors won't ordinarily need to worry about this.
While this built-in handler attempts to clean up anything that an
archive module could conceivably have left behind, it is possible
that some modules are doing unexpected things that require
additional cleanup.  Module authors should be sure to do any extra
required cleanup in a PG_CATCH block within the archiving callback.

The archiving callback is now called in a short-lived memory
context that the archiver process resets between invocations.  If a
module requires longer-lived storage, it must maintain its own
memory context.

Thanks to these changes, the basic_archive module can be greatly
simplified.

Suggested-by: Andres Freund
Reviewed-by: Andres Freund, Yong Li
Discussion: https://postgr.es/m/20230217215624.GA3131134%40nathanxps13

13 months agoImprove eviction algorithm in ReorderBuffer using max-heap for many subtransactions.
Masahiko Sawada [Wed, 3 Apr 2024 02:40:42 +0000 (11:40 +0900)]
Improve eviction algorithm in ReorderBuffer using max-heap for many subtransactions.

Previously, when selecting the transaction to evict during logical
decoding, we check all transactions to find the largest
transaction. This could lead to a significant replication lag
especially in the case where there are many subtransactions.

This commit improves the eviction algorithm in ReorderBuffer using the
max-heap with transaction size as the key to efficiently find the
largest transaction.

The max-heap starts with empty. While the max-heap is empty, we don't
do anything for the max-heap when updating the memory
counter. Therefore, we get the largest transaction in O(N) time, where
N is the number of transactions including top-level transactions and
subtransactions.

We build the max-heap just before selecting the largest transactions
if the number of transactions being decoded is higher than the
threshold, MAX_HEAP_TXN_COUNT_THRESHOLD. After building the max-heap,
we also update the max-heap when updating the memory counter. The
intention is to efficiently find the largest transaction in O(1) time
instead of incurring the cost of memory counter updates (O(log
N)). Once the number of transactions got lower than the threshold, we
reset the max-heap.

The performance benchmark results showed significant speed up (more
than x30 speed up on my machine) in decoding a transaction with 100k
subtransactions, whereas there is no visible overhead in other cases.

Reviewed-by: Amit Kapila, Hayato Kuroda, Vignesh C, Ajin Cherian,
Tomas Vondra, Shubham Khanna, Peter Smith, Álvaro Herrera,
Euler Taveira
Discussion: https://postgr.es/m/CAD21AoAfKTgrBrLq96GcTv9d6k97zaQcDM-rxfKEt4GSe0qnaQ%40mail.gmail.com

13 months agoDon't adjust ressortgroupref in generate_setop_child_grouplist()
David Rowley [Wed, 3 Apr 2024 02:39:29 +0000 (15:39 +1300)]
Don't adjust ressortgroupref in generate_setop_child_grouplist()

This is already done inside assignSortGroupRef(), therefore is
redundant.

Oversight from 66c0185a3.

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

13 months agoAdd functions to binaryheap for efficient key removal and update.
Masahiko Sawada [Wed, 3 Apr 2024 01:44:21 +0000 (10:44 +0900)]
Add functions to binaryheap for efficient key removal and update.

Previously, binaryheap didn't support updating a key and removing a
node in an efficient way. For example, in order to remove a node from
the binaryheap, the caller had to pass the node's position within the
array that the binaryheap internally has. Removing a node from the
binaryheap is done in O(log n) but searching for the key's position is
done in O(n).

This commit adds a hash table to binaryheap in order to track the
position of each nodes in the binaryheap. That way, by using newly
added functions such as binaryheap_update_up() etc., both updating a
key and removing a node can be done in O(1) on an average and O(log n)
in worst case. This is known as the indexed binary heap. The caller
can specify to use the indexed binaryheap by passing indexed = true.

The current code does not use the new indexing logic, but it will be
used by an upcoming patch.

Reviewed-by: Vignesh C, Peter Smith, Hayato Kuroda, Ajin Cherian,
Tomas Vondra, Shubham Khanna
Discussion: https://postgr.es/m/CAD21AoDffo37RC-eUuyHJKVEr017V2YYDLyn1xF_00ofptWbkg%40mail.gmail.com

13 months agoMake binaryheap enlargeable.
Masahiko Sawada [Wed, 3 Apr 2024 01:27:43 +0000 (10:27 +0900)]
Make binaryheap enlargeable.

The node array space of the binaryheap is doubled when there is no
available space.

Reviewed-by: Vignesh C, Peter Smith, Hayato Kuroda, Ajin Cherian,
Tomas Vondra, Shubham Khanna
Discussion: https://postgr.es/m/CAD21AoDffo37RC-eUuyHJKVEr017V2YYDLyn1xF_00ofptWbkg%40mail.gmail.com

13 months agoMove WaitLSNShmemInit() to CreateOrAttachShmemStructs()
Alexander Korotkov [Tue, 2 Apr 2024 23:55:03 +0000 (02:55 +0300)]
Move WaitLSNShmemInit() to CreateOrAttachShmemStructs()

Thanks to Andres Freund, Thomas Munrom and David Rowley for investigating
this issue.

Discussion: https://postgr.es/m/CAPpHfdvap5mMLikt8CUjA0osAvCJHT0qnYeR3f84EJ_Kvse0mg%40mail.gmail.com

13 months agoDon't zero tuple_fraction when planning UNIONs with ORDER BYs
David Rowley [Tue, 2 Apr 2024 22:40:33 +0000 (11:40 +1300)]
Don't zero tuple_fraction when planning UNIONs with ORDER BYs

Since 66c0185a3, the planner is able to use Merge Append -> Unique to
implement UNION queries and each subquery is prompted to produce Paths
correctly sorted by the UNION's targetlist.

Here we remove some now redundant code which was zeroing the
tuple_fraction at the parent level.  This will allow the planner to
consider cheap startup paths when planning the UNION's subqueries.

EXCEPT and INTERSECT set operations still have the tuple_fraction zeroed
in generate_nonunion_paths().  These operations currently always read
all of their subqueries' tuples.

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

13 months agoImplement pg_wal_replay_wait() stored procedure
Alexander Korotkov [Tue, 2 Apr 2024 19:48:03 +0000 (22:48 +0300)]
Implement pg_wal_replay_wait() stored procedure

pg_wal_replay_wait() is to be used on standby and specifies waiting for
the specific WAL location to be replayed before starting the transaction.
This option is useful when the user makes some data changes on primary and
needs a guarantee to see these changes on standby.

The queue of waiters is stored in the shared memory array sorted by LSN.
During replay of WAL waiters whose LSNs are already replayed are deleted from
the shared memory array and woken up by setting of their latches.

pg_wal_replay_wait() needs to wait without any snapshot held.  Otherwise,
the snapshot could prevent the replay of WAL records implying a kind of
self-deadlock.  This is why it is only possible to implement
pg_wal_replay_wait() as a procedure working in a non-atomic context,
not a function.

Catversion is bumped.

Discussion: https://postgr.es/m/eb12f9b03851bb2583adab5df9579b4b%40postgrespro.ru
Author: Kartyshov Ivan, Alexander Korotkov
Reviewed-by: Michael Paquier, Peter Eisentraut, Dilip Kumar, Amit Kapila
Reviewed-by: Alexander Lakhin, Bharath Rupireddy, Euler Taveira
13 months agoAvoid deadlock during orphan temp table removal.
Tom Lane [Tue, 2 Apr 2024 18:59:04 +0000 (14:59 -0400)]
Avoid deadlock during orphan temp table removal.

If temp tables have dependencies (such as sequences) then it's
possible for autovacuum's cleanup of orphan temp tables to deadlock
against an incoming backend that's trying to clean out the temp
namespace for its own use.  That can happen because RemoveTempRelations'
performDeletion call can visit objects within the namespace in
an order different from the order in which a per-table deletion
will visit them.

To fix, observe that performDeletion will begin by taking an exclusive
lock on the temp namespace (even though it won't actually delete it).
So, if we can get a shared lock on the namespace, we can be sure we're
not running concurrently with RemoveTempRelations, while also not
conflicting with ordinary use of the namespace.  This requires
introducing a conditional version of LockDatabaseObject, but that's no
big deal.  (It's surprising we've got along without that this long.)

Report and patch by Mikhail Zhilin.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/c43ce028-2bc2-4865-9b89-3f706246eed5@postgrespro.ru

13 months agoAvoid function call overhead of pg_popcount() in syslogger.c.
Nathan Bossart [Tue, 2 Apr 2024 15:32:49 +0000 (10:32 -0500)]
Avoid function call overhead of pg_popcount() in syslogger.c.

Instead of calling the pg_popcount() function for a single byte, we
can look up the value in the pg_number_of_ones array.

Discussion: https://postgr.es/m/20240401221117.GB2362108%40nathanxps13

13 months agoRefactor code for setting pg_popcount* function pointers.
Nathan Bossart [Tue, 2 Apr 2024 15:16:00 +0000 (10:16 -0500)]
Refactor code for setting pg_popcount* function pointers.

Presently, there are three copies of this code, and a proposed
follow-up patch would add more code to each copy.  This commit
introduces a new inline function for this code and makes use of it
in the pg_popcount*_choose functions, thereby reducing code
duplication.

Author: Paul Amonson
Discussion: https://postgr.es/m/BL1PR11MB5304097DF7EA81D04C33F3D1DCA6A%40BL1PR11MB5304.namprd11.prod.outlook.com

13 months agoUnwind #if spaghetti in hmac_openssl.c a bit.
Tom Lane [Tue, 2 Apr 2024 14:41:37 +0000 (10:41 -0400)]
Unwind #if spaghetti in hmac_openssl.c a bit.

Make this code a little less confusing by defining a separate macro
that controls whether we'll use ResourceOwner facilities to track
the existence of a pg_hmac_ctx context.

The proximate reason to touch this is that since b8bff07da, we got
"unused function" warnings if building with older OpenSSL, because
the #if guards around the ResourceOwner wrapper function definitions
were different from those around the calls of those functions.
Pulling the ResourceOwner machinations outside of the #ifdef HAVE_xxx
guards fixes that and makes the code clearer too.

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

13 months agoAllow SIGINT to cancel psql database reconnections.
Robert Haas [Tue, 2 Apr 2024 14:26:10 +0000 (10:26 -0400)]
Allow SIGINT to cancel psql database reconnections.

After installing the SIGINT handler in psql, SIGINT can no longer cancel
database reconnections. For instance, if the user starts a reconnection
and then needs to do some form of interaction (ie psql is polling),
there is no way to cancel the reconnection process currently.

Use PQconnectStartParams() in order to insert a cancel_pressed check
into the polling loop.

Tristan Partin, reviewed by Gurjeet Singh, Heikki Linnakangas, Jelte
Fennema-Nio, and me.

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

13 months agoExpose PQsocketPoll via libpq
Robert Haas [Tue, 2 Apr 2024 14:15:56 +0000 (10:15 -0400)]
Expose PQsocketPoll via libpq

This is useful when connecting to a database asynchronously via
PQconnectStart(), since it handles deciding between poll() and
select(), and some of the required boilerplate.

Tristan Partin, reviewed by Gurjeet Singh, Heikki Linnakangas, Jelte
Fennema-Nio, and me.

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

13 months agoUse streaming I/O in pg_prewarm.
Thomas Munro [Tue, 2 Apr 2024 11:57:17 +0000 (00:57 +1300)]
Use streaming I/O in pg_prewarm.

Instead of calling ReadBuffer() repeatedly, use the new streaming
interface.  This commit provides a very simple example of such a
transformation.

Discussion: https://postgr.es/m/CA+hUKGJkOiOCa+mag4BF+zHo7qo=o9CFheB8=g6uT5TUm2gkvA@mail.gmail.com

13 months agoProvide API for streaming relation data.
Thomas Munro [Tue, 2 Apr 2024 11:17:06 +0000 (00:17 +1300)]
Provide API for streaming relation data.

Introduce an abstraction allowing relation data to be accessed as a
stream of buffers, with an implementation that is more efficient than
the equivalent sequence of ReadBuffer() calls.

Client code supplies a callback that can say which block number it wants
next, and then consumes individual buffers one at a time from the
stream.  This division puts read_stream.c in control of how far ahead it
can see and allows it to read clusters of neighboring blocks with
StartReadBuffers().  It also issues POSIX_FADV_WILLNEED advice ahead of
time when random access is detected.

Other variants of I/O stream will be proposed in future work (for
example to support recovery, whose LsnReadQueue device in
xlogprefetcher.c is a distant cousin of this code and should eventually
be replaced by this), but this basic API is sufficient for many common
executor usage patterns involving predictable access to a single fork of
a single relation.

Several patches using this API are proposed separately.

This stream concept is loosely based on ideas from Andres Freund on how
we should pave the way for later work on asynchronous I/O.

Author: Thomas Munro <[email protected]>
Author: Heikki Linnakangas <[email protected]> (contributions)
Author: Melanie Plageman <[email protected]> (contributions)
Suggested-by: Andres Freund <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Reviewed-by: Melanie Plageman <[email protected]>
Reviewed-by: Nazir Bilal Yavuz <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Tested-by: Tomas Vondra <[email protected]>
Discussion: https://postgr.es/m/CA+hUKGJkOiOCa+mag4BF+zHo7qo=o9CFheB8=g6uT5TUm2gkvA@mail.gmail.com

13 months agoProvide vectored variant of ReadBuffer().
Thomas Munro [Tue, 2 Apr 2024 11:03:08 +0000 (00:03 +1300)]
Provide vectored variant of ReadBuffer().

Break ReadBuffer() up into two steps.  StartReadBuffers() and
WaitReadBuffers() give us two main advantages:

1.  Multiple consecutive blocks can be read with one system call.
2.  Advice (hints of future reads) can optionally be issued to the
kernel ahead of time.

The traditional ReadBuffer() function is now implemented in terms of
those functions, to avoid duplication.

A new GUC io_combine_limit is defined, and the functions for limiting
per-backend pin counts are made into public APIs.  Those are provided
for use by callers of StartReadBuffers(), when deciding how many buffers
to read at once.  The following commit will add a higher level mechanism
for doing that automatically with a practical interface.

With some more infrastructure in later work, StartReadBuffers() could
be extended to start real asynchronous I/O instead of just issuing
advice and leaving WaitReadBuffers() to do the work synchronously.

Author: Thomas Munro <[email protected]>
Author: Andres Freund <[email protected]> (some optimization tweaks)
Reviewed-by: Melanie Plageman <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Reviewed-by: Nazir Bilal Yavuz <[email protected]>
Reviewed-by: Dilip Kumar <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Tested-by: Tomas Vondra <[email protected]>
Discussion: https://postgr.es/m/CA+hUKGJkOiOCa+mag4BF+zHo7qo=o9CFheB8=g6uT5TUm2gkvA@mail.gmail.com

13 months agoDon't use the pg_am system catalog in new test
Alvaro Herrera [Tue, 2 Apr 2024 11:10:16 +0000 (13:10 +0200)]
Don't use the pg_am system catalog in new test

This causes deadlocks because it's a highly trafficked catalog.  Use a
regular table created by the same test instead.

Discussion: https://postgr.es/m/f3e61e27-19d0-5e40-3eb2-53282fa0532a@gmail.com

13 months agoRevert "Custom reloptions for table AM"
Alexander Korotkov [Tue, 2 Apr 2024 08:26:59 +0000 (11:26 +0300)]
Revert "Custom reloptions for table AM"

This reverts commit c95c25f9af4bc77f2f66a587735c50da08c12b37 due to multiple
design issues spotted after commit.

Reported-by: Jeff Davis
Discussion: https://postgr.es/m/11550b536211d5748bb2865ed6cb3502ff073bf7.camel%40j-davis.com

13 months agoUse TidStore for dead tuple TIDs storage during lazy vacuum.
Masahiko Sawada [Tue, 2 Apr 2024 01:15:37 +0000 (10:15 +0900)]
Use TidStore for dead tuple TIDs storage during lazy vacuum.

Previously, we used a simple array for storing dead tuple IDs during
lazy vacuum, which had a number of problems:

* The array used a single allocation and so was limited to 1GB.
* The allocation was pessimistically sized according to table size.
* Lookup with binary search was slow because of poor CPU cache and
  branch prediction behavior.

This commit replaces that array with the TID store from commit
30e144287a.

Since the backing radix tree makes small allocations as needed, the
1GB limit is now gone. Further, the total memory used is now often
smaller by an order of magnitude or more, depending on the
distribution of blocks and offsets. These two features should make
multiple rounds of heap scanning and index cleanup an extremely rare
event. TID lookup during index cleanup is also several times faster,
even more so when index order is correlated with heap tuple order.

Since there is no longer a predictable relationship between the number
of dead tuples vacuumed and the space taken up by their TIDs, the
number of tuples no longer provides any meaningful insights for users,
nor is the maximum number predictable. For that reason this commit
also changes to byte-based progress reporting, with the relevant
columns of pg_stat_progress_vacuum renamed accordingly to
max_dead_tuple_bytes and dead_tuple_bytes.

For parallel vacuum, both the TID store and supplemental information
specific to vacuum are shared among the parallel vacuum workers. As
with the previous array, we don't take any locks on TidStore during
parallel vacuum since writes are still only done by the leader
process.

Bump catalog version.

Reviewed-by: John Naylor, (in an earlier version) Dilip Kumar
Discussion: https://postgr.es/m/CAD21AoAfOZvmfR0j8VmZorZjL7RhTiQdVttNuC4W-Shdc2a-AA%40mail.gmail.com

13 months agoFix assert failure when planning setop subqueries with CTEs
David Rowley [Mon, 1 Apr 2024 23:15:45 +0000 (12:15 +1300)]
Fix assert failure when planning setop subqueries with CTEs

66c0185a3 adjusted the UNION planner to request that union child queries
produce Paths correctly ordered to implement the UNION by way of
MergeAppend followed by Unique.  The code there made a bad assumption
that if the root->parent_root->parse had setOperations set that the
query must be the child subquery of a set operation.  That's not true
when it comes to planning a non-inlined CTE which is parented by a set
operation.  This causes issues as the CTE's targetlist has no
requirement to match up to the SetOperationStmt's groupClauses

Fix this by adding a new parameter to both subquery_planner() and
grouping_planner() to explicitly pass the SetOperationStmt only when
planning set operation child subqueries.

Thank you to Tom Lane for helping to rationalize the decision on the
best function signature for subquery_planner().

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/242fc7c6-a8aa-2daf-ac4c-0a231e2619c1@gmail.com

13 months agoAvoid "unused variable" warning on non-USE_SSL_ENGINE platforms.
Tom Lane [Mon, 1 Apr 2024 23:01:18 +0000 (19:01 -0400)]
Avoid "unused variable" warning on non-USE_SSL_ENGINE platforms.

If we are building with openssl but USE_SSL_ENGINE didn't get set,
initialize_SSL's variable "pkey" is declared but used nowhere.
Apparently this combination hasn't been exercised in the buildfarm
before now, because I've not seen this warning before, even though
the code has been like this a long time.  Move the declaration
to silence the warning (and remove its useless initialization).

Per buildfarm member sawshark.  Back-patch to all supported branches.

13 months agoIntroduce 'options' argument to heap_page_prune()
Heikki Linnakangas [Mon, 1 Apr 2024 21:56:05 +0000 (00:56 +0300)]
Introduce 'options' argument to heap_page_prune()

Currently there is only one option, HEAP_PAGE_PRUNE_MARK_UNUSED_NOW
which replaces the old boolean argument, but upcoming patches will
introduce at least one more. Having a lot of boolean arguments makes
it hard to see at the call sites what the arguments mean, so prefer a
bitmask of options with human-readable names.

Author: Melanie Plageman <[email protected]>
Author: Heikki Linnakangas <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240401172219.fngjosaqdgqqvg4e@liskov

13 months agoInvent --transaction-size option for pg_restore.
Tom Lane [Mon, 1 Apr 2024 20:46:24 +0000 (16:46 -0400)]
Invent --transaction-size option for pg_restore.

This patch allows pg_restore to wrap its commands into transaction
blocks, somewhat like --single-transaction, except that we commit
and start a new block after every N objects.  Using this mode
with a size limit of 1000 or so objects greatly reduces the number
of transactions consumed by the restore, while preventing any
one transaction from taking enough locks to overrun the receiving
server's shared lock table.

(A value of 1000 works well with the default lock table size of
around 6400 locks.  Higher --transaction-size values can be used
if one has increased the receiving server's lock table size.)

Excessive consumption of XIDs has been reported as a problem for
pg_upgrade in particular, but it could be bad for any restore; and the
change also reduces the number of fsyncs and amount of WAL generated,
so it should provide speed benefits too.

This patch does not try to make parallel workers batch the SQL
commands they issue.  The trouble with doing that is that other
workers may need to see the objects a worker creates right away.
Possibly this can be improved later.

In this patch I have hard-wired pg_upgrade to use a transaction size
of 1000 divided by the number of parallel restore jobs allowed
(without that, we'd still be at risk of overrunning the shared lock
table).  Perhaps there would be value in adding another pg_upgrade
option to allow user control of that, but I'm unsure that it's worth
the trouble; I think few users would use it, and any who did would see
not that much benefit compared to the default.

Patch by me, but the original idea to batch SQL commands during
restore is due to Robins Tharakan.

Discussion: https://postgr.es/m/a9f9376f1c3343a6bb319dce294e20ac@EX13D05UWC001.ant.amazon.com

13 months agoRearrange pg_dump's handling of large objects for better efficiency.
Tom Lane [Mon, 1 Apr 2024 20:25:56 +0000 (16:25 -0400)]
Rearrange pg_dump's handling of large objects for better efficiency.

Commit c0d5be5d6 caused pg_dump to create a separate BLOB metadata TOC
entry for each large object (blob), but it did not touch the ancient
decision to put all the blobs' data into a single "BLOBS" TOC entry.
This is bad for a few reasons: for databases with millions of blobs,
the TOC becomes unreasonably large, causing performance issues;
selective restore of just some blobs is quite impossible; and we
cannot parallelize either dump or restore of the blob data, since our
architecture for that relies on farming out whole TOC entries to
worker processes.

To improve matters, let's group multiple blobs into each blob metadata
TOC entry, and then make corresponding per-group blob data TOC entries.
Selective restore using pg_restore's -l/-L switches is then possible,
though only at the group level.  (Perhaps we should provide a switch
to allow forcing one-blob-per-group for users who need precise
selective restore and don't have huge numbers of blobs.  This patch
doesn't do that, instead just hard-wiring the maximum number of blobs
per entry at 1000.)

The blobs in a group must all have the same owner, since the TOC entry
format only allows one owner to be named.  In this implementation
we also require them to all share the same ACL (grants); the archive
format wouldn't require that, but pg_dump's representation of
DumpableObjects does.  It seems unlikely that either restriction
will be problematic for databases with huge numbers of blobs.

The metadata TOC entries now have a "desc" string of "BLOB METADATA",
and their "defn" string is just a newline-separated list of blob OIDs.
The restore code has to generate creation commands, ALTER OWNER
commands, and drop commands (for --clean mode) from that.  We would
need special-case code for ALTER OWNER and drop in any case, so the
alternative of keeping the "defn" as directly executable SQL code
for creation wouldn't buy much, and it seems like it'd bloat the
archive to little purpose.

Since we require the blobs of a metadata group to share the same ACL,
we can furthermore store only one copy of that ACL, and then make
pg_restore regenerate the appropriate commands for each blob.  This
saves space in the dump file not only by removing duplicative SQL
command strings, but by not needing a separate TOC entry for each
blob's ACL.  In turn, that reduces client-side memory requirements for
handling many blobs.

ACL TOC entries that need this special processing are labeled as
"ACL"/"LARGE OBJECTS nnn..nnn".  If we have a blob with a unique ACL,
continue to label it as "ACL"/"LARGE OBJECT nnn".  We don't actually
have to make such a distinction, but it saves a few cycles during
restore for the easy case, and it seems like a good idea to not change
the TOC contents unnecessarily.

The data TOC entries ("BLOBS") are exactly the same as before,
except that now there can be more than one, so we'd better give them
identifying tag strings.

Also, commit c0d5be5d6 put the new BLOB metadata TOC entries into
SECTION_PRE_DATA, which perhaps is defensible in some ways, but
it's a rather odd choice considering that we go out of our way to
treat blobs as data.  Moreover, because parallel restore handles
the PRE_DATA section serially, this means we'd only get part of the
parallelism speedup we could hope for.  Move these entries into
SECTION_DATA, letting us parallelize the lo_create calls not just the
data loading when there are many blobs.  Add dependencies to ensure
that we won't try to load data for a blob we've not yet created.

As this stands, we still generate a separate TOC entry for any comment
or security label attached to a blob.  I feel comfortable in believing
that comments and security labels on blobs are rare, so this patch
should be enough to get most of the useful TOC compression for blobs.

We have to bump the archive file format version number, since existing
versions of pg_restore wouldn't know they need to do something special
for BLOB METADATA, plus they aren't going to work correctly with
multiple BLOBS entries or multiple-large-object ACL entries.

The directory and tar-file format handlers need some work
for multiple BLOBS entries: they used to hard-wire the file name
as "blobs.toc", which is replaced here with "blobs_<dumpid>.toc".
The 002_pg_dump.pl test script also knows about that and requires
minor updates.  (I had to drop the test for manually-compressed
blobs.toc files with LZ4, because lz4's obtuse command line
design requires explicit specification of the output file name
which seems impractical here.  I don't think we're losing any
useful test coverage thereby; that test stanza seems completely
duplicative with the gzip and zstd cases anyway.)

In passing, centralize management of the lo_buf used to hold data
while restoring blobs.  The code previously had each format handler
create lo_buf, which seems rather pointless given that the format
handlers all make it the same way.  Moreover, the format handlers
never use lo_buf directly, making this setup a failure from a
separation-of-concerns standpoint.  Let's move the responsibility into
pg_backup_archiver.c, which is the only module concerned with lo_buf.
The reason to do this in this patch is that it allows a centralized
fix for the now-false assumption that we never restore blobs in
parallel.  Also, get rid of dead code in DropLOIfExists: it's been a
long time since we had any need to be able to restore to a pre-9.0
server.

Discussion: https://postgr.es/m/a9f9376f1c3343a6bb319dce294e20ac@EX13D05UWC001.ant.amazon.com

13 months agoAvoid possible longjmp-induced logic error in PLy_trigger_build_args.
Tom Lane [Mon, 1 Apr 2024 19:15:03 +0000 (15:15 -0400)]
Avoid possible longjmp-induced logic error in PLy_trigger_build_args.

The "pltargs" variable wasn't marked volatile, which makes it unsafe
to change its value within the PG_TRY block.  It looks like the worst
outcome would be to fail to release a refcount on Py_None during an
(improbable) error exit, which would likely go unnoticed in the field.
Still, it's a bug.  A one-liner fix could be to mark pltargs volatile,
but on the whole it seems cleaner to arrange things so that we don't
change its value within PG_TRY.

Per report from Xing Guo.  This has been there for quite awhile,
so back-patch to all supported branches.

Discussion: https://postgr.es/m/CACpMh+DLrk=fDv07MNpBT4J413fDAm+gmMXgi8cjPONE+jvzuw@mail.gmail.com

13 months agoFix assorted resource leaks in new pg_createsubscriber code.
Tom Lane [Mon, 1 Apr 2024 17:47:27 +0000 (13:47 -0400)]
Fix assorted resource leaks in new pg_createsubscriber code.

Various error paths did not release resources before returning.
While it's likely that the program would just exit shortly later,
none of the functions in question have summary exit(1) calls,
so they should not be assuming that.

Ranier Vilela and Tom Lane, per reports from Coverity

Discussion: https://postgr.es/m/CAEudQAr2_SZFxB4kXJiL4+2UaNZxUk5UBJtj0oXyJYMGZu-03g@mail.gmail.com

13 months agoHandle non-chain tuples outside of heap_prune_chain()
Heikki Linnakangas [Mon, 1 Apr 2024 17:33:50 +0000 (20:33 +0300)]
Handle non-chain tuples outside of heap_prune_chain()

Handle dead branches of aborted HOT chains outside heap_prune_chain()
as a separate phase. This simplifies the logic in heap_prune_chain(),
as well as allowing us to clean up more RECENTLY_DEAD -> DEAD chains.

To accomplish this efficiently, partition tuples into HOT and non-HOT
while first collecting visibility information for each tuple in
heap_page_prune(). Then call heap_prune_chain() only on potential
chain members. Then mop up the leftover HOT tuples afterwards.

As part of this, keep track of which items on page have already been
processed, in 'processed' array. This replaces the 'marked' array
which was only set for tuples marked for removal or redirection. The
'processed' array is updated also for items that are left unchanged,
when we conclude that an item can be left unchanged. At the end of
pruning, every item on the page should be marked as processed in the
array; an assertion is added for that.

Author: Melanie Plageman <[email protected]>
Author: Heikki Linnakangas <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240330055710.kqg6ii2cdojsxgje@liskov

13 months agoRefactor heap_prune_chain()
Heikki Linnakangas [Mon, 1 Apr 2024 10:28:44 +0000 (13:28 +0300)]
Refactor heap_prune_chain()

Keep track of the number of deleted tuples in PruneState and record this
information when recording a tuple dead, unused or redirected. This
removes a special case from the traversal and chain processing logic as
well as setting a precedent of recording the impact of prune actions in
the record functions themselves. This paradigm will be used in future
commits which move tracking of additional statistics on pruning actions
from lazy_scan_prune() to heap_prune_chain().

Simplify heap_prune_chain()'s chain traversal logic by handling each
case explicitly. That is, do not attempt to share code when processing
different types of chains. For each category of chain, process it
specifically and procedurally: first handling the root, then any
intervening tuples, and, finally, the end of the chain.

While we are at it, add a few new comments to heap_prune_chain()
clarifying some special cases involving RECENTLY_DEAD tuples.

Author: Melanie Plageman <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240330055710.kqg6ii2cdojsxgje@liskov

13 months agoMinor refactoring in heap_page_prune
Heikki Linnakangas [Mon, 1 Apr 2024 09:07:30 +0000 (12:07 +0300)]
Minor refactoring in heap_page_prune

Pass 'page', 'blockno' and 'maxoff' to heap_prune_chain() as
arguments, so that it doesn't need to fetch them from the buffer. This
saves a few cycles per chain.

Remove the "if (off_loc != NULL)" checks, and require the caller to
pass a non-NULL 'off_loc'. Pass a pointer to a dummy local variable
when it's not needed. Those checks are cheap, but it's still better to
avoid them in the per-chain loops when we can do so easily.

The CPU time saving from these changes are hardly measurable, but
fewer instructions is good anyway, so why not. I spotted the potential
for these while reviewing Melanie Plageman's patch set to combine
prune and freeze records.

Discussion: https://www.postgresql.org/message-id/CAAKRu_abm2tHhrc0QSQa%3D%3DsHe%3DVA1%3Doz1dJMQYUOKuHmu%2B9Xrg%40mail.gmail.com

13 months agoAdd new COPY option LOG_VERBOSITY.
Masahiko Sawada [Mon, 1 Apr 2024 06:25:25 +0000 (15:25 +0900)]
Add new COPY option LOG_VERBOSITY.

This commit adds a new COPY option LOG_VERBOSITY, which controls the
amount of messages emitted during processing. Valid values are
'default' and 'verbose'.

This is currently used in COPY FROM when ON_ERROR option is set to
ignore. If 'verbose' is specified, a NOTICE message is emitted for
each discarded row, providing additional information such as line
number, column name, and the malformed value. This helps users to
identify problematic rows that failed to load.

Author: Bharath Rupireddy
Reviewed-by: Michael Paquier, Atsushi Torikoshi, Masahiko Sawada
Discussion: https://www.postgresql.org/message-id/CALj2ACUk700cYhx1ATRQyRw-fBM%2BaRo6auRAitKGff7XNmYfqQ%40mail.gmail.com

13 months agoRevert "Speed up tail processing when hashing aligned C strings"
John Naylor [Sun, 31 Mar 2024 07:18:36 +0000 (14:18 +0700)]
Revert "Speed up tail processing when hashing aligned C strings"

This reverts commit 07f0f6abfc7f6c55cede528d9689dedecefc734a.

This has shown failures on both Valgrind and big-endian machines,
per members skink and pike.

13 months agoSpeed up tail processing when hashing aligned C strings
John Naylor [Sun, 31 Mar 2024 05:19:16 +0000 (12:19 +0700)]
Speed up tail processing when hashing aligned C strings

After encountering the NUL terminator, the word-at-a-time loop exits
and we must hash the remaining bytes. Previously we calculated the
terminator's position and re-loaded the remaining bytes from the input
string. We already have all the data we need in a register, so let's
just mask off the bytes we need and hash them immediately. The mask can
be cheaply computed without knowing the terminator's position. We still
need that position for the length calculation, but the CPU can now
do that in parallel with other work, shortening the dependency chain.

Ants Aasma and John Naylor

Discussion: https://postgr.es/m/CANwKhkP7pCiW_5fAswLhs71-JKGEz1c1%2BPC0a_w1fwY4iGMqUA%40mail.gmail.com

13 months agoLet table AM insertion methods control index insertion
Alexander Korotkov [Sat, 30 Mar 2024 20:39:03 +0000 (22:39 +0200)]
Let table AM insertion methods control index insertion

Previously, the executor did index insert unconditionally after calling
table AM interface methods tuple_insert() and multi_insert().  This commit
introduces the new parameter insert_indexes for these two methods.  Setting
'*insert_indexes' to true saves the current logic.  Setting it to false
indicates that table AM cares about index inserts itself and doesn't want the
caller to do that.

Discussion: https://postgr.es/m/CAPpHfdurb9ycV8udYqM%3Do0sPS66PJ4RCBM1g-bBpvzUfogY0EA%40mail.gmail.com
Reviewed-by: Pavel Borisov, Matthias van de Meent, Mark Dilger
13 months agoCustom reloptions for table AM
Alexander Korotkov [Sat, 30 Mar 2024 20:36:25 +0000 (22:36 +0200)]
Custom reloptions for table AM

Let table AM define custom reloptions for its tables.  This allows to
specify AM-specific parameters by WITH clause when creating a table.

The code may use some parts from prior work by Hao Wu.

Discussion: https://postgr.es/m/CAPpHfdurb9ycV8udYqM%3Do0sPS66PJ4RCBM1g-bBpvzUfogY0EA%40mail.gmail.com
Discussion: https://postgr.es/m/AMUA1wBBBxfc3tKRLLdU64rb.1.1683276279979.Hmail.wuhao%40hashdata.cn
Reviewed-by: Reviewed-by: Pavel Borisov, Matthias van de Meent
13 months agoGeneralize relation analyze in table AM interface
Alexander Korotkov [Sat, 30 Mar 2024 20:34:04 +0000 (22:34 +0200)]
Generalize relation analyze in table AM interface

Currently, there is just one algorithm for sampling tuples from a table written
in acquire_sample_rows().  Custom table AM can just redefine the way to get the
next block/tuple by implementing scan_analyze_next_block() and
scan_analyze_next_tuple() API functions.

This approach doesn't seem general enough.  For instance, it's unclear how to
sample this way index-organized tables.  This commit allows table AM to
encapsulate the whole sampling algorithm (currently implemented in
acquire_sample_rows()) into the relation_analyze() API function.

Discussion: https://postgr.es/m/CAPpHfdurb9ycV8udYqM%3Do0sPS66PJ4RCBM1g-bBpvzUfogY0EA%40mail.gmail.com
Reviewed-by: Pavel Borisov, Matthias van de Meent
13 months agoAdd pg_basetype() function to extract a domain's base type.
Tom Lane [Sat, 30 Mar 2024 17:57:19 +0000 (13:57 -0400)]
Add pg_basetype() function to extract a domain's base type.

This SQL-callable function behaves much like our internal utility
function getBaseType(), except it returns NULL rather than failing for
an invalid type OID.  (That behavior is modeled on our experience with
other catalog-inquiry functions such as the ACL checking functions.)
The key advantage over doing a join to pg_type is that it will loop
as needed to find the bottom base type of a nest of domains.

Steve Chavez, reviewed by jian he and others

Discussion: https://postgr.es/m/CAGRrpzZSX8j=MQcbCSEisFA=ic=K3bknVfnFjAv1diVJxFHJvg@mail.gmail.com

13 months agoStabilize postgres_fdw test
Alvaro Herrera [Sat, 30 Mar 2024 13:16:54 +0000 (14:16 +0100)]
Stabilize postgres_fdw test

The test fails when RESET statement_timeout takes longer than 10ms.
Avoid the problem by using SET LOCAL instead.

Overall, this test is not ideal: 10ms could be shorter than the time to
have sent the query to the "remote" server, so it's possible that on
some machines this test doesn't actually witness a remote query being
cancelled.  We may want to improve on this someday by using some other
testing technique, but for now it's better than nothing.  I verified
manually that one round of remote cancellation occurs when this runs on
my machine.

Discussion: https://postgr.es/m/CAGECzQRsdWnj=YaaPCnA8d7E1AdbxRPBYmyBQRMPUijR2MpM_w@mail.gmail.com

13 months agodoc: Improve "Partition Maintenance" section
Alvaro Herrera [Sat, 30 Mar 2024 13:08:13 +0000 (14:08 +0100)]
doc: Improve "Partition Maintenance" section

This adds some reference links and clarifies the wording a bit.

Author: Robert Treat <[email protected]>
Reviewed-by: Ashutosh Bapat <[email protected]>
Discussion: https://postgr.es/m/CABV9wwNGn-pweak6_pvL5PJ1mivDNPKfg0Tck_1oTUETv5Y=dg@mail.gmail.com

13 months agoAdd support for MERGE ... WHEN NOT MATCHED BY SOURCE.
Dean Rasheed [Sat, 30 Mar 2024 10:00:26 +0000 (10:00 +0000)]
Add support for MERGE ... WHEN NOT MATCHED BY SOURCE.

This allows MERGE commands to include WHEN NOT MATCHED BY SOURCE
actions, which operate on rows that exist in the target relation, but
not in the data source. These actions can execute UPDATE, DELETE, or
DO NOTHING sub-commands.

This is in contrast to already-supported WHEN NOT MATCHED actions,
which operate on rows that exist in the data source, but not in the
target relation. To make this distinction clearer, such actions may
now be written as WHEN NOT MATCHED BY TARGET.

Writing WHEN NOT MATCHED without specifying BY SOURCE or BY TARGET is
equivalent to writing WHEN NOT MATCHED BY TARGET.

Dean Rasheed, reviewed by Alvaro Herrera, Ted Yu and Vik Fearing.

Discussion: https://postgr.es/m/CAEZATCWqnKGc57Y_JanUBHQXNKcXd7r=0R4NEZUVwP+syRkWbA@mail.gmail.com

13 months agoAdd unicode_strtitle() for Unicode Default Case Conversion.
Jeff Davis [Sat, 30 Mar 2024 00:35:07 +0000 (17:35 -0700)]
Add unicode_strtitle() for Unicode Default Case Conversion.

This brings the titlecasing implementation for the builtin provider
out of formatting.c and into unicode_case.c, along with
unicode_strlower() and unicode_strupper(). Accepts an arbitrary word
boundary callback.

Simple for now, but can be extended to support the Unicode Default
Case Conversion algorithm with full case mapping.

Discussion: https://postgr.es/m/3bc653b5d562ae9e2838b11cb696816c328a489a[email protected]
Reviewed-by: Peter Eisentraut
13 months agoRemove superfluous trailing semicolons
Daniel Gustafsson [Fri, 29 Mar 2024 22:51:43 +0000 (23:51 +0100)]
Remove superfluous trailing semicolons

Two semicolons were accidentally added to rows which were already
terminated semicolons.  While harmless, fix by removing these.

Author: Richard Guo <[email protected]>
Discussion: https://postgr.es/m/CAMbWs4_fnJ0+yOgFioswzLE7t6R8P6cqbuacFVeZqbESFAjs1A@mail.gmail.com

13 months agoUse version for builtin collations.
Jeff Davis [Fri, 29 Mar 2024 17:52:24 +0000 (10:52 -0700)]
Use version for builtin collations.

Given that the version field already exists, there's little reason not
to use it. Suggestion from Peter Eisentraut.

Discussion: https://postgr.es/m/613c120a-5413-4fa7-a501-6590eae558f8@eisentraut.org
Reviewed-by: Peter Eisentraut
13 months agoTry to stabilize flappy test result.
Tom Lane [Fri, 29 Mar 2024 14:40:31 +0000 (10:40 -0400)]
Try to stabilize flappy test result.

This recently-added test case checks the plan of an inner join
between two identical tables.  It's just chance which join order
the planner will pick, and in the presence of any variation in
the underlying statistics, the displayed plan might change.
Add a WHERE condition to break the cost symmetry and hopefully
stabilize matters.

(We're still trying to understand exactly why the underlying
statistics aren't as stable as intended, but this seems like
a good change anyway, since this test would surely bite us
again in future.)

While here, clean up assorted comment spelling, grammar, and
whitespace problems.

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

13 months agoAdd allow_alter_system GUC.
Robert Haas [Fri, 29 Mar 2024 12:44:45 +0000 (08:44 -0400)]
Add allow_alter_system GUC.

This is marked PGC_SIGHUP, so it can only be set in a configuration
file, not anywhere else; and it is also marked GUC_DISALLOW_IN_AUTO_FILE,
so it can't be set using ALTER SYSTEM. When set to false, the
ALTER SYSTEM command is disallowed.

There was considerable concern that this would be misinterpreted as
a security feature, which it is not, because a determined superuser
has various ways of bypassing it. Hence, a lot of work has gone into
wordsmithing the documentation, in the hopes of avoiding any such
confusion.

Jelte Fennemia-Nio and Gabriele Bartolini, with wording suggestions
for the documentation from many others.

Discussion: http://postgr.es/m/CA%2BVUV5rEKt2%2BCdC_KUaPoihMu%2Bi5ChT4WVNTr4CD5-xXZUfuQw%40mail.gmail.com

13 months agoAllow "internal" subtransactions in parallel mode.
Tom Lane [Thu, 28 Mar 2024 16:43:10 +0000 (12:43 -0400)]
Allow "internal" subtransactions in parallel mode.

Allow use of BeginInternalSubTransaction() in parallel mode, so long
as the subtransaction doesn't attempt to acquire an XID or increment
the command counter.  Given those restrictions, the other parallel
processes don't need to know about the subtransaction at all, so
this should be safe.  The benefit is that it allows subtransactions
intended for error recovery, such as pl/pgsql exception blocks,
to be used in PARALLEL SAFE functions.

Another reason for doing this is that the API of
BeginInternalSubTransaction() doesn't allow reporting failure.
pl/python for one, and perhaps other PLs, copes very poorly with an
error longjmp out of BeginInternalSubTransaction().  The headline
feature of this patch removes the only easily-triggerable failure
case within that function.  There remain some resource-exhaustion
and similar cases, which we now deal with by promoting them to FATAL
errors, so that callers need not try to clean up.  (It is likely
that such errors would leave us with corrupted transaction state
inside xact.c, making recovery difficult if not impossible anyway.)

Although this work started because of a report of a pl/python crash,
we're not going to do anything about that in the back branches.
Back-patching this particular fix is obviously not very wise.
While we could contemplate some narrower band-aid, pl/python is
already an untrusted language, so it seems okay to classify this
as a "so don't do that" case.

Patch by me, per report from Hao Zhang.  Thanks to Robert Haas for
review.

Discussion: https://postgr.es/m/CALY6Dr-2yLVeVPhNMhuBnRgOZo1UjoTETgtKBx1B2gUi8yy+3g@mail.gmail.com

13 months agoALTER TABLE: rework determination of access method ID
Alvaro Herrera [Thu, 28 Mar 2024 15:51:20 +0000 (16:51 +0100)]
ALTER TABLE: rework determination of access method ID

Avoid setting an access method OID for relation kinds that don't take
one.  Code review for new feature added in 374c7a229042.

Author: Justin Pryzby <[email protected]>
Reported-by: Alexander Lakhin <[email protected]>
Discussion: https://postgr.es/m/e5516ac1-5264-c3c0-d822-9e6f614ea93b@gmail.com

13 months agoUpdate comment in set_dummy_rel_pathlist().
Tom Lane [Thu, 28 Mar 2024 15:44:00 +0000 (11:44 -0400)]
Update comment in set_dummy_rel_pathlist().

This comment claimed that set_dummy_rel_pathlist() has callers
other than (possibly indirectly) set_rel_size().  It doesn't,
so revise the argument to not rely on that.

Noted by Richard Guo.

Discussion: https://postgr.es/m/CAMbWs4-KFEU_fDuJPNCOkUu3rwvZvKBEytkd9VrM4kH4-2h1CQ@mail.gmail.com

13 months agoRemove translation markers from libpq-be-fe-helpers.h
Alvaro Herrera [Thu, 28 Mar 2024 12:12:12 +0000 (13:12 +0100)]
Remove translation markers from libpq-be-fe-helpers.h

Apparently these markers cause the modules to not link correctly in some
platforms, at least per buildfarm member indri; moreover, this code is
only used in modules that don't have a translation.  If we someday add
i18n support to contrib/ it might be worth revisiting this.

13 months agolibpq-be-fe-helpers.h: wrap new cancel APIs
Alvaro Herrera [Thu, 28 Mar 2024 10:31:03 +0000 (11:31 +0100)]
libpq-be-fe-helpers.h: wrap new cancel APIs

Commit 61461a300c1c introduced new functions to libpq for cancelling
queries.  This commit introduces a helper function that backend-side
libraries and extensions can use to invoke those.  This function takes a
timeout and can itself be interrupted while it is waiting for a cancel
request to be sent and processed, instead of being blocked.

This replaces the usage of the old functions in postgres_fdw and dblink.

Finally, it also adds some test coverage for the cancel support in
postgres_fdw.

Author: Jelte Fennema-Nio <[email protected]>
Discussion: https://postgr.es/m/CAGECzQT_VgOWWENUqvUV9xQmbaCyXjtRRAYO8W07oqashk_N+g@mail.gmail.com

13 months agoRemove obsolete comment about VACUUM retrying pruning
Heikki Linnakangas [Thu, 28 Mar 2024 08:18:48 +0000 (10:18 +0200)]
Remove obsolete comment about VACUUM retrying pruning

Commit 1ccc1e05ae removed the retry logic that the comment talked
about.

Reviewed-by: Melanie Plageman <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240328015326.x5gnzsohl6j23b42@liskov

13 months agoImprove tab completion for ALTER TABLE ALTER COLUMN SET in psql.
Masahiko Sawada [Thu, 28 Mar 2024 07:30:10 +0000 (16:30 +0900)]
Improve tab completion for ALTER TABLE ALTER COLUMN SET in psql.

The commit changes the tab completion to add DATA TYPE after
ALTER TABLE ... ALTER COLUMN ... SET.

Author: Vignesh C
Reviewed-by: Shubham Khanna, Masahiko Sawada
Discussion: https://postgr.es/m/CALDaNm1aEdJb-QJi%3DGWStkfj_%2BEDUK_VtDkn%2BTjQ2z7HyU0MBw%40mail.gmail.com

13 months agoImprove style of pg_lfind32().
Nathan Bossart [Thu, 28 Mar 2024 01:26:05 +0000 (20:26 -0500)]
Improve style of pg_lfind32().

This commit simplifies pg_lfind32() a bit by moving the standard
one-by-one linear search code to an inline helper function.

Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/20240327013616.GA3940109%40nathanxps13

13 months agoRethink create and attach APIs of shared TidStore.
Masahiko Sawada [Thu, 28 Mar 2024 01:03:28 +0000 (10:03 +0900)]
Rethink create and attach APIs of shared TidStore.

Previously, the behavior of TidStoreCreate() was inconsistent between
local and shared TidStore instances in terms of memory limitation. For
local TidStore, a memory context was created with initial and maximum
memory block sizes, as well as a minimum memory context size, based on
the specified max_bytes values. However, for shared TidStore, the
provided DSA area was used for TID storage. Although commit bb952c8c8b
allowed specifying the initial and maximum DSA segment sizes, callers
would have needed to clamp their own limits, which was not consistent
and user-friendly.

With this commit, when creating a shared TidStore, a dedicated DSA
area is created for TID storage instead of using a provided DSA
area. The initial and maximum DSA segment sizes are chosen based on
the specified max_bytes. Other processes can attach to the shared
TidStore using the handle of the created DSA returned by the new
TidStoreGetDSA() function and the DSA pointer returned by
TidStoreGetHandle(). The created DSA has the same lifetime as the
shared TidStore and is deleted when all processes detach from it.

To improve clarity, the TidStoreCreate() function has been divided
into two separate functions: TidStoreCreateLocal() and
TidStoreCreateShared().

Reviewed-by: John Naylor
Discussion: https://postgr.es/m/CAD21AoAyc1j%3DBCdUqZfk6qbdjZ68UgRx1Gkpk0oah4K7S0Ri9g%40mail.gmail.com

13 months agodoc: fix CREATE ROLE typo
Bruce Momjian [Wed, 27 Mar 2024 21:58:11 +0000 (17:58 -0400)]
doc:  fix CREATE ROLE typo

This wording typo was added in PG 16.

Reported-by: [email protected]
Discussion: https://postgr.es/m/171150077554.7105.801523271545956671@wrigleys.postgresql.org

Backpatch-through: 16

13 months agoRun perltidy on generate-unicode_version.pl.
Jeff Davis [Wed, 27 Mar 2024 20:21:29 +0000 (13:21 -0700)]
Run perltidy on generate-unicode_version.pl.

13 months agoFix unnecessary use of moving-aggregate mode with non-moving frame.
Tom Lane [Wed, 27 Mar 2024 17:39:03 +0000 (13:39 -0400)]
Fix unnecessary use of moving-aggregate mode with non-moving frame.

When a plain aggregate is used as a window function, and the window
frame start is specified as UNBOUNDED PRECEDING, the frame's head
cannot move so we do not need to use moving-aggregate mode.  The check
for that was put into initialize_peragg(), failing to notice that
ExecInitWindowAgg() calls that function before it's filled in
winstate->frameOptions.  Since makeNode() would have zeroed the field,
this didn't provoke uninitialized-value complaints, nor would the
erroneous decision have resulted in more than a little inefficiency.
Still, it's wrong, so move the initialization of
winstate->frameOptions earlier to make it work properly.

While here, also fix a thinko in a comment.  Both errors crept in in
commit a9d9acbf2 which introduced the moving-aggregate mode.

Spotted by Vallimaharajan G.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/18e7f2a5167.fe36253866818.977923893562469143@zohocorp.com

13 months agoAdjust documentation for syncfs().
Nathan Bossart [Wed, 27 Mar 2024 15:23:13 +0000 (10:23 -0500)]
Adjust documentation for syncfs().

Commit 8c16ad3b43 created a new appendix for syncfs(), which is
excessive for such a small amount of content.  This commit moves
the description of the caveats to be aware of when using syncfs()
back to the documentation for recovery_init_sync_method.  The
documentation for the other utilities with syncfs() support now
directs readers to recovery_init_sync_method for information about
these caveats.

Reported-by: Peter Eisentraut, Robert Haas
Suggested-by: Robert Haas
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/42804669-7063-1320-ed37-3226d5f1067d%40eisentraut.org
Discussion: https://postgr.es/m/CA%2BTgmobUiqKr%2BZMCLc5Qap-sXBnjfGUU%2BZBmzYEjUuWyjsGr1g%40mail.gmail.com

13 months agoRename COMPAT_OPTIONS_CLIENT to COMPAT_OPTIONS_OTHER.
Robert Haas [Wed, 27 Mar 2024 14:45:28 +0000 (10:45 -0400)]
Rename COMPAT_OPTIONS_CLIENT to COMPAT_OPTIONS_OTHER.

The user-facing name is "Other Platforms and Clients", but the
internal name seems too focused on clients specifically, especially
given the plan to add a new setting to this session that is about
platform or deployment model compatibility rather than client
compatibility.

Jelte Fennema-Nio

Discussion: http://postgr.es/m/CAGECzQTfMbDiM6W3av+3weSnHxJvPmuTEcjxVvSt91sQBdOxuQ@mail.gmail.com

13 months agoFix unstable aggregate regression test
David Rowley [Wed, 27 Mar 2024 11:13:48 +0000 (00:13 +1300)]
Fix unstable aggregate regression test

Buildfarm member avocet has shown a plan change by switching the
finalize aggregate stage to use a GroupAggregate rather than a
HashAggregate.  This is consistent with autovacuum having triggered on
the table, per analysis by Alexander Lakhin.

Fix this by disabling autovacuum on the table.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/m/d4493a28-589a-5328-fed5-250f2d7d3e2a@gmail.com
Backpatch-through: 16, where this test was added.

13 months agoAdd functions to generate random numbers in a specified range.
Dean Rasheed [Wed, 27 Mar 2024 10:12:39 +0000 (10:12 +0000)]
Add functions to generate random numbers in a specified range.

This adds 3 new variants of the random() function:

    random(min integer, max integer) returns integer
    random(min bigint, max bigint) returns bigint
    random(min numeric, max numeric) returns numeric

Each returns a random number x in the range min <= x <= max.

For the numeric function, the number of digits after the decimal point
is equal to the number of digits that "min" or "max" has after the
decimal point, whichever has more.

The main entry points for these functions are in a new C source file.
The existing random(), random_normal(), and setseed() functions are
moved there too, so that they can all share the same PRNG state, which
is kept private to that file.

Dean Rasheed, reviewed by Jian He, David Zhang, Aleksander Alekseev,
and Tomas Vondra.

Discussion: https://postgr.es/m/CAEZATCV89Vxuq93xQdmc0t-0Y2zeeNQTdsjbmV7dyFBPykbV4Q@mail.gmail.com

13 months agoFix some typos and grammar issues from commit 87985cc92522
Alexander Korotkov [Wed, 27 Mar 2024 09:46:12 +0000 (11:46 +0200)]
Fix some typos and grammar issues from commit 87985cc92522

Reported-by: Alexander Lakhin
13 months agoFix random failure in 004_subscription.
Amit Kapila [Wed, 27 Mar 2024 08:45:03 +0000 (14:15 +0530)]
Fix random failure in 004_subscription.

After the upgrade, the failed test was ensuring that the changes made on
the publisher should be replicated to the subscriber. We missed waiting
for one of the subscriptions to catch up.

Per buildfarm

Author: Vignesh C
Reviewed-by: Kuroda Hayato
Discussion: https://postgr.es/m/CALDaNm0z=fLtio1h50K8WossUGXU+gy0H9y9=RYh1DDZiq2EDw@mail.gmail.com

13 months agoChange last_inactive_time to inactive_since in pg_replication_slots.
Amit Kapila [Wed, 27 Mar 2024 03:57:44 +0000 (09:27 +0530)]
Change last_inactive_time to inactive_since in pg_replication_slots.

Commit a11f330b55 added last_inactive_time to show the last time the slot
was inactive. But, it tells the last time that a currently-inactive slot
previously *WAS* active. This could be unclear, so we changed the name to
inactive_since.

Reported-by: Robert Haas
Author: Bharath Rupireddy
Reviewed-by: Bertrand Drouvot, Shveta Malik, Amit Kapila
Discussion: https://postgr.es/m/CA+Tgmob_Ta-t2ty8QrKHBGnNLrf4ZYcwhGHGFsuUoFrAEDw4sA@mail.gmail.com
Discussion: https://postgr.es/m/CALj2ACUXS0SfbHzsX8bqo+7CZhocsV52Kiu7OWGb5HVPAmJqnA@mail.gmail.com

13 months agoAllow specifying initial and maximum segment sizes for DSA.
Masahiko Sawada [Wed, 27 Mar 2024 02:43:29 +0000 (11:43 +0900)]
Allow specifying initial and maximum segment sizes for DSA.

Previously, the DSA segment size always started with 1MB and grew up
to DSA_MAX_SEGMENT_SIZE. It was inconvenient in certain scenarios,
such as when the caller desired a soft constraint on the total DSA
segment size, limiting it to less than 1MB.

This commit introduces the capability to specify the initial and
maximum DSA segment sizes when creating a DSA area, providing more
flexibility and control over memory usage.

Reviewed-by: John Naylor, Tomas Vondra
Discussion: https://postgr.es/m/CAD21AoAYGGC1ePjVX0H%2Bpp9rH%3D9vuPK19nNOiu12NprdV5TVJA%40mail.gmail.com

13 months agoFix compiler warning for pg_lfind32().
Nathan Bossart [Wed, 27 Mar 2024 01:27:46 +0000 (20:27 -0500)]
Fix compiler warning for pg_lfind32().

The newly-introduced "one_by_one" label produces -Wunused-label
warnings when building without SIMD support.  To fix, move the
label into the SIMD section of this function.

Oversight in commit 7644a7340c.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/3189995.1711495704%40sss.pgh.pa.us

13 months agoAdd commit 64e401b62b to .git-blame-ignore-revs.
Nathan Bossart [Tue, 26 Mar 2024 20:08:47 +0000 (15:08 -0500)]
Add commit 64e401b62b to .git-blame-ignore-revs.

13 months agoRemove some redundant set_cheapest() calls.
Tom Lane [Tue, 26 Mar 2024 20:02:37 +0000 (16:02 -0400)]
Remove some redundant set_cheapest() calls.

Commit e2fa76d80 centralized the responsibility for doing
set_cheapest() for a baserel, but these functions added later
seemingly didn't get the memo.  There's no apparent reason why
we need the cheapest path for these relation types to be available
any sooner than it is for other base relation types, so delete the
duplicate calls.  Doesn't save much since there's only one path
in these cases, but it might improve clarity.

Richard Guo

Discussion: https://postgr.es/m/CAMbWs4-KFEU_fDuJPNCOkUu3rwvZvKBEytkd9VrM4kH4-2h1CQ@mail.gmail.com

13 months agoOptimize roles_is_member_of() with a Bloom filter.
Nathan Bossart [Tue, 26 Mar 2024 19:43:37 +0000 (14:43 -0500)]
Optimize roles_is_member_of() with a Bloom filter.

When the list of roles gathered by roles_is_member_of() grows very
large, a Bloom filter is created to help avoid some linear searches
through the list.  The threshold for creating the Bloom filter is
set arbitrarily high and may require future adjustment.

Suggested-by: Tom Lane
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/CAGvXd3OSMbJQwOSc-Tq-Ro1CAz%3DvggErdSG7pv2s6vmmTOLJSg%40mail.gmail.com

13 months agoFix failure of ALTER FOREIGN TABLE SET SCHEMA to move sequences.
Tom Lane [Tue, 26 Mar 2024 19:28:16 +0000 (15:28 -0400)]
Fix failure of ALTER FOREIGN TABLE SET SCHEMA to move sequences.

Ordinary ALTER TABLE SET SCHEMA will also move any owned sequences
into the new schema.  We failed to do likewise for foreign tables,
because AlterTableNamespaceInternal believed that only certain
relkinds could have indexes, owned sequences, or constraints.
We could simply add foreign tables to that relkind list, but it
seems likely that the same oversight could be made again in
future.  Instead let's remove the relkind filter altogether.
These functions shouldn't cost much when there are no objects
that they need to process, and surely this isn't an especially
performance-critical case anyway.

Per bug #18407 from Vidushi Gupta.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18407-4fd07373d252c6a0@postgresql.org

13 months agoMicro-optimize pg_lfind32().
Nathan Bossart [Tue, 26 Mar 2024 19:03:32 +0000 (14:03 -0500)]
Micro-optimize pg_lfind32().

This commit improves the performance of pg_lfind32() in many cases
by modifying it to process the remaining "tail" of elements with
SIMD instructions instead of processing them one-by-one.  Since the
SIMD code processes a large block of elements, this means that we
will process a subset of elements more than once, but that won't
affect the correctness of the result, and testing has shown that
this helps more cases than it regresses.  With this change, the
standard one-by-one linear search code is only used for small
arrays and for platforms without SIMD support.

Suggested-by: John Naylor
Reviewed-by: John Naylor
Discussion: https://postgr.es/m/20231129171526.GA857928%40nathanxps13

13 months agoPropagate pathkeys from CTEs up to the outer query.
Tom Lane [Tue, 26 Mar 2024 17:05:49 +0000 (13:05 -0400)]
Propagate pathkeys from CTEs up to the outer query.

If we know the sort order of a CTE's output, and it is relevant
to the outer query, label the CTE's outer-query access path using
those pathkeys.  This may enable optimizations such as avoiding
a sort in the outer query.

The code for hoisting pathkeys into the outer query already exists
for regular RTE_SUBQUERY subqueries, but it wasn't getting used for
CTEs, possibly out of concern for maintaining an optimization fence
between the CTE and the outer query.  However, on the same arguments
used for commit f7816aec2, there seems no harm in letting the outer
query know what the inner query decided to do.

In support of this, we now remember the best Path as well as Plan
for each subquery for the rest of the planner run.  There may be
future applications for having that at hand, and it surely costs
little to build one more List.

Richard Guo (minor mods by me)

Discussion: https://postgr.es/m/CAMbWs49xYd3f8CrE8-WW3--dV1zH_sDSDn-vs2DzHj81Wcnsew@mail.gmail.com

13 months agoC comment: mention no doc for negative start of substring(text)
Bruce Momjian [Tue, 26 Mar 2024 16:27:41 +0000 (12:27 -0400)]
C comment:  mention no doc for negative start of substring(text)

Also add URL to hackers discussion.

Backpatch-through: master

13 months agoAllow "make check"-style testing to work with musl C library.
Tom Lane [Tue, 26 Mar 2024 15:44:49 +0000 (11:44 -0400)]
Allow "make check"-style testing to work with musl C library.

The musl dynamic linker saves a pointer to the process' environment
value of LD_LIBRARY_PATH very early in startup.  When we move/clobber
the environment to make more room for ps status strings, we clobber
that value and thereby prevent libraries from being found via
LD_LIBRARY_PATH, which breaks the use of a temporary installation
for testing purposes.  To fix, stop collecting usable space for
ps status if we notice that the variable we are about to clobber
is LD_LIBRARY_PATH.  This will result in some reduction in how long
the ps status can be, but it's only likely to occur in temporary
test contexts, so it doesn't seem like a big problem.  In any case,
we don't have to do it if we see we are on glibc, which surely is
where the majority of our Linux testing is done.

Thomas Munro, Bruce Momjian, and Tom Lane, per report from Wolfgang
Walther.  Back-patch to all supported branches, with the hope that
we'll set up a buildfarm animal to test on this platform.

Discussion: https://postgr.es/m/fddd1cd6-dc16-40a2-9eb5-d7fef2101488@technowledgy.de

13 months agoRemove ObjectClass type
Peter Eisentraut [Tue, 26 Mar 2024 07:51:18 +0000 (08:51 +0100)]
Remove ObjectClass type

ObjectClass is an enum whose values correspond to catalog OIDs.  But
the extra layer of redirection, which is used only in small parts of
the code, and the similarity to ObjectType, are confusing and
cumbersome.

One advantage has been that some switches processing the OCLASS enum
don't have "default:" cases.  This is so that the compiler tells us
when we fail to add support for some new object class.  But you can
also handle that with some assertions and proper test coverage.  It's
not even clear how strong this benefit is.  For example, in
AlterObjectNamespace_oid(), you could still put a new OCLASS into the
"ignore object types that don't have schema-qualified names" case, and
it might or might not be wrong.  Also, there are already various
OCLASS switches that do have a default case, so it's not even clear
what the preferred coding style should be.

Reviewed-by: jian he <[email protected]>
Reviewed-by: Michael Paquier <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CAGECzQT3caUbcCcszNewCCmMbCuyP7XNAm60J3ybd6PN5kH2Dw%40mail.gmail.com

13 months agoMessage fixes for pg_createsubscriber
Peter Eisentraut [Tue, 26 Mar 2024 07:22:46 +0000 (08:22 +0100)]
Message fixes for pg_createsubscriber

Author: Kyotaro Horiguchi <[email protected]>
Discussion: https://www.postgresql.org/message-id/20240326.140116.1116279856046587865[email protected]

13 months agoFix inconsistent function prototypes with function definitions.
Masahiko Sawada [Tue, 26 Mar 2024 04:13:26 +0000 (13:13 +0900)]
Fix inconsistent function prototypes with function definitions.

Introduced by 30e144287a.

Reviewed-by: John Naylor
Discussion: https://postgr.es/m/CAD21AoCaDT%2B-ZaVjbtvumms0tyyHPNLELK2UX-MLG9XCgioaNw%40mail.gmail.com

13 months agoFix a calculation in TidStoreCreate().
Masahiko Sawada [Tue, 26 Mar 2024 04:06:06 +0000 (13:06 +0900)]
Fix a calculation in TidStoreCreate().

Since we expect that the max_bytes is in bytes, not in kilobytes, it
should not be multiplied by 1024.

Introduced by 30e144287a.

Reported-by: John Naylor, David Rowley
Reviewed-by: John Naylor
Discussion: https://postgr.es/m/CANWCAZZTE-14ofsucofTuhFsfuDGBNf%3DNZb22TMYT8bxA41oQQ%40mail.gmail.com
Discussion: https://postgr.es/m/CAApHDvojg82NDaDEpj1WEZSbVTafj%3DDRmW%2BFrkBdW8ScL4OFxA%40mail.gmail.com