postgresql.git
2 years agoAdd glossary entries related to superusers
Alvaro Herrera [Fri, 18 Nov 2022 10:59:26 +0000 (11:59 +0100)]
Add glossary entries related to superusers

Extracted from a more ambitious patch.

Author: David G. Johnston <david.g.johnston@gmail.com>
Discussion: https://postgr.es/m/CAKFQuwZC4K0XYBm0bwBMDOZySBqhOSekDhLuaw4vPi+ozi8gqQ@mail.gmail.com

2 years agopsql: Improve tab completion for GRANT/REVOKE
Michael Paquier [Fri, 18 Nov 2022 02:26:49 +0000 (11:26 +0900)]
psql: Improve tab completion for GRANT/REVOKE

This commit improves the handling of the following clauses:
- Addition of "CREATE" for ALTER DEFAULT PRIVILEGES .. GRANT/REVOKE.
- Addition of GRANT|ADMIN|INHERIT OPTION FOR for REVOKE, with some
completion for roles, INHERIT being added recently by e3ce2de.
- Addition of GRANT WITH ADMIN|INHERIT.

The list of privilege options common to GRANT and REVOKE is refactored
to avoid its duplication.

Author: Shi Yu
Reviewed-by: Kyotaro Horiguchi, Michael Paquier, Peter Smith
Discussion: https://postgr.es/m/OSZPR01MB6310FCE8609185A56344EED2FD559@OSZPR01MB6310.jpnprd01.prod.outlook.com

2 years agoci: Add task testing windows with mingw
Andres Freund [Fri, 18 Nov 2022 00:22:25 +0000 (16:22 -0800)]
ci: Add task testing windows with mingw

For now the task has been set to be manually triggered, as we are already
limited by the amount of CI time available for windows, particularly on cfbot.

Author: Melih Mutlu <m.melihmutlu@gmail.com>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Justin Pryzby <pryzby@telsasoft.com>
Reviewed-by: Nazir Bilal Yavuz <byavuz81@gmail.com>
Discussion: https://postgr.es/m/CAGPVpCSKS9E0An4=e7ZDnme+y=WOcQFJYJegKO8kE9=gh8NJKQ@mail.gmail.com

2 years agoStandardize rmgrdesc recovery conflict XID output.
Peter Geoghegan [Thu, 17 Nov 2022 22:55:08 +0000 (14:55 -0800)]
Standardize rmgrdesc recovery conflict XID output.

Standardize on the name snapshotConflictHorizon for all XID fields from
WAL records that generate recovery conflicts when in hot standby mode.
This supersedes the previous latestRemovedXid naming convention.

The new naming convention places emphasis on how the values are actually
used by REDO routines.  How the values are generated during original
execution (details of which vary by record type) is deemphasized.  Users
of tools like pg_waldump can now grep for snapshotConflictHorizon to see
all potential sources of recovery conflicts in a standardized way,
without necessarily having to consider which specific record types might
be involved.

Also bring a couple of WAL record types that didn't follow any kind of
naming convention into line.  These are heapam's VISIBLE record type and
SP-GiST's VACUUM_REDIRECT record type.  Now every WAL record whose REDO
routine calls ResolveRecoveryConflictWithSnapshot() passes through the
snapshotConflictHorizon field from its WAL record.  This is follow-up
work to the refactoring from commit 9e540599 that made FREEZE_PAGE WAL
records use a standard snapshotConflictHorizon style XID cutoff.

No bump in XLOG_PAGE_MAGIC, since the underlying format of affected WAL
records doesn't change.

Author: Peter Geoghegan <pg@bowt.ie>
Reviewed-By: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CAH2-Wzm2CQUmViUq7Opgk=McVREHSOorYaAjR1ZpLYkRN7_dPw@mail.gmail.com

2 years agoFix MERGE tuple count with DO NOTHING
Alvaro Herrera [Thu, 17 Nov 2022 17:56:11 +0000 (18:56 +0100)]
Fix MERGE tuple count with DO NOTHING

Reporting tuples for which nothing is done is useless and goes against
the documented behavior, so don't do it.

Backpatch to 15.

Reported by: Luca Ferrari
Discussion: https://postgr.es/m/CAKoxK+42MmACUh6s8XzASQKizbzrtOGA6G1UjzCP75NcXHsiNw@mail.gmail.com

2 years agoUse correct type name in comments about freezing.
Peter Geoghegan [Thu, 17 Nov 2022 17:34:12 +0000 (09:34 -0800)]
Use correct type name in comments about freezing.

Oversight in commit 9e540599, which added freeze plan deduplication.

2 years agoAccount for IPC::Run::result() Windows behavior change.
Noah Misch [Thu, 17 Nov 2022 15:35:06 +0000 (07:35 -0800)]
Account for IPC::Run::result() Windows behavior change.

This restores compatibility with the not-yet-released successor of
version 20220807.0.  Back-patch to 9.4, which introduced this code.

Reviewed by Andrew Dunstan.

Discussion: https://postgr.es/m/20221117061805.GA4020280@rfd.leadboat.com

2 years agolibpq: Handle NegotiateProtocolVersion message
Peter Eisentraut [Thu, 17 Nov 2022 14:14:44 +0000 (15:14 +0100)]
libpq: Handle NegotiateProtocolVersion message

Before, receiving a NegotiateProtocolVersion message would result in a
confusing error message like

    expected authentication request from server, but received v

This adds proper handling of this protocol message and produces an
on-topic error message from it.

Reviewed-by: Jacob Champion <jchampion@timescale.com>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/f9c7862f-b864-8ef7-a861-c4638c83e209%40enterprisedb.com

2 years agolibpq: Correct processing of startup response messages
Peter Eisentraut [Thu, 17 Nov 2022 13:12:04 +0000 (14:12 +0100)]
libpq: Correct processing of startup response messages

After sending a startup message, libpq expects either an error
response ('E') or an authentication request ('R').  Before processing
the message, it ensures it has read enough bytes to correspond to the
length specified in the message.  However, when processing the 'R'
message, if an EOF status is returned it loops back waiting for more
input, even though we already checked that we have enough input.  In
this particular case, this is probably not reachable anyway, because
other code ensures we have enough bytes for an authentication request
message, but the code is wrong and misleading.  In the more general
case, processing a faulty message could result in an EOF status, which
would then result in an infinite loop waiting for the end of a message
that will never come.  The correction is to make this an error.

Reported-by: Jacob Champion <jchampion@timescale.com>
Discussion: https://www.postgresql.org/message-id/flat/f9c7862f-b864-8ef7-a861-c4638c83e209@enterprisedb.com

2 years agoFix wording in comment
Daniel Gustafsson [Thu, 17 Nov 2022 12:17:19 +0000 (13:17 +0100)]
Fix wording in comment

Author: vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm0jKY__83tUsem79+YqfjTWTAkDfiPS0T_Z4y0AYGd_HQ@mail.gmail.com

2 years agoFix outdated comment in ExecDelete
Alvaro Herrera [Thu, 17 Nov 2022 11:52:20 +0000 (12:52 +0100)]
Fix outdated comment in ExecDelete

This commend references a struct that disappeared before MERGE was
merged ... and ExecDelete is not called by the committed MERGE anyway.
Revert to the original wording.

Backpatch to 15

2 years agoAllow initdb to complete on systems without "locale" command
Peter Eisentraut [Thu, 17 Nov 2022 11:12:11 +0000 (12:12 +0100)]
Allow initdb to complete on systems without "locale" command

This partially reverts 2fe3bdbd691a5d11626308e7d660440be6c210c8, which
added an error check on the "locale -a" execution.  This is removed
again, adding a comment explaining why.  We already had code that
shows a warning if no system locales could be found, which should be
sufficient for feedback to the user.

Discussion: https://www.postgresql.org/message-id/flat/b2b491d1-3b36-15b9-6910-5b5540b27f5c%40enterprisedb.com

2 years agodoc: Fix wording of MERGE actions in README
Daniel Gustafsson [Thu, 17 Nov 2022 09:07:06 +0000 (10:07 +0100)]
doc: Fix wording of MERGE actions in README

UPDATE was listed twice and DELETE was omitted, replace one UPDATE
with DELETE instead.

Backpatch through v15 where MERGE was added.

Author: Myo Wai Thant <myo.waithant@fujitsu.com>
Reviewed-by: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/OSAPR01MB43247E46931E9E9CFC4AA0F29A079@OSAPR01MB4324.jpnprd01.prod.outlook.com
Backpatch-through: 15

2 years agoFix typos in comments
Daniel Gustafsson [Thu, 17 Nov 2022 08:12:51 +0000 (09:12 +0100)]
Fix typos in comments

Fix various misspellings of xl_running_xacts.

Author: Japin Li <japinli@hotmail.com>
Discussion: https://postgr.es/m/MEYP282MB1669CA2A39ACF0172774ED27B6069@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM

2 years agoRemove unneeded include in test_slru.c
Michael Paquier [Thu, 17 Nov 2022 07:00:09 +0000 (16:00 +0900)]
Remove unneeded include in test_slru.c

As introduced in 006b69f, the order of the headers was incorrect.
However, it happens that lwlock.h can just be dropped from the list, so
let's be clean and remove it, fixing the order of the listed headers.

2 years agoExport with_icu when running src/bin/scripts tests with meson
Peter Eisentraut [Thu, 17 Nov 2022 06:43:50 +0000 (07:43 +0100)]
Export with_icu when running src/bin/scripts tests with meson

Author: Marina Polyakova <m.polyakova@postgrespro.ru>
Discussion: https://www.postgresql.org/message-id/flat/534fed4a262fee534662bd07a691c5ef@postgrespro.ru

2 years agoUpdate some more ObjectType switch statements to not have default
Peter Eisentraut [Thu, 17 Nov 2022 06:08:44 +0000 (07:08 +0100)]
Update some more ObjectType switch statements to not have default

This allows the compiler to complain if a case has been missed.  In
these instances, the tradeoff of having to list a few unneeded cases
to silence the compiler seems better than the risk of actually missing
one.

Discussion: https://www.postgresql.org/message-id/flat/fce5c98a-45da-19e7-dad0-21096bccd66e%40enterprisedb.com

2 years agoImprove ruleutils' printout of LATERAL references within subplans.
Tom Lane [Thu, 17 Nov 2022 01:06:09 +0000 (20:06 -0500)]
Improve ruleutils' printout of LATERAL references within subplans.

Commit 1cc29fe7c, which taught EXPLAIN to print PARAM_EXEC Params as
the referenced expressions, included some checks to prevent matching
Params found in SubPlans or InitPlans to NestLoopParams of upper query
levels.  At the time, this seemed possibly necessary to avoid false
matches because of the planner's habit of re-using the same PARAM_EXEC
slot in multiple places in a plan.  Furthermore, in the absence of
LATERAL no such reference could be valid anyway.  But it's possible
now that we have LATERAL, and in the wake of 46c508fbc and 1db5667ba
I believe the false-match hazard is gone.  Hence, remove the
in_same_plan_level checks.  As shown in the regression test changes,
this provides a useful improvement in readability for EXPLAIN of
LATERAL-using subplans.

Richard Guo, reviewed by Greg Stark and myself

Discussion: https://postgr.es/m/CAMbWs4-YSOcQXAagJetP95cAeZPqzOy5kM5yijG0PVW5ztRb4w@mail.gmail.com

2 years agoFix slowdown in TAP tests due to recent walreceiver change.
Thomas Munro [Wed, 16 Nov 2022 22:30:14 +0000 (11:30 +1300)]
Fix slowdown in TAP tests due to recent walreceiver change.

Commit 05a7be93 changed the timing of the first reply sent by a
walreceiver, which caused a few TAP tests that call wait_for_catchup()
when they haven't actually streamed anything yet to wait ~10 seconds
(wal_receiver_status_interval).

Before commit 05a7be93 the initial reply was sent after 100ms, but
there's no reason not to send it immediately as a slight improvement.
Do the same for HS feedback for consistency.

Author: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://postgr.es/m/742545.1668377284%40sss.pgh.pa.us

2 years agoInvent "multibitmapsets", and use them to speed up antijoin detection.
Tom Lane [Wed, 16 Nov 2022 18:58:42 +0000 (13:58 -0500)]
Invent "multibitmapsets", and use them to speed up antijoin detection.

Implement a data structure that is a List of Bitmapsets, which is
essentially a 2-D boolean array except that the rows need not all
be the same width.  Operations such as union and intersection are
meaningful for these, just as they are for Bitmapsets.  Eventually
we might build many of the same operations that we have written for
Bitmapsets, but for the first use-case we just need a few.

That first use-case is for antijoin detection: reduce_outer_joins
needs to find the set of Vars that are certain to be non-null in a
successfully joined (not null-extended) left join row, and also
find the set of Vars subject to higher-level IS NULL constraints,
and intersect them.  We had been doing this by making Lists of
the Var nodes and then using list_intersect, which works but is
pretty inefficient compared to a bitmapset-like intersection.
Potentially it's O(N^2) if there are a lot of Vars involved,
which fortunately there generally aren't; still it's not great.
Moreover, that method requires the Vars of interest to be exactly
equal() in the join condition and the upper IS NULL condition,
which is problematic for my WIP patch that labels Vars according
to which outer joins have possibly nulled them.

Discussion: https://postgr.es/m/892228.1668437838@sss.pgh.pa.us
Discussion: https://postgr.es/m/CAMbWs4-mvPPCJ1W6iK6dD5HiNwoJdi6mZp=-7mE8N9Sh+cd0tQ@mail.gmail.com

2 years agoAdd missing object classes to object_address test
Peter Eisentraut [Wed, 16 Nov 2022 18:44:38 +0000 (19:44 +0100)]
Add missing object classes to object_address test

Per the comment, fill in classes mentioned in getObjectIdentityParts()
but not in the test.

2 years agoShave some cycles off subscription/t/100_bugs.pl tests.
Tom Lane [Wed, 16 Nov 2022 17:35:25 +0000 (12:35 -0500)]
Shave some cycles off subscription/t/100_bugs.pl tests.

We can re-use the clusters set up for this test script's first test,
instead of generating new ones.  On my machine this is good for
about a 20% reduction in this script's runtime, from ~6.5 sec to
~5.2 sec.

This idea could be taken further, but it'd require a much more invasive
patch.  These cases are easy because the Perl variable names were
already being re-used.

Anton A. Melnikov

Discussion: https://postgr.es/m/eb7aa992-c2d7-6ce7-4942-0c784231a362@inbox.ru

2 years agoVariable renaming in preparation for refactoring
Peter Eisentraut [Wed, 16 Nov 2022 15:17:18 +0000 (16:17 +0100)]
Variable renaming in preparation for refactoring

Rename page -> block and dp -> page where appropriate.  The old naming
mixed up block and page in confusing ways.

Author: Melanie Plageman <melanieplageman@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/CAAKRu_YSOnhKsDyFcqJsKtBSrd32DP-jjXmv7hL0BPD-z0TGXQ@mail.gmail.com

2 years agoRemove useless casts
Peter Eisentraut [Wed, 16 Nov 2022 15:01:06 +0000 (16:01 +0100)]
Remove useless casts

Maybe these are left from when PageGetItem() was a macro, but now they
are clearly useless.

2 years agoTurn HeapKeyTest macro into inline function
Peter Eisentraut [Wed, 16 Nov 2022 12:25:59 +0000 (13:25 +0100)]
Turn HeapKeyTest macro into inline function

It is easier to read as a function.

Author: Melanie Plageman <melanieplageman@gmail.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://www.postgresql.org/message-id/flat/CAAKRu_YSOnhKsDyFcqJsKtBSrd32DP-jjXmv7hL0BPD-z0TGXQ@mail.gmail.com

2 years agoRemove unused include
Peter Eisentraut [Wed, 16 Nov 2022 10:28:44 +0000 (11:28 +0100)]
Remove unused include

Author: Melanie Plageman <melanieplageman@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/CAAKRu_YSOnhKsDyFcqJsKtBSrd32DP-jjXmv7hL0BPD-z0TGXQ@mail.gmail.com

2 years agodoc: document the TAP test environment variables
Daniel Gustafsson [Wed, 16 Nov 2022 09:25:21 +0000 (10:25 +0100)]
doc: document the TAP test environment variables

The TAP tests can, to some degree, be controlled by a set of environment
variables. These were however only documented in a README and not in the
main documentation.  This adds documentation of these variables, as well
as changes one CPAN reference to a ulink for consistency.  While there,
also tag CPAN as an acronym as it's listed in the acronyms section.

Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/YyPd9unV14SX2bLF@paquier.xyz

2 years agodoc: update metacpan.org links to avoid redirects
Daniel Gustafsson [Wed, 16 Nov 2022 09:24:37 +0000 (10:24 +0100)]
doc: update metacpan.org links to avoid redirects

The /release/ links are redirected to /dist/ and /pod/release/ to
/release/../view/, so update our links accordingly to avoid 301
redirects.

Discussion: https://postgr.es/m/CA672723-BAD2-436E-B6E6-163841E11A1B@yesql.se

2 years agoUse multi-inserts for pg_ts_config_map
Michael Paquier [Wed, 16 Nov 2022 05:32:09 +0000 (14:32 +0900)]
Use multi-inserts for pg_ts_config_map

Two locations working on pg_ts_config_map are switched from
CatalogTupleInsert() to a multi-insert approach with tuple slots:
- ALTER TEXT SEARCH CONFIGURATION ADD/ALTER MAPPING when inserting new
entries.  The number of entries to insert is known in advance, so is the
number of slots needed.  Note that CatalogTupleInsertWithInfo() is now
used for the entry updates.
- CREATE TEXT SEARCH CONFIGURATION, where up to ~20-ish records could be
inserted at once.  The number of slots is not known in advance, hence
a slot initialization is delayed until a tuple is stored in it.

Like all the changes of this kind (1ff416163110c6 or e3931d01), an
insert batch is capped at 64kB.

Author: Michael Paquier, Ranier Vilela
Reviewed-by: Kyotaro Horiguchi
Discussion: https://postgr.es/m/Y3M5bovrkTQbAO4W@paquier.xyz

2 years agoFix test in ae168c794f, per buildfarm.
Jeff Davis [Wed, 16 Nov 2022 03:35:12 +0000 (19:35 -0800)]
Fix test in ae168c794f, per buildfarm.

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/Y3Q8SGMXhInL4o3X@paquier.xyz

2 years agoUse multi-inserts for pg_enum
Michael Paquier [Wed, 16 Nov 2022 03:41:29 +0000 (12:41 +0900)]
Use multi-inserts for pg_enum

This allows to insert at once all the enum values defined with a given
type into pg_enum, reducing the WAL produced by roughly 10%~.  pg_enum's
indexes are opened and closed now once rather than N times.  The number
of items to insert is known in advance, making this change
straight-forward, and would happen on a CREATE TYPE .. AS ENUM.

The amount of data inserted is capped at 64kB for each insert batch.
This is similar to commits 63110c6 and e3931d01, that worked on
different catalogs.

Reported-by: Ranier Vilela
Author: Michael Paquier
Reviewed-by: Kyotaro Horiguchi, Ranier Vilela
Discussion: https://postgr.es/m/Y3M5bovrkTQbAO4W@paquier.xyz

2 years agoAvoid some overhead with open and close of catalog indexes
Michael Paquier [Wed, 16 Nov 2022 01:49:05 +0000 (10:49 +0900)]
Avoid some overhead with open and close of catalog indexes

This commit improves two code paths to open and close indexes a
minimum amount of times when doing a series of catalog updates or
inserts.  CatalogTupleInsert() is costly when using it for multiple
inserts or updates compared to CatalogTupleInsertWithInfo(), as it would
need to open and close the indexes of the catalog worked each time an
operation is done.

This commit updates the following places:
- REINDEX CONCURRENTLY when copying statistics from one index relation
to the other.  Multi-INSERTs are avoided here, as this would begin to
show benefits only for indexes with multiple expressions, for example,
which may not be the most common pattern.  This change is noticeable in
profiles with indexes having many expressions, for example, and it would
improve any callers of CopyStatistics().
- Update of statistics on ANALYZE, that mixes inserts and updates.
In each case, the catalog indexes are opened only if at least one
insertion and/or update is required, to minimize the cost of the
operation.  Like the previous coding, no indexes are opened as long as
at least one insert or update of pg_statistic has happened.

Author: Ranier Vilela
Reviewed-by: Kyotaro Horiguchi, Michael Paquier
Discussion: https://postgr.es/m/CAEudQAqh0F9y6Di_Wc8xW4zkWm_5SDd-nRfVsCn=h0Nm1C_mrg@mail.gmail.com

2 years agoAdd test module for SLRUs
Michael Paquier [Wed, 16 Nov 2022 00:52:21 +0000 (09:52 +0900)]
Add test module for SLRUs

This commit introduces a basic facility to test SLRUs, in terms of
initialization, page reads, writes, flushes, truncation and deletions,
using SQL wrappers around the APIs of slru.c.  This should be easily
extensible at will, and it can be used as a starting point for someone
willing to implement an external module that makes use of SLRUs (LWLock
tranche registering and SLRU initialization particularly).

As this requires a loaded library, the tests use a custom configuration
file and are disabled under installcheck.

Author: Aleksander Alekseev, Michael Paquier
Reviewed-by: Pavel Borisov, Daniel Gustafsson, Noah Misch, Maxim Orlov
Discussion: https://postgr.es/m/CAJ7c6TOFoWcHOW4BVe3BG_uikCrO9B91ayx9d6rh5JZr_tPESg@mail.gmail.com

2 years agoMark argument of RegisterCustomRmgr() as const.
Jeff Davis [Tue, 15 Nov 2022 23:58:12 +0000 (15:58 -0800)]
Mark argument of RegisterCustomRmgr() as const.

2 years agoAdd test module for Custom WAL Resource Manager feature.
Jeff Davis [Tue, 15 Nov 2022 21:10:27 +0000 (13:10 -0800)]
Add test module for Custom WAL Resource Manager feature.

Author: Bharath Rupireddy, Jeff Davis
Discussion: https://postgr.es/m/CALj2ACVTBNA1wfVCsikfhygAbZe6kFY8Oz6PhOyhHyA4vAGouA%40mail.gmail.com

2 years agoDeduplicate freeze plans in freeze WAL records.
Peter Geoghegan [Tue, 15 Nov 2022 15:48:41 +0000 (07:48 -0800)]
Deduplicate freeze plans in freeze WAL records.

Make heapam WAL records that describe freezing performed by VACUUM more
space efficient by storing each distinct "freeze plan" once, alongside
an array of associated page offset numbers (one per freeze plan).  The
freeze plans required for most heap pages tend to naturally have a great
deal of redundancy, so this technique is very effective in practice.  It
often leads to freeze WAL records that are less than 20% of the size of
equivalent WAL records generated using the previous approach.

The freeze plan concept was introduced by commit 3b97e6823b, which fixed
bugs in VACUUM's handling of MultiXacts.  We retain the concept of
freeze plans, but go back to using page offset number arrays.  There is
no loss of generality here because deduplication is an additive process
that gets applied mechanically when FREEZE_PAGE WAL records are built.

More than anything else, freeze plan deduplication is an optimization
that reduces the marginal cost of freezing additional tuples on pages
that will need to have at least one or two tuples frozen in any case.
Ongoing work that adds page-level freezing to VACUUM will take full
advantage of the improved cost profile through batching.

Also refactor some of the details surrounding recovery conflicts needed
to REDO freeze records in passing: make original execution responsible
for generating a standard latestRemovedXid cutoff, rather than working
backwards to get the same cutoff in the REDO routine.  Bugfix commit
66fbcb0d2e did it the other way around, which is equivalent but obscures
what's going on.

Also rename the cutoff field from the WAL record/struct (rename the
field cutoff_xid to latestRemovedXid to match similar WAL records).
Processing of conflicts by REDO routines is already completely uniform,
so tools like pg_waldump should present the information driving the
process uniformly.  There are two remaining WAL record types that still
don't quite follow this convention (heapam's VISIBLE record type and
SP-GiST's VACUUM_REDIRECT record type).  They can be brought into line
by later work that totally standardizes how the cutoffs are presented.

Bump XLOG_PAGE_MAGIC.

Author: Peter Geoghegan <pg@bowt.ie>
Reviewed-By: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-By: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-By: Justin Pryzby <pryzby@telsasoft.com>
Discussion: https://postgr.es/m/CAH2-Wz=XytErMnb8FAyFd+OQEbiipB0Q2FmFdXrggPL4VBnRYQ@mail.gmail.com

2 years agoCheck return value of pclose() correctly
Peter Eisentraut [Tue, 15 Nov 2022 14:35:37 +0000 (15:35 +0100)]
Check return value of pclose() correctly

Some callers didn't check the return value of pclose() or
ClosePipeStream() correctly.  Either they didn't check it at all or
they treated it like the return of fclose().

The correct way is to first check whether the return value is -1, and
then report errno, and then check the return value like a result from
system(), for which we already have wait_result_to_str() to make it
simpler.  To make this more compact, expand wait_result_to_str() to
also handle -1 explicitly.

Reviewed-by: Ankit Kumar Pandey <itsankitkp@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/8cd9fb02-bc26-65f1-a809-b1cb360eef73@enterprisedb.com

2 years agodoc: Use more concise wording for pl/pgSQL TG_ variables
Daniel Gustafsson [Tue, 15 Nov 2022 13:51:02 +0000 (14:51 +0100)]
doc: Use more concise wording for pl/pgSQL TG_ variables

To improve readability of the TG_ variables definition lists, this moves
the datatypes up to the defined term to avoid having each entry start
with "Data type". This also removes redundant wording that that didn't
carry any information from the descriptions.

Author: Christoph Berg <myon@debian.org>
Reviewed-by: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
Discussion: https://postgr.es/m/Yw4Noe3A2s87A0qq@msg.df7cb.de

2 years agopsql: Add command to use extended query protocol
Peter Eisentraut [Tue, 15 Nov 2022 12:50:27 +0000 (13:50 +0100)]
psql: Add command to use extended query protocol

This adds a new psql command \bind that sets query parameters and
causes the next query to be sent using the extended query protocol.
Example:

    SELECT $1, $2 \bind 'foo' 'bar' \g

This may be useful for psql scripting, but one of the main purposes is
also to be able to test various aspects of the extended query protocol
from psql and to write tests more easily.

Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/e8dd1cd5-0e04-3598-0518-a605159fe314@enterprisedb.com

2 years agolibpq error message refactoring, part 2
Peter Eisentraut [Tue, 15 Nov 2022 10:50:04 +0000 (11:50 +0100)]
libpq error message refactoring, part 2

This applies the new APIs to the code.

Reviewed-by: Alvaro Herrera <alvherre@alvh.no-ip.org>
Discussion: https://www.postgresql.org/message-id/flat/7c0232ef-7b44-68db-599d-b327d0640a77@enterprisedb.com

2 years agolibpq error message refactoring
Peter Eisentraut [Tue, 15 Nov 2022 10:50:04 +0000 (11:50 +0100)]
libpq error message refactoring

libpq now contains a mix of error message strings that end with
newlines and don't end with newlines, due to some newer code paths
with new ways of passing errors around.  This leads to confusion and
mistakes both during development and translation.

This adds new functions libpq_append_error() and
libpq_append_conn_error() that encapsulate common code paths for
producing error message strings.  Notably, these functions append the
newline, so that the string appearing in the code does not end with a
newline.  This makes (almost) all error message strings in libpq
uniform in this regard (and also consistent with how we handle it
outside of libpq code).  (There are a few exceptions that are
difficult to fit into this scheme, but they are only a few.)

Reviewed-by: Alvaro Herrera <alvherre@alvh.no-ip.org>
Discussion: https://www.postgresql.org/message-id/flat/7c0232ef-7b44-68db-599d-b327d0640a77@enterprisedb.com

2 years agoDisallow setting archive_library and archive_command at the same time
Peter Eisentraut [Tue, 15 Nov 2022 09:03:12 +0000 (10:03 +0100)]
Disallow setting archive_library and archive_command at the same time

Setting archive_library and archive_command at the same time is now an
error.  Before, archive_library would take precedence over
archive_command.

Author: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Peter Eisentraut <peter.eisentraut@enterprisedb.com>
Reviewed-by: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Discussion: https://www.postgresql.org/message-id/20220914222736.GA3042279%40nathanxps13

2 years agoImprove comments referring snapshot's subxip array.
Amit Kapila [Tue, 15 Nov 2022 04:07:19 +0000 (09:37 +0530)]
Improve comments referring snapshot's subxip array.

It was referred to as subxact array in a few places and subxip array in
others. By changing it to subxip array, we make it consistent with similar
references to xip array.

Author: Japin Li
Reviewd by: Julien Rouhaud, Richard Guo
Discussion: https://postgr.es/m/MEYP282MB1669DCE7AC193A947CED2A95B6009@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM

2 years agoFix cleanup lock acquisition in SPLIT_ALLOCATE_PAGE replay.
Amit Kapila [Mon, 14 Nov 2022 05:13:33 +0000 (10:43 +0530)]
Fix cleanup lock acquisition in SPLIT_ALLOCATE_PAGE replay.

During XLOG_HASH_SPLIT_ALLOCATE_PAGE replay, we were checking for a
cleanup lock on the new bucket page after acquiring an exclusive lock on
it and raising a PANIC error on failure. However, it is quite possible
that checkpointer can acquire the pin on the same page before acquiring a
lock on it, and then the replay will lead to an error. So instead, directly
acquire the cleanup lock on the new bucket page during
XLOG_HASH_SPLIT_ALLOCATE_PAGE replay operation.

Reported-by: Andres Freund
Author: Robert Haas
Reviewed-By: Amit Kapila, Andres Freund, Vignesh C
Backpatch-through: 11
Discussion: https://postgr.es/m/20220810022617.fvjkjiauaykwrbse@awork3.anarazel.de

2 years agoAdd error context callback when tokenizing authentication files
Michael Paquier [Mon, 14 Nov 2022 02:58:10 +0000 (11:58 +0900)]
Add error context callback when tokenizing authentication files

The parsing of the authentication files for HBA and ident entries
happens in two phases:
- Tokenization of the files, creating a list of TokenizedAuthLines.
- Validation of the HBA and ident entries, building a set of HbaLines or
IdentLines.

The second phase doing the validation provides already some error
context about the configuration file and the line where a problem
happens, but there is no such information in the first phase when
tokenizing the files.  This commit adds an ErrorContextCallback in
tokenize_auth_file(), with a context made of the line number and the
configuration file name involved in a problem.  This is useful for files
included in an HBA file for user and database lists, and it will become
much more handy to track problems for files included via a potential
@include[_dir,_if_exists].

The error context is registered so as the full chain of events is
reported when using cascaded inclusions when for example
tokenize_auth_file() recurses over itself on new files, displaying one
context line for each file gone through when tokenizing things.

Author: Michael Paquier
Reviewed-by: Julien Rouhaud
Discussion: https://postgr.es/m/Y2xUBJ+S+Z0zbxRW@paquier.xyz

2 years agoInvent open_auth_file() in hba.c to refactor authentication file opening
Michael Paquier [Mon, 14 Nov 2022 01:21:42 +0000 (10:21 +0900)]
Invent open_auth_file() in hba.c to refactor authentication file opening

This adds a check on the recursion depth when including authentication
configuration files, something that has never been done when processing
'@' files for database and user name lists in pg_hba.conf.  On HEAD,
this was leading to a rather confusing error, as of:
FATAL:  exceeded maxAllocatedDescs (NN) while trying to open file "/path/blah.conf"

This refactors the code so as the error reported is now the following,
which is the same as for GUCs:
FATAL: could not open file "/path/blah.conf": maximum nesting depth exceeded

This reduces a bit the verbosity of the error message used for files
included in user and database lists, reporting only the file name of
what's failing to load, without mentioning the relative or absolute path
specified after '@' in a HBA file.  The absolute path is built upon what
'@' defines anyway, so there is no actual loss of information.  This
makes the future inclusion logic much simpler.  A follow-up patch will
add an error context to be able to track on which line of which file the
inclusion is failing, to close the loop, providing all the information
needed to know the full chain of events.

This logic has been extracted from a larger patch written by Julien,
rewritten by me to have a unique code path calling AllocateFile() on
authentication files, and is useful on its own.  This new interface
will be used later for authentication files included with
@include[_dir,_if_exists], in a follow-up patch.

Author: Michael Paquier, Julien Rouhaud
Discussion: https://www.postgresql.org/message-id/Y2xUBJ+S+Z0zbxRW@paquier.xyz

2 years agolibpq: Add missing newlines to error messages
Peter Eisentraut [Sun, 13 Nov 2022 20:09:09 +0000 (21:09 +0100)]
libpq: Add missing newlines to error messages

2 years agolibpq: Remove unneeded cast and adjust format placeholder
Peter Eisentraut [Sun, 13 Nov 2022 20:09:05 +0000 (21:09 +0100)]
libpq: Remove unneeded cast and adjust format placeholder

2 years agoMake Bitmapsets be valid Nodes.
Tom Lane [Sun, 13 Nov 2022 15:22:45 +0000 (10:22 -0500)]
Make Bitmapsets be valid Nodes.

Add a NodeTag field to struct Bitmapset.  This is free because of
alignment considerations on 64-bit hardware.  While it adds some
space on 32-bit machines, we aren't optimizing for that case anymore.
The advantage is that data structures such as Lists of Bitmapsets
are now first-class objects to the Node infrastructure, and don't
require special-case code to handle.

This patch includes removal of one such special case, in indxpath.c:
bms_equal_any() can now be replaced by list_member().  There may be
more existing code that could be simplified, but I didn't look very
hard.  We also get to drop the read_write_ignore annotations on a
couple of RelOptInfo fields.

The outfuncs/readfuncs support is arranged so that nothing changes
in the string representation of a Bitmapset field; therefore, this
doesn't need a catversion bump.

Amit Langote and Tom Lane

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

2 years agoUse installed postgresql.conf.sample for GUC sanity TAP test
Andrew Dunstan [Sun, 13 Nov 2022 14:07:53 +0000 (09:07 -0500)]
Use installed postgresql.conf.sample for GUC sanity TAP test

The current code looks for the sample file in the source directory, but
it seems better to test against the installed sample file.

Backpatch to release 15 where the test was introduced.

Discussion: https://postgr.es/m/73eea68e-3b6f-5f63-6024-25ed26b52016@dunslane.net

Reviewed by Tom Lane, Alvaro Herrera, Michael Paquier.

2 years agoMake PostgreSQL::Test::Cluster::config_data more flexible
Andrew Dunstan [Sun, 13 Nov 2022 13:45:14 +0000 (08:45 -0500)]
Make PostgreSQL::Test::Cluster::config_data more flexible

Currently this only allows for one argument, which must be present, and
always returns a single string. With this change the following now all
work:

  $all_config = $node->config_data;
  %config_map = ($node->config_data);
  $incdir = $node->config_data('--include-dir');
  ($incdir, $sharedir) = $node->config_data(
      qw(--include-dir --share-dir));

Backpatch to release 15 where this was introduced.

Discussion: https://postgr.es/m/73eea68e-3b6f-5f63-6024-25ed26b52016@dunslane.net

Reviewed by Tom Lane, Alvaro Herrera, Michael Paquier.

2 years agoRefactor aclcheck functions
Peter Eisentraut [Sun, 13 Nov 2022 07:11:17 +0000 (08:11 +0100)]
Refactor aclcheck functions

Instead of dozens of mostly-duplicate pg_foo_aclcheck() functions,
write one common function object_aclcheck() that can handle almost all
of them.  We already have all the information we need, such as which
system catalog corresponds to which catalog table and which column is
the ACL column.

There are a few pg_foo_aclcheck() that don't work via the generic
function and have special APIs, so those stay as is.

I also changed most pg_foo_aclmask() functions to static functions,
since they are not used outside of aclchk.c.

Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Reviewed-by: Antonin Houska <ah@cybertec.at>
Discussion: https://www.postgresql.org/message-id/flat/95c30f96-4060-2f48-98b5-a4392d3b6066@enterprisedb.com

2 years agoRefactor ownercheck functions
Peter Eisentraut [Sun, 13 Nov 2022 07:11:17 +0000 (08:11 +0100)]
Refactor ownercheck functions

Instead of dozens of mostly-duplicate pg_foo_ownercheck() functions,
write one common function object_ownercheck() that can handle almost
all of them.  We already have all the information we need, such as
which system catalog corresponds to which catalog table and which
column is the owner column.

Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Reviewed-by: Antonin Houska <ah@cybertec.at>
Discussion: https://www.postgresql.org/message-id/flat/95c30f96-4060-2f48-98b5-a4392d3b6066@enterprisedb.com

2 years agoAdd repalloc0 and repalloc0_array
Peter Eisentraut [Sat, 12 Nov 2022 19:31:27 +0000 (20:31 +0100)]
Add repalloc0 and repalloc0_array

These zero out the space added by repalloc.  This is a common pattern
that is quite hairy to code by hand.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/b66dfc89-9365-cb57-4e1f-b7d31813eeec@enterprisedb.com

2 years agoIf wait_for_catchup fails under has_wal_read_bug, skip balance of test.
Noah Misch [Sat, 12 Nov 2022 19:19:50 +0000 (11:19 -0800)]
If wait_for_catchup fails under has_wal_read_bug, skip balance of test.

Test files should now ignore has_wal_read_bug() so long as
wait_for_catchup() is their only known way of reaching the bug.  That's
at least five files today, a number expected to grow over time.  This
commit removes skip logic from three.  By doing so, systems having the
bug regain the ability to catch other kinds of defects via those three
tests.  The other two, 002_databases.pl and 031_recovery_conflict.pl,
have been unprotected.  Back-patch to v15, where done_testing() first
became our standard.

Discussion: https://postgr.es/m/20221030031639.GA3082137@rfd.leadboat.com

2 years agoFix volatility marking of timestamptz_trunc_zone.
Tom Lane [Sat, 12 Nov 2022 18:29:41 +0000 (13:29 -0500)]
Fix volatility marking of timestamptz_trunc_zone.

It's safe to mark this as immutable, because it does not depend
on the timezone GUC setting.  Oversight in commit 600b04d6b.

(There's an argument that timezone definitions do change from
time to time, but we have not worried about that in marking
other timestamp-related functions; for example AT TIME ZONE
has always been considered immutable.  The situation is no
worse than our problems with time-varying locales, surely.)

Przemysław Sztoch

Discussion: https://postgr.es/m/eaa3fabe-50fc-bbe8-b096-ce62ddadab85@sztoch.pl

2 years agoDocument WAL rules related to PD_ALL_VISIBLE in README.
Jeff Davis [Sat, 12 Nov 2022 16:37:50 +0000 (08:37 -0800)]
Document WAL rules related to PD_ALL_VISIBLE in README.

Also improve comments.

Discussion: https://postgr.es/m/a50005c1c537f89bb359057fd70e66bb83bce969.camel@j-davis.com
Reviewed-by: Peter Geoghegan
2 years agoFix theoretical torn page hazard.
Jeff Davis [Thu, 10 Nov 2022 22:46:30 +0000 (14:46 -0800)]
Fix theoretical torn page hazard.

The original report was concerned with a possible inconsistency
between the heap and the visibility map, which I was unable to
confirm. The concern has been retracted.

However, there did seem to be a torn page hazard when using
checksums. By not setting the heap page LSN during redo, the
protections of minRecoveryPoint were bypassed. Fixed, along with a
misleading comment.

It may have been impossible to hit this problem in practice, because
it would require a page tear between the checksum and the flags, so I
am marking this as a theoretical risk. But, as discussed, it did
violate expectations about the page LSN, so it may have other
consequences.

Backpatch to all supported versions.

Reported-by: Konstantin Knizhnik
Reviewed-by: Konstantin Knizhnik
Discussion: https://postgr.es/m/fed17dac-8cb8-4f5b-d462-1bb4908c029e@garret.ru
Backpatch-through: 11

2 years agoRemove obsolete comments and code from prior to f8f4227976.
Jeff Davis [Fri, 11 Nov 2022 16:40:01 +0000 (08:40 -0800)]
Remove obsolete comments and code from prior to f8f4227976.

XLogReadBufferForRedo() and XLogReadBufferForRedoExtended() only return
BLK_NEEDS_REDO if the record LSN is greater than the page LSN, so
the redo routine doesn't need to do the LSN check again.

Discussion: https://postgr.es/m/0c37b80e62b1f3007d5a6d1292bd8fa0c275627a.camel@j-davis.com

2 years agomeson: Define HAVE_LOCALE_T for msvc
Peter Eisentraut [Fri, 11 Nov 2022 15:00:48 +0000 (16:00 +0100)]
meson: Define HAVE_LOCALE_T for msvc

Meson doesn't see the redefinition of locale_t done in
src/include/port/win32_port.h, so it is not defining HAVE_LOCALE_T,
HAVE_WCSTOMBS_L nor HAVE_MBSTOWCS_L as the current
src/tools/msvc/build.pl script does.  Add manual overrides to fix.

Author: Author: Juan Jose Santamaria Flecha <juanjo.santamaria@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/CAC%2BAXB1wJEqfKCuVcNpoH%3Dgxd61N%3D7c2fR3Ew6YRPpSfEUA%3DyQ%40mail.gmail.com

2 years agoSupport writing "CREATE/ALTER TABLE ... SET STORAGE DEFAULT".
Tom Lane [Thu, 10 Nov 2022 23:20:49 +0000 (18:20 -0500)]
Support writing "CREATE/ALTER TABLE ... SET STORAGE DEFAULT".

We already allow explicitly writing DEFAULT for SET COMPRESSION,
so it seems a bit inflexible and non-orthogonal to not have it
for STORAGE.

Aleksander Alekseev

Discussion: https://postgr.es/m/CAJ7c6TMX9ui+6y3TQFaXJYVpZyBukvqhQbVDJ8OUokeLRhtnpA@mail.gmail.com

2 years agoFix alter_table.sql test case to test what it claims to.
Tom Lane [Thu, 10 Nov 2022 22:24:26 +0000 (17:24 -0500)]
Fix alter_table.sql test case to test what it claims to.

The stanza "SET STORAGE may need to add a TOAST table" does not
test what it's supposed to, and hasn't done so since we added
the ability to store constant column default values as metadata.
We need to use a non-constant default to get the expected table
rewrite to actually happen.

Fix that, and add the missing checks that would have exposed the
problem to begin with.

Noted while reviewing a patch that made changes in this test case.
Back-patch to v11 where the problem came in.

2 years agoFix comments atop ReorderBufferAddInvalidations.
Amit Kapila [Thu, 10 Nov 2022 11:26:49 +0000 (16:56 +0530)]
Fix comments atop ReorderBufferAddInvalidations.

The comments atop seem to indicate that we always accumulate invalidation
messages in a top-level transaction which is neither required nor matches
with the code.

Author: Amit Kapila
Reviewd by: Masahiko Sawada
Backpatch-through: 14, where it was introduced in commit c55040ccd0
Discussion: https://postgr.es/m/CAA4eK1LxGgnUroPz8STb6OfjVU1yaHoSA+T63URwmGCLdMJ0LA@mail.gmail.com

2 years agoFix comment of SimpleLruInit() in slru.c
Michael Paquier [Thu, 10 Nov 2022 07:32:29 +0000 (16:32 +0900)]
Fix comment of SimpleLruInit() in slru.c

sync_handler was not mentioned in the comment block of the function.

Oversight in dee663f.

Author: Aleksander Alekseev
Discussion: https://postgr.es/m/CAJ7c6TPUd9BwNY47TtMxaijLHSbyHNdhu=kvbGnvO_bi+oC6_Q@mail.gmail.com
Backpatch-through: 14

2 years agoApply a better fix to mdunlinkfork().
Tom Lane [Wed, 9 Nov 2022 19:15:38 +0000 (14:15 -0500)]
Apply a better fix to mdunlinkfork().

Replace the stopgap fix I made in 0e758ae89 with a cleaner one.

The real problem with 4ab5dae94 is that it contorted this function's
logic substantially, by introducing a third code path that required
different behavior in the function's main loop.  That seems quite
unnecessary on closer inspection: the new IsBinaryUpgrade case can
just share the behavior of the other immediate-unlink cases.  Hence,
revert 4ab5dae94 and most of 0e758ae89 (keeping the latter's
save/restore errno fix), and add IsBinaryUpgrade to the set of
conditions tested to choose immediate unlink.

Also fix some additional places with sloppy handling of errno,
to ensure we have an invariant that we always continue processing
after any non-ENOENT failure of do_truncate.  I doubt that that's
fixing any bug of field importance, so I don't feel it necessary to
back-patch; but we might as well get it right while we're here.

Also improve the comments, which had drifted a bit from what the
code actually does, and neglected to mention some important
considerations.

Back-patch to v15, not because this is fixing any bug but because
it doesn't seem like a good idea for v15's mdunlinkfork logic to be
significantly different from both v14 and v16.

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

2 years agoRemove redundant declaration for XidInMVCCSnapshot
Alvaro Herrera [Wed, 9 Nov 2022 17:27:31 +0000 (18:27 +0100)]
Remove redundant declaration for XidInMVCCSnapshot

This was added for no good reason by c91560defc57, after b7eda3e0e334
had just moved the prototype from utils/tqual.h to utils/snapmgr.h.

Author: Japin Li <japinli@hotmail.com>
Discussion: https://postgr.es/m/MEYP282MB16693A409F3282A9DB287BADB63E9@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM

2 years agoReport a more useful error for reloptions on a partitioned table.
Tom Lane [Wed, 9 Nov 2022 17:28:34 +0000 (12:28 -0500)]
Report a more useful error for reloptions on a partitioned table.

Previously, trying to set storage parameters on a partitioned table
always led to "unrecognized parameter foo", because the code expected
there might be some valid parameters; but there aren't any.  The docs
make clear that it's intended that there never will be any, so let's
replace this useless search with a more to-the-point message.

Simon Riggs and Karina Litskevich

Discussion: https://postgr.es/m/CANbhV-H=eZ9kTR9mUgKGK0Qv9uXP=U+dQg3rinQHfTdFMhBA2A@mail.gmail.com

2 years agoDoc: add comments about PreventInTransactionBlock/IsInTransactionBlock.
Tom Lane [Wed, 9 Nov 2022 16:08:52 +0000 (11:08 -0500)]
Doc: add comments about PreventInTransactionBlock/IsInTransactionBlock.

Add a little to the header comments for these functions to make it
clearer what guarantees about commit behavior are provided to callers.
(See commit f92944137 for context.)

Although this is only a comment change, it's really documentation
aimed at authors of extensions, so it seems appropriate to back-patch.

Yugo Nagata and Tom Lane, per further discussion of bug #17434.

Discussion: https://postgr.es/m/17434-d9f7a064ce2a88a3@postgresql.org

2 years agoProvide sigaction() for Windows.
Thomas Munro [Wed, 9 Nov 2022 00:05:16 +0000 (13:05 +1300)]
Provide sigaction() for Windows.

Commit 9abb2bfc left behind code to block signals inside signal
handlers on Windows, because our signal porting layer didn't have
sigaction().  Provide a minimal implementation that is capable of
blocking signals, to get rid of platform differences.  See also related
commit c94ae9d8.

Discussion: https://postgr.es/m/CA%2BhUKGKKKfcgx6jzok9AYenp2TNti_tfs8FMoJpL8%2B0Gsy%3D%3D_A%40mail.gmail.com

2 years agoUse AbsoluteConfigLocation() when building an included path in hba.c
Michael Paquier [Tue, 8 Nov 2022 23:47:02 +0000 (08:47 +0900)]
Use AbsoluteConfigLocation() when building an included path in hba.c

The code building an absolute path to a file included, as prefixed by
'@' in authentication files, for user and database lists uses the same
logic as for GUCs, except that it has no need to know about DataDir as
there is always a calling file to rely to build the base directory path.
The refactoring done in a1a7bb8 makes this move straight-forward, and
unifies the code used for GUCs and authentication files, and the
intention is to rely also on that for the upcoming patch to be able to
include full files from HBA or ident files.

Note that this gets rid of an inconsistency introduced in 370f909, that
copied the logic coming from GUCs but applied it for files included in
authentication files, where the result buffer given to
join_path_components() must have a size of MAXPGPATH.  Based on a
double-check of the existing code, all the other callers of
join_path_components() already do that, except the code path changed
here.

Discussion: https://postgr.es/m/Y2igk7q8OMpg+Yta@paquier.xyz

2 years agoDoc: improve tutorial section about grouped aggregates.
Tom Lane [Tue, 8 Nov 2022 23:25:03 +0000 (18:25 -0500)]
Doc: improve tutorial section about grouped aggregates.

Commit fede15417 introduced FILTER by jamming it into the existing
example introducing HAVING, which seems pedagogically poor to me;
and it added no information about what the keyword actually does.
Not to mention that the claimed output didn't match the sample
data being used in this running example.

Revert that and instead make an independent example using FILTER.
To help drive home the point that it's a per-aggregate filter,
we need to use two aggregates not just one; for consistency
expand all the examples in this segment to do that.

Also adjust the example using WHERE ... LIKE so that it'd produce
nonempty output with this sample data, and show that output.

Back-patch, as the previous patch was.  (Sadly, v10 is now out
of scope.)

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

2 years agoUnify some internal error message wordings
Peter Eisentraut [Tue, 8 Nov 2022 17:45:29 +0000 (18:45 +0100)]
Unify some internal error message wordings

2 years agoProduce more-optimal plans for bitmap scans on boolean columns.
Tom Lane [Tue, 8 Nov 2022 15:36:04 +0000 (10:36 -0500)]
Produce more-optimal plans for bitmap scans on boolean columns.

The planner simplifies boolean comparisons such as "x = true" and
"x = false" down to "x" and "NOT x" respectively, to have a canonical
form to ease comparisons.  However, if we want to use an index on x,
the index AM APIs require us to reconstitute the comparison-operator
form of the indexqual.  While that works, in bitmap indexscans the
canonical form of the qual was emitted as a "filter" condition
although it really only needs to be a "recheck" condition, because
create_bitmap_scan_plan didn't recognize the equivalence of that
form with the generated indexqual.  booleq() is pretty cheap so that
likely doesn't make very much difference, but it's unsightly so
let's clean it up.

To fix, add a case to predicate_implied_by() to recognize the
equivalence of such clauses.  This is a relatively low-cost place to
add a check, and perhaps it will have additional use cases in future.

Richard Guo and Tom Lane, per discussion of bug #17618 from Sindy
Senorita.

Discussion: https://postgr.es/m/17618-7a2240bfaa7e84ae@postgresql.org

2 years agoSuppress useless wakeups in walreceiver.
Thomas Munro [Tue, 8 Nov 2022 07:36:36 +0000 (20:36 +1300)]
Suppress useless wakeups in walreceiver.

Instead of waking up 10 times per second to check for various timeout
conditions, keep track of when we next have periodic work to do.

Author: Thomas Munro <thomas.munro@gmail.com>
Author: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Reviewed-by: Alvaro Herrera <alvherre@alvh.no-ip.org>
Discussion: https://postgr.es/m/CA%2BhUKGJGhX4r2LPUE3Oy9BX71Eum6PBcS8L3sJpScR9oKaTVaA%40mail.gmail.com

2 years agopsql: Add information in \d+ about foreign partitions and child tables
Michael Paquier [Tue, 8 Nov 2022 05:19:09 +0000 (14:19 +0900)]
psql: Add information in \d+ about foreign partitions and child tables

\d+ is already able to show if a partition or a child table is
"PARTITIONED" via its relkind, hence the addition of a keyword for
"FOREIGN" in the relation description is basically free.

Author: Ian Lawrence Barwick
Reviewed-by: Tom Lane, Michael Paquier
Discussion: https://postgr.es/m/CAB8KJ=iwzbEz2HR9EhNxQLVhMk2G_OYtQPJ9V=jWLadseggrOA@mail.gmail.com

2 years agoUse pg_pwrite_zeros() in walmethods.c
Michael Paquier [Tue, 8 Nov 2022 03:37:11 +0000 (12:37 +0900)]
Use pg_pwrite_zeros() in walmethods.c

This change impacts pg_receivewal and pg_basebackup, for the pre-padding
with zeros of all the new non-compressed WAL segments, so as the code is
more robust on partial writes.  This makes the code consistent with the
backend (XLogFileInitInternal) when wal_init_zeros is enabled for the
WAL segment initialization.

Author: Bharath Rupireddy
Reviewed-by: Nathan Bossart, Andres Freund, Thomas Munro, Michael
Paquier
Discussion: https://postgr.es/m/CALj2ACUq7nAb7=bJNbK3yYmp-SZhJcXFR_pLk8un6XgDzDF3OA@mail.gmail.com

2 years agoIntroduce pg_pwrite_zeros() in fileutils.c
Michael Paquier [Tue, 8 Nov 2022 03:23:46 +0000 (12:23 +0900)]
Introduce pg_pwrite_zeros() in fileutils.c

This routine is designed to write zeros to a file using vectored I/O,
for a size given by its caller, being useful when it comes to
initializing a file with a final size already known.

XLogFileInitInternal() in xlog.c is changed to use this new routine when
initializing WAL segments with zeros (wal_init_zero enabled).  Note that
the aligned buffers used for the vectored I/O writes have a size of
XLOG_BLCKSZ, and not BLCKSZ anymore, as pg_pwrite_zeros() relies on
PGAlignedBlock while xlog.c originally used PGAlignedXLogBlock.

This routine will be used in a follow-up patch to do the pre-padding of
WAL segments for pg_receivewal and pg_basebackup when these are not
compressed.

Author: Bharath Rupireddy
Reviewed-by: Nathan Bossart, Andres Freund, Thomas Munro, Michael
Paquier
Discussion: https://www.postgresql.org/message-id/CALj2ACUq7nAb7%3DbJNbK3yYmp-SZhJcXFR_pLk8un6XgDzDF3OA%40mail.gmail.com

2 years agoFix initialization of pg_stat_get_lastscan()
Michael Paquier [Tue, 8 Nov 2022 01:50:09 +0000 (10:50 +0900)]
Fix initialization of pg_stat_get_lastscan()

A NULL result should be reported when a stats timestamp is set to 0, but
c037471 missed that, leading to a confusing timestamp value after for
example a DML on a freshly-created relation with no scans done on it
yet.

This impacted the following attributes for two system views:
- pg_stat_all_tables.last_idx_scan
- pg_stat_all_tables.last_seq_scan
- pg_stat_all_indexes.last_idx_scan

Reported-by: Robert Treat
Analyzed-by: Peter Eisentraut
Author: Dave Page
Discussion: https://postgr.es/m/CABV9wwPzMfSaz3EfKXXDxKmMprbxwF5r6WPuxqA=5mzRUqfTGg@mail.gmail.com

2 years agoFix compiler warning on MSVC
David Rowley [Mon, 7 Nov 2022 21:54:04 +0000 (10:54 +1300)]
Fix compiler warning on MSVC

MSVC does not understand that ereport(ERROR) does not return, so just
return the first enum PartitionStrategy value to keep the compiler from
complaining about the missing return.

Discussion: https://postgr.es/m/20221104161934.GB16921@telsasoft.com

2 years agoFix failure to remove non-first segments of temporary tables.
Tom Lane [Mon, 7 Nov 2022 16:36:45 +0000 (11:36 -0500)]
Fix failure to remove non-first segments of temporary tables.

Commit 4ab5dae94 broke mdunlinkfork's logic for removing additional
segments of a multi-gigabyte table, because it neglected to advance
"segno" after unlinking the first segment, in the code path where it
chooses to unlink that one immediately.  Then the main remove loop
gets ENOENT at segment zero and figures it's done, so we never remove
whatever additional segments might exist.

The main problem here is with large temporary tables, but WAL replay
of a drop of a large regular table would also fail to remove extra
segments.  The third case where this path is taken is for non-main
forks; but I doubt it matters for those since they probably never
exceed 1GB.

The simplest fix is just to increment segno after that unlink().
(Probably this logic could do with a more thorough rethink, but not
with mere hours to go before 15.1 wraps.)

While here, also fix an incautious assumption that
register_forget_request cannot change errno.  I don't think that
that has any really bad consequences, as we'd end up trying to unlink
the zero'th segment either way, but it greatly complicates reasoning
about what could happen here.  Also make a couple of other cosmetic
fixes.

Per bug #17679 from Balazs Szilfai.  Back-patch into v15, as the
faulty patch was.

Discussion: https://postgr.es/m/17679-1095d04450cf6a6e@postgresql.org

2 years agoMove code related to configuration files in directories to new file
Michael Paquier [Mon, 7 Nov 2022 03:31:38 +0000 (12:31 +0900)]
Move code related to configuration files in directories to new file

The code in charge of listing and classifying a set of configuration
files in a directory was located in guc-file.l, being used currently for
GUCs under "include_dir".  This code is planned to be used for an
upcoming feature able to include configuration files for ident and HBA
files from a directory, similarly to GUCs.  In both cases, the file
names, suffixed by ".conf", have to be ordered alphabetically.  This
logic is moved to a new file, called conffiles.c, so as it is easier to
share this facility between GUCs and the HBA/ident parsing logic.

Author: Julien Rouhaud, Michael Paquier
Discussion: https://postgr.es/m/Y2IgaH5YzIq2b+iR@paquier.xyz

2 years agoDon't pass down nonnullable_vars while reducing outer joins.
Tom Lane [Sat, 5 Nov 2022 19:58:51 +0000 (15:58 -0400)]
Don't pass down nonnullable_vars while reducing outer joins.

We weren't actually using the passed-down list for anything, other
than computing the new value to be passed down further.  I (tgl)
probably had the idea that we'd need this data eventually; but
no use-case has emerged in a good long while, so let's just stop
expending useless cycles here.

Richard Guo

Discussion: https://postgr.es/m/CAMbWs48KLy9aBb=sZ5MoNmnqAcGHaW_JTGWLCgoE_uMW7S6C-A@mail.gmail.com

2 years agoHandle SubPlan cases in find_nonnullable_rels/vars.
Tom Lane [Sat, 5 Nov 2022 19:24:36 +0000 (15:24 -0400)]
Handle SubPlan cases in find_nonnullable_rels/vars.

We can use some variants of SubPlan to deduce that Vars appearing
in the testexpr must be non-null.

Richard Guo

Discussion: https://postgr.es/m/CAMbWs4-jV=199A2Y_6==99dYnpnmaO_Wz_RGkRTTaCB=Pihw2w@mail.gmail.com

2 years agoRemove redundant breaks in HeapTupleSatisfiesVisibility
Andres Freund [Sat, 5 Nov 2022 04:56:34 +0000 (21:56 -0700)]
Remove redundant breaks in HeapTupleSatisfiesVisibility

Author: Melanie Plageman <melanieplageman@gmail.com>
Discussion: https://postgr.es/m/CAAKRu_ZJg_N7zHtWP+JoSY_hrce4+GKioL137Y2c2En-kuXQ7g@mail.gmail.com

2 years agoRemove unneeded includes of <sys/stat.h>
Michael Paquier [Sat, 5 Nov 2022 03:31:28 +0000 (12:31 +0900)]
Remove unneeded includes of <sys/stat.h>

Since bfb9dfd, none of the files updated in this commit have any stat()
calls, so these inclusions are not necessary, for the same reasons as
233cf6e.

Per discussion with John Naylor.

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

2 years agomeson: Split 'main' suite into 'regress' and 'isolation'
Andres Freund [Sat, 5 Nov 2022 01:08:44 +0000 (18:08 -0700)]
meson: Split 'main' suite into 'regress' and 'isolation'

Several people didn't like the 'main' name and found it confusing that the
main regression and isolation tests were in one suite.

Author: Justin Pryzby <pryzbyj@telsasoft.com>
Discussion: https://postgr.es/m/20221001221514.2yy257v4zdfhwiy2@awork3.anarazel.de
Discussion: https://postgr.es/m/20221021123435.GU16921@telsasoft.com

2 years agomeson: Mark PROVE as not required
Andres Freund [Sat, 5 Nov 2022 01:08:05 +0000 (18:08 -0700)]
meson: Mark PROVE as not required

In the meson build the prove binary is currently not even used. It will soon
be, for PGXS compatibility, but even then we should build without it around.

Author: Justin Pryzby <pryzbyj@telsasoft.com>
Discussion: https://postgr.es/m/20221021034040.GT16921@telsasoft.com
Discussion: https://postgr.es/m/20221104235412.GE16921@telsasoft.com

2 years agoFix CREATE DATABASE so we can pg_upgrade DBs with OIDs above 2^31.
Tom Lane [Fri, 4 Nov 2022 14:39:52 +0000 (10:39 -0400)]
Fix CREATE DATABASE so we can pg_upgrade DBs with OIDs above 2^31.

Commit aa0105141 repeated one of the oldest mistakes in our book:
thinking that OID is the same as int32.  It isn't of course, and
unsurprisingly the first person who came along with a database
OID above 2 billion broke it.  Repair.

Per bug #17677 from Sergey Pankov.  Back-patch to v15.

Discussion: https://postgr.es/m/17677-a99fa067d7ed71c9@postgresql.org

2 years agoCorrect error message for row-level triggers with transition tables on partitioned...
Etsuro Fujita [Fri, 4 Nov 2022 10:15:00 +0000 (19:15 +0900)]
Correct error message for row-level triggers with transition tables on partitioned tables.

"Triggers on partitioned tables cannot have transition tables." is
incorrect as we allow statement-level triggers on partitioned tables to
have transition tables.

This has been wrong since commit 86f575948; back-patch to v11 where that
commit came in.

Reviewed by Tom Lane.

Discussion: https://postgr.es/m/CAPmGK17gk4vXLzz2iG%2BG4LWRWCoVyam70nZ3OuGm1hMJwDrhcg%40mail.gmail.com

2 years agoDoc: Improve the description of confirmed_flush_lsn in pg_replication_slots.
Amit Kapila [Fri, 4 Nov 2022 03:30:46 +0000 (09:00 +0530)]
Doc: Improve the description of confirmed_flush_lsn in pg_replication_slots.

Make it clear that the data corresponding to the transactions committed
before confirmed_flush_lsn is not available anymore.

Author: Ashutosh Sharma
Reviewd by: Ashutosh Bapat
Discussion: https://postgr.es/m/CAE9k0P=hiqRXUonnmtS-5Pu8SbO=yF6vcrVBcfEf2+93ng_f5Q@mail.gmail.com

2 years agoRemove outdated include
John Naylor [Fri, 4 Nov 2022 00:50:57 +0000 (07:50 +0700)]
Remove outdated include

In the wake of bfb9dfd93, there are no longer any stat() calls in
guc-file.l, but the work leading to dac048f71 did not get the memo.

Noted by Michael Paquier

Discussion: https://www.postgresql.org/message-id/Y2OosGi1Xh9x/lEn%40paquier.xyz

2 years agoCreate FKs properly when attaching table as partition
Alvaro Herrera [Thu, 3 Nov 2022 19:40:21 +0000 (20:40 +0100)]
Create FKs properly when attaching table as partition

Commit f56f8f8da6af added some code in CloneFkReferencing that's way too
lax about a Constraint node it manufactures, not initializing enough
struct members -- initially_valid in particular was forgotten.  This
causes some FKs in partitions added by ALTER TABLE ATTACH PARTITION to
be marked as not validated.  Set initially_valid true, which fixes the
bug.

While at it, make the struct initialization more complete.  Very similar
code was added in two other places by the same commit; make them all
follow the same pattern for consistency, though no bugs are apparent
there.

This bug has never been reported: I only happened to notice while
working on commit 614a406b4ff1.  The test case that was added there with
the improper result is repaired.

Backpatch to 12.

Discussion: https://postgr.es/m/20221005105523.bhuhkdx4olajboof@alvherre.pgsql

2 years agoMake AssertPointerAlignment available to frontend code
Peter Eisentraut [Thu, 3 Nov 2022 15:53:46 +0000 (11:53 -0400)]
Make AssertPointerAlignment available to frontend code

We don't need separate definitions for frontend and backend, since the
contained Assert() will take care of the difference.  So this also
makes it simpler overall.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://www.postgresql.org/message-id/f64365b1-d5f9-ef83-41fe-404810f10e5a@enterprisedb.com

2 years agoAvoid crash after function syntax error in a replication worker.
Tom Lane [Thu, 3 Nov 2022 16:01:57 +0000 (12:01 -0400)]
Avoid crash after function syntax error in a replication worker.

If a syntax error occurred in a SQL-language or PL/pgSQL-language
CREATE FUNCTION or DO command executed in a logical replication worker,
we'd suffer a null pointer dereference or assertion failure.  That
seems like a rather contrived case, but nonetheless worth fixing.

The cause is that function_parse_error_transpose assumes it must be
executing within the context of a Portal, but logical/worker.c
doesn't create a Portal since it's not running the standard executor.
We can just back off the hard Assert check and make it fail gracefully
if there's not an ActivePortal.  (I have a feeling that the aggressive
check here was my fault originally, probably because I wasn't sure if
the case would always hold and wanted to find out.  Well, now we know.)

The hazard seems to exist in all branches that have logical replication,
so back-patch to v10.

Maxim Orlov, Anton Melnikov, Masahiko Sawada, Tom Lane

Discussion: https://postgr.es/m/b570c367-ba38-95f3-f62d-5f59b9808226@inbox.ru
Discussion: https://postgr.es/m/adf0452f-8c6b-7def-d35e-ab516c80088e@inbox.ru

2 years agoResolve partition strategy during early parsing
Alvaro Herrera [Thu, 3 Nov 2022 15:25:54 +0000 (16:25 +0100)]
Resolve partition strategy during early parsing

This has little practical value, but there's no reason to let the
partition strategy names travel through DDL as strings.

Reviewed-by: Japin Li <japinli@hotmail.com>
Discussion: https://postgr.es/m/20221021093216.ffupd7epy2mytkux@alvherre.pgsql

2 years agoAdd casts to simplehash.h to silence C++ warnings.
Tom Lane [Thu, 3 Nov 2022 14:47:31 +0000 (10:47 -0400)]
Add casts to simplehash.h to silence C++ warnings.

Casting the result of palloc etc. to the intended type is more per
project style anyway.

(The fact that cpluspluscheck doesn't notice these problems is
because it doesn't expand any macros, which seems like a troubling
shortcoming.  Don't have a good idea about improving that.)

Back-patch to v13, which is as far as the patch applies cleanly;
doesn't seem worth working harder.

David Geier

Discussion: https://postgr.es/m/aa5d88a3-71f4-3455-11cf-82de0372c941@gmail.com

2 years agoStraighten include order in guc-file.l
John Naylor [Thu, 3 Nov 2022 05:38:44 +0000 (12:38 +0700)]
Straighten include order in guc-file.l

Oversight in dac048f71eb

Michael Paquier

Reviewed by Julien Rouhaud
Discussion: https://www.postgresql.org/message-id/Y2IATvRGo347Lvd1%40paquier.xyz

2 years agoAllow use of __sync_lock_test_and_set for spinlocks on any machine.
Tom Lane [Wed, 2 Nov 2022 21:37:26 +0000 (17:37 -0400)]
Allow use of __sync_lock_test_and_set for spinlocks on any machine.

If we have no special-case code in s_lock.h for the current platform,
but the compiler has __sync_lock_test_and_set, use that instead of
failing.  It's unlikely that anybody's __sync_lock_test_and_set
would be so awful as to be worse than our semaphore-based fallback,
but if it is, they can (continue to) use --disable-spinlocks.

This allows removal of the RISC-V special case installed by commit
c32fcac56, which generated exactly the same code but only on that
platform.  Usefully, the RISC-V buildfarm animals should now test
at least the int variant of this patch.

I've manually tested both variants on ARM by dint of removing the
ARM-specific stanza.  We don't want to drop that, because it already
has some special knowledge and is likely to grow more over time.
Likewise, this is not meant to preclude installing special cases
for other arches if that proves worthwhile.

Per discussion of a request to install the same code for loongarch64.
Like the previous patch, we might as well back-patch to supported
branches.

Discussion: https://postgr.es/m/761ac43d44b84d679ba803c2bd947cc0@HSMAILSVR04.hs.handsome.com.cn

2 years agopg_dump: Refactor code that constructs ALTER ... OWNER TO commands
Peter Eisentraut [Wed, 2 Nov 2022 21:17:27 +0000 (17:17 -0400)]
pg_dump: Refactor code that constructs ALTER ... OWNER TO commands

Avoid having to list all the possible object types twice.  Instead,
only _getObjectDescription() needs to know about specific object
types.  It communicates back to _printTocEntry() whether an owner is
to be set.

In passing, remove the logic to use ALTER TABLE to set the owner of
views and sequences.  This is no longer necessary.  Furthermore, if
pg_dump doesn't recognize the object type, this is now a fatal error,
not a warning.

Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/0a00f923-599a-381b-923f-0d802a727715@enterprisedb.com

2 years agoDefend against unsupported partition relkind in logical replication worker.
Tom Lane [Wed, 2 Nov 2022 16:29:39 +0000 (12:29 -0400)]
Defend against unsupported partition relkind in logical replication worker.

Since partitions can be foreign tables not only plain tables, but
logical replication only supports plain tables, we'd better check the
relkind of a partition after we find it.  (There was some discussion
of checking this when adding a partitioned table to a subscription;
but that would be inadequate since the troublesome partition could be
added later.)  Without this, the situation leads to a segfault or
assertion failure.

In passing, add a separate variable for the target Relation of
a cross-partition UPDATE; reusing partrel seemed mighty confusing
and error-prone.

Shi Yu and Tom Lane, per report from Ilya Gladyshev.  Back-patch
to v13 where logical replication into partitioned tables became
a thing.

Discussion: https://postgr.es/m/6b93e3748ba43298694f376ca8797279d7945e29.camel@gmail.com