postgresql.git
3 years agoVACUUM VERBOSE: Show dead items for an empty table.
Peter Geoghegan [Fri, 15 Apr 2022 21:20:56 +0000 (14:20 -0700)]
VACUUM VERBOSE: Show dead items for an empty table.

Be consistent about the lines that VACUUM VERBOSE outputs by including
an "index scan not needed: " line for completely empty tables. This
makes the output more readable, especially with multiple distinct VACUUM
operations processed by the same VACUUM command.  It's also more
consistent; even empty tables can use the failsafe, which wasn't
reported in the standard way until now.

Follow-up to commit 6e20f460, which taught VACUUM VERBOSE to be more
consistent about reporting on scanned pages with empty tables.

3 years agoAdjust VACUUM's removable cutoff log message.
Peter Geoghegan [Fri, 15 Apr 2022 20:21:43 +0000 (13:21 -0700)]
Adjust VACUUM's removable cutoff log message.

The age of OldestXmin (a.k.a. "removable cutoff") when VACUUM ends often
indicates the approximate number of XIDs consumed while VACUUM ran.
However, there is at least one important exception: the cutoff could be
held back by a snapshot that was acquired before our VACUUM even began.
Successive VACUUM operations may even use exactly the same old cutoff in
extreme cases involving long held snapshots.

The log messages that described how removable cutoff aged (which were
added by commit 872770fd) created the impression that we were reporting
on how VACUUM's usable cutoff advanced while VACUUM ran, which was
misleading in these extreme cases.  Fix by using a more general wording.

Per gripe from Tom Lane.

In passing, relocate related instrumentation code for clarity.

Author: Peter Geoghegan <pg@bowt.ie>
Discussion: https://postgr.es/m/1643035.1650035653@sss.pgh.pa.us

3 years agoRevert "Temporarily add some probes of tenk1's relallvisible in create_index.sql."
Tom Lane [Fri, 15 Apr 2022 17:29:39 +0000 (13:29 -0400)]
Revert "Temporarily add some probes of tenk1's relallvisible in create_index.sql."

This reverts commit 5bb2b6abc8d6cf120a814317816e4384bcbb9c1e.
Not needed anymore.

3 years agoSmall cleanups in SQL/JSON code
Andrew Dunstan [Fri, 15 Apr 2022 11:47:12 +0000 (07:47 -0400)]
Small cleanups in SQL/JSON code

These are to keep Coverity happy. In one case remove a redundant NULL
check, and in another explicitly ignore a function result that is already
known.

3 years agopgstat: set timestamps of fixed-numbered stats after a crash.
Andres Freund [Fri, 15 Apr 2022 00:40:25 +0000 (17:40 -0700)]
pgstat: set timestamps of fixed-numbered stats after a crash.

When not loading stats at startup (i.e. pgstat_discard_stats() getting
called), reset timestamps of fixed numbered stats would be left at
0. Oversight in 5891c7a8ed8.

Instead use pgstat_reset_after_failure() and add tests verifying that
fixed-numbered reset timestamps are set appropriately.

Reported-By: "David G. Johnston" <david.g.johnston@gmail.com>
Discussion: https://postgr.es/m/CAKFQuwamFuaQHKdhcMt4Gbw5+Hca2UE741B8gOOXoA=TtAd2Yw@mail.gmail.com

3 years agoHave CLUSTER ignore partitions not owned by caller
Alvaro Herrera [Thu, 14 Apr 2022 20:11:06 +0000 (22:11 +0200)]
Have CLUSTER ignore partitions not owned by caller

If a partitioned table has partitions owned by roles other than the
owner of the partitioned table, don't include them in the to-be-
clustered list.  This is similar to what VACUUM FULL does (except we do
it sooner, because there is no reason to postpone it).  Add a simple
test to verify that only owned partitions are clustered.

While at it, change memory context switch-and-back to occur once per
partition instead of outside of the loop.

Author: Justin Pryzby <pryzby@telsasoft.com>
Reviewed-by: Zhihong Yu <zyu@yugabyte.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/20220411140609.GF26620@telsasoft.com

3 years agoReword text on ROW SHARE lock as acquired by SELECT FOR <lock>
Alvaro Herrera [Thu, 14 Apr 2022 19:52:20 +0000 (21:52 +0200)]
Reword text on ROW SHARE lock as acquired by SELECT FOR <lock>

It was missing lock levels FOR KEY SHARE and FOR NO KEY EXCLUSIVE; but
also SELECT FOR UPDATE is not a command separate from SELECT, as the
original text implied.  It is clearer to state that FOR <lock strength>
is an option of regular SELECT.

Per suggestion from Joey Bodoia <jbodoia21@cmc.edu>

Reviewed-by: Joey Bodoia <jbodoia21@cmc.edu> (offlist)
Reviewed-by: Erikjan Rijkers <er@xs4all.nl>
Discussion: https://postgr.es/m/164908765512.682.17348032020747341013@wrigleys.postgresql.org

3 years agoTemporarily add some probes of tenk1's relallvisible in create_index.sql.
Tom Lane [Thu, 14 Apr 2022 16:14:01 +0000 (12:14 -0400)]
Temporarily add some probes of tenk1's relallvisible in create_index.sql.

This is to gather some more evidence about why buildfarm member wrasse
is failing.  We should revert it (or at least scale it way back) once
that's resolved.

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

3 years agoImprove a couple of sql/json error messages
Andrew Dunstan [Thu, 14 Apr 2022 14:26:29 +0000 (10:26 -0400)]
Improve a couple of sql/json error messages

Fix the grammar in two, and add a hint to one.

3 years agoFix transformJsonBehavior
Andrew Dunstan [Thu, 14 Apr 2022 12:57:09 +0000 (08:57 -0400)]
Fix transformJsonBehavior

Commit 1a36bc9dba8 conained some logic that was a little opaque and
could have involved a NULL dereference, as complained about by Coverity.
Make the logic more transparent and in doing so avoid the NULL
dereference.

3 years agopageinspect: Fix handling of all-zero pages
Michael Paquier [Thu, 14 Apr 2022 06:08:03 +0000 (15:08 +0900)]
pageinspect: Fix handling of all-zero pages

Getting from get_raw_page() an all-zero page is considered as a valid
case by the buffer manager and it can happen for example when finding a
corrupted page with zero_damaged_pages enabled (using zero_damaged_pages
to look at corrupted pages happens), or after a crash when a relation
file is extended before any WAL for its new data is generated (before a
vacuum or autovacuum job comes in to do some cleanup).

However, all the functions of pageinspect, as of the index AMs (except
hash that has its own idea of new pages), heap, the FSM or the page
header have never worked with all-zero pages, causing various crashes
when going through the page internals.

This commit changes all the pageinspect functions to be compliant with
all-zero pages, where the choice is made to return NULL or no rows for
SRFs when finding a new page.  get_raw_page() still works the same way,
returning a batch of zeros in the bytea of the page retrieved.  A hard
error could be used but NULL, while more invasive, is useful when
scanning relation files in full to get a batch of results for a single
relation in one query.  Tests are added for all the code paths
impacted.

Reported-by: Daria Lepikhova
Author: Michael Paquier
Discussion: https://postgr.es/m/561e187b-3549-c8d5-03f5-525c14e65bd0@postgrespro.ru
Backpatch-through: 10

3 years agoAdd missing spaces after single-line comments
David Rowley [Wed, 13 Apr 2022 21:28:56 +0000 (09:28 +1200)]
Add missing spaces after single-line comments

Only 1 of 3 of these changes appear to be handled by pgindent. That change
is new to v15.  The remaining two appear to be left alone by pgindent. The
exact reason for that is not 100% clear to me.  It seems related to the
fact that it's a line that contains *only* a single line comment and no
actual code.  It does not seem worth investigating this in too much
detail.  In any case, these do not conform to our usual practices, so fix
them.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoDocs: fix some spelling mistakes and also do some wordsmithing
David Rowley [Wed, 13 Apr 2022 21:16:05 +0000 (09:16 +1200)]
Docs: fix some spelling mistakes and also do some wordsmithing

All except one of these are new to v15.  Only one of the wordsmithing
changes appears in older versions. The wordsmithing improvement does not
seem significant enough to warrant backpatching.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoFix case sensitivity in psql's tab completion for GUC names.
Tom Lane [Wed, 13 Apr 2022 20:26:34 +0000 (16:26 -0400)]
Fix case sensitivity in psql's tab completion for GUC names.

Input for these should be case-insensitive, but was not completely
so.  Comparing to the similar queries for timezone names, I realized
that we'd missed forcing the comparison pattern to lower-case.
With that, it behaves as I expect.

While here, flatten the sub-selects in these queries; I don't
find that those add any readability.

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

3 years agoFurther tweak the default behavior of psql's \dconfig.
Tom Lane [Wed, 13 Apr 2022 19:03:58 +0000 (15:03 -0400)]
Further tweak the default behavior of psql's \dconfig.

Define "parameters with non-default settings" as being those that
not only have pg_settings.source different from 'default', but
also have a current value different from the hard-wired boot_val.
Adding the latter restriction removes a number of not-very-interesting
cases where the active setting is chosen by initdb but in practice
tends to be the same all the time.

Per discussion with Jonathan Katz.

Discussion: https://postgr.es/m/YlFQLzlPi4QD0wSi@msg.df7cb.de

3 years agoPrevent access to no-longer-pinned buffer in heapam_tuple_lock().
Tom Lane [Wed, 13 Apr 2022 17:35:02 +0000 (13:35 -0400)]
Prevent access to no-longer-pinned buffer in heapam_tuple_lock().

heap_fetch() used to have a "keep_buf" parameter that told it to return
ownership of the buffer pin to the caller after finding that the
requested tuple TID exists but is invisible to the specified snapshot.
This was thoughtlessly removed in commit 5db6df0c0, which broke
heapam_tuple_lock() (formerly EvalPlanQualFetch) because that function
needs to do more accesses to the tuple even if it's invisible.  The net
effect is that we would continue to touch the page for a microsecond or
two after releasing pin on the buffer.  Usually no harm would result;
but if a different session decided to defragment the page concurrently,
we could see garbage data and mistakenly conclude that there's no newer
tuple version to chain up to.  (It's hard to say whether this has
happened in the field.  The bug was actually found thanks to a later
change that allowed valgrind to detect accesses to non-pinned buffers.)

The most reasonable way to fix this is to reintroduce keep_buf,
although I made it behave slightly differently: buffer ownership
is passed back only if there is a valid tuple at the requested TID.
In HEAD, we can just add the parameter back to heap_fetch().
To avoid an API break in the back branches, introduce an additional
function heap_fetch_extended() in those branches.

In HEAD there is an additional, less obvious API change: tuple->t_data
will be set to NULL in all cases where buffer ownership is not returned,
in particular when the tuple exists but fails the time qual (and
!keep_buf).  This is to defend against any other callers attempting to
access non-pinned buffers.  We concluded that making that change in back
branches would be more likely to introduce problems than cure any.

In passing, remove a comment about heap_fetch that was obsoleted by
9a8ee1dc6.

Per bug #17462 from Daniil Anisimov.  Back-patch to v12 where the bug
was introduced.

Discussion: https://postgr.es/m/17462-9c98a0f00df9bd36@postgresql.org

3 years agoRemove extraneous blank lines before block-closing braces
Alvaro Herrera [Wed, 13 Apr 2022 17:14:20 +0000 (19:14 +0200)]
Remove extraneous blank lines before block-closing braces

These are useless and distracting.  We wouldn't have written the code
with them to begin with, so there's no reason to keep them.

Author: Justin Pryzby <pryzby@telsasoft.com>
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com
Discussion: https://postgr.es/m/attachment/133167/0016-Extraneous-blank-lines.patch

3 years agoRelease cache tuple when no longer needed
Alvaro Herrera [Wed, 13 Apr 2022 16:19:38 +0000 (18:19 +0200)]
Release cache tuple when no longer needed

There was a small buglet in commit 52e4f0cd472d whereby a tuple acquired
from cache was not released, giving rise to WARNING messages; fix that.

While at it, restructure the code a bit on stylistic grounds.

Author: Hou zj <houzj.fnst@fujitsu.com>
Reported-by: Peter Smith <smithpb2250@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAHut+PvKTyhTBtYCQsP6Ph7=o-oWRSX+v+PXXLXp81-o2bazig@mail.gmail.com

3 years agoFix finalization for json_objectagg and friends
Andrew Dunstan [Wed, 13 Apr 2022 14:26:38 +0000 (10:26 -0400)]
Fix finalization for json_objectagg and friends

Commit f4fb45d15c misguidedly tried to free some state during aggregate
finalization for json_objectagg. This resulted in attempts to access
freed memory, especially when the function is used as a window function.
Commit 4eb9798879 attempted to ameliorate that, but in fact it should
just be ripped out, which is done here. Also add some regression tests
for json_objectagg in various flavors as a window function.

Original report from Jaime Casanova, diagnosis by Andres Freund.

Discussion: https://postgr.es/m/YkfeMNYRCGhySKyg@ahch-to

3 years agoFix incorrect format placeholders
Peter Eisentraut [Wed, 13 Apr 2022 12:04:51 +0000 (14:04 +0200)]
Fix incorrect format placeholders

3 years agoDocs: wording improvement for compute_query_id = regress
David Rowley [Wed, 13 Apr 2022 09:28:25 +0000 (21:28 +1200)]
Docs: wording improvement for compute_query_id = regress

It's more accurate to say that the query identifier is not shown when
compute_query_id = regress rather than to say it is hidden.

This change (ebf6c5249) appeared in v14, so it makes sense to backpatch
this small adjustment to keep the documents consistent between v14 and
master.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com
Backpatch-through: 14, where compute_query_id = regress was added

3 years agoRemove "recheck" argument from check_index_is_clusterable()
Michael Paquier [Wed, 13 Apr 2022 06:32:35 +0000 (15:32 +0900)]
Remove "recheck" argument from check_index_is_clusterable()

The last usage of this argument in this routine can be tracked down to
7e2f9062, aka 11 years ago.  Getting rid of this argument can also be an
advantage for extensions calling check_index_is_clusterable(), as it
removes any need to worry about the meaning of what a recheck would be
at this level.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411140609.GF26620@telsasoft.com

3 years agoDocs: tidy up various usages of the productname tag
David Rowley [Wed, 13 Apr 2022 05:42:13 +0000 (17:42 +1200)]
Docs: tidy up various usages of the productname tag

This tries to bring a bit more consistency to the use of the <productname>
tag in the documents.  This fixes a couple of mistakes with our own
product.  We definitely should be consistently calling that PostgreSQL
when we're referring to the modern-day version of the software.

This also tidies up a couple of inconsistencies with the case of other
product names, namely Emacs and Python.  We also get rid of some incorrect
usages of <productname> and replace them with <literal>.

Many of these mistakes exist in the back branches, but they don't quite
seem critical enough to warrant fixing them in prior versions at this
stage.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoRework compression options of pg_receivewal
Michael Paquier [Wed, 13 Apr 2022 02:09:51 +0000 (11:09 +0900)]
Rework compression options of pg_receivewal

Since babbbb5 and the introduction of LZ4 in pg_receivewal, the
compression of the WAL archived is controlled by two options:
- --compression-method with "gzip", "none" or "lz4" as possible value.
- --compress=N to specify a compression level.  This includes a
backward-incompatible change where a value of 0 leads to a failure
instead of no compression enforced.

This commit takes advantage of a4b5754 and 3603f7c to rework the
compression options of pg_receivewal, as of:
- The removal of --compression-method.
- The extenction of --compress to use the same grammar as pg_basebackup,
with a METHOD:DETAIL format, where a METHOD is "gzip", "none" or "lz4"
and a DETAIL is a comma-separated list of options, the only keyword
supported is now "level" to control the compression level.  If only an
integer is specified as value of this option, "none" is implied on 0
and "gzip" is implied otherwise.  This brings back --compress to be
backward-compatible with ~14, while still supporting LZ4.

This has also the advantage of centralizing the set of checks used by
pg_receivewal to validate its compression options.

Author: Michael Paquier
Reviewed-by: Robert Haas, Georgios Kokolatos
Discussion: https://postgr.es/m/YlPQGNAAa04raObK@paquier.xyz

3 years agoDocs: adjust wording about basebackup_to_shell's required_role GUC
David Rowley [Wed, 13 Apr 2022 00:01:23 +0000 (12:01 +1200)]
Docs: adjust wording about basebackup_to_shell's required_role GUC

Author: Justin Pryzby
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoDocs: adjust pg_upgrade syntax to mark -B as optional
David Rowley [Tue, 12 Apr 2022 23:18:54 +0000 (11:18 +1200)]
Docs: adjust pg_upgrade syntax to mark -B as optional

This was made optional in 959f6d6a1.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com
Backpatch-through: 13, where -B was made optional

3 years agoDoc: tweak textsearch.sgml for SEO purposes.
Tom Lane [Tue, 12 Apr 2022 22:21:04 +0000 (18:21 -0400)]
Doc: tweak textsearch.sgml for SEO purposes.

Google seems to like to return textsearch.html for queries about
GIN and GiST indexes, even though it's not a primary reference
for either.  It seems likely that that's because those keywords
appear in the page title.  Since "GIN and GiST Index Types" is
not a very apposite title for this material anyway, rename the
section in hopes of stopping that.

Also provide explicit links to the GIN and GiST chapters, to help
anyone who finds their way to this page regardless.

Per gripe from Jan Piotrowski.  Back-patch to supported branches.
(Unfortunately Google is likely to continue returning the 9.1
version of this page, but improving that situation is a matter
for the www team.)

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

3 years agoDocs: avoid confusing use of the word "synchronized"
David Rowley [Tue, 12 Apr 2022 21:15:02 +0000 (09:15 +1200)]
Docs: avoid confusing use of the word "synchronized"

It's misleading to call the data directory the "synchronized data
directory" when discussing a crash scenario when using pg_rewind's
--no-sync option.  Here we just remove the word "synchronized" to avoid
any possible confusion.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com
Backpatch-through: 12, where --no-sync was added

3 years agoRevert the addition of GetMaxBackends() and related stuff.
Robert Haas [Tue, 12 Apr 2022 18:45:23 +0000 (14:45 -0400)]
Revert the addition of GetMaxBackends() and related stuff.

This reverts commits 0147fc74567596aa64f23, and 5ecd018.
There is no longer agreement that introducing this function
was the right way to address the problem. The consensus now
seems to favor trying to make a correct value for MaxBackends
available to mdules executing their _PG_init() functions.

Nathan Bossart

Discussion: http://postgr.es/m/20220323045229.i23skfscdbvrsuxa@jrouhaud

3 years agoRemove not-very-useful early checks of __pg_log_level in logging.h.
Tom Lane [Tue, 12 Apr 2022 17:25:29 +0000 (13:25 -0400)]
Remove not-very-useful early checks of __pg_log_level in logging.h.

Enforce __pg_log_level message filtering centrally in logging.c,
instead of relying on the calling macros to do it.  This is more
reliable (e.g. it works correctly for direct calls to pg_log_generic)
and it saves a percent or so of total code size because we get rid of
so many duplicate checks of __pg_log_level.

This does mean that argument expressions in a logging macro will be
evaluated even if we end up not printing anything.  That seems of
little concern for INFO and higher levels as those messages are printed
by default, and most of our frontend programs don't even offer a way to
turn them off.  I left the unlikely() checks in place for DEBUG
messages, though.

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

3 years agoDoc: update description of random() function.
Tom Lane [Tue, 12 Apr 2022 15:36:45 +0000 (11:36 -0400)]
Doc: update description of random() function.

Commit 3804539e4 neglected to update the documentation's claim that
random() uses a "linear congruential algorithm".  In hopes of avoiding
the same mistake if someone replaces our PRNG again, just say it's a
deterministic pseudo-random number generator and leave it at that.
Anybody who really wants to know can look in the source code.

COMPATIBILITY NOTE FOR RELEASE NOTES: 3804539e4's commit message
really should have mentioned that the random() sequence after
setseed(), while still repeatable, will differ from what you got
in pre-v15 releases.

Noted by Dagfinn Ilmari Mannsåker; wording suggestion by Dean Rasheed.

Discussion: https://postgr.es/m/875ynfpiru.fsf@wibble.ilmari.org

3 years agoUse WRITE_ENUM_FIELD for enum field
Peter Eisentraut [Tue, 12 Apr 2022 14:19:00 +0000 (16:19 +0200)]
Use WRITE_ENUM_FIELD for enum field

3 years agoMake node output prefix match node structure name
Peter Eisentraut [Tue, 12 Apr 2022 14:18:01 +0000 (16:18 +0200)]
Make node output prefix match node structure name

as done in e58136069687b9cf29c27281e227ac397d72141d

3 years agoadjust_partition_colnos mustn't be called if not needed
Alvaro Herrera [Tue, 12 Apr 2022 13:19:57 +0000 (15:19 +0200)]
adjust_partition_colnos mustn't be called if not needed

Add an assert to make this very explicit, as well as a code comment.
The former should silence Coverity complaining about this.

Introduced by 7103ebb7aae8.

Reported-by: Ranier Vilela
Discussion: https://postgr.es/m/CAEudQAqTTAOzXiYybab+1DQOb3ZUuK99=p_KD+yrRFhcDbd0jg@mail.gmail.com

3 years agoFix documentation for pg_stat_recovery_prefetch.
Thomas Munro [Tue, 12 Apr 2022 09:19:47 +0000 (21:19 +1200)]
Fix documentation for pg_stat_recovery_prefetch.

The table was in the wrong section and using an older type of link, as
reported by Sirisha, and also using an older table layout, as I noticed
while trying to figure out how and when it might have got out of sync.

Defect in commit 5dc0418f.

Author: sirisha chamarthi <sirichamarthi22@gmail.com>
Author: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CAKrAKeVk-LRHMdyT6x_p33eF6dCorM2jed5h_eHdRdv0reSYTA@mail.gmail.com

3 years agoFix grammatical errors and typos in logical replication docs.
Amit Kapila [Tue, 12 Apr 2022 08:44:32 +0000 (14:14 +0530)]
Fix grammatical errors and typos in logical replication docs.

Author: Justin Pryzby
Reviewed By: Masahiko Sawada
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoRemove WalCompressionMethod in favor of pg_compress_algorithm
Michael Paquier [Tue, 12 Apr 2022 08:28:17 +0000 (17:28 +0900)]
Remove WalCompressionMethod in favor of pg_compress_algorithm

The same structure, with the same set of elements (for none, lz4, gzip
and zstd), exists in compression.h, so let's make use of the centralized
version instead of duplicating things.  Some of the variables used
previously for WalCompressionMethod are renamed to stick better with the
new structure and routine names.

WalCompressionMethod was leading to some confusion in walmethods.c, as
it was sometimes used to refer to some data unrelated to WAL.

Reported-by: Robert Haas
Author: Michael Paquier
Reviewed-by: Robert Haas, Georgios Kokolatos
Discussion: https://postgr.es/m/YlPQGNAAa04raObK@paquier.xyz

3 years agoChange mechanism to set up source targetlist in MERGE
Alvaro Herrera [Tue, 12 Apr 2022 07:29:39 +0000 (09:29 +0200)]
Change mechanism to set up source targetlist in MERGE

We were setting MERGE source subplan's targetlist by expanding the
individual attributes of the source relation completely, early in the
parse analysis phase.  This failed to work when the condition of an
action included a whole-row reference, causing setrefs.c to error out
with
  ERROR:  variable not found in subplan target lists
because at that point there is nothing to resolve the whole-row
reference with.  We can fix this by having preprocess_targetlist expand
the source targetlist for Vars required from the source rel by all
actions.  Moreover, by using this expansion mechanism we can do away
with the targetlist expansion in transformMergeStmt, which is good
because then we no longer pull in columns that aren't needed for
anything.

Add a test case for the problem.

While at it, remove some redundant code in preprocess_targetlist():
MERGE was doing separately what is already being done for UPDATE/DELETE,
so we can just rely on the latter and remove the former.  (The handling
of inherited rels was different for MERGE, but that was a no-longer-
necessary hack.)

Fix outdated, related comments for fix_join_expr also.

Author: Richard Guo <guofenglinux@gmail.com>
Author: Álvaro Herrera <alvherre@alvh.no-ip.org>
Reported-by: Joe Wildish <joe@lateraljoin.com>
Discussion: https://postgr.es/m/fab3b90a-914d-46a9-beb0-df011ee39ee5@www.fastmail.com

3 years agoRename backup_compression.{c,h} to compression.{c,h}
Michael Paquier [Tue, 12 Apr 2022 04:38:54 +0000 (13:38 +0900)]
Rename backup_compression.{c,h} to compression.{c,h}

Compression option handling (level, algorithm or even workers) can be
used across several parts of the system and not only base backups.
Structures, objects and routines are renamed in consequence, to remove
the concept of base backups from this part of the code making this
change straight-forward.

pg_receivewal, that has gained support for LZ4 since babbbb5, will make
use of this infrastructure for its set of compression options, bringing
more consistency with pg_basebackup.  This cleanup needs to be done
before releasing a beta of 15.  pg_dump is a potential future target, as
well, and adding more compression options to it may happen in 16~.

Author: Michael Paquier
Reviewed-by: Robert Haas, Georgios Kokolatos
Discussion: https://postgr.es/m/YlPQGNAAa04raObK@paquier.xyz

3 years agoMake XLogRecGetBlockTag() throw error if there's no such block.
Tom Lane [Mon, 11 Apr 2022 21:43:46 +0000 (17:43 -0400)]
Make XLogRecGetBlockTag() throw error if there's no such block.

All but a few existing callers assume without checking that this
function succeeds.  While it probably will, that's a poor excuse for
not checking.  Let's make it return void and instead throw an error
if it doesn't find the block reference.  Callers that actually need
to handle the no-such-block case must now use the underlying function
XLogRecGetBlockTagExtended.

In addition to being a bit less error-prone, this should also serve
to suppress some Coverity complaints about XLogRecGetBlockRefInfo.

While at it, clean up some inconsistency about use of the
XLogRecHasBlockRef macro: make XLogRecGetBlockTagExtended use
that instead of open-coding the same condition, and avoid calling
XLogRecHasBlockRef twice in relevant code paths.  (That is,
calling XLogRecHasBlockRef followed by XLogRecGetBlockTag is now
deprecated: use XLogRecGetBlockTagExtended instead.)

Patch HEAD only; this doesn't seem to have enough value to consider
a back-branch API break.

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

3 years agoRemove comment about historic heap vacuuming issue.
Peter Geoghegan [Mon, 11 Apr 2022 21:20:46 +0000 (14:20 -0700)]
Remove comment about historic heap vacuuming issue.

Remove comment block about how heap page vacuuming used to set tuples
with storage to LP_UNUSED in a rare edge case that can no longer happen
following commit 8523492d4e.  The comments seem unnecessary now, since
it's now generally clear that heap vacuuming only applies to LP_DEAD
items from VACUUM's first heap pass following more recent work from
commits 12b5ade902 and 4f8d9d1217.

3 years agoRemove dead code in do_pg_backup_start().
Tom Lane [Mon, 11 Apr 2022 19:56:01 +0000 (15:56 -0400)]
Remove dead code in do_pg_backup_start().

As of commit 39969e2a1, no caller of do_pg_backup_start() passes NULL
for labelfile or tblspcmapfile, nor is it plausible that any would
do so in the future.  Remove the code that coped with that case,
as (a) it's dead and (b) it causes Coverity to bleat about possibly
leaked storage.

While here, do some janitorial work on the function's header comment.

3 years agoTweak the default behavior of psql's \dconfig.
Tom Lane [Mon, 11 Apr 2022 19:11:46 +0000 (15:11 -0400)]
Tweak the default behavior of psql's \dconfig.

\dconfig without an argument originally printed all parameters,
but it seems more useful to print only those parameters with
non-default settings.  You can easily get the show-everything
behavior with "\dconfig *", but that output is unwieldy and
seems unlikely to be wanted very often.

Per suggestion from Christoph Berg.

Discussion: https://postgr.es/m/YlFQLzlPi4QD0wSi@msg.df7cb.de

3 years agoExplicitly ignore guaranteed-true result from pgstat_lock_entry().
Tom Lane [Mon, 11 Apr 2022 17:22:37 +0000 (13:22 -0400)]
Explicitly ignore guaranteed-true result from pgstat_lock_entry().

With nowait passed as false, pgstat_lock_entry() must return true
so there's no need to check its result.  Coverity seems unconvinced
of this, so whack it upside the head with a (void) cast.

3 years agofgetc() returns int, not char.
Tom Lane [Mon, 11 Apr 2022 17:15:46 +0000 (13:15 -0400)]
fgetc() returns int, not char.

This has no practical effect, since this code doesn't actually need to
distinguish EOF (-1) from \0377; but it silences a Coverity complaint.

3 years agoDoc build fix: remove tab from filelist.sgml.
Jeff Davis [Mon, 11 Apr 2022 15:41:28 +0000 (08:41 -0700)]
Doc build fix: remove tab from filelist.sgml.

Author: Amit Kapila
Discussion: https://postgr.es/m/CAA4eK1K6z=gu-jppU1dtsyr2BC-pzrq3TYe=RfY+w386dfdiFA@mail.gmail.com

3 years agoImprove readability of SQL/JSON documentation.
Andrew Dunstan [Mon, 11 Apr 2022 15:48:40 +0000 (11:48 -0400)]
Improve readability of SQL/JSON documentation.

Per review from Justin Pryzby.

Discussion: https://postgr.es/m/f50aca87-6b35-a1b0-2286-f815a589dd83@dunslane.net

3 years agoAdd color support for new frontend detail/hint messages
Peter Eisentraut [Mon, 11 Apr 2022 15:36:44 +0000 (17:36 +0200)]
Add color support for new frontend detail/hint messages

As before, the defaults are similar to gcc's default appearance.

3 years agoAvoid re-writing files unnecessarily in src/tools/copyright.pl.
Tom Lane [Mon, 11 Apr 2022 15:20:13 +0000 (11:20 -0400)]
Avoid re-writing files unnecessarily in src/tools/copyright.pl.

The existing coding resulted in touching every copyright-containing
file in the tree, even if it was already up to date.  That doesn't
matter much for the annual run, but it's an annoyance if you try
to use the script for mop-up at the close of a devel cycle, as
I just did.

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

3 years agodocs: Note the recovery_min_apply_delay bloats pg_wal.
Robert Haas [Fri, 8 Apr 2022 15:02:59 +0000 (11:02 -0400)]
docs: Note the recovery_min_apply_delay bloats pg_wal.

Those WAL files that we're waiting to apply have to be stored
somewhere.

Thom Brown

Discussion: http://postgr.es/m/CAA-aLv4SkJRK6GGcd0Axt8kt6_eWMEbtG7f8NJpFh+rNshtdNA@mail.gmail.com

3 years agoDocs: Mention that relpersistence is for sequences now too
David Rowley [Mon, 11 Apr 2022 08:50:20 +0000 (20:50 +1200)]
Docs: Mention that relpersistence is for sequences now too

Per 344d62fb9.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoFix various typos and spelling mistakes in code comments
David Rowley [Mon, 11 Apr 2022 08:49:41 +0000 (20:49 +1200)]
Fix various typos and spelling mistakes in code comments

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoDocs: Fix various mistakes and typos
David Rowley [Mon, 11 Apr 2022 08:48:48 +0000 (20:48 +1200)]
Docs: Fix various mistakes and typos

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220411020336.GB26620@telsasoft.com

3 years agoFix the dates of some copyright notices
Michael Paquier [Mon, 11 Apr 2022 07:36:25 +0000 (16:36 +0900)]
Fix the dates of some copyright notices

0ad8032 and 4e34747 are at the origin of that.  Julien has found the one
in parse_jsontable.c, while I have spotted the rest.

Author: Julien Rouhaud, Michael Paquier
Discussion: https://postgr.es/m/20220411060838.ftnzyvflpwu6f74w@jrouhaud

3 years agoPut new command-line options into alphabetical order in help output
Peter Eisentraut [Mon, 11 Apr 2022 05:39:25 +0000 (07:39 +0200)]
Put new command-line options into alphabetical order in help output

3 years agodoc: Clarify behavior of query planner locking with REINDEX
Michael Paquier [Mon, 11 Apr 2022 00:49:13 +0000 (09:49 +0900)]
doc: Clarify behavior of query planner locking with REINDEX

The documentation of REINDEX has never mentioned that the query planner
may take an ACCESS SHARE lock on the indexes depending on the query
used.  This adds also a note about prepared queries not impacted when
they do not use the index(es) rebuilt.

Author: Frédéric Yhuel
Reviewed-by: Guillaume Lelarge, Justin Pryzby
Discussion: https://postgr.es/m/65d08718-6f11-978a-4b5a-72b807d4c663@dalibo.com

3 years agoDoc: fix typos in documentation
Daniel Gustafsson [Sun, 10 Apr 2022 19:42:43 +0000 (21:42 +0200)]
Doc: fix typos in documentation

Commits 39969e2a1e4 and 5c279a6d350 accidentally included a typo each
in the user facing documentation.

3 years agoDoc: reformat descriptions of pgbench output formats.
Tom Lane [Sun, 10 Apr 2022 19:31:42 +0000 (15:31 -0400)]
Doc: reformat descriptions of pgbench output formats.

This is mostly driven by trying to get rid of line-too-wide
warnings in PDF output; but I think converting to a <variablelist>
makes it more readable anyway.

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

3 years agoFix pgperlsyncheck following SSL TAP test refactoring
Andrew Dunstan [Sun, 10 Apr 2022 13:04:24 +0000 (09:04 -0400)]
Fix pgperlsyncheck following SSL TAP test refactoring

Commit 4a7e964fc6 made pgperlsyncheck fail, but apparently nobody
noticed, although the buildfarm module that does more or less the same
thing was modified. So fix the in-core test. I will look at unifying the
two sets of tests so we avoid a future mismatch.

3 years agoAdd timestamp and elapsed time decorations to TAP test logs
Andrew Dunstan [Sun, 10 Apr 2022 12:46:12 +0000 (08:46 -0400)]
Add timestamp and elapsed time decorations to TAP test logs

These apply to traces from Test::More functions such as ok(), is(),
diag() and note(). Output from other sources (e.g. external programs
such a initdb) is not affected. The elapsed time is the time since the
last such trace (or the beginning of the test in the first case). Times
and timestamps are at millisecond precision.

Discussion: https://postgr.es/m/20220401172150.rsycz4lrn7ewruil@alap3.anarazel.de

3 years agoDoc: shorten JSON_SERIALIZE example to avoid a PDF build warning.
Tom Lane [Sat, 9 Apr 2022 19:09:38 +0000 (15:09 -0400)]
Doc: shorten JSON_SERIALIZE example to avoid a PDF build warning.

There's no particular reason why this example has to use a
3-element array rather than 2-element.  Shortening it makes
the result bytea narrow enough to not cause a margin overrun
in A4 format.

3 years agoFix whitespace
Peter Eisentraut [Sat, 9 Apr 2022 14:17:41 +0000 (16:17 +0200)]
Fix whitespace

3 years agoAdd missing serial commas
Peter Eisentraut [Sat, 9 Apr 2022 14:15:01 +0000 (16:15 +0200)]
Add missing serial commas

3 years agoAdd missing source files to nls.mk
Peter Eisentraut [Sat, 9 Apr 2022 13:46:37 +0000 (15:46 +0200)]
Add missing source files to nls.mk

3 years agoSilence compiler warnings for unsupported compression methods.
Tom Lane [Fri, 8 Apr 2022 22:14:24 +0000 (18:14 -0400)]
Silence compiler warnings for unsupported compression methods.

wrasse, at least, moans about the lack of any "return" statement
in these functions.  You'd think pretty much everything would
know that exit(1) doesn't return, but evidently not.

3 years agoImprove frontend error logging style.
Tom Lane [Fri, 8 Apr 2022 18:55:14 +0000 (14:55 -0400)]
Improve frontend error logging style.

Get rid of the separate "FATAL" log level, as it was applied
so inconsistently as to be meaningless.  This mostly involves
s/pg_log_fatal/pg_log_error/g.

Create a macro pg_fatal() to handle the common use-case of
pg_log_error() immediately followed by exit(1).  Various
modules had already invented either this or equivalent macros;
standardize on pg_fatal() and apply it where possible.

Invent the ability to add "detail" and "hint" messages to a
frontend message, much as we have long had in the backend.

Except where rewording was needed to convert existing coding
to detail/hint style, I have (mostly) resisted the temptation
to change existing message wording.

Patch by me.  Design and patch reviewed at various stages by
Robert Haas, Kyotaro Horiguchi, Peter Eisentraut and
Daniel Gustafsson.

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

3 years agoFix busted .gitignore entry.
Tom Lane [Fri, 8 Apr 2022 18:22:47 +0000 (14:22 -0400)]
Fix busted .gitignore entry.

Typo in commit 2258e76f9.

3 years agoRename delayChkpt to delayChkptFlags.
Robert Haas [Fri, 8 Apr 2022 15:44:17 +0000 (11:44 -0400)]
Rename delayChkpt to delayChkptFlags.

Before commit 412ad7a55639516f284cd0ef9757d6ae5c7abd43, delayChkpt
was a Boolean. Now it's an integer. Extensions using it need to be
appropriately updated, so let's rename the field to make sure that
a hard compilation failure occurs.

Replacing delayChkpt with delayChkptFlags made a few comments extend
past 80 characters, so I reflowed them and changed some wording very
slightly.

The back-branches will need a different change to restore compatibility
with existing minor releases; this is just for master.

Per suggestion from Tom Lane.

Discussion: http://postgr.es/m/a7880f4d-1d74-582a-ada7-dad168d046d1@enterprisedb.com

3 years agopsql: Fix translation marking
Peter Eisentraut [Fri, 8 Apr 2022 13:07:35 +0000 (15:07 +0200)]
psql: Fix translation marking

Commit 5a2832465fd8984d089e8c44c094e6900d987fcd added
addFooterToPublicationDesc() as a wrapper around
printTableAddFooter().  The translation marker _() was moved to the
body of addFooterToPublicationDesc(), but addFooterToPublicationDesc()
was not added to GETTEXT_TRIGGERS, so those strings were lost for
translation.  To fix, add the translation markers to the call sites of
addFooterToPublicationDesc() and remove the translation marker from
the body of the function.  This seems easiest since there were only
two callers and it keeps the API consistent with
printTableAddFooter().  While we're here, add some const decorations
to the prototype of addFooterToPublicationDesc() for consistency with
printTableAddFooter().

3 years agoApply PGDLLIMPORT markings broadly.
Robert Haas [Fri, 8 Apr 2022 12:16:38 +0000 (08:16 -0400)]
Apply PGDLLIMPORT markings broadly.

Up until now, we've had a policy of only marking certain variables
in the PostgreSQL header files with PGDLLIMPORT, but now we've
decided to mark them all. This means that extensions running on
Windows should no longer operate at a disadvantage as compared to
extensions running on Linux: if the variable is present in a header
file, it should be accessible.

Discussion: http://postgr.es/m/CA+TgmoYanc1_FSfimhgiWSqVyP5KKmh5NP2BWNwDhO8Pg2vGYQ@mail.gmail.com

3 years agoHelper script to apply PGDLLIMPORT markings.
Robert Haas [Fri, 8 Apr 2022 12:06:10 +0000 (08:06 -0400)]
Helper script to apply PGDLLIMPORT markings.

This script isn't terribly smart and won't necessarily catch every
case, but it catches many of them and is better than a totally
manual approach.

Patch by me, reviewed by Andrew Dunstan.

Discussion: http://postgr.es/m/CA+TgmoYanc1_FSfimhgiWSqVyP5KKmh5NP2BWNwDhO8Pg2vGYQ@mail.gmail.com

3 years agoAdd JIT counters to pg_stat_statements
Magnus Hagander [Fri, 8 Apr 2022 11:51:01 +0000 (13:51 +0200)]
Add JIT counters to pg_stat_statements

This adds cumulative counters for jit operations to pg_stat_statements,
making it easier to diagnose how JIT is used in an installation.

These changes merge into the 1.10 changes applied in 76cbf7edb6 without
creating a new version.

Reviewed-By: Julien Rouhaud
Discussion: https://www.postgresql.org/message-id/flat/CABUevEySt4NTYqvWzwyAW_0-jG1bjN-y+tykapAnA0FALOs+Lw@mail.gmail.com

3 years agoFix buildfarm failures in pg_walinspect tests.
Jeff Davis [Fri, 8 Apr 2022 10:21:12 +0000 (03:21 -0700)]
Fix buildfarm failures in pg_walinspect tests.

3 years agoCheck XLogRecHasBlockRef() before XLogRecHasBlockImage().
Jeff Davis [Fri, 8 Apr 2022 09:30:57 +0000 (02:30 -0700)]
Check XLogRecHasBlockRef() before XLogRecHasBlockImage().

Trial fix of buildfarm failures on kestrel and tamandua.

3 years agoFix buildfarm failure from commit 2258e76f90.
Jeff Davis [Fri, 8 Apr 2022 08:33:58 +0000 (01:33 -0700)]
Fix buildfarm failure from commit 2258e76f90.

3 years agoAdd contrib/pg_walinspect.
Jeff Davis [Fri, 8 Apr 2022 07:02:10 +0000 (00:02 -0700)]
Add contrib/pg_walinspect.

Provides similar functionality to pg_waldump, but from a SQL interface
rather than a separate utility.

Author: Bharath Rupireddy
Reviewed-by: Greg Stark, Kyotaro Horiguchi, Andres Freund, Ashutosh Sharma, Nitin Jadhav, RKN Sai Krishna
Discussion: https://postgr.es/m/CALj2ACUGUYXsEQdKhEdsBzhGEyF3xggvLdD8C0VT72TNEfOiog%40mail.gmail.com

3 years agoRemove error message hints mentioning configure options
Peter Eisentraut [Fri, 8 Apr 2022 05:41:09 +0000 (07:41 +0200)]
Remove error message hints mentioning configure options

These are usually not useful since users will use packaged
distributions and won't be interested in rebuilding their installation
from source.  Also, we have only used these kinds of hints for some
features and in some places, not consistently throughout.

Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/flat/2552aed7-d0e9-280a-54aa-2dc7073f371d%40enterprisedb.com

3 years agopgstat: Update docs to match the shared memory stats reality.
Andres Freund [Fri, 8 Apr 2022 04:35:35 +0000 (21:35 -0700)]
pgstat: Update docs to match the shared memory stats reality.

This includes removing documentation for stats_temp_directory, adding
documentation for stats_fetch_consistency, rephrasing references to the stats
collector and documenting that starting a cleanly shut down standby will not
remove stats anymore. The latter point might require further wordsmithing, it
wasn't easy to adjust some of the existing content.

Author: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Author: Andres Freund <andres@anarazel.de>
Reviewed-By: Thomas Munro <thomas.munro@gmail.com>
Reviewed-By: Justin Pryzby <pryzby@telsasoft.com>
Reviewed-By: "David G. Johnston" <david.g.johnston@gmail.com>
Reviewed-By: Lukas Fittl <lukas@fittl.com>
Discussion: https://postgr.es/m/20220303021600.hs34ghqcw6zcokdh@alap3.anarazel.de

3 years agopg_stat_statements: Track I/O timing for temporary file blocks
Michael Paquier [Fri, 8 Apr 2022 04:12:07 +0000 (13:12 +0900)]
pg_stat_statements: Track I/O timing for temporary file blocks

This commit adds two new columns to pg_stat_statements, called
temp_blk_read_time and temp_blk_write_time.  Those columns respectively
show the time spent to read and write temporary file blocks on disk,
whose tracking has been added in efb0ef9.  This information is
available when track_io_timing is enabled, like blk_read_time and
blk_write_time.

pg_stat_statements is updated to version to 1.10 as an effect of the
newly-added columns.  Tests for the upgrade path 1.9->1.10 are added.

PGSS_FILE_HEADER is bumped for the new stats file format.

Author: Masahiko Sawada
Reviewed-by: Georgios Kokolatos, Melanie Plageman, Julien Rouhaud,
Ranier Vilela
Discussion: https://postgr.es/m/CAD21AoAJgotTeP83p6HiAGDhs_9Fw9pZ2J=_tYTsiO5Ob-V5GQ@mail.gmail.com

3 years agoDocumentation for SQL/JSON features
Andrew Dunstan [Fri, 8 Apr 2022 03:36:50 +0000 (23:36 -0400)]
Documentation for SQL/JSON features

This documents the features added in commits f79b803dccf4fb45d15c,
33a377608f1a36bc9dba606948b05849082c2cc34e34747c88, and
fadb48b00e.

I have cleaned up the aggregate section of the submitted docs, but there
is still a deal of copy editing required. However, I thought it best to
have some documentation sooner rather than later so testers can have a
better idea what they are playing with.

Nikita Glukhov

Reviewers have included (in no particular order) Andres Freund, Alexander
Korotkov, Pavel Stehule, Andrew Alsup, Erik Rijkers, Zhihong Yu,
Himanshu Upadhyaya, Daniel Gustafsson, Justin Pryzby.

Discussion: https://postgr.es/m/cd0bb935-0158-78a7-08b5-904886deac4b@postgrespro.ru
Discussion: https://postgr.es/m/7e2cb85d-24cf-4abb-30a5-1a33715959bd@postgrespro.ru

3 years agoTrack I/O timing for temporary file blocks in EXPLAIN (BUFFERS)
Michael Paquier [Fri, 8 Apr 2022 02:27:21 +0000 (11:27 +0900)]
Track I/O timing for temporary file blocks in EXPLAIN (BUFFERS)

Previously, the output of EXPLAIN (BUFFERS) option showed only the I/O
timing spent reading and writing shared and local buffers.  This commit
adds on top of that the I/O timing for temporary buffers in the output
of EXPLAIN (for spilled external sorts, hashes, materialization. etc).
This can be helpful for users in cases where the I/O related to
temporary buffers is the bottleneck.

Like its cousin, this information is available only when track_io_timing
is enabled.  Playing the patch, this is showing an extra overhead of up
to 1% even when using gettimeofday() as implementation for interval
timings, which is slightly within the usual range noise still that's
measurable.

Author: Masahiko Sawada
Reviewed-by: Georgios Kokolatos, Melanie Plageman, Julien Rouhaud,
Ranier Vilela
Discussion: https://postgr.es/m/CAD21AoAJgotTeP83p6HiAGDhs_9Fw9pZ2J=_tYTsiO5Ob-V5GQ@mail.gmail.com

3 years agoFix recovery_prefetch docs.
Thomas Munro [Fri, 8 Apr 2022 01:28:04 +0000 (13:28 +1200)]
Fix recovery_prefetch docs.

Correct a typo and a couple of sentences that weren't updated to reflect
recent changes to the code.

Reported-by: Justin Pryzby <pryzby@telsasoft.com>
Discussion: https://postgr.es/m/20220407125555.GC24419%40telsasoft.com

3 years agopgstat: Hide instability in stats.spec with -DCATCACHE_FORCE_RELEASE.
Andres Freund [Fri, 8 Apr 2022 01:20:50 +0000 (18:20 -0700)]
pgstat: Hide instability in stats.spec with -DCATCACHE_FORCE_RELEASE.

With -DCATCACHE_FORCE_RELEASE a few tests failed. Those were trying to test
behavior in the absence of invalidation processing and
-DCATCACHE_FORCE_RELEASE obviously adds a lot of invalidation processing. The
test already tried to handle debug_discard_caches > 0, by disabling it for
individual tests.

Instead hide potentially problematic function calls in a wrapper function that
catches the does-not-exist error. The error isn't the actually interesting
bit, it's whether the stats entry still exist afterwards.

I confirmed that the tests still catches leaked function stats if I nuke the
protections against that in pgstat_function.c.

Per buildfarm animal prion.

Discussion: https://postgr.es/m/20220407165709.jgdkrzqlkcwue6ko@alap3.anarazel.de

3 years agopgstat: add/extend tests for resetting various kinds of stats.
Andres Freund [Thu, 7 Apr 2022 22:17:07 +0000 (15:17 -0700)]
pgstat: add/extend tests for resetting various kinds of stats.

- subscriber stats reset path was untested
- slot stat sreset path for all slots was untested
- pg_stat_database.sessions etc was untested
- pg_stat_reset_shared() was untested, for any kind of shared stats
- pg_stat_reset() was untested

Author: Melanie Plageman <melanieplageman@gmail.com>
Author: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220303021600.hs34ghqcw6zcokdh@alap3.anarazel.de

3 years agoTruncate line pointer array during heap pruning.
Peter Geoghegan [Thu, 7 Apr 2022 22:42:12 +0000 (15:42 -0700)]
Truncate line pointer array during heap pruning.

Reclaim space from the line pointer array when heap pruning leaves
behind a contiguous group of LP_UNUSED items at the end of the array.
This happens during subsequent page defragmentation.  Certain kinds of
heap line pointer bloat are ameliorated by this new optimization.

Follow-up work to commit 3c3b8a4b26, which taught VACUUM to truncate the
line pointer array in about the same way during VACUUM's second pass
over the heap.  We now apply line pointer array truncation during both
the first and the second pass over the heap made by VACUUM.  We can also
perform line pointer array truncation during opportunistic pruning.

Matthias van de Meent, with small tweaks by me.

Author: Matthias van de Meent <boekewurm+postgres@gmail.com>
Discussion: https://postgr.es/m/CAEze2WjgaQc55Y5f5CQd3L=eS5CZcff2Obxp=O6pto8-f0hC4w@mail.gmail.com
Discussion: https://postgr.es/m/CAEze2Wg36%2B4at2eWJNcYNiW2FJmht34x3YeX54ctUSs7kKoNcA%40mail.gmail.com

3 years agoTeach planner and executor about monotonic window funcs
David Rowley [Thu, 7 Apr 2022 22:34:36 +0000 (10:34 +1200)]
Teach planner and executor about monotonic window funcs

Window functions such as row_number() always return a value higher than
the previously returned value for tuples in any given window partition.

Traditionally queries such as;

SELECT * FROM (
   SELECT *, row_number() over (order by c) rn
   FROM t
) t WHERE rn <= 10;

were executed fairly inefficiently.  Neither the query planner nor the
executor knew that once rn made it to 11 that nothing further would match
the outer query's WHERE clause.  It would blindly continue until all
tuples were exhausted from the subquery.

Here we implement means to make the above execute more efficiently.

This is done by way of adding a pg_proc.prosupport function to various of
the built-in window functions and adding supporting code to allow the
support function to inform the planner if the window function is
monotonically increasing, monotonically decreasing, both or neither.  The
planner is then able to make use of that information and possibly allow
the executor to short-circuit execution by way of adding a "run condition"
to the WindowAgg to allow it to determine if some of its execution work
can be skipped.

This "run condition" is not like a normal filter.  These run conditions
are only built using quals comparing values to monotonic window functions.
For monotonic increasing functions, quals making use of the btree
operators for <, <= and = can be used (assuming the window function column
is on the left). You can see here that once such a condition becomes false
that a monotonic increasing function could never make it subsequently true
again.  For monotonically decreasing functions the >, >= and = btree
operators for the given type can be used for run conditions.

The best-case situation for this is when there is a single WindowAgg node
without a PARTITION BY clause.  Here when the run condition becomes false
the WindowAgg node can simply return NULL.  No more tuples will ever match
the run condition.  It's a little more complex when there is a PARTITION
BY clause.  In this case, we cannot return NULL as we must still process
other partitions.  To speed this case up we pull tuples from the outer
plan to check if they're from the same partition and simply discard them
if they are.  When we find a tuple belonging to another partition we start
processing as normal again until the run condition becomes false or we run
out of tuples to process.

When there are multiple WindowAgg nodes to evaluate then this complicates
the situation.  For intermediate WindowAggs we must ensure we always
return all tuples to the calling node.  Any filtering done could lead to
incorrect results in WindowAgg nodes above.  For all intermediate nodes,
we can still save some work when the run condition becomes false.  We've
no need to evaluate the WindowFuncs anymore.  Other WindowAgg nodes cannot
reference the value of these and these tuples will not appear in the final
result anyway.  The savings here are small in comparison to what can be
saved in the top-level WingowAgg, but still worthwhile.

Intermediate WindowAgg nodes never filter out tuples, but here we change
WindowAgg so that the top-level WindowAgg filters out tuples that don't
match the intermediate WindowAgg node's run condition.  Such filters
appear in the "Filter" clause in EXPLAIN for the top-level WindowAgg node.

Here we add prosupport functions to allow the above to work for;
row_number(), rank(), dense_rank(), count(*) and count(expr).  It appears
technically possible to do the same for min() and max(), however, it seems
unlikely to be useful enough, so that's not done here.

Bump catversion

Author: David Rowley
Reviewed-by: Andy Fan, Zhihong Yu
Discussion: https://postgr.es/m/CAApHDvqvp3At8++yF8ij06sdcoo1S_b2YoaT9D4Nf+MObzsrLQ@mail.gmail.com

3 years agoExtend plsample example to include a trigger handler.
Tom Lane [Thu, 7 Apr 2022 22:26:13 +0000 (18:26 -0400)]
Extend plsample example to include a trigger handler.

Mark Wong and Konstantina Skovola, reviewed by Chapman Flack

Discussion: https://postgr.es/m/Yd8Cz22eHi80XS30@workstation-mark-wong

3 years agoAdd minimal tests for recovery conflict handling.
Andres Freund [Thu, 7 Apr 2022 19:46:51 +0000 (12:46 -0700)]
Add minimal tests for recovery conflict handling.

Previously none of our tests triggered recovery conflicts. The test is
primarily motivated by needing tests for recovery conflict stats for shared
memory based pgstats. But it's also a decent start for recovery conflict
handling in general.

The only type of recovery conflict not tested yet are rcovery deadlock
conflicts.

By configuring log_recovery_conflict_waits the test adds some very minimal
testing for that path as well.

Author: Melanie Plageman <melanieplageman@gmail.com>
Author: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220303021600.hs34ghqcw6zcokdh@alap3.anarazel.de

3 years agopgstat: test stats interactions with physical replication.
Andres Freund [Mon, 21 Mar 2022 19:58:51 +0000 (12:58 -0700)]
pgstat: test stats interactions with physical replication.

Tests that standbys:
- drop stats for objects when the those records are replayed
- persist stats across graceful restarts
- discard stats after immediate / crash restarts

Author: Melanie Plageman <melanieplageman@gmail.com>
Author: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220303021600.hs34ghqcw6zcokdh@alap3.anarazel.de

3 years agoRevert "Rewrite some RI code to avoid using SPI"
Alvaro Herrera [Thu, 7 Apr 2022 21:42:13 +0000 (23:42 +0200)]
Revert "Rewrite some RI code to avoid using SPI"

This reverts commit 99392cdd78b788295e52b9f4942fa11992fd5ba9.
We'd rather rewrite ri_triggers.c as a whole rather than piecemeal.

Discussion: https://postgr.es/m/E1ncXX2-000mFt-Pe@gemulon.postgresql.org

3 years agopsql: add \dconfig command to show server's configuration parameters.
Tom Lane [Thu, 7 Apr 2022 21:09:44 +0000 (17:09 -0400)]
psql: add \dconfig command to show server's configuration parameters.

Plain \dconfig is basically equivalent to SHOW except that you can
give it a pattern with wildcards, either to match multiple GUCs or
because you don't exactly remember the name you want.

\dconfig+ adds type, context, and access-privilege information,
mainly because every other kind of object privilege has a psql command
to show it, so GUC privileges should too.  (A form of this command was
in some versions of the patch series leading up to commit a0ffa885e.
We pulled it out then because of doubts that the design and code were
up to snuff, but I think subsequent work has resolved that.)

In passing, fix incorrect completion of GUC names in GRANT/REVOKE
ON PARAMETER: a0ffa885e neglected to use the VERBATIM form of
COMPLETE_WITH_QUERY, so it misbehaved for custom (qualified) GUC
names.

Mark Dilger and Tom Lane

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

3 years agopgstat: add tests for handling of restarts, including crashes.
Andres Freund [Thu, 7 Apr 2022 19:07:50 +0000 (12:07 -0700)]
pgstat: add tests for handling of restarts, including crashes.

Test that stats are restored during normal restarts, discarded after a crash /
immediate restart, and that a corrupted stats file leads to stats being reset.

Author: Melanie Plageman <melanieplageman@gmail.com>
Author: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220303021600.hs34ghqcw6zcokdh@alap3.anarazel.de

3 years agoRewrite some RI code to avoid using SPI
Alvaro Herrera [Thu, 7 Apr 2022 19:04:36 +0000 (21:04 +0200)]
Rewrite some RI code to avoid using SPI

Modify the subroutines called by RI trigger functions that want to check
if a given referenced value exists in the referenced relation to simply
scan the foreign key constraint's unique index, instead of using SPI to
execute
  SELECT 1 FROM referenced_relation WHERE ref_key = $1
This saves a lot of work, especially when inserting into or updating a
referencing relation.

This rewrite allows to fix a PK row visibility bug caused by a partition
descriptor hack which requires ActiveSnapshot to be set to come up with
the correct set of partitions for the RI query running under REPEATABLE
READ isolation.  We now set that snapshot indepedently of the snapshot
to be used by the PK index scan, so the two no longer interfere.  The
buggy output in src/test/isolation/expected/fk-snapshot.out of the
relevant test case added by commit 00cb86e75d6d has been corrected.
(The bug still exists in branch 14, however, but this fix is too
invasive to backpatch.)

Author: Amit Langote <amitlangote09@gmail.com>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Corey Huinker <corey.huinker@gmail.com>
Reviewed-by: Li Japin <japinli@hotmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Zhihong Yu <zyu@yugabyte.com>
Discussion: https://postgr.es/m/CA+HiwqGkfJfYdeq5vHPh6eqPKjSbfpDDY+j-kXYFePQedtSLeg@mail.gmail.com

3 years agoFix test instability introduced in e349c95d3e9 due to async deduplication.
Andres Freund [Thu, 7 Apr 2022 18:54:51 +0000 (11:54 -0700)]
Fix test instability introduced in e349c95d3e9 due to async deduplication.

The statement emitting notifies tried to make sure page boundaries were
crossed, but failed to do so reliably due to deduplication.

Reported-By: chap@anastigmatix.net
Discussion: https://postgr.es/m/20220407185408.n7dvsgqsb3q6uze7@alap3.anarazel.de

3 years agoAdd isolation tests for snapshot behavior in ri_triggers.c
Alvaro Herrera [Thu, 7 Apr 2022 17:57:29 +0000 (19:57 +0200)]
Add isolation tests for snapshot behavior in ri_triggers.c

They are to check the behavior of RI_FKey_check() and
ri_Check_Pk_Match().  A test case whereby RI_FKey_check() queries a
partitioned PK table under REPEATABLE READ isolation produces wrong
output due to a bug of the partition-descriptor logic and that is noted
as such in the comment in the test.  A subsequent commit will fix the
bug and replace the buggy output by the correct one.

Author: Amit Langote <amitlangote09@gmail.com>
Discussion: https://postgr.es/m/1627848.1636676261@sss.pgh.pa.us

3 years agoRevert "Logical decoding of sequences"
Tomas Vondra [Thu, 7 Apr 2022 16:13:13 +0000 (18:13 +0200)]
Revert "Logical decoding of sequences"

This reverts a sequence of commits, implementing features related to
logical decoding and replication of sequences:

 - 0da92dc530c9251735fc70b20cd004d9630a1266
 - 80901b32913ffa59bf157a4d88284b2b3a7511d9
 - b779d7d8fdae088d70da5ed9fcd8205035676df3
 - d5ed9da41d96988d905b49bebb273a9b2d6e2915
 - a180c2b34de0989269fdb819bff241a249bf5380
 - 75b1521dae1ff1fde17fda2e30e591f2e5d64b6a
 - 2d2232933b02d9396113662e44dca5f120d6830e
 - 002c9dd97a0c874fd1693a570383e2dd38cd40d5
 - 05843b1aa49df2ecc9b97c693b755bd1b6f856a9

The implementation has issues, mostly due to combining transactional and
non-transactional behavior of sequences. It's not clear how this could
be fixed, but it'll require reworking significant part of the patch.

Discussion: https://postgr.es/m/95345a19-d508-63d1-860a-f5c2f41e8d40@enterprisedb.com

3 years agodoc: Fix man page whitespace issues
Peter Eisentraut [Thu, 7 Apr 2022 16:23:28 +0000 (18:23 +0200)]
doc: Fix man page whitespace issues

Whitespace between tags is significant, and in some cases it creates
extra vertical space in man pages.  The fix is to remove some newlines
in the markup.

3 years agoFix off-by-one error in pg_waldump, introduced in 5c279a6d350.
Jeff Davis [Thu, 7 Apr 2022 16:14:49 +0000 (09:14 -0700)]
Fix off-by-one error in pg_waldump, introduced in 5c279a6d350.

Per report by Bharath Rupireddy.

Discussion: https://postgr.es/m/CALj2ACX+PWDK2MYjdu8CB1ot7OUSo6kd5-fkkEgduEsTSZjAEw@mail.gmail.com

3 years agoFix another buildfarm issue from commit 5c279a6d350.
Jeff Davis [Thu, 7 Apr 2022 15:40:16 +0000 (08:40 -0700)]
Fix another buildfarm issue from commit 5c279a6d350.

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

3 years agoUnlogged sequences
Peter Eisentraut [Thu, 7 Apr 2022 14:13:23 +0000 (16:13 +0200)]
Unlogged sequences

Add support for unlogged sequences.  Unlike for unlogged tables, this
is not a performance feature.  It allows sequences associated with
unlogged tables to be excluded from replication.

A new subcommand ALTER SEQUENCE ... SET LOGGED/UNLOGGED is added.

An identity/serial sequence now automatically gets and follows the
persistence level (logged/unlogged) of its owning table.  (The
sequences owned by temporary tables were already temporary through the
separate mechanism in RangeVarAdjustRelationPersistence().)  But you
can still change the persistence of an owned sequence separately.
Also, pg_dump and pg_upgrade preserve the persistence of existing
sequences.

Discussion: https://www.postgresql.org/message-id/flat/04e12818-2f98-257c-b926-2845d74ed04f%402ndquadrant.com