postgresql.git
13 months agoImprove consistency of replication slot statistics
Michael Paquier [Mon, 11 Mar 2024 01:25:01 +0000 (10:25 +0900)]
Improve consistency of replication slot statistics

The replication slot stats stored in shared memory rely on an internal
index number.  Both pgstat_reset_replslot() and pgstat_fetch_replslot()
lacked some LWLock protections with ReplicationSlotControlLock while
operating on these index numbers.  This issue could cause these two
functions to potentially operate on incorrect slots when taken in
isolation in the event of slots dropped and/or re-created concurrently.

Note that pg_stat_get_replication_slot() is called once per slot when
querying pg_stat_replication_slots, meaning that the stats are retrieved
across multiple ReplicationSlotControlLock acquisitions.  So, while this
commit improves more consistency, it may still be possible that
statistics are not completely consistent for a single scan of
pg_stat_replication_slots under concurrent replication slot drop or
creation activity.

The issue should unlikely be a problem in practice, causing the report
of inconsistent stats or or the stats reset of an incorrect slot, so no
backpatch is done.

Author: Bertrand Drouvot
Reviewed-by: Heikki Linnakangas, Shveta Malik, Michael Paquier
Discussion: https://postgr.es/m/[email protected]

13 months agoAdd some checkpoint and redo LSNs to a couple of recovery errors
Michael Paquier [Mon, 11 Mar 2024 00:08:05 +0000 (09:08 +0900)]
Add some checkpoint and redo LSNs to a couple of recovery errors

Two FATALs and one PANIC gain details about the LSNs they fail at:
- When restoring from a backup_label, the FATAL log generated when not
finding the checkpoint record now reports its LSN.
- When restoring from a backup_label, the FATAL log generated when not
finding the redo record referenced by a checkpoint record now shows both
the redo and checkpoint record LSNs.
- When not restoring from a backup_label, the PANIC error generated when
not finding the checkpoint record now reports its LSN.

This information is useful when debugging corruption issues, and these
LSNs may not show up in the logs depending on the level of logging
configured in the backend.

Author: David Steele
Discussion: https://postgr.es/m/0e90da89-77ca-4ccf-872c-9626d755e288@pgmasters.net

13 months agoImprove support for ExplainOneQuery() hook
Michael Paquier [Sun, 10 Mar 2024 23:40:40 +0000 (08:40 +0900)]
Improve support for ExplainOneQuery() hook

There is a hook called ExplainOneQuery_hook that gives modules the
possibility to plug into this code path, but, like utility.c for utility
statement execution, there is no corresponding "standard" routine in
the case of EXPLAIN executed for one Query.

This commit adds a new standard_ExplainOneQuery() in explain.c, which is
able to run explain on a non-utility Query without calling its hook.

Per the feedback received from a couple of hackers, this change gives
the possibility to cut a few hundred lines of code in some of the
popular out-of-core modules as these maintained a copy of
ExplainOneQuery(), adding custom extra information at the beginning or
the end of the EXPLAIN output.

Author: Mats Kindahl
Reviewed-by: Aleksander Alekseev, Jelte Fennema-Nio, Andrei Lepikhov
Discussion: https://postgr.es/m/CA+14427V_B4EAoC_o-iYYucRdMSOTfpuH9k-QbexffY1HYJBiA@mail.gmail.com

13 months agoFix deparsing of Consts in postgres_fdw ORDER BY
David Rowley [Sun, 10 Mar 2024 23:27:11 +0000 (12:27 +1300)]
Fix deparsing of Consts in postgres_fdw ORDER BY

For UNION ALL queries where a union child query contained a foreign
table, if the targetlist of that query contained a constant, and the
top-level query performed an ORDER BY which contained the column for the
constant value, then postgres_fdw would find the EquivalenceMember with
the Const and then try to produce an ORDER BY containing that Const.

This caused problems with INT typed Consts as these could appear to be
requests to order by an ordinal column position rather than the constant
value.  This could lead to either an error such as:

ERROR:  ORDER BY position <int const> is not in select list

or worse, if the constant value is a valid column, then we could just
sort by the wrong column altogether.

Here we fix this issue by just not including these Consts in the ORDER
BY clause.

In passing, add a new section for testing ORDER BY in the postgres_fdw
tests and move two existing tests which were misplaced in the WHERE
clause testing section into it.

Reported-by: Michał Kłeczek
Reviewed-by: Ashutosh Bapat, Richard Guo
Bug: #18381
Discussion: https://postgr.es/m/0714C8B8-8D82-4ABB-9F8D-A0C3657E7B6E%40kleczek.org
Discussion: https://postgr.es/m/18381-137456acd168bf93%40postgresql.org
Backpatch-through: 12, oldest supported version

13 months agoCombine headerscheck and cpluspluscheck scripts
Peter Eisentraut [Sun, 10 Mar 2024 06:33:57 +0000 (07:33 +0100)]
Combine headerscheck and cpluspluscheck scripts

They are mostly the same, and it is tedious to maintain two copies of
essentially the same exclude list.  headerscheck now has a new option
--cplusplus to select the cpluspluscheck functionality.  The top-level
make targets are still the same.

Reviewed-by: Thomas Munro <[email protected]>
Reviewed-by: Michael Paquier <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/4754a5b0-a32b-4036-a99a-6de14cf9fd72@eisentraut.org

13 months agoCatalog changes preparing for builtin collation provider.
Jeff Davis [Sat, 9 Mar 2024 22:48:18 +0000 (14:48 -0800)]
Catalog changes preparing for builtin collation provider.

Rename pg_collation.colliculocale to colllocale, and
pg_database.daticulocale to datlocale. These names reflects that the
fields will be useful for the upcoming builtin provider as well, not
just for ICU.

This is purely a rename; no changes to the meaning of the fields.

Discussion: https://postgr.es/m/ff4c2f2f9c8fc7ca27c1c24ae37ecaeaeaff6b53.camel%40j-davis.com
Reviewed-by: Peter Eisentraut
13 months agoMake contrib/tablefunc crosstab() also check typmod
Joe Conway [Sat, 9 Mar 2024 22:32:32 +0000 (17:32 -0500)]
Make contrib/tablefunc crosstab() also check typmod

contrib/tablefunc connectby() checks both type OID and typmod for
its output columns while crosstab() only checks type OID. Fix that
by makeing the crosstab() check look more like the connectby() check.

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

13 months agoSimplify and merge unwanted-module drop logic in AdjustUpgrade.pm.
Tom Lane [Sat, 9 Mar 2024 21:20:44 +0000 (16:20 -0500)]
Simplify and merge unwanted-module drop logic in AdjustUpgrade.pm.

In be7800674 and followups, we failed to notice that there was
already a better way to do it: instead of using DROP DATABASE
IF EXISTS, we can check the list of existing DBs.  Also, there
seems no reason not to merge this into the pre-existing code
for getting rid of unwanted module databases.

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

13 months agoImprove wrong-tuple-type error reports in contrib/tablefunc.
Tom Lane [Sat, 9 Mar 2024 20:48:21 +0000 (15:48 -0500)]
Improve wrong-tuple-type error reports in contrib/tablefunc.

These messages were fairly confusing, and didn't match the
column names used in the SGML docs.  Try to improve that.
Also use error codes more specific than ERRCODE_SYNTAX_ERROR.

Patch by me, reviewed by Joe Conway

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

13 months agoRun perltidy on 002_pg_upgrade.pl.
Jeff Davis [Sat, 9 Mar 2024 19:51:10 +0000 (11:51 -0800)]
Run perltidy on 002_pg_upgrade.pl.

13 months agoFix cross-version pg_upgrade test.
Jeff Davis [Sat, 9 Mar 2024 19:48:52 +0000 (11:48 -0800)]
Fix cross-version pg_upgrade test.

Pass each statement as a separate '-c' arg, so they don't get combined
into a single transaction.

Discussion: https://postgr.es/m/bca97aecb50b2026b7dbc26604bf31861c819a64[email protected]
Reviewed-by: Tom Lane
13 months agoDocument units of "timeout" in ConditionVariableTimedSleep()
Michael Paquier [Sat, 9 Mar 2024 06:44:41 +0000 (15:44 +0900)]
Document units of "timeout" in ConditionVariableTimedSleep()

The timeout is passed down to WaitLatch() as milliseconds.

Author: Shveta Malik
Discussion: https://postgr.es/m/CAJpy0uC=xiBQD1WapgYYvOiytap6ULJaakLd867zZXqu9tYc8w@mail.gmail.com

13 months agoFix type signedness error in commit 5c40364dd6.
Jeff Davis [Fri, 8 Mar 2024 23:58:32 +0000 (15:58 -0800)]
Fix type signedness error in commit 5c40364dd6.

Use ssize_t instead of size_t.

Discussion: https://postgr.es/m/b20d6d97-7338-48ea-ba33-837a1c8ef98e@iki.fi
Reported-by: Heikki Linnakangas
13 months agoFix errorhandling for reading from a pipe
Daniel Gustafsson [Fri, 8 Mar 2024 21:53:06 +0000 (22:53 +0100)]
Fix errorhandling for reading from a pipe

When reading a line from a pipe failed on no data being read, the
errorhandling was erroneously logging with %m even thoug no error
description is available for %m to print.  This flaw accidentally
introduced in 5c7038d70bb.

Reported-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/baa34329-f431-46af-bf74-1a78fdc90e4f@eisentraut.org

13 months agoReplace perror with custom postgres logging
Daniel Gustafsson [Fri, 8 Mar 2024 21:50:20 +0000 (22:50 +0100)]
Replace perror with custom postgres logging

perror() is not used in postgres anymore out of policy, this replaces
the final callsites with the custom postgres logging framework.

Reviewed-by: Tom Lane <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/89B00F63-40F7-4D82-8353-DC9CABBAC1D1@yesql.se

13 months agoImprove WIN32 waiting logic in psql's \watch command.
Tom Lane [Fri, 8 Mar 2024 17:07:35 +0000 (12:07 -0500)]
Improve WIN32 waiting logic in psql's \watch command.

do_watch had some leftover logic for enabling siglongjmp out of
waiting for input.  That's never done anything on Windows (cf.
psql_cancel_callback), and do_watch no longer relies on it for
non-Windows, so let's drop it.

Also, when the user cancels \watch by pressing ^C, the Windows
code would run the query one more time before exiting.  That doesn't
seem very desirable, and it's not what happens on other platforms.
Use the "done" flag similarly to non-Windows to avoid the extra query
execution.

Yugo Nagata (with minor fixes by me)

Discussion: https://postgr.es/m/20240305220552.85fd4afd6b6b8103bf4fe3d0@sraoss.co.jp

13 months agoAdmit deferrable PKs into rd_pkindex, but flag them as such
Alvaro Herrera [Fri, 8 Mar 2024 15:32:29 +0000 (16:32 +0100)]
Admit deferrable PKs into rd_pkindex, but flag them as such

... and in particular don't return them as replica identity.

The motivation for this change is letting the primary keys be seen by
code that derives NOT NULL constraints from them, when creating
inheritance children; before this change, if you had a deferrable PK,
pg_dump would not recreate the attnotnull marking properly, because the
column would not be considered as having anything to back said marking
after dropping the throwaway NOT NULL constraint.

The reason we don't want these PKs as replica identities is that
replication can corrupt data, if the uniqueness constraint is
transiently broken.

Reported-by: Amul Sul <[email protected]>
Reviewed-by: Dean Rasheed <[email protected]>
Discussion: https://postgr.es/m/CAAJ_b94QonkgsbDXofakHDnORQNgafd1y3Oa5QXfpQNJyXyQ7A@mail.gmail.com

13 months agoAvoid recursion in MemoryContext functions
Alexander Korotkov [Fri, 8 Mar 2024 11:01:36 +0000 (13:01 +0200)]
Avoid recursion in MemoryContext functions

You might run out of stack space with recursion, which is not nice in
functions that might be used e.g. at cleanup after transaction
abort. MemoryContext contains pointer to parent and siblings, so we
can traverse a tree of contexts iteratively, without using
stack. Refactor the functions to do that.

MemoryContextStats() still recurses, but it now has a limit to how
deep it recurses. Once the limit is reached, it prints just a summary
of the rest of the hierarchy, similar to how it summarizes contexts
with lots of children. That seems good anyway, because a context dump
with hundreds of nested contexts isn't very readable.

Report by Egor Chindyaskin and Alexander Lakhin.

Discussion: https://postgr.es/m/1672760457.940462079%40f306.i.mail.ru
Author: Heikki Linnakangas
Reviewed-by: Robert Haas, Andres Freund, Alexander Korotkov, Tom Lane
13 months agoAvoid stack overflow in ShowTransactionStateRec()
Alexander Korotkov [Fri, 8 Mar 2024 11:01:12 +0000 (13:01 +0200)]
Avoid stack overflow in ShowTransactionStateRec()

The function recurses, but didn't perform stack-depth checks. It's
just a debugging aid, so instead of the usual check_stack_depth()
call, stop the printing if we'd risk stack overflow.

Here's an example of how to test this:

    (n=1000000; printf "BEGIN;"; for ((i=1;i<=$n;i++)); do printf "SAVEPOINT s$i;"; done; printf "SET log_min_messages = 'DEBUG5'; SAVEPOINT sp;") | psql >/dev/null

In the passing, swap building the list of child XIDs and recursing to
parent. That saves memory while recursing, reducing the risk of out of
memory errors with lots of subtransactions. The saving is not very
significant in practice, but this order seems more logical anyway.

Report by Egor Chindyaskin and Alexander Lakhin.

Discussion: https://www.postgresql.org/message-id/1672760457.940462079%40f306.i.mail.ru
Author: Heikki Linnakangas
Reviewed-by: Robert Haas, Andres Freund, Alexander Korotkov
13 months agoTurn tail recursion into iteration in CommitTransactionCommand()
Alexander Korotkov [Fri, 8 Mar 2024 11:00:40 +0000 (13:00 +0200)]
Turn tail recursion into iteration in CommitTransactionCommand()

Usually the compiler will optimize away the tail recursion anyway, but
if it doesn't, you can drive the function into stack overflow. For
example:

    (n=1000000; printf "BEGIN;"; for ((i=1;i<=$n;i++)); do printf "SAVEPOINT s$i;"; done; printf "ERROR; COMMIT;") | psql >/dev/null

In order to get better readability and less changes to the existing code the
recursion-replacing loop is implemented as a wrapper function.

Report by Egor Chindyaskin and Alexander Lakhin.
Discussion: https://postgr.es/m/1672760457.940462079%40f306.i.mail.ru
Author: Alexander Korotkov, Heikki Linnakangas

14 months agoRevert "Fix link error for test_radixtree module on Windows"
John Naylor [Fri, 8 Mar 2024 04:08:01 +0000 (11:08 +0700)]
Revert "Fix link error for test_radixtree module on Windows"

This reverts commit 9552e3ace317ac8bb0a80613c0e5cd6536c96dc8.

I (john) forgot to revert this locally when a more principled
fix was found, which has the same message title.

14 months agoFix link error for test_radixtree module on Windows
John Naylor [Fri, 8 Mar 2024 03:57:40 +0000 (10:57 +0700)]
Fix link error for test_radixtree module on Windows

Add PGDLLIMPORT to pg_popcount32/64. In passing, fix a typo.

Diagnosis by Masahiko Sawada, patch by David Rowley

Per buildfarm members drongo and fairywren

Discussion: https://postgr.es/m/CAD21AoAMm1mQd%3Dw4PrfrKK%3DOMP8j8%3D7ntJRPF8%2B%3D10iUuvwiCA%40mail.gmail.com
Discussion: https://postgr.es/m/CAApHDvov7724UrD1Ug0D1eV%2B9Pd_x5VEQmw-6HVG9w1WdCxXPA%40mail.gmail.com

14 months agoFix link error for test_radixtree module on Windows
John Naylor [Fri, 8 Mar 2024 03:25:23 +0000 (10:25 +0700)]
Fix link error for test_radixtree module on Windows

Add back "link_with" directive, similar to the one removed by 1f1d73a8b,
but only for Windows, but use the "_shlib" variation.

Diagnosis by Masahiko Sawada, proposed fix adjusted and tested by me

Per buildfarm members drongo and fairywren

Discussion: https://postgr.es/m/CAD21AoAMm1mQd%3Dw4PrfrKK%3DOMP8j8%3D7ntJRPF8%2B%3D10iUuvwiCA%40mail.gmail.com

14 months agoIntroduce a new GUC 'standby_slot_names'.
Amit Kapila [Fri, 8 Mar 2024 02:40:45 +0000 (08:10 +0530)]
Introduce a new GUC 'standby_slot_names'.

This patch provides a way to ensure that physical standbys that are
potential failover candidates have received and flushed changes before
the primary server making them visible to subscribers. Doing so guarantees
that the promoted standby server is not lagging behind the subscribers
when a failover is necessary.

The logical walsender now guarantees that all local changes are sent and
flushed to the standby servers corresponding to the replication slots
specified in 'standby_slot_names' before sending those changes to the
subscriber.

Additionally, the SQL functions pg_logical_slot_get_changes,
pg_logical_slot_peek_changes and pg_replication_slot_advance are modified
to ensure that they process changes for failover slots only after physical
slots specified in 'standby_slot_names' have confirmed WAL receipt for those.

Author: Hou Zhijie and Shveta Malik
Reviewed-by: Masahiko Sawada, Peter Smith, Bertrand Drouvot, Ajin Cherian, Nisha Moond, Amit Kapila
Discussion: https://postgr.es/m/514f6f2f-6833-4539-39f1-96cd1e011f23@enterprisedb.com

14 months agoCope with a deficiency in OpenSSL 3.x's error reporting.
Tom Lane [Fri, 8 Mar 2024 00:37:51 +0000 (19:37 -0500)]
Cope with a deficiency in OpenSSL 3.x's error reporting.

In OpenSSL 3.0.0 and later, ERR_reason_error_string randomly refuses
to provide a string for error codes representing system errno values
(e.g., "No such file or directory").  There is a poorly-documented way
to extract the errno from the SSL error code in this case, so do that
and apply strerror, rather than falling back to reporting the error
code's numeric value as we were previously doing.

Problem reported by David Zhang, although this is not his proposed
patch; it's instead based on a suggestion from Heikki Linnakangas.
Back-patch to all supported branches, since any of them are likely
to be used with recent OpenSSL.

Discussion: https://postgr.es/m/b6fb018b-f05c-4afd-abd3-318c649faf18@highgo.ca

14 months agoAdd support for DEFAULT in ALTER TABLE .. SET ACCESS METHOD
Michael Paquier [Fri, 8 Mar 2024 00:31:52 +0000 (09:31 +0900)]
Add support for DEFAULT in ALTER TABLE .. SET ACCESS METHOD

This option can be used to switch a relation to use the access method
set by default_table_access_method when running the command.

This has come up when discussing the possibility to support setting
pg_class.relam for partitioned tables (left out here as future work),
while being useful on its own for relations with physical storage as
these must have an access method set.

Per suggestion from Justin Pryzby.

Author: Michael Paquier
Reviewed-by: Justin Pryzby
Discussion: https://postgr.es/m/ZeCZ89xAVFeOmrQC@pryzbyj2023

14 months agoUpdate comment of AlterTableCmd->name in parsenodes.h
Michael Paquier [Thu, 7 Mar 2024 23:44:13 +0000 (08:44 +0900)]
Update comment of AlterTableCmd->name in parsenodes.h

Since b0483263dda0, this field can be used to store an access method
name for ALTER TABLE, but access methods were not mentioned in the
field's description.

Issue noticed while working on the area.

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

14 months agoUnicode case mapping tables and functions.
Jeff Davis [Thu, 7 Mar 2024 19:15:06 +0000 (11:15 -0800)]
Unicode case mapping tables and functions.

Implements Unicode simple case mapping, in which all code points map
to exactly one other code point unconditionally.

These tables are generated from UnicodeData.txt, which is already
being used by other infrastructure in src/common/unicode. The tables
are checked into the source tree, so they only need to be regenerated
when we update the Unicode version.

In preparation for the builtin collation provider, and possibly useful
for other callers.

Discussion: https://postgr.es/m/ff4c2f2f9c8fc7ca27c1c24ae37ecaeaeaff6b53.camel%40j-davis.com
Reviewed-by: Peter Eisentraut, Daniel Verite, Jeremy Schneider
14 months agoFix description and grouping of RangeTblEntry.inh
Peter Eisentraut [Thu, 7 Mar 2024 10:50:24 +0000 (11:50 +0100)]
Fix description and grouping of RangeTblEntry.inh

The inh field of RangeTblEntry was doubly confusingly documented.
Some parts of the code insisted that it was only valid for
RTE_RELATION entries, other parts said the field was valid for all
entries.  Neither was quite correct.  More correctly, the field is
valid for RTE_RELATION entries but is also used in the planner for
RTE_SUBQUERY entries.  So it makes more sense to group it with other
fields that are primarily for RTE_RELATION but borrowed by
RTE_SUBQUERY.  (The exact position was chosen so that it is next to
relkind for better struct packing, and next to relid, since relid and
inh are sort of the input fields and the others are filled in later.)
Also add documentation for the planner's use at the struct definition.

Discussion: https://www.postgresql.org/message-id/6c1fbccc-85c8-40d3-b08b-4f47f2093711@eisentraut.org

14 months agoBlind attempt to fix ODR violations
John Naylor [Thu, 7 Mar 2024 09:59:25 +0000 (16:59 +0700)]
Blind attempt to fix ODR violations

Remove apparently useless "link_with" directive. Even if this isn't the
root cause, it makes the .build file more like the other test modules.

Reviewed by Masahiko Sawada

Follow-up to ee1b30f12, per buildfarm members olingo and grassquit.

Discussion: https://postgr.es/m/CANWCAZaJAaO8MimTU%2BY-DZutM6HQLQu%3DK2HyoQULdB3v_6BSCg%40mail.gmail.com

14 months agoFix handling of self-modified tuples in MERGE.
Dean Rasheed [Thu, 7 Mar 2024 09:57:02 +0000 (09:57 +0000)]
Fix handling of self-modified tuples in MERGE.

When an UPDATE or DELETE action in MERGE returns TM_SelfModified,
there are 2 possible causes:

1). The target tuple was already updated or deleted by the current
    command. This can happen if the target row joins to more than one
    source row, and the SQL standard explicitly says that this must be
    an error.

2). The target tuple was already updated or deleted by a later command
    in the current transaction. This can happen if the tuple is
    modified by a BEFORE trigger or a volatile function used in the
    query, and should be an error for the same reason that it is in a
    plain UPDATE or DELETE command.

In MERGE's primary error handling block, it failed to check for (2),
causing it to return a misleading error message in such cases.

In the secondary error handling block, following a concurrent update
from another session, it failed to check for (1), causing it to
silently ignore target rows joined to more than one source row,
instead of reporting an error.

Fix this, and add tests for both of these cases.

Per report from Wenjiang Zhang. Back-patch to v15, where MERGE was
introduced.

Discussion: https://postgr.es/m/tencent_41DE0FF443FE14B94A5898D373792109E408%40qq.com

14 months agoFix incorrect format specifier for int64
John Naylor [Thu, 7 Mar 2024 07:25:30 +0000 (14:25 +0700)]
Fix incorrect format specifier for int64

Follow-up to ee1b30f12, per buildfarm member mamba.

Discussion: https://postgr.es/m/CANWCAZYwyRMU%2BOTVOjK%3Dno1hm-W3ZQ5vrSFM1MFAaLtLydvwzA%40mail.gmail.com

14 months agoFix redefinition of typedefs
John Naylor [Thu, 7 Mar 2024 07:11:49 +0000 (14:11 +0700)]
Fix redefinition of typedefs

Per buildfarm members sifaka and longfin, clang with
-Wtypedef-redefinition warns of duplicate typedefs unless building with
C11. Follow-up to ee1b30f12.

Masahiko Sawada

Discussion: https://postgr.es/m/CANWCAZauSg%3DLUbBbXhpeQtBuPifmzQNTYS6O8NsoAPz1zL-Txg%40mail.gmail.com

14 months agoAdd template for adaptive radix tree
John Naylor [Thu, 7 Mar 2024 05:40:11 +0000 (12:40 +0700)]
Add template for adaptive radix tree

This implements a radix tree data structure based on the design in
"The Adaptive Radix Tree: ARTful Indexing for Main-Memory Databases"
by Viktor Leis, Alfons Kemper, and ThomasNeumann, 2013. The main
technique that makes it adaptive is using several different node types,
each with a different capacity of elements, and a different algorithm
for accessing them. The nodes start small and grow/shrink as needed.

The main advantage over hash tables is efficient sorted iteration and
better memory locality when successive keys are lexicographically
close together. The implementation currently assumes 64-bit integer
keys, and traversing the tree is in general slower than a linear
probing hash table, so this is not a general-purpose associative array.

The paper describes two other techniques not implemented here,
namely "path compression" and "lazy expansion". These can further
reduce memory usage and speed up traversal, but the former would add
significant complexity and the latter requires storing the full key
with the value. We do trivially compress the path when leading bytes
of the key are zeros, however.

For value storage, we use "combined pointer/value slots", as
recommended in the paper. Values of size equal or smaller than the the
platform's pointer type are stored in the array of child pointers in
the last level node, while larger values are each stored in a separate
allocation. This is for now fixed at compile time, but it would be
fairly trivial to allow determining at runtime how variable-length
values are stored.

One innovation in our implementation compared to the ART paper is
decoupling the notion of node "size class" from "kind". The size
classes within a given node kind have the same underlying type, but
a variable capacity for children, so we can introduce additional node
sizes with little additional code.

To enable different use cases to specialize for different value types
and for shared/local memory, we use macro-templatized code generation
in the same manner as simplehash.h and sort_template.h.

Future commits will use this infrastructure for storing TIDs.

Patch by Masahiko Sawada and John Naylor, but a substantial amount of
credit is due to Andres Freund, whose proof-of-concept was a valuable
source of coding idioms and awareness of performance pitfalls, and
who reviewed earlier versions.

Discussion: https://postgr.es/m/CAD21AoAfOZvmfR0j8VmZorZjL7RhTiQdVttNuC4W-Shdc2a-AA%40mail.gmail.com

14 months agoRevert "Add recovery TAP test for race condition with slot invalidations"
Michael Paquier [Thu, 7 Mar 2024 00:57:52 +0000 (09:57 +0900)]
Revert "Add recovery TAP test for race condition with slot invalidations"

This reverts commit 08a52ab151ca, due to some sporadic instability in
the test.  Getting the test right should require some redesign with a
second injection point, but let's revert it for now to avoid these
issues in the CI as a lot of patches are under discussion in this last
commit fest.

Per buildfarm members hachi and gokiburi.

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

14 months agoRevert "Fix parallel-safety check of expressions and predicate for index builds"
Michael Paquier [Wed, 6 Mar 2024 23:30:35 +0000 (08:30 +0900)]
Revert "Fix parallel-safety check of expressions and predicate for index builds"

This reverts commit eae7be600be7, following a discussion with Tom Lane,
due to concerns that this impacts the decisions made by the planner for
the number of workers spawned based on the inlining and const-folding of
index expressions and predicate for cases that would have worked until
this commit.

Discussion: https://postgr.es/m/162802.1709746091@sss.pgh.pa.us
Backpatch-through: 12

14 months agoAdd Unicode property tables.
Jeff Davis [Wed, 6 Mar 2024 20:50:01 +0000 (12:50 -0800)]
Add Unicode property tables.

Provide functions to test for Unicode properties, such as Alphabetic
or Cased. These functions use tables derived from Unicode data files,
similar to the tables for Unicode normalization or general category,
and those tables can be updated with the 'update-unicode' build
target.

Use Unicode properties to provide functions to test for regex
character classes, like 'punct' or 'alnum'.

Infrastructure in preparation for a builtin collation provider, and
may also be useful for other callers.

Discussion: https://postgr.es/m/ff4c2f2f9c8fc7ca27c1c24ae37ecaeaeaff6b53.camel%40j-davis.com
Reviewed-by: Daniel Verite, Peter Eisentraut, Jeremy Schneider
14 months agoFix type-checking of RECORD-returning functions in FROM.
Tom Lane [Wed, 6 Mar 2024 19:41:13 +0000 (14:41 -0500)]
Fix type-checking of RECORD-returning functions in FROM.

In the corner case where a function returning RECORD has been
simplified to a RECORD constant or an inlined ROW() expression,
ExecInitFunctionScan failed to cross-check the function's result
rowtype against the coldeflist provided by the calling query.
That happened because get_expr_result_type is able to extract a
tupdesc from such expressions, which led ExecInitFunctionScan to
ignore the coldeflist.  (Instead, it used the extracted tupdesc
to check the function's output, which of course always succeeds.)

I have not been able to demonstrate any really serious consequences
from this, because if some column of the result is of the wrong
type and is directly referenced by a Var of the calling query,
CheckVarSlotCompatibility will catch it.  However, we definitely do
fail to report the case where the function returns more columns than
the coldeflist expects, and in the converse case where it returns
fewer columns, we get an assert failure (but, seemingly, no worse
results in non-assert builds).

To fix, always build the expected tupdesc from the coldeflist if there
is one, and consult get_expr_result_type only when there isn't one.

Also remove the failing Assert, even though it is no longer reached
after this fix.  It doesn't seem to be adding anything useful, since
later checking will deal with cases with the wrong number of columns.

The only other place I could find that is doing something similar
is inline_set_returning_function.  There's no live bug there because
we cannot be looking at a Const or RowExpr, but for consistency
change that code to agree with ExecInitFunctionScan.

Per report from PetSerAl.  After some debate I've concluded that
this should be back-patched.  There is a small risk that somebody
has been relying on such a case not throwing an error, but I judge
this outweighed by the risk that I've missed some way in which the
failure to cross-check has worse consequences than sketched above.

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

14 months agoFix signedness error in 9f225e992 for gcc
John Naylor [Wed, 6 Mar 2024 08:54:25 +0000 (15:54 +0700)]
Fix signedness error in 9f225e992 for gcc

The first argument of vshrq_n_s8 needs to be a signed vector type,
but it was passed unsigned. Clang is more lax with conversion, but
gcc needs a cast.

Fix by me, tested by Masahiko Sawada

Per buildfarm members splitfin, batta, widowbird, snakefly, parula,
massasauga

Discussion: https://postgr.es/m/20240306074106.mg6w4koohdlworbs%40alap3.anarazel.de

14 months agoFix parallel-safety check of expressions and predicate for index builds
Michael Paquier [Wed, 6 Mar 2024 08:23:56 +0000 (17:23 +0900)]
Fix parallel-safety check of expressions and predicate for index builds

As coded, the planner logic that calculates the number of parallel
workers to use for a parallel index build uses expressions and
predicates from the relcache, which are flattened for the planner by
eval_const_expressions().

As reported in the bug, an immutable parallel-unsafe function flattened
in the relcache would become a Const, which would be considered as
parallel-safe, even if the predicate or the expressions including the
function are not safe in parallel workers.  Depending on the expressions
or predicate used, this could cause the parallel build to fail.

Tests are included that check parallel index builds with parallel-unsafe
predicate and expressions.  Two routines are added to lsyscache.h to be
able to retrieve expressions and predicate of an index from its pg_index
data.

Reported-by: Alexander Lakhin
Author: Tender Wang
Reviewed-by: Jian He, Michael Paquier
Discussion: https://postgr.es/m/CAHewXN=UaAaNn9ruHDH3Os8kxLVmtWqbssnf=dZN_s9=evHUFA@mail.gmail.com
Backpatch-through: 12

14 months agoMove some bitmap logic out of bitmapset.c
John Naylor [Tue, 6 Dec 2022 06:39:41 +0000 (13:39 +0700)]
Move some bitmap logic out of bitmapset.c

Move the logic for selecting appropriate pg_bitutils.h
functions based on word size to bitmapset.h for wider
visibility.

Reviewed (in a previous version) by Tom Lane
Discussion: https://postgr.es/m/CAFBsxsFW2JjTo58jtDB%2B3sZhxMx3t-3evew8%3DAcr%2BGGhC%2BkFaA%40mail.gmail.com

14 months agoIntroduce helper SIMD functions for small byte arrays
John Naylor [Wed, 6 Mar 2024 07:22:15 +0000 (14:22 +0700)]
Introduce helper SIMD functions for small byte arrays

vector8_min - helper for emulating ">=" semantics

vector8_highbit_mask - used to turn the result of a vector
comparison into a bitmask

Masahiko Sawada

Reviewed by Nathan Bossart, with additional adjustments by me
Discussion: https://postgr.es/m/CAFBsxsHbBm_M22gLBO%2BAZT4mfMq3L_oX3wdKZxjeNnT7fHsYMQ%40mail.gmail.com

14 months agoDoc: Improve replication slot synchronization section.
Amit Kapila [Wed, 6 Mar 2024 05:46:51 +0000 (11:16 +0530)]
Doc: Improve replication slot synchronization section.

Author: Peter Smith
Reviewed-by: Michael Paquier, Laurenz Albe
Discussion: https://postgr.es/m/CAHut+Ps01fV9bjhj6njCFiHu0W0gu1Jcu0tKo0RYMhHx-hZZ7g@mail.gmail.com

14 months agoAdd recovery TAP test for race condition with slot invalidations
Michael Paquier [Wed, 6 Mar 2024 05:38:25 +0000 (14:38 +0900)]
Add recovery TAP test for race condition with slot invalidations

This commit adds a recovery test to provide coverage for the bug fixed
in 818fefd8fd, using an injection point to wait just after the process
of an active slot is killed.  The trick is to give enough time for
effective_xmin and effective_catalog_xmin to advance so as the slot
invalidation robustness can be checked since the active process is
killed without holding its slot's mutex for a short time.

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

14 months agoAdd --copy-file-range option to pg_upgrade.
Thomas Munro [Tue, 5 Mar 2024 22:39:50 +0000 (11:39 +1300)]
Add --copy-file-range option to pg_upgrade.

The copy_file_range() system call is available on at least Linux and
FreeBSD, and asks the kernel to use efficient ways to copy ranges of a
file.  Options available to the kernel include sharing block ranges
(similar to --clone mode), and pushing down block copies to the storage
layer.

For automated testing, see PG_TEST_PG_UPGRADE_MODE.  (Perhaps in a later
commit we could consider setting this mode for one of the CI targets.)

Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/CA%2BhUKGKe7Hb0-UNih8VD5UNZy5-ojxFb3Pr3xSBBL8qj2M2%3DdQ%40mail.gmail.com

14 months agoRemove surplus trailing semicolon
David Rowley [Tue, 5 Mar 2024 21:57:31 +0000 (10:57 +1300)]
Remove surplus trailing semicolon

Author: Richard Guo
Discussion: https://postgr.es/m/CAMbWs4-qjotfa7G=5PEOw4LDDDX58MmTwDdpdoU3Quse_BKv1Q@mail.gmail.com

14 months agoAdd a few recent commits to .git-blame-ignore-revs.
Nathan Bossart [Tue, 5 Mar 2024 20:15:06 +0000 (14:15 -0600)]
Add a few recent commits to .git-blame-ignore-revs.

14 months agoRun pgindent again on the same file.
Jeff Davis [Tue, 5 Mar 2024 19:16:23 +0000 (11:16 -0800)]
Run pgindent again on the same file.

Apparently, pgindent got confused by the double space. The first time
I ran it, it moved the function name to the next line. The second time
I ran it, it moved the function name back, but without the double
space.

Now the results appear stable.

14 months agoRun pgindent for commit ef4cfdce0e.
Jeff Davis [Tue, 5 Mar 2024 18:58:24 +0000 (10:58 -0800)]
Run pgindent for commit ef4cfdce0e.

14 months agodocs: Update HOT update docs for 19d8e2308b
Jeff Davis [Tue, 5 Mar 2024 17:25:46 +0000 (09:25 -0800)]
docs: Update HOT update docs for 19d8e2308b

Commit 19d8e2308b changed when the HOT update optimization is possible
but neglected to update the Heap-Only Tuples (HOT) documentation.  This
patch updates that documentation accordingly.

Author: Elizabeth Christensen
Backpatch-through: 16
Reviewed-By: Stephen Frost, Alvaro Herrera
Discussion: https://postgr.es/m/CABoUFXRjisr58Ct_3VsFEdQx+fJeQTWTdJnM7XAp=8MUbtoa9A@mail.gmail.com

14 months agoUpdate sepgsql expected output.
Jeff Davis [Tue, 5 Mar 2024 16:44:38 +0000 (08:44 -0800)]
Update sepgsql expected output.

Fix for buildfarm member rhinoceros after commit 2af07e2f74.

14 months agoFix references to renamed function in comments
Heikki Linnakangas [Tue, 5 Mar 2024 16:23:58 +0000 (18:23 +0200)]
Fix references to renamed function in comments

I renamed the function in commit 024c521117, but missed these
comments.

Reported-by: Richard Guo
Discussion: https://www.postgresql.org/message-id/CAMbWs4-jR6qc7JRMKwz-zXQy_AYLUZ3PHjGep4B91of321cqWw@mail.gmail.com

14 months agoImprove field order in RangeTblEntry
Peter Eisentraut [Tue, 5 Mar 2024 12:34:43 +0000 (13:34 +0100)]
Improve field order in RangeTblEntry

When perminfoindex was added, it was just added at the end of the
block.  It would make sense to keep it closer to more related fields.
In passing, also add an inline comment, like the other fields have.
(Other field reorderings and documentation improvements in
RangeTblEntry are being discussed, but it's better not to mix them
together.)

Discussion: https://www.postgresql.org/message-id/flat/6c1fbccc-85c8-40d3-b08b-4f47f2093711%40eisentraut.org

14 months agoFix misspelled assertions
Alvaro Herrera [Tue, 5 Mar 2024 11:13:12 +0000 (12:13 +0100)]
Fix misspelled assertions

Remove an extra & operator, per Tom Lane.  My bugs, introduced with
commit 53c2a97a9266.

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

14 months agoRework redundant code in subtrans.c
Alvaro Herrera [Tue, 5 Mar 2024 11:09:18 +0000 (12:09 +0100)]
Rework redundant code in subtrans.c

When this code was written the duplicity didn't matter, but with all the
SLRU-bank stuff we just added, it has become excessive.  Turn it into a
simpler loop with no code duplication.  Also add a test so that this
code becomes covered.

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

14 months agoRename pg_constraint.conwithoutoverlaps to conperiod
Peter Eisentraut [Tue, 5 Mar 2024 10:15:06 +0000 (11:15 +0100)]
Rename pg_constraint.conwithoutoverlaps to conperiod

pg_constraint.conwithoutoverlaps was recently added to support primary
keys and unique constraints with the WITHOUT OVERLAPS clause.  An
upcoming patch provides the foreign-key side of this functionality,
but the syntax there is different and uses the keyword PERIOD.  It
would make sense to use the same pg_constraint field for both of
these, but then we should pick a more general name that conveys "this
constraint has a temporal/period-related feature".  conperiod works
for that and is nicely compact.  Changing this now avoids possibly
having to introduce versioning into clients.  Note there are still
some "without overlaps" variables left, which deal specifically with
the parsing of the primary key/unique constraint feature.

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

14 months agoFix a leftover reference to backend_id in comment
Heikki Linnakangas [Tue, 5 Mar 2024 07:15:02 +0000 (09:15 +0200)]
Fix a leftover reference to backend_id in comment

Commit 024c521117 replaced backend_id with proc_number.

Reported-by: Alexander Lakhin
14 months agoFix buildfarm failures from 2af07e2f74.
Jeff Davis [Tue, 5 Mar 2024 03:42:16 +0000 (19:42 -0800)]
Fix buildfarm failures from 2af07e2f74.

Use GUC_ACTION_SAVE rather than GUC_ACTION_SET, necessary for working
with parallel query.

Now that the call requires more arguments, wrap the call in a new
function to avoid code duplication and offer a place for a comment.

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

14 months agoFix incorrectly reported stats kind in "can't happen" ERROR
David Rowley [Tue, 5 Mar 2024 03:17:02 +0000 (16:17 +1300)]
Fix incorrectly reported stats kind in "can't happen" ERROR

The error message(s) were reporting the stats kind of 'f', which is not
correct as that's for the "dependencies" statistics kind.

Reported-by: Horst Reiterer
Reviewed-by: Richard Guo
Discussion: https://postgr.es/m/18375-ba99383eb9062d6a@postgresql.org
Backpatch-through: 12, where MCV extended stats were added.

14 months agoFix search_path to a safe value during maintenance operations.
Jeff Davis [Tue, 5 Mar 2024 01:31:38 +0000 (17:31 -0800)]
Fix search_path to a safe value during maintenance operations.

While executing maintenance operations (ANALYZE, CLUSTER, REFRESH
MATERIALIZED VIEW, REINDEX, or VACUUM), set search_path to
'pg_catalog, pg_temp' to prevent inconsistent behavior.

Functions that are used for functional indexes, in index expressions,
or in materialized views and depend on a different search path must be
declared with CREATE FUNCTION ... SET search_path='...'.

This change was previously committed as 05e1737351, then reverted in
commit 2fcc7ee7af because it was too late in the cycle.

Preparation for the MAINTAIN privilege, which was previously reverted
due to search_path manipulation hazards.

Discussion: https://postgr.es/m/d4ccaf3658cb3c281ec88c851a09733cd9482f22[email protected]
Discussion: https://postgr.es/m/E1q7j7Y-000z1H-Hr%40gemulon.postgresql.org
Discussion: https://postgr.es/m/e44327179e5c9015c8dda67351c04da552066017.camel%40j-davis.com
Reviewed-by: Greg Stark, Nathan Bossart, Noah Misch
14 months agoAdd macro for customizing an archiving WARNING message.
Nathan Bossart [Mon, 4 Mar 2024 21:41:42 +0000 (15:41 -0600)]
Add macro for customizing an archiving WARNING message.

Presently, if an archive module's check_configured_cb callback
returns false, a generic WARNING message is emitted, which
unfortunately provides no actionable details about the reason why
the module is not configured.  This commit introduces a macro that
archive module authors can use to add a DETAIL line to this WARNING
message.

Co-authored-by: Tung Nguyen
Reviewed-by: Daniel Gustafsson, Álvaro Herrera
Discussion: https://postgr.es/m/4109578306242a7cd5661171647e11b2%40oss.nttdata.com

14 months agoExplicitly list dependent types as extension members in pg_depend.
Tom Lane [Mon, 4 Mar 2024 19:49:31 +0000 (14:49 -0500)]
Explicitly list dependent types as extension members in pg_depend.

Auto-generated array types, multirange types, and relation rowtypes
are treated as dependent objects: they can't be dropped separately
from the base object, nor can they have their own ownership or
permissions.  We previously felt that, for objects that are in an
extension, only the base object needs to be listed as an extension
member in pg_depend.  While that's sufficient to prevent inappropriate
drops, it results in undesirable answers if someone asks whether a
dependent type belongs to the extension.  It looks like the dependent
type is just some random separately-created object that happens to
depend on the base object.  Notably, this results in postgres_fdw
concluding that expressions involving an array type are not shippable
to the remote server, even when the defining extension has been
whitelisted.

To fix, cause GenerateTypeDependencies to make extension dependencies
for dependent types as well as their base objects, and adjust
ExecAlterExtensionContentsStmt so that object addition and removal
operations recurse to dependent types.  The latter change means that
pg_upgrade of a type-defining extension will end with the dependent
type(s) now also listed as extension members, even if they were
not that way in the source database.  Normally we want pg_upgrade
to precisely reproduce the source extension's state, but it seems
desirable to make an exception here.

This is arguably a bug fix, but we can't back-patch it since it
causes changes in the expected contents of pg_depend.  (Because
it does, I've bumped catversion, even though there's no change
in the immediate post-initdb catalog contents.)

Tom Lane and David Geier

Discussion: https://postgr.es/m/4a847c55-489f-4e8d-a664-fc6b1cbe306f@gmail.com

14 months agopg_verifybackup: Refactor parse_manifest_file.
Robert Haas [Mon, 4 Mar 2024 19:42:17 +0000 (14:42 -0500)]
pg_verifybackup: Refactor parse_manifest_file.

Return a pointer to the manifest_data instead of individual pointers
to relevant data stored within the manifest_data object. The previous
approach scales poorly if we add more things to the backup manifest,
as has been proposed.

Amul Sul, reviewed by Sravan Velagandula, Michael Paquier, and me.

Discussion: http://postgr.es/m/CAAJ_b95=1LONf99-M_ep588fL_WgLJfdnb7XG4GWE7JDD22E4w@mail.gmail.com

14 months agoFix pgindent damage.
Robert Haas [Mon, 4 Mar 2024 19:37:13 +0000 (14:37 -0500)]
Fix pgindent damage.

Apparently, I neglected to pgindent the prior commit.

Per buildfarm.

14 months agoFix incremental backup interaction with XLOG_DBASE_CREATE_FILE_COPY.
Robert Haas [Mon, 4 Mar 2024 18:33:12 +0000 (13:33 -0500)]
Fix incremental backup interaction with XLOG_DBASE_CREATE_FILE_COPY.

After XLOG_DBASE_CREATE_FILE_COPY, a correct incremental backup needs
to copy in full everything with the database and tablespace OID
mentioned in that record; but that record doesn't specifically mention
the blocks, or even the relfilenumbers, of the affected relations.
As a result, we were failing to copy data that we should have copied.

To fix, enter the DB OID and tablespace OID into the block reference
table with relfilenumber 0 and limit block 0; and treat that as a
limit block of 0 for every relfilenumber whose DB OID and tablespace
OID match.

Also, add a test case.

Patch by me, reviewed by Noah Misch.

Discussion: http://postgr.es/m/CA+Tgmob0xa=ByvGLMdAgkUZyVQE=r4nyYZ_VEa40FCfEDFnTKA@mail.gmail.com

14 months agoFurther further fix pg_upgrade crossversion test for adminpack.
Tom Lane [Mon, 4 Mar 2024 18:10:30 +0000 (13:10 -0500)]
Further further fix pg_upgrade crossversion test for adminpack.

Apparently, buildfarm animal crake has the adminpack regression DB
named as "regression_adminpack" in some branches.  Not clear why
I didn't see that when testing here.  In any case, drop that too.

Discussion: https://postgr.es/m/0CFB76D0-0510-48B2-9916-1199F93BC28C@yesql.se

14 months agoFix initdb's -c option to treat the GUC name case-insensitively.
Tom Lane [Mon, 4 Mar 2024 17:00:39 +0000 (12:00 -0500)]
Fix initdb's -c option to treat the GUC name case-insensitively.

The backend treats GUC names case-insensitively, so this code should
too.  This avoids ending up with a confusing set of redundant entries
in the generated postgresql.conf file.

Per report from Kyotaro Horiguchi.  Back-patch to v16 where this
feature was added (in commit 3e51b278d).

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

14 months agoRework locking code in GetMultiXactIdMembers
Alvaro Herrera [Mon, 4 Mar 2024 16:48:01 +0000 (17:48 +0100)]
Rework locking code in GetMultiXactIdMembers

After commit 53c2a97a9266, the code flow around the "retry" goto label
in GetMultiXactIdMembers was confused about what was possible: we never
return there with a held lock, so there's no point in testing for one.
This realization lets us simplify the code a bit.  While at it, make the
scope of a couple of local variables in the same function a bit tighter.

Per Coverity.

14 months agoSimplify coding in slru.c
Alvaro Herrera [Mon, 4 Mar 2024 16:37:47 +0000 (17:37 +0100)]
Simplify coding in slru.c

New code in 53c2a97a9266 uses direct array access to
shared->bank_locks[bankno].lock which can be made a little bit more
legible by using the SimpleLruGetBankLock helper function.
Nothing terribly serious, but let's add some clarity.

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

14 months agoFurther fix pg_upgrade crossversion test for adminpack.
Tom Lane [Mon, 4 Mar 2024 16:31:32 +0000 (11:31 -0500)]
Further fix pg_upgrade crossversion test for adminpack.

The DROP DATABASE step needs an "if exists" option, as the oldest
branches we test don't have the contrib_regression_adminpack DB.
Also remove unnecessary command to drop the extension from the
regression database; no version has installed it there during
buildfarm testing.

Discussion: https://postgr.es/m/0CFB76D0-0510-48B2-9916-1199F93BC28C@yesql.se

14 months agoFix crossversion test for unsupported versions
Daniel Gustafsson [Mon, 4 Mar 2024 14:09:59 +0000 (15:09 +0100)]
Fix crossversion test for unsupported versions

The fix in be78006741 only accounted for supported versions of postgres
but the crossversion test use 11 as the source version, which is an EOL
version.  Fix by removing the lower bound in the adminpack cleanup.

Discussion: https://postgr.es/m/0CFB76D0-0510-48B2-9916-1199F93BC28C@yesql.se

14 months agoAdjust pg_upgrade crossversion test for adminpack
Daniel Gustafsson [Mon, 4 Mar 2024 13:37:45 +0000 (14:37 +0100)]
Adjust pg_upgrade crossversion test for adminpack

Commit cc09e6549f which removed the adminpack extension failed to
instrument the crossversion pg_upgrade test to drop the extension
before attempting an upgrade to v17.

Discussion: https://postgr.es/m/0CFB76D0-0510-48B2-9916-1199F93BC28C@yesql.se

14 months agoPut back required #include
Peter Eisentraut [Mon, 4 Mar 2024 12:16:18 +0000 (13:16 +0100)]
Put back required #include

Fix for dbbca2cf29: "storage/shmem.h" is required with
-Dspinlocks=false.

14 months agoRemove the adminpack contrib extension
Daniel Gustafsson [Mon, 4 Mar 2024 11:39:22 +0000 (12:39 +0100)]
Remove the adminpack contrib extension

The adminpack extension was only used to support pgAdmin III,  which
in turn was declared EOL many years ago. Removing the extension also
allows us to remove functions from core as well which were only used
to support old version of adminpack.

Reviewed-by: Tom Lane <[email protected]>
Reviewed-by: Nathan Bossart <[email protected]>
Reviewed-by: Bharath Rupireddy <[email protected]>
Discussion: https://postgr.es/m/CALj2ACUmL5TraYBUBqDZBi1C+Re8_=SekqGYqYprj_W8wygQ8w@mail.gmail.com

14 months agoRemove unused #include's from backend .c files
Peter Eisentraut [Mon, 4 Mar 2024 11:00:11 +0000 (12:00 +0100)]
Remove unused #include's from backend .c files

as determined by include-what-you-use (IWYU)

While IWYU also suggests to *add* a bunch of #include's (which is its
main purpose), this patch does not do that.  In some cases, a more
specific #include replaces another less specific one.

Some manual adjustments of the automatic result:

- IWYU currently doesn't know about includes that provide global
  variable declarations (like -Wmissing-variable-declarations), so
  those includes are being kept manually.

- All includes for port(ability) headers are being kept for now, to
  play it safe.

- No changes of catalog/pg_foo.h to catalog/pg_foo_d.h, to keep the
  patch from exploding in size.

Note that this patch touches just *.c files, so nothing declared in
header files changes in hidden ways.

As a small example, in src/backend/access/transam/rmgr.c, some IWYU
pragma annotations are added to handle a special case there.

Discussion: https://www.postgresql.org/message-id/flat/af837490-6b2f-46df-ba05-37ea6a6653fc%40eisentraut.org

14 months agoRemove unused 'countincludesself' argument to pq_sendcountedtext()
Heikki Linnakangas [Mon, 4 Mar 2024 10:56:05 +0000 (12:56 +0200)]
Remove unused 'countincludesself' argument to pq_sendcountedtext()

It has been unused since we removed support for protocol version 2.

14 months agoRemove unused ParallelWorkerInfo.pid field
Heikki Linnakangas [Mon, 4 Mar 2024 10:56:02 +0000 (12:56 +0200)]
Remove unused ParallelWorkerInfo.pid field

The pid was originally used in error context of messages propagated
from parallel workers, but commit 292794f82b removed that. If the need
arises in the future, you can also get the pid with
"shm_mq_get_sender(pcxt->worker[i].error_mqh)->pid".

14 months agoFix doc omission for MERGE into updatable views.
Dean Rasheed [Mon, 4 Mar 2024 10:48:40 +0000 (10:48 +0000)]
Fix doc omission for MERGE into updatable views.

Commit 5f2e179bd3 missed one place in rules.sgml that should have
mentioned MERGE. Also, be more specific when saying that MERGE doesn't
support rules, since it does support SELECT rules.

14 months agodoc: Fix datatype for postgres_fdw option
Daniel Gustafsson [Mon, 4 Mar 2024 09:52:19 +0000 (10:52 +0100)]
doc: Fix datatype for postgres_fdw option

The datatype for analyze_sampling had accidentally been set to text
and not string.  Backpatch to v16 where analyze_sampling first was
introduced.

Author: Shinya Kato <[email protected]>
Reviewed-by: Laurenz Albe <[email protected]>
Discussion: https://postgr.es/m/7fd9166b9fda267411793f39986d7f24@oss.nttdata.com
Backpatch-through: v16

14 months agoUse MyBackendType in more places to check what process this is
Heikki Linnakangas [Mon, 4 Mar 2024 08:25:12 +0000 (10:25 +0200)]
Use MyBackendType in more places to check what process this is

Remove IsBackgroundWorker, IsAutoVacuumLauncherProcess(),
IsAutoVacuumWorkerProcess(), and IsLogicalSlotSyncWorker() in favor of
new Am*Process() macros that use MyBackendType. For consistency with
the existing Am*Process() macros.

Reviewed-by: Andres Freund
Discussion: https://www.postgresql.org/message-id/f3ecd4cb-85ee-4e54-8278-5fabfb3a4ed0@iki.fi

14 months agoRemove MyAuxProcType, use MyBackendType instead
Heikki Linnakangas [Mon, 4 Mar 2024 08:25:09 +0000 (10:25 +0200)]
Remove MyAuxProcType, use MyBackendType instead

MyAuxProcType was redundant with MyBackendType.

Reviewed-by: Reid Thompson, Andres Freund
Discussion: https://www.postgresql.org/message-id/f3ecd4cb-85ee-4e54-8278-5fabfb3a4ed0@iki.fi

14 months agoOptimize GenerationAlloc() and SlabAlloc()
David Rowley [Mon, 4 Mar 2024 04:42:10 +0000 (17:42 +1300)]
Optimize GenerationAlloc() and SlabAlloc()

In a similar effort to 413c18401, separate out the hot and cold paths in
GenerationAlloc() and SlabAlloc() to avoid having to setup the stack frame
for the hot path.

This additionally adjusts how we use the GenerationContext's freeblock.
Freeblock, when set, is now always empty and we only switch to using it
when the current allocation request finds the current block does not have
enough space and the freeblock is large enough to accomodate the
allocation.

This commit also adjusts GenerationFree() so that if we pfree the final
allocation in the current generation block, we now mark that block as
empty and keep it as the current block.  Previously we free'd that block
and set the current block to NULL.  Doing that meant we needed a special
case in GenerationAlloc to check if GenerationContext.block was NULL.
So this both reduces free/malloc calls and reduces the work done in
GenerationAlloc().

In passing, improve some comments in aset.c

Discussion: https://postgr.es/m/CAApHDvpHVSJqqb4B4OZLixr=CotKq-eKkbwZqvZVo_biYvUvQA@mail.gmail.com

14 months agoSupport partition pruning on boolcol IS [NOT] UNKNOWN
David Rowley [Mon, 4 Mar 2024 01:40:03 +0000 (14:40 +1300)]
Support partition pruning on boolcol IS [NOT] UNKNOWN

While working on 4c2369ac5, I noticed we went out of our way not to
support clauses on boolean partitioned tables in the form of "IS
UNKNOWN" and "IS NOT UNKNOWN".  It's almost as much code to disallow
this as it is to allow it, so let's allow it.

Discussion: https://postgr.es/m/CAApHDvobKtcN6+xOuOfcutfp6T7jP=JPA9y3=MAEqnuKdDsQrw@mail.gmail.com

14 months agoAdd PostgreSQL::Test::Cluster::wait_for_event()
Michael Paquier [Mon, 4 Mar 2024 01:25:50 +0000 (10:25 +0900)]
Add PostgreSQL::Test::Cluster::wait_for_event()

Per a demand from the author and the reviewer of this commit, this adds
to Cluster.pm a helper routine that can be used to monitor when a
process reaches a wanted wait event.  This can be used in combination
with the module injection_points for the "wait" callback, though it is
not limited to it as this monitors pg_stat_activity for a wait_event and
a backend_type.

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

14 months agoAdd regression test for restart points during promotion
Michael Paquier [Mon, 4 Mar 2024 00:49:03 +0000 (09:49 +0900)]
Add regression test for restart points during promotion

This test serves as a way to demonstrate how to use the features
introduced in 37b369dc67bc, while providing coverage for 7863ee4def65
that caused the startup process to throw "PANIC: could not locate a
valid checkpoint record" when starting recovery.  The test checks that a
node is able to properly restart following a crash when a restart point
was finishing across a promotion, with an injection point added in the
middle of CreateRestartPoint() to stop the restartpoint in flight.  Note
that this test fails when 7863ee4def65 is reverted.

Kyotaro Horiguchi is the original author of this test, that has been
originally posted on the thread where 7863ee4def65 was discussed.  I
have just upgraded and polished it to rely on injection points, making
it much cheaper to reproduce the failure.

This test requires injection points to be enabled in the builds, hence
meson and ./configure need an update to pass this knowledge down to the
test.  The name of the new injection point follows the same naming
convention as 6a1ea02c491d.  The Makefile's EXTRA_INSTALL of recovery
TAP tests is updated to include modules/injection_points.

Author: Kyotaro Horiguchi, Michael Paquier
Reviewed-by: Andrey Borodin, Bertrand Drouvot
Discussion: https://postgr.es/m/[email protected]

14 months agoinjection_points: Add wait and wakeup of processes
Michael Paquier [Mon, 4 Mar 2024 00:19:13 +0000 (09:19 +0900)]
injection_points: Add wait and wakeup of processes

This commit adds two features to the in-core module for injection
points:
- A new callback called "wait" that can be attached to an injection
point to make it wait.
- A new SQL function to update the shared state and broadcast the update
using a condition variable.  This function uses an input an injection
point name.

This offers the possibility to stop a process in flight and wake it up
in a controlled manner, which is useful when implementing tests that aim
to trigger scenarios for race conditions (some tests are planned for
integration).  The logic uses a set of counters with a condition
variable to monitor and broadcast the changes.  Up to 8 waits can be
registered in a single run, which should be plenty enough.  Waits can be
monitored in pg_stat_activity, based on the injection point name which
is registered in a custom wait event under the "Extension" category.

The shared memory state used by the module is registered using the DSM
registry, and is optional, so there is no need to load the module with
shared_preload_libraries to be able to use these features.

Author: Michael Paquier
Reviewed-by: Andrey Borodin, Bertrand Drouvot
Discussion: https://postgr.es/m/[email protected]

14 months agoReplace BackendIds with 0-based ProcNumbers
Heikki Linnakangas [Sun, 3 Mar 2024 17:38:22 +0000 (19:38 +0200)]
Replace BackendIds with 0-based ProcNumbers

Now that BackendId was just another index into the proc array, it was
redundant with the 0-based proc numbers used in other places. Replace
all usage of backend IDs with proc numbers.

The only place where the term "backend id" remains is in a few pgstat
functions that expose backend IDs at the SQL level. Those IDs are now
in fact 0-based ProcNumbers too, but the documentation still calls
them "backend ids". That term still seems appropriate to describe what
the numbers are, so I let it be.

One user-visible effect is that pg_temp_0 is now a valid temp schema
name, for backend with ProcNumber 0.

Reviewed-by: Andres Freund
Discussion: https://www.postgresql.org/message-id/8171f1aa-496f-46a6-afc3-c46fe7a9b407@iki.fi

14 months agoRedefine backend ID to be an index into the proc array
Heikki Linnakangas [Sun, 3 Mar 2024 17:37:28 +0000 (19:37 +0200)]
Redefine backend ID to be an index into the proc array

Previously, backend ID was an index into the ProcState array, in the
shared cache invalidation manager (sinvaladt.c). The entry in the
ProcState array was reserved at backend startup by scanning the array
for a free entry, and that was also when the backend got its backend
ID. Things become slightly simpler if we redefine backend ID to be the
index into the PGPROC array, and directly use it also as an index to
the ProcState array. This uses a little more memory, as we reserve a
few extra slots in the ProcState array for aux processes that don't
need them, but the simplicity is worth it.

Aux processes now also have a backend ID. This simplifies the
reservation of BackendStatusArray and ProcSignal slots.

You can now convert a backend ID into an index into the PGPROC array
simply by subtracting 1. We still use 0-based "pgprocnos" in various
places, for indexes into the PGPROC array, but the only difference now
is that backend IDs start at 1 while pgprocnos start at 0. (The next
commmit will get rid of the term "backend ID" altogether and make
everything 0-based.)

There is still a 'backendId' field in PGPROC, now part of 'vxid' which
encapsulates the backend ID and local transaction ID together. It's
needed for prepared xacts. For regular backends, the backendId is
always equal to pgprocno + 1, but for prepared xact PGPROC entries,
it's the ID of the original backend that processed the transaction.

Reviewed-by: Andres Freund, Reid Thompson
Discussion: https://www.postgresql.org/message-id/8171f1aa-496f-46a6-afc3-c46fe7a9b407@iki.fi

14 months agoGUC table: Add description to computed variables
Alvaro Herrera [Sun, 3 Mar 2024 13:53:47 +0000 (14:53 +0100)]
GUC table: Add description to computed variables

Per suggestion from Kyotaro Horiguchi
Discussion: https://postgr.es/m/20240229.130404.1411153273308142188[email protected]

14 months agoDocumentation update for Standard Collations.
Jeff Davis [Sat, 2 Mar 2024 21:37:43 +0000 (13:37 -0800)]
Documentation update for Standard Collations.

Correct out-of-date text that said the "default" collation is always
based on LC_COLLATE and LC_CTYPE.

Also reformat into a list to make it easier to understand and compare
the available collations, and briefly document the stability
characteristics of each one.

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

14 months agoFix overflow in Windows replacement pg_pread/pg_pwrite.
Thomas Munro [Sat, 2 Mar 2024 19:40:41 +0000 (08:40 +1300)]
Fix overflow in Windows replacement pg_pread/pg_pwrite.

When calling the Windows file I/O APIs there is an implicit conversion
from size_t to DWORD, which could overflow.  Clamp the size at 1GB to
avoid that.

Not a really a live bug as we don't expect anything in PostgreSQL to
call with such large values.

Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/1672202.1703441340%40sss.pgh.pa.us

14 months agoReturn ssize_t in fd.c I/O functions.
Thomas Munro [Fri, 1 Mar 2024 22:59:34 +0000 (11:59 +1300)]
Return ssize_t in fd.c I/O functions.

In the past, FileRead() and FileWrite() used types based on the Unix
read() and write() functions from before C and POSIX standardization,
though not exactly (we had int for amount instead of unsigned).  In
commit 2d4f1ba6 we changed to the appropriate standard C types, just
like the modern POSIX functions they wrap, but again not exactly: the
return type stayed as int.  In theory, a ssize_t value could be returned
by the underlying call that is too large for an int.

That wasn't really a live bug, because we don't expect PostgreSQL code
to perform reads or writes of gigabytes, and OSes probably apply
internal caps smaller than that anyway.  This change is done on the
principle that the return might as well follow the standard interfaces
consistently.

Reported-by: Tom Lane <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/1672202.1703441340%40sss.pgh.pa.us

14 months agoSimplify pg_enc2gettext_tbl[] with C99-designated initializer syntax
Michael Paquier [Fri, 1 Mar 2024 09:03:48 +0000 (18:03 +0900)]
Simplify pg_enc2gettext_tbl[] with C99-designated initializer syntax

This commit switches pg_enc2gettext_tbl[] in encnames.c to use a
C99-designated initializer syntax.

pg_bind_textdomain_codeset() is simplified so as it is possible to do
a direct lookup at the gettext() array with a value of the enum pg_enc
rather than doing a loop through all its elements, as long as the
encoding value provided by GetDatabaseEncoding() is in the correct range
of supported encoding values.  Note that PG_MULE_INTERNAL gains a value
in the array, pointing to NULL.

Author: Jelte Fennema-Nio
Discussion: https://postgr.es/m/CAGECzQT3caUbcCcszNewCCmMbCuyP7XNAm60J3ybd6PN5kH2Dw@mail.gmail.com

14 months agoFix BF failure introduced by commit b3f6b14cf4.
Amit Kapila [Fri, 1 Mar 2024 04:55:36 +0000 (10:25 +0530)]
Fix BF failure introduced by commit b3f6b14cf4.

The test added by commit b3f6b14cf4 uses a non-superuser and forgot to set
up pg_hba.conf to allow connections from it. The special setup is only
needed on Windows machines that don't use UNIX sockets.

As per buildfarm

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

14 months agoConvert unloggedLSN to an atomic variable.
Nathan Bossart [Thu, 29 Feb 2024 20:34:10 +0000 (14:34 -0600)]
Convert unloggedLSN to an atomic variable.

Currently, this variable is an XLogRecPtr protected by a spinlock.
By converting it to an atomic variable, we can remove the spinlock,
which saves a small amount of shared memory space.  Since this code
is not performance-critical, we use atomic operations with full
barrier semantics to make it easy to reason about correctness.

Author: John Morris
Reviewed-by: Michael Paquier, Robert Haas, Andres Freund, Stephen Frost, Bharath Rupireddy
Discussion: https://postgr.es/m/BYAPR13MB26772534335255E50318C574A0409%40BYAPR13MB2677.namprd13.prod.outlook.com
Discussion: https://postgr.es/m/MN2PR13MB2688FD8B757316CB5C54C8A2A0DDA%40MN2PR13MB2688.namprd13.prod.outlook.com

14 months agoConvert archiver's force_dir_scan variable to an atomic variable.
Nathan Bossart [Thu, 29 Feb 2024 16:17:55 +0000 (10:17 -0600)]
Convert archiver's force_dir_scan variable to an atomic variable.

Commit bd5132db55 introduced new atomic read/write functions with
full barrier semantics, which are intended to simplify converting
non-performance-critical code to use atomic variables.  This commit
demonstrates one such conversion.

Reviewed-by: Yong Li
Discussion: https://postgr.es/m/20231110205128.GB1315705%40nathanxps13

14 months agoIntroduce atomic read/write functions with full barrier semantics.
Nathan Bossart [Thu, 29 Feb 2024 16:00:44 +0000 (10:00 -0600)]
Introduce atomic read/write functions with full barrier semantics.

Writing correct code using atomic variables is often difficult due
to the memory barrier semantics (or lack thereof) of the underlying
operations.  This commit introduces atomic read/write functions
with full barrier semantics to ease this cognitive load.  For
example, some spinlocks protect a single value, and these new
functions make it easy to convert the value to an atomic variable
(thus eliminating the need for the spinlock) without modifying the
barrier semantics previously provided by the spinlock.  Since these
functions may be less performant than the other atomic reads and
writes, they are not suitable for every use-case.  However, using a
single atomic operation with full barrier semantics may be more
performant in cases where a separate explicit barrier would
otherwise be required.

The base implementations for these new functions are atomic
exchanges (for writes) and atomic fetch/adds with 0 (for reads).
These implementations can be overwritten with better architecture-
specific versions as they are discovered.

This commit leaves converting existing code to use these new
functions as a future exercise.

Reviewed-by: Andres Freund, Yong Li, Jeff Davis
Discussion: https://postgr.es/m/20231110205128.GB1315705%40nathanxps13

14 months agoSupport MERGE into updatable views.
Dean Rasheed [Thu, 29 Feb 2024 15:56:59 +0000 (15:56 +0000)]
Support MERGE into updatable views.

This allows the target relation of MERGE to be an auto-updatable or
trigger-updatable view, and includes support for WITH CHECK OPTION,
security barrier views, and security invoker views.

A trigger-updatable view must have INSTEAD OF triggers for every type
of action (INSERT, UPDATE, and DELETE) mentioned in the MERGE command.
An auto-updatable view must not have any INSTEAD OF triggers. Mixing
auto-update and trigger-update actions (i.e., having a partial set of
INSTEAD OF triggers) is not supported.

Rule-updatable views are also not supported, since there is no
rewriter support for non-SELECT rules with MERGE operations.

Dean Rasheed, reviewed by Jian He and Alvaro Herrera.

Discussion: https://postgr.es/m/CAEZATCVcB1g0nmxuEc-A+gGB0HnfcGQNGYH7gS=7rq0u0zOBXA@mail.gmail.com

14 months agoAdd missing RangeTblEntry field to jumble
Peter Eisentraut [Thu, 29 Feb 2024 13:05:56 +0000 (14:05 +0100)]
Add missing RangeTblEntry field to jumble

RangeTblEntry.funcordinality should be jumbled, because the WITH
ORDINALITY clause changes the query result.

This was apparently an oversight in the past.

Discussion: https://www.postgresql.org/message-id/flat/d7f421f8-fd6d-4759-adc3-247090a5d44b%40eisentraut.org

14 months agoRemove field UpdateContext->updated in nodeModifyTable.c
Dean Rasheed [Thu, 29 Feb 2024 11:49:30 +0000 (11:49 +0000)]
Remove field UpdateContext->updated in nodeModifyTable.c

This field has been redundant ever since it was added by commit
25e777cf8e, which split up ExecUpdate() and ExecDelete() into reusable
pieces. The only place that reads it is ExecMergeMatched(), if the
result from ExecUpdateAct() is TM_Ok. However, all paths through
ExecUpdateAct() that return TM_Ok also set this field to true, so the
return status by itself is sufficient to tell if the update happened.

Removing this field is a modest simplification, and it brings the
UPDATE path in ExecMergeMatched() more into line with ExecUpdate(),
ensuring that ExecUpdateEpilogue() is always called if ExecUpdateAct()
returns TM_Ok, reducing the chance of bugs.

Dean Rasheed, reviewed by Alvaro Herrera.

Discussion: https://postgr.es/m/CAEZATCWGGmigGBzLHkJm5Ccv2mMxXmwi3%2Buq0yhwDHm-tsvSLg%40mail.gmail.com