users/rhaas/postgres.git
5 years agoDoc: update sections 9.7 and 9.8 for new function table layout.
Tom Lane [Mon, 20 Apr 2020 22:44:12 +0000 (18:44 -0400)]
Doc: update sections 9.7 and 9.8 for new function table layout.

Also some mop-up in section 9.9.

5 years agoMove the server's backup manifest code to a separate file.
Robert Haas [Mon, 20 Apr 2020 18:37:38 +0000 (14:37 -0400)]
Move the server's backup manifest code to a separate file.

basebackup.c is already a pretty big and complicated file, so it
makes more sense to keep the backup manifest support routines
in a separate file, for clarity and ease of maintenance.

Discussion: http://postgr.es/m/CA+TgmoavRak5OdP76P8eJExDYhPEKWjMb0sxW7dF01dWFgE=uA@mail.gmail.com

5 years agoAdd tab-completion for ALTER INDEX .. [NO] DEPENDS ON
Alvaro Herrera [Mon, 20 Apr 2020 17:42:41 +0000 (13:42 -0400)]
Add tab-completion for ALTER INDEX .. [NO] DEPENDS ON

... as added in the prior commit.

(We'd like to have tab-completion for the other object types too, but
they don't have sub-command completion yet.)

Author: Ibrar Ahmed <[email protected]>
Reviewed-by: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/CALtqXTcogrFEVP9uou5vFtnGsn+vHZUu9+9a0inarfYVOHScYQ@mail.gmail.com

5 years agoAdd ALTER .. NO DEPENDS ON
Alvaro Herrera [Mon, 20 Apr 2020 17:42:12 +0000 (13:42 -0400)]
Add ALTER .. NO DEPENDS ON

Commit f2fcad27d59c (9.6 era) added the ability to mark objects as
dependent an extension, but forgot to add a way for such dependencies to
be removed.  This commit fixes that oversight.

Strictly speaking this should be backpatched to 9.6, but due to lack of
demand we're not doing so at this time.

Discussion: https://postgr.es/m/20200217225333[email protected]
Reviewed-by: ahsan hadi <[email protected]>
Reviewed-by: Ibrar Ahmed <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
5 years agoDoc: update sections 9.5 and 9.6 for new function table layout.
Tom Lane [Mon, 20 Apr 2020 16:29:28 +0000 (12:29 -0400)]
Doc: update sections 9.5 and 9.6 for new function table layout.

Along the way, update the older examples for bytea to use "hex"
output format.  That lets us get rid of the lame disclaimer about
how the examples assume bytea_output = escape, which was only half
true anyway because none of the more-recently-added examples had
paid any attention to that.

5 years agoAllow pg_read_all_stats to access all stats views again
Magnus Hagander [Mon, 20 Apr 2020 10:53:40 +0000 (12:53 +0200)]
Allow pg_read_all_stats to access all stats views again

The views pg_stat_progress_* had not gotten the memo that
pg_read_all_stats is supposed to be able to read all statistics. Also
make a pass over all text-returning pg_stat_xyz functions that could
return "insufficient privilege" and make sure they also respect
pg_read_all_status.

Reported-by: Andrey M. Borodin
Reviewed-by: Andrey M. Borodin, Kyotaro Horiguchi
Discussion: https://postgr.es/m/13145F2F-8458-4977-9D2D-7B2E862E5722@yandex-team.ru

5 years agoDoc: update the rest of section 9.4 for new function table layout.
Tom Lane [Sun, 19 Apr 2020 21:44:28 +0000 (17:44 -0400)]
Doc: update the rest of section 9.4 for new function table layout.

Notably, this replaces the previous handwaving about these functions'
behavior with "character"-type inputs with some actual facts.

5 years agoFix missing pfree() in logtape.c, missed by 24d85952.
Jeff Davis [Sun, 19 Apr 2020 17:32:26 +0000 (10:32 -0700)]
Fix missing pfree() in logtape.c, missed by 24d85952.

5 years agoDoc: update sections 9.1-9.3 for new function table layout.
Tom Lane [Sun, 19 Apr 2020 16:17:02 +0000 (12:17 -0400)]
Doc: update sections 9.1-9.3 for new function table layout.

I took the opportunity to do some copy-editing in this area as well,
and to add some new material such as a note about BETWEEN's syntactical
peculiarities.

Of note is that quite a few of the examples of transcendental functions
needed to be updated, because the displayed output no longer matched
what you get on a modern server.  I believe some of these cases are
side-effects of the new Ryu algorithm in float8out.  Others appear to be
because the examples predate the addition of type numeric, and were
expecting that float8 calculations would be done although the given
syntax would actually lead to calling the numeric function nowadays.

5 years agoFix update-unicode target
Peter Eisentraut [Sun, 19 Apr 2020 12:59:29 +0000 (14:59 +0200)]
Fix update-unicode target

The normalization-check target needs to be run last, after moving the
newly generated files into place.  Also, we need an additional
dependency so that unicode_norm.o is rebuilt first.  Otherwise,
norm_test will still test the old files but against the new expected
results, which will probably fail.

5 years agoDoc: sync functableentry markup choices with website style.
Tom Lane [Sat, 18 Apr 2020 19:36:43 +0000 (15:36 -0400)]
Doc: sync functableentry markup choices with website style.

Jonathan Katz felt that slightly different indentation settings made
for a better-looking result, so sync stylesheet-fo.xsl (for PDF) and
stylesheet.css (for non-website-style HTML) with those choices.

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

5 years agoFix race conditions in synchronous standby management.
Tom Lane [Sat, 18 Apr 2020 18:02:44 +0000 (14:02 -0400)]
Fix race conditions in synchronous standby management.

We have repeatedly seen the buildfarm reach the Assert(false) in
SyncRepGetSyncStandbysPriority.  This apparently is due to failing to
consider the possibility that the sync_standby_priority values in
shared memory might be inconsistent; but they will be whenever only
some of the walsenders have updated their values after a change in
the synchronous_standby_names setting.  That function is vastly too
complex for what it does, anyway, so rewriting it seems better than
trying to apply a band-aid fix.

Furthermore, the API of SyncRepGetSyncStandbys is broken by design:
it returns a list of WalSnd array indexes, but there is nothing
guaranteeing that the contents of the WalSnd array remain stable.
Thus, if some walsender exits and then a new walsender process
takes over that WalSnd array slot, a caller might make use of
WAL position data that it should not, potentially leading to
incorrect decisions about whether to release transactions that
are waiting for synchronous commit.

To fix, replace SyncRepGetSyncStandbys with a new function
SyncRepGetCandidateStandbys that copies all the required data
from shared memory while holding the relevant mutexes.  If the
associated walsender process then exits, this data is still safe to
make release decisions with, since we know that that much WAL *was*
sent to a valid standby server.  This incidentally means that we no
longer need to treat sync_standby_priority as protected by the
SyncRepLock rather than the per-walsender mutex.

SyncRepGetSyncStandbys is no longer used by the core code, so remove
it entirely in HEAD.  However, it seems possible that external code is
relying on that function, so do not remove it from the back branches.
Instead, just remove the known-incorrect Assert.  When the bug occurs,
the function will return a too-short list, which callers should treat
as meaning there are not enough sync standbys, which seems like a
reasonably safe fallback until the inconsistent state is resolved.
Moreover it's bug-compatible with what has been happening in non-assert
builds.  We cannot do anything about the walsender-replacement race
condition without an API/ABI break.

The bogus assertion exists back to 9.6, but 9.6 is sufficiently
different from the later branches that the patch doesn't apply at all.
I chose to just remove the bogus assertion in 9.6, feeling that the
probability of a bad outcome from the walsender-replacement race
condition is too low to justify rewriting the whole patch for 9.6.

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

5 years agoFix possible crash with GENERATED ALWAYS columns
David Rowley [Sat, 18 Apr 2020 02:10:37 +0000 (14:10 +1200)]
Fix possible crash with GENERATED ALWAYS columns

In some corner cases, this could also lead to corrupted values being
included in the tuple.

Users who are concerned that they are affected by this should first
upgrade and then perform a base backup of their database and restore onto
an off-line server. They should then query each table with generated
columns to ensure there are no rows where the generated expression does
not match a newly calculated version of the GENERATED ALWAYS expression.
If no crashes occur and no rows are returned then you're not affected.

Fixes bug #16369.

Reported-by: Cameron Ezell
Discussion: https://postgr.es/m/16369-5845a6f1bef59884@postgresql.org
Backpatch-through: 12 (where GENERATED ALWAYS columns were added.)

5 years agoDoc: revise formatting of function/operator tables.
Tom Lane [Sat, 18 Apr 2020 00:50:26 +0000 (20:50 -0400)]
Doc: revise formatting of function/operator tables.

The table layout ideas proposed in commit e894c6183 were not as widely
popular as I'd hoped.  After discussion, we've settled on a layout
that's effectively a single-column table with cell contents much like a
<varlistentry> description of the function or operator; though we're not
actually using <varlistentry>, because it'd add way too much vertical
space.  Instead the effect is accomplished using line-break processing
instructions to separate the description and example(s), plus CSS or FO
customizations to produce indentation of all but the first line in each
cell.  While technically this is a bit grotty, it does have the
advantage that we won't need to write nearly as much boilerplate markup.

This patch updates tables 9.30, 9.31, and 9.33 (which were touched by
the previous patch) to the revised style, and additionally converts
table 9.10.  A lot of work still remains to do, but hopefully it won't
be too controversial.

Thanks to Andrew Dunstan, Pierre Giraud, Robert Haas, Alvaro Herrera,
David Johnston, Jonathan Katz, Isaac Morland for valuable ideas.

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

5 years agoRevert "Only provide new libpq sslpasskey hook for openssl-enabled builds"
Andrew Dunstan [Fri, 17 Apr 2020 20:53:01 +0000 (16:53 -0400)]
Revert "Only provide new libpq sslpasskey hook for openssl-enabled builds"

This reverts commit 9e24109f1a4e4d8d1d372b004d6a0dd06e673fe7.

This caused build errors when building without openssl, and it's
simplest just to revert it.

5 years agoOnly provide openssl_tls_init_hook if building with openssl
Andrew Dunstan [Fri, 17 Apr 2020 19:57:19 +0000 (15:57 -0400)]
Only provide openssl_tls_init_hook if building with openssl

This should have been protected by #ifdef USE_OPENSSL in commit
896fcdb230.

Per the real complaint this time from Daniel Gustafsson.

5 years agoUse a slightly more liberal regex to detect Visual Studio version
Andrew Dunstan [Fri, 17 Apr 2020 18:44:33 +0000 (14:44 -0400)]
Use a slightly more liberal regex to detect Visual Studio version

Apparently in some language versions of Visual Studio nmake outputs some
material after the version number and before the end of the line. This
has been seen in Chinese versions. Therefore, we no longer demand that
the version string comes at the end of a line.

Per complaint from Cuiping Lin.

Backpatch to all live branches.

5 years agoOnly provide new libpq sslpasskey hook for openssl-enabled builds
Andrew Dunstan [Fri, 17 Apr 2020 18:11:18 +0000 (14:11 -0400)]
Only provide new libpq sslpasskey hook for openssl-enabled builds

In commit 4dc6355210 I neglected to put #ifdef USE_OPENSSL around the
declarations of the new items. This is remedied here.

Per complaint from Daniel Gustafsson.

5 years agoFix possible future cache reference leak in ALTER EXTENSION ADD/DROP.
Tom Lane [Fri, 17 Apr 2020 17:41:59 +0000 (13:41 -0400)]
Fix possible future cache reference leak in ALTER EXTENSION ADD/DROP.

recordExtObjInitPriv and removeExtObjInitPriv were sloppy about
calling ReleaseSysCache.  The cases cannot occur given current usage
in ALTER EXTENSION ADD/DROP, since we wouldn't get here for these
relkinds; but it seems wise to clean up better.

In passing, extend test logic in test_pg_dump to exercise the
dropped-column code paths here.

Since the case is unreachable at present, there seems no great
need to back-patch; hence fix HEAD only.

Kyotaro Horiguchi, with test case and comment adjustments by me

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

5 years agoAdd index term for backup manifest in documentation.
Fujii Masao [Fri, 17 Apr 2020 09:37:38 +0000 (18:37 +0900)]
Add index term for backup manifest in documentation.

Author: Fujii Masao
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/951743d0-fd7e-8e2b-d489-1368a58b7304@oss.nttdata.com

5 years agoFix minor memory leak in pg_basebackup and pg_receivewal
Michael Paquier [Fri, 17 Apr 2020 01:45:08 +0000 (10:45 +0900)]
Fix minor memory leak in pg_basebackup and pg_receivewal

The result of the query used to retrieve the WAL segment size from the
backend was not getting freed in two code paths.  Both pg_basebackup and
pg_receivewal exit immediately if a failure happened on this query, so
this was not an actual problem, but it could be an issue if this code
gets used for other tools in different ways, be they future tools in
this code tree or external, existing, ones.

Oversight in commit fc49e24, so backpatch down to 11.

Author: Jie Zhang
Discussion: https://postgr.es/m/970ad9508461469b9450b64027842331@G08CNEXMBPEKD06.g08.fujitsu.local
Backpatch-through: 11

5 years agoRemove unneeded constraint dependency tracking
David Rowley [Thu, 16 Apr 2020 22:29:49 +0000 (10:29 +1200)]
Remove unneeded constraint dependency tracking

It was previously thought that remove_useless_groupby_columns() needed to
keep track of which constraints the generated plan depended upon, however,
this is unnecessary. The confusion likely arose regarding this because of
check_functional_grouping(), which does need to track the dependency to
ensure VIEWs with columns which are functionally dependant on the GROUP BY
remain so. For remove_useless_groupby_columns(), cached plans will just
become invalidated when the primary key's underlying index is removed
through the normal relcache invalidation code.

Here we just remove the unneeded code which records the dependency and
updates the comments. The previous comments claimed that we could not use
UNIQUE constraints for the same optimization due to lack of a
pg_constraint record for NOT NULL constraints (which are required because
NULLs can be duplicated in a unique index). Since we don't actually need a
pg_constraint record to handle the invalidation, it looks like we could
add code to do this in the future. But not today.

We're not really fixing any bug in the code here, this fix is just to set
the record straight on UNIQUE constraints. This code was added back in
9.6, but due to lack of any bug, we'll not be backpatching this.

Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/CAApHDvrdYa=VhOoMe4ZZjZ-G4ALnD-xuAeUNCRTL+PYMVN8OnQ@mail.gmail.com

5 years agoFix cache reference leak in contrib/sepgsql.
Tom Lane [Thu, 16 Apr 2020 18:45:54 +0000 (14:45 -0400)]
Fix cache reference leak in contrib/sepgsql.

fixup_whole_row_references() did the wrong thing with a dropped column,
resulting in a commit-time warning about a cache reference leak.

I (tgl) added a test case exercising this, but back-patched the test
only as far as v10; the patch didn't apply cleanly to 9.6 and it
didn't seem worth the trouble to adapt it.  The bug is pretty old
though, so apply the code change all the way back.

Michael Luo, with cosmetic improvements by me

Discussion: https://postgr.es/m/BYAPR08MB5606D1453D7F50E2AF4D2FD29AD80@BYAPR08MB5606.namprd08.prod.outlook.com

5 years agoFix the usage of parallel and full options of vacuum command.
Amit Kapila [Thu, 16 Apr 2020 05:14:03 +0000 (10:44 +0530)]
Fix the usage of parallel and full options of vacuum command.

Earlier we were inconsistent in allowing the usage of parallel and
full options.  Change it such that we disallow them only when they are
combined in a way that we don't support.

In passing, improve the comments in some of the existing tests of parallel
vacuum.

Reported-by: Tushar Ahuja
Author: Justin Pryzby, Amit Kapila
Reviewed-by: Sawada Masahiko, Michael Paquier, Mahendra Singh Thalor and
Amit Kapila
Discussion: https://postgr.es/m/58c8d171-e665-6fa3-a9d3-d9423b694dae%40enterprisedb.com

5 years agoDisable silently generation of manifests with servers <= 12 in pg_basebackup
Michael Paquier [Thu, 16 Apr 2020 04:57:07 +0000 (13:57 +0900)]
Disable silently generation of manifests with servers <= 12 in pg_basebackup

Since 0d8c9c1, pg_basebackup would generate an error if connected to a
backend version older than 12 where backup manifests are not supported.
Avoiding this error is possible by using the --no-manifest option.

This error handling could be confusing for some users, where patching a
backup script that interacts with multiple backend versions would cause
the addition of --no-manifest to potentially not generate a backup
manifest even for Postgres 13 and newer versions.  As we want to
encourage the use of backup manifests as much as possible, this commit
silently disables manifests where not supported, instead of generating
an error.

While on it, rework a bit the code to make it more consistent with the
surroundings when generating the BASE_BACKUP command.

Per discussion with Andres Freund, Stephen Frost, Robert Haas, Álvaro
Herrera, Kyotaro Horiguchi, Tom Lane, David Steele, and me.

Author: Michael Paquier
Discussion: https://postgr.es/m/20200410080910[email protected]

5 years agoSlightly simplify nbtree split point choice loop.
Peter Geoghegan [Wed, 15 Apr 2020 22:47:26 +0000 (15:47 -0700)]
Slightly simplify nbtree split point choice loop.

Spotted during post-commit review of the nbtree deduplication commit
(commit 0d861bbb).

5 years agoFix minor memory leak in pg_dump
Michael Paquier [Wed, 15 Apr 2020 06:56:01 +0000 (15:56 +0900)]
Fix minor memory leak in pg_dump

A query used to read default ACL information from the catalogs did not
free a set of PQExpBuffer.

Oversight in commit e2090d9, so backpatch down to 9.6.

Author: Jie Zhang
Reviewed-by: Sawada Masahiko
Discussion: https://postgr.es/m/05bcbc5857f948efa0b451b85a48ae10@G08CNEXMBPEKD06.g08.fujitsu.local
Backpatch-through: 9.6

5 years agoCode review for backup manifest.
Fujii Masao [Wed, 15 Apr 2020 02:15:12 +0000 (11:15 +0900)]
Code review for backup manifest.

This commit prevents pg_basebackup from receiving backup_manifest file
when --no-manifest is specified. Previously, when pg_basebackup was
writing a tarfile to stdout, it tried to receive backup_manifest file even
when --no-manifest was specified, and reported an error.

Also remove unused -m option from pg_basebackup.

Also fix typo in BASE_BACKUP command documentation.

Author: Fujii Masao
Reviewed-by: Michael Paquier, Robert Haas
Discussion: https://postgr.es/m/01e3ed3a-8729-5aaa-ca84-e60e3ca59db8@oss.nttdata.com

5 years agoRemove obsolete "hole in center of page" comment.
Peter Geoghegan [Tue, 14 Apr 2020 21:38:28 +0000 (14:38 -0700)]
Remove obsolete "hole in center of page" comment.

A comment from the Berkeley days incorrectly claimed that the page
management code cares about the contents of the hole in the center of
the page (at least in the case of the left half of an nbtree page
split).  Commit 8fa30f906be added an addendum that stated that the
original comment was "probably obsolete".  It's definitely obsolete,
though, so remove the original comment plus the addendum.

5 years agoAccount for collation when coercing the output of a SQL function.
Tom Lane [Tue, 14 Apr 2020 21:30:13 +0000 (17:30 -0400)]
Account for collation when coercing the output of a SQL function.

Commit 913bbd88d overlooked that the result of coerce_to_target_type
might need collation fixups.  Per report from Andreas Joseph Krogh.

Discussion: https://postgr.es/m/VisenaEmail.72.37d08ec2b8cb8fb5.17179940cd3@tc7-visena

5 years agoStop requiring an explicit return from perl subroutines
Andrew Dunstan [Tue, 14 Apr 2020 20:55:34 +0000 (16:55 -0400)]
Stop requiring an explicit return from perl subroutines

The consensus of the project appears to be that this provides little
benefit and is simply an annoyance.

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

5 years agoSet Perl search path more idiomatically
Andrew Dunstan [Tue, 14 Apr 2020 20:47:07 +0000 (16:47 -0400)]
Set Perl search path more idiomatically

Back in commits 1df92eeafef884a96819, and 592123efbb I used some
hackish code to set the script search path, unaware despite decades of
perl that there was a completely standard way to do this. This patch
changes those cases to use the standard perl FindBin package.

5 years agoDocument the backup manifest file format.
Robert Haas [Tue, 14 Apr 2020 17:41:32 +0000 (13:41 -0400)]
Document the backup manifest file format.

Patch by me, at the request of Andres Freund. Reviewed by
Justin Pryzby, Erik Rijkers, Álvaro Herrera, and Andrew
Dunstan.

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

5 years agoRearrange _bt_insertonpg() "update metapage" code.
Peter Geoghegan [Tue, 14 Apr 2020 16:33:18 +0000 (09:33 -0700)]
Rearrange _bt_insertonpg() "update metapage" code.

Nest the "update metapage as part of insert into root-like page" branch
inside the broader "insert into internal page" branch.  This improves
readability.

5 years agoFix collection of typos and grammar mistakes in the tree, volume 2
Michael Paquier [Tue, 14 Apr 2020 05:45:43 +0000 (14:45 +0900)]
Fix collection of typos and grammar mistakes in the tree, volume 2

This fixes some comments and documentation new as of Postgres 13, and is
a follow-up of the work done in dd0f37e.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20200408165653[email protected]

5 years agoAdd defensive "split_only_page" nbtree assertion.
Peter Geoghegan [Tue, 14 Apr 2020 04:11:03 +0000 (21:11 -0700)]
Add defensive "split_only_page" nbtree assertion.

Clearly it's not okay for nbtree to split a page that is the only page
on its level, and then find that it has to split the parent one level up
in turn.  There is simply no code to handle the split_only_page case in
the _bt_insertonpg() "newitem won't fit" branch (only the "newitem fits"
branch handles split_only_page).  Add a defensive assertion that will
fail if a split_only_page call to _bt_insertonpg() somehow ends up
splitting the target/parent page.

I (pgeoghegan) believe that we don't need split_only_page handling for
the "newitem won't fit" branch because anybody calling _bt_insertonpg()
like this would have to hold a lock on the same one and only child page.

5 years agoComments and doc fixes for commit 40d964ec99.
Amit Kapila [Tue, 14 Apr 2020 02:40:27 +0000 (08:10 +0530)]
Comments and doc fixes for commit 40d964ec99.

Reported-by: Justin Pryzby
Author: Justin Pryzby, with few changes by me
Reviewed-by: Amit Kapila and Sawada Masahiko
Discussion: https://postgr.es/m/20200322021801[email protected]

5 years agoMake _bt_insertonpg() more like _bt_split().
Peter Geoghegan [Tue, 14 Apr 2020 02:26:41 +0000 (19:26 -0700)]
Make _bt_insertonpg() more like _bt_split().

It seems like a good idea for nbtree's retail insert code to be
absolutely consistent with nbtree's page split code for anything that
naturally requires equivalent handling.  Anything that concerns
inserting newitem (which is handled as part of the page split atomic
action when a page split is required) should work in exactly the same
way.  With that in mind, make _bt_insertonpg() handle 'cbuf' in a way
that matches _bt_split().

5 years agoAdd a wait_for_catchup() before immediate stop of a test master.
Noah Misch [Tue, 14 Apr 2020 01:47:28 +0000 (18:47 -0700)]
Add a wait_for_catchup() before immediate stop of a test 

Per buildfarm member hoverfly, a slow walsender could make the test
fail.  Back-patch to v10, where the test was introduced.

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

5 years agoSilence Perl warning
Alvaro Herrera [Mon, 13 Apr 2020 23:54:09 +0000 (19:54 -0400)]
Silence Perl warning

Now that warnings are enabled across the board, this code that tries to
print an undef variable emits one.  Silently printing the empty string
achieves the previous behavior.

Author: Álvaro Herrera <[email protected]>
Reviewed-by: Andrew Dunstan <[email protected]>
Discussion: https://postgr.es/m/[email protected]

5 years agoHarmonize nbtree page split point code.
Peter Geoghegan [Mon, 13 Apr 2020 23:39:55 +0000 (16:39 -0700)]
Harmonize nbtree page split point code.

An nbtree split point can be thought of as a point between two adjoining
tuples from an imaginary version of the page being split that includes
the incoming/new item (in addition to the items that really are on the
page).  These adjoining tuples are called the lastleft and firstright
tuples.

The variables that represent split points contained a field called
firstright, which is an offset number of the first data item from the
original page that goes on the new right page.  The corresponding tuple
from origpage was usually the same thing as the actual firstright tuple,
but not always: the firstright tuple is sometimes the new/incoming item
instead.  This situation seems unnecessarily confusing.

Make things clearer by renaming the origpage offset returned by
_bt_findsplitloc() to "firstrightoff".  We now have a firstright tuple
and a firstrightoff offset number which are comparable to the
newitem/lastleft tuples and the newitemoff/lastleftoff offset numbers
respectively.  Also make sure that we are consistent about how we
describe nbtree page split point state.

Push the responsibility for dealing with pg_upgrade'd !heapkeyspace
indexes down to lower level code, relieving _bt_split() from dealing
with it directly.  This means that we always have a palloc'd left page
high key on the leaf level, no matter what.  This enables simplifying
some of the code (and code comments) within _bt_split().

Finally, restructure the page split code to make it clearer why suffix
truncation (which only takes place during leaf page splits) is
completely different to the first data item truncation that takes place
during internal page splits.  Tuples are marked as having fewer
attributes stored in both cases, and the firstright tuple is truncated
in both cases, so it's easy to imagine somebody missing the distinction.

5 years agoUse perl's $/ more idiomatically
Andrew Dunstan [Mon, 13 Apr 2020 16:06:11 +0000 (12:06 -0400)]
Use perl's $/ more idiomatically

This replaces a few occurrences of ugly code with a more clean and
idiomatic usage. The problem was highlighted by perlcritic, but we're
not enforcing the policy that led to the discovery.

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

5 years agoUse perl warnings pragma consistently
Andrew Dunstan [Mon, 13 Apr 2020 15:55:45 +0000 (11:55 -0400)]
Use perl warnings pragma consistently

We've had a mixture of the warnings pragma, the -w switch on the shebang
line, and no warnings at all. This patch removes the -w swicth and add
the warnings pragma to all perl sources missing it. It raises the
severity of the TestingAndDebugging::RequireUseWarnings  perlcritic
policy to level 5, so that we catch any future violations.

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

5 years agoPrint policy name in perlcritic messages
Andrew Dunstan [Mon, 13 Apr 2020 15:46:18 +0000 (11:46 -0400)]
Print policy name in perlcritic messages

This makes it easier to do a web search for details of the policy that's
been violated, as well as displaying the name that might be needed for a
policy override.

Various perlcritic settings changes are being discussed, but this one
should be uncontroversial.

5 years agoRename pg_validatebackup to pg_verifybackup some more.
Robert Haas [Mon, 13 Apr 2020 14:48:23 +0000 (10:48 -0400)]
Rename pg_validatebackup to pg_verifybackup some more.

The previous commit missed an instance.

Noriyoshi Shinoda

Discussion: http://postgr.es/m/TU4PR8401MB115291AE850BA7CF1AEB2F0BEEDD0@TU4PR8401MB1152.NAMPRD84.PROD.OUTLOOK.COM

5 years agoCosmetic fixups for WAL usage work.
Amit Kapila [Mon, 13 Apr 2020 10:01:16 +0000 (15:31 +0530)]
Cosmetic fixups for WAL usage work.

Reported-by: Justin Pryzby and Euler Taveira
Author: Justin Pryzby and Julien Rouhaud
Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/CAB-hujrP8ZfUkvL5OYETipQwA=e3n7oqHFU=4ZLxWS_Cza3kQQ@mail.gmail.com

5 years agoImprove error messages after LoadLibrary()
Peter Eisentraut [Mon, 13 Apr 2020 08:21:15 +0000 (10:21 +0200)]
Improve error messages after LoadLibrary()

Move the file name to a format parameter to ease translatability.  Add
error code where missing.  Make the wording consistent.

5 years agoDoc: introduce new layout for tables of functions and operators.
Tom Lane [Sun, 12 Apr 2020 22:03:20 +0000 (18:03 -0400)]
Doc: introduce new layout for tables of functions and operators.

We've long fought with the draconian space limitations of our
traditional table layout for describing SQL functions and operators.
This commit introduces a new approach, though so far I've only applied
it to a few of those tables.  The new way makes use of DocBook's support
for different layouts in different rows of a table, and allows the
descriptions and examples for a function or operator to run to several
lines without as much ugliness and wasted space as before.

The core layout concept is now

     Name              Signature
                      Description
                 Example     Example Result

so that a function or operator really has three table rows not one,
but we group them to look like one row by having the name column
have only one entry for all three rows.  (Actually, there could be
four or more rows if you wanted to have more than one example, which
is another thing that was painful before but works easily now.)
This is handled by a "morerows" annotation on the name entry, which
isn't perfect (notably, the toolchain is not smart enough to avoid
breaking these row groups across PDF pages) but there seems no better
solution in DocBook.  The name column is normally fairly narrow,
allowing plenty of space for the other column(s), and not wasting too
much space when one of the other components runs to multiple lines.

The varying row layout is managed by defining named "spans" and then
tagging entries with a "spanname" of "name", "sig", "desc", "example",
or "exresult".  This provides a bit of semantic annotation to go with
the formatting improvement, which seems like a good thing.  (It seems
that we have to re-define these spans afresh for each table, which is
annoying, but it's not any worse than the duplication involved in
the table headers.  At least that gives us an opportunity to vary the
relative column widths per-table, which is handy since function tables
sometimes need much wider name columns than operator tables.)

Signature entries should be written in the style
    <function>fname</function>(<type>typename</type> ...)
    <returnvalue>typename</returnvalue>
The <returnvalue> tag produces a right arrow before the result type
name.  (I'll document that convention in a user-visible place later.)

While this provides significantly more horizontal space than before
for examples, it's still true that PDF output is a lot narrower than
typical webpage viewing windows, so some examples need to be broken
in places where there is no whitespace.  I've added &zwsp; markers in
suitable places to allow the tables to render warning-free in PDF.

I've so far converted only the date/time operator, date/time function,
and enum function tables in sections 9.9 and 9.10; these were chosen
to provide a reasonable sample of the formatting problems that need
to be solved.  Assuming that this looks good on the website and doesn't
provoke howls of anguish, I'll work on the other similar tables in the
near future.

There's a moderate amount of new editorial content in this patch along
with the raw formatting changes; for instance I had to write text
descriptions for operators that lacked them.  I failed to resist the
temptation to improve some other descriptions and examples, too.

Patch by me, with thanks to Alexander Lakhin for assistance with
figuring out some formatting issues.

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

5 years agoDoc: introduce and document "&zwsp;" for allowing optional line breaks.
Tom Lane [Sun, 12 Apr 2020 18:03:24 +0000 (14:03 -0400)]
Doc: introduce and document "&zwsp;" for allowing optional line breaks.

We already had a couple of places using zero-width spaces for formatting
hackery, and we're going to need more if we ever want the PDF manuals to
look decent.  But please let's not write hard-coded Unicode escapes.
We can avoid that by using a custom entity, which also provides a place
to put a teeny bit of documentation about what it is and how to use it.

I'd previously posted a patch using "&break;" for this, but on reflection
that would be horrible to grep for.  Instead let's use "&zwsp;", based
on the name of the Unicode symbol ("zero width space").

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

5 years agoRename pg_validatebackup to pg_verifybackup.
Robert Haas [Sun, 12 Apr 2020 15:26:05 +0000 (11:26 -0400)]
Rename pg_validatebackup to pg_verifybackup.

Also, use "verify" rather than "validate" to refer to the process
being undertaken here. Per discussion, that is a more appropriate
term.

Discussion: https://www.postgresql.org/message-id/172c9d9b-1d0a-1b94-1456-376b1e017322@2ndquadrant.com
Discussion: http://postgr.es/m/CA+TgmobLgMh6p8FmLbj_rv9Uhd7tPrLnAyLgGd2SoSj=qD-bVg@mail.gmail.com

5 years agoDoc: Fix contrib/amcheck tip.
Peter Geoghegan [Sun, 12 Apr 2020 04:07:20 +0000 (21:07 -0700)]
Doc: Fix contrib/amcheck tip.

Fixes an oversight in commit 20fbb711.

5 years agoSuppress -Wimplicit-fallthrough warning in new LIMIT WITH TIES code.
Tom Lane [Sat, 11 Apr 2020 19:02:38 +0000 (15:02 -0400)]
Suppress -Wimplicit-fallthrough warning in new LIMIT WITH TIES code.

The placement of the fall-through comment in this code appears not to
work to suppress the warning in recent gcc.  Move it to the bottom of
the case group, and add an assertion that we didn't get there through
some other code path.  Also improve wording of nearby comments.

Julien Rouhaud, comment hacking by me

Discussion: https://postgr.es/m/CAOBaU_aLdPGU5wCpaowNLF-Q8328iR7mj1yJAhMOVsdLwY+sdg@mail.gmail.com

5 years agoOptimize RelationFindReplTupleSeq() for CLOBBER_CACHE_ALWAYS.
Noah Misch [Sat, 11 Apr 2020 17:30:12 +0000 (10:30 -0700)]
Optimize RelationFindReplTupleSeq() for CLOBBER_CACHE_ALWAYS.

Specifically, remember lookup_type_cache() results instead of retrieving
them once per comparison.  Under CLOBBER_CACHE_ALWAYS, this reduced
src/test/subscription/t/001_rep_changes.pl elapsed time by an order of
magnitude, which reduced check-world elapsed time by 9%.

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

5 years agoWhen WalSndCaughtUp, sleep only in WalSndWaitForWal().
Noah Misch [Sat, 11 Apr 2020 17:30:00 +0000 (10:30 -0700)]
When WalSndCaughtUp, sleep only in WalSndWaitForWal().

Before sleeping, WalSndWaitForWal() sends a keepalive if MyWalSnd->write
< sentPtr.  That is important in logical replication.  When the latest
physical LSN yields no logical replication messages (a common case),
that keepalive elicits a reply, and processing the reply updates
pg_stat_replication.replay_lsn.  WalSndLoop() lacks that; when
WalSndLoop() slept, replay_lsn advancement could stall until
wal_receiver_status_interval elapsed.  This sometimes stalled
src/test/subscription/t/001_rep_changes.pl for up to 10s.

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

5 years agoMake EXPLAIN report maximum hashtable usage across multiple rescans.
Tom Lane [Sat, 11 Apr 2020 16:39:19 +0000 (12:39 -0400)]
Make EXPLAIN report maximum hashtable usage across multiple rescans.

Before discarding the old hash table in ExecReScanHashJoin, capture
its statistics, ensuring that we report the maximum hashtable size
across repeated rescans of the hash input relation.  We can repurpose
the existing code for reporting hashtable size in parallel workers
to help with this, making the patch pretty small.  This also ensures
that if rescans happen within parallel workers, we get the correct
maximums across all instances.

Konstantin Knizhnik and Tom Lane, per diagnosis by Thomas Munro
of a trouble report from Alvaro Herrera.

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

5 years agoClear dangling pointer to avoid bogus EXPLAIN printout in a corner case.
Tom Lane [Sat, 11 Apr 2020 16:29:06 +0000 (12:29 -0400)]
Clear dangling pointer to avoid bogus EXPLAIN printout in a corner case.

ExecReScanHashJoin will destroy the join's hash table if it expects
that the inner relation will produce different rows on rescan.
Up to now it's not bothered to clear the additional pointer to that
hash table that exists in the child HashState node.  However, it's
possible for the query to terminate without building a fresh hash
table (this happens if the outer relation is found to be empty
during the final rescan).  So we can end with a dangling pointer
to a deleted hash table.  That was harmless originally, but since
9.0 EXPLAIN ANALYZE has used that pointer to print hash table
statistics.  In debug builds this reproducibly results in garbage
statistics.  In non-debug builds there's frequently no ill effects,
but in principle one could get wrong EXPLAIN ANALYZE output, or
perhaps even a crash if free() has released the hashtable memory
back to the OS.

To fix, just make sure we clear the additional pointer when destroying
the hash table.  In problematic cases, EXPLAIN ANALYZE will then print
no hashtable statistics (reverting to its pre-9.0 behavior).  This isn't
ideal, but since the problem manifests only in unusual corner cases,
it's hard to justify taking any risks to do better in the back
branches.  A follow-on patch will improve matters in HEAD.

Konstantin Knizhnik and Tom Lane, per diagnosis by Thomas Munro
of a trouble report from Alvaro Herrera.

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

5 years agoFix RELCACHE_FORCE_RELEASE issue
Peter Eisentraut [Sat, 11 Apr 2020 13:07:25 +0000 (15:07 +0200)]
Fix RELCACHE_FORCE_RELEASE issue

Introduced by 83fd4532a72179c370e318075a10e0e2aa832024.  To fix, the
tuple descriptors need to be copied into the current memory context.

Discussion: https://www.postgresql.org/message-id/04d78603-edae-9243-9dde-fe3037176a7d@2ndquadrant.com

5 years agoFix relcache reference leak
Peter Eisentraut [Sat, 11 Apr 2020 07:44:14 +0000 (09:44 +0200)]
Fix relcache reference leak

Introduced by 83fd4532a72179c370e318075a10e0e2aa832024

5 years agodoc: restore intentional typo
Andrew Gierth [Sat, 11 Apr 2020 07:04:57 +0000 (08:04 +0100)]
doc: restore intentional typo

Commit ac8623760 "fixed" a typo in an example of what would happen in
the event of a typo. Restore the original typo and add a comment about
its intentionality. Backpatch to 12 where the error was introduced.

Per report from irc user Nicolás Alvarez.

5 years agoAdd contrib/amcheck debug message.
Peter Geoghegan [Sat, 11 Apr 2020 00:44:08 +0000 (17:44 -0700)]
Add contrib/amcheck debug message.

Add a DEBUG1 message indicating that verification of the index structure
is underway.  Also reduce the severity level of the existing "tree
level" debug message to DEBUG1.  It should never have been made DEBUG2.
Any B-Tree index with more than a couple of levels will generally also
have so many pages that the per-page DEBUG2 messages will become
completely unmanageable.

In passing, add a new "Tip" to the docs that advises users that run into
corruption that the debug messages might provide useful additional
context.

5 years agoDoc: clarify locking requirements for ALTER TABLE ADD FOREIGN KEY.
Tom Lane [Fri, 10 Apr 2020 17:12:58 +0000 (13:12 -0400)]
Doc: clarify locking requirements for ALTER TABLE ADD FOREIGN KEY.

The docs explained that a SHARE ROW EXCLUSIVE lock is needed on the
referenced table, but failed to say the same about the table being
altered.  Since the page says that ACCESS EXCLUSIVE lock is taken
unless otherwise stated, this left readers with the wrong conclusion.

Discussion: https://postgr.es/m/834603375.3470346.1586482852542@mail.yahoo.com

5 years agoSuppress unused-variable warning.
Tom Lane [Fri, 10 Apr 2020 16:00:28 +0000 (12:00 -0400)]
Suppress unused-variable warning.

Ashutosh Bapat

Discussion: https://postgr.es/m/CAG-ACPWPB8Lc_aFj25eiPFqi31YB5vmaZnb39mbHSf5Yej=miA@mail.gmail.com

5 years agoDoc: sync CREATE GROUP syntax synopsis with CREATE ROLE.
Tom Lane [Fri, 10 Apr 2020 14:44:09 +0000 (10:44 -0400)]
Doc: sync CREATE GROUP syntax synopsis with CREATE ROLE.

CREATE GROUP is an exact alias for CREATE ROLE, and CREATE USER is
almost an exact alias, as can easily be confirmed by checking the
code.  So the man page syntax descriptions ought to match up.  The
last few additions of role options seem to have forgotten to update
create_group.sgml, though.  Fix that, and add a naggy reminder to
create_role.sgml in hopes of not forgetting again.

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

5 years agoFix collection of typos and grammar mistakes in the tree
Michael Paquier [Fri, 10 Apr 2020 02:18:39 +0000 (11:18 +0900)]
Fix collection of typos and grammar mistakes in the tree

This fixes some comments and documentation new as of Postgres 13.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20200408165653[email protected]

5 years agoFurther stabilize results of 019_replslot_limit.pl.
Tom Lane [Thu, 9 Apr 2020 21:28:58 +0000 (17:28 -0400)]
Further stabilize results of 019_replslot_limit.pl.

Depending on specific values of restart_lsn or pg_current_wal_lsn()
is obviously unsafe.  The previous coding tried to dodge this issue
by rounding off, but that's not good enough, as shown by multiple
buildfarm members.  Nuke all the uses of these values except for
null-ness checks, pending some credible argument why we should think
something else could be usefully stable.

Kyotaro Horiguchi, further modified by me

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

5 years agoFurther cleanup of ts_headline code.
Tom Lane [Thu, 9 Apr 2020 19:38:43 +0000 (15:38 -0400)]
Further cleanup of ts_headline code.

Suppress a probably-meaningless uninitialized-variable warning
(induced by my previous patch, I'm sorry to say).

Improve mark_hl_fragments()'s test for overlapping cover strings:
it failed to consider the possibility that the current string is
strictly within another one.  That's unlikely given the preceding
splitting into MaxWords fragments, but I don't think it's impossible.

Discussion: https://postgr.es/m/16345-2e0cf5cddbdcd3b4@postgresql.org

5 years agoDoc: improve documentation about ts_headline() function.
Tom Lane [Thu, 9 Apr 2020 19:11:08 +0000 (15:11 -0400)]
Doc: improve documentation about ts_headline() function.

Now that I've had my nose in that code, I thought the docs about
it left something to be desired.

5 years agoFix default text search parser's ts_headline code for phrase queries.
Tom Lane [Thu, 9 Apr 2020 17:19:23 +0000 (13:19 -0400)]
Fix default text search parser's ts_headline code for phrase queries.

This code could produce very poor results when asked to highlight a
string based on a query using phrase-match operators.  The root cause
is that hlCover(), which is supposed to find a minimal substring that
matches the query, was written assuming that word position is not
significant.  I'm only 95% convinced that its algorithm was correct even
for plain AND/OR queries; but it definitely fails completely for phrase
matches, causing it to possibly not identify a cover string at all.

Hence, rewrite hlCover() with a less-tense algorithm that just tries
all the possible substrings, earlier and shorter ones first.  (This is
not as bad as it sounds performance-wise, because all of the string
matching has been done already: the repeated tsquery match checks
boil down to pointer comparisons.)

Unfortunately, since that approach produces more candidate cover
strings than before, it also exposes that there were bugs in the
heuristics in mark_hl_words() for selecting a best cover string.
Fixes there include:
* Do not apply the ShortWord filter to words that appear in the query.
* Remove a misguided optimization for quickly rejecting a cover.
* Fix order-of-operation bug that could cause computation of a
wrong figure of merit (poslen) when shortening a cover.
* Change the preference rule so that candidate headlines that do not
include their whole cover string (after MaxWords trimming) are lowest
priority, since they may not actually satisfy the user's query.

This results in some changes in existing regression test cases,
but they all seem reasonable.  Note in particular that the tests
involving strings like "1 2 3" were previously being affected by
the ShortWord filter, masking the normal matching behavior.

Per bug #16345 from Augustinas Jokubauskas; the new test cases are
based on that example.  Back-patch to 9.6 where phrase search was
added to tsquery.

Discussion: https://postgr.es/m/16345-2e0cf5cddbdcd3b4@postgresql.org

5 years agoCosmetic improvements for default text search parser's ts_headline code.
Tom Lane [Thu, 9 Apr 2020 16:36:59 +0000 (12:36 -0400)]
Cosmetic improvements for default text search parser's ts_headline code.

This code was woefully unreadable and under-commented.  Try to improve
matters by adding comments, using some macros to make complicated
if-tests more readable, using boolean type where appropriate, etc.
There are a couple of tiny coding improvements too, but this commit
includes (I hope) no behavioral change.

Nonetheless, back-patch as far as 9.6, because a followup bug-fixing
commit depends on this.

Discussion: https://postgr.es/m/16345-2e0cf5cddbdcd3b4@postgresql.org

5 years agoFix CREATE TABLE LIKE INCLUDING GENERATED column order issue
Peter Eisentraut [Thu, 9 Apr 2020 14:17:55 +0000 (16:17 +0200)]
Fix CREATE TABLE LIKE INCLUDING GENERATED column order issue

CREATE TABLE LIKE INCLUDING GENERATED would fail if a generated column
referred to a column with a higher attribute number.  This is because
the column mapping mechanism created the mapping incrementally as
columns are added.  This was sufficient for previous uses of that
mechanism (omitting dropped columns), and it also happened to work if
generated columns only referred to columns with lower attribute
numbers, but here it failed.

This fix is to build the attribute mapping in a separate loop before
processing the columns in detail.

Bug: #16342
Reported-by: Ethan Waldo <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
5 years agoFix typo in pg_validatebackup documentation.
Fujii Masao [Thu, 9 Apr 2020 13:38:24 +0000 (22:38 +0900)]
Fix typo in pg_validatebackup documentation.

Author: Fujii Masao
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/78f76a3d-1a28-a97d-0394-5c96985dd1c0@oss.nttdata.com

5 years agoExclude backup_manifest file that existed in database, from BASE_BACKUP.
Fujii Masao [Thu, 9 Apr 2020 13:37:11 +0000 (22:37 +0900)]
Exclude backup_manifest file that existed in database, from BASE_BACKUP.

If there is already a backup_manifest file in the database cluster,
it belongs to the past backup that was used to start this server.
It is not correct for the backup being taken now. So this commit
changes pg_basebackup so that it always skips such backup_manifest
file. The backup_manifest file for the current backup will be injected
separately if users want it.

Author: Fujii Masao
Reviewed-by: Robert Haas
Discussion: https://postgr.es/m/78f76a3d-1a28-a97d-0394-5c96985dd1c0@oss.nttdata.com

5 years agoAllow parallel create index to accumulate buffer usage stats.
Amit Kapila [Thu, 9 Apr 2020 04:19:30 +0000 (09:49 +0530)]
Allow parallel create index to accumulate buffer usage stats.

Currently, we don't account for buffer usage incurred by parallel workers
for parallel create index.  This commit allows each worker to record the
buffer usage stats and leader backend to accumulate that stats at the
end of the operation.  This will allow pg_stat_statements to display
correct buffer usage stats for (parallel) create index command.

Reported-by: Julien Rouhaud
Author: Sawada Masahiko
Reviewed-by: Dilip Kumar, Julien Rouhaud and Amit Kapila
Backpatch-through: 11, where this was introduced
Discussion: https://postgr.es/m/20200328151721.GB12854@nol

5 years agoAdd note in pg_stat_statements documentation about planning statistics.
Fujii Masao [Thu, 9 Apr 2020 03:56:36 +0000 (12:56 +0900)]
Add note in pg_stat_statements documentation about planning statistics.

The added note explains that the numbers of planning and execution in
the statement are not always expected to match because their statistics are
updated at their respective end phase, and only for successful operations.

Author: Pascal Legrand, Julien Rouhaud, tweaked a bit by Fujii Masao
Discussion: https://postgr.es/m/1585857868967[email protected]

5 years agoMsys2 tweaks for pg_validatebackup corruption test
Andrew Dunstan [Wed, 8 Apr 2020 21:50:55 +0000 (17:50 -0400)]
Msys2 tweaks for pg_validatebackup corruption test

1. Tell Msys2 not to mangle the tablespace map parameter
2. If rmdir doesn't work, fall back to trying unlink on the entry in
   pg_tblspc.

Discussion: https://postgr.es/m/7330a7c7-ce5f-9769-39a1-bdb0b32bb4a6@2ndQuadrant.com

5 years agocreateuser: Change a fprintf to pg_log_error
Peter Eisentraut [Wed, 8 Apr 2020 17:19:45 +0000 (19:19 +0200)]
createuser: Change a fprintf to pg_log_error

5 years agoStabilize incremental_sort tests
Tomas Vondra [Wed, 8 Apr 2020 16:30:11 +0000 (18:30 +0200)]
Stabilize incremental_sort tests

The test never did ANALYZE on the test table, so the plans depended on
various defaults (e.g. number of groups being 200). This worked most of
the time, but with CLOBBER_CACHE_ALWAYS the autoanalyze often managed
to build accurate stats, changing the  plan.

Fixed by increasing the size of test tables a bit, making the Sort a bit
more expensive than Incremental Sort. The tests were constructed to test
transitions in the Incremental Sort algorithm, and this change does not
break that.

Reviewed-by: James Coleman
Discussion: https://postgr.es/m/CAPpHfds1waRZ=NOmueYq0sx1ZSCnt+5QJvizT8ndT2=etZEeAQ@mail.gmail.com

5 years agoFix pg_dump/pg_restore to restore event trigger comments later.
Tom Lane [Wed, 8 Apr 2020 15:23:39 +0000 (11:23 -0400)]
Fix pg_dump/pg_restore to restore event trigger comments later.

Repair an oversight in commit 8728b2c70: if we're postponing restore
of event triggers to the end, we must also postpone restoring any
comments on them, since of course we cannot create the comments first.
(This opens yet another opportunity for an event trigger to bollix
the restore, but there's no help for that.)

Per bug #16346 from Alexander Lakhin.

Like the previous commit, back-patch to all supported branches.

Hamid Akhtar and Tom Lane

Discussion: https://postgr.es/m/16346-6210ad7a0ea81be1@postgresql.org

5 years agoRationalize GetWalRcv{Write,Flush}RecPtr().
Thomas Munro [Wed, 8 Apr 2020 11:45:09 +0000 (23:45 +1200)]
Rationalize GetWalRcv{Write,Flush}RecPtr().

GetWalRcvWriteRecPtr() previously reported the latest *flushed*
location.  Adopt the conventional terminology used elsewhere in the tree
by renaming it to GetWalRcvFlushRecPtr(), and likewise for some related
variables that used the term "received".

Add a new definition of GetWalRcvWriteRecPtr(), which returns the latest
*written* value.  This will allow later patches to use the value for
non-data-integrity purposes, without having to wait for the flush
pointer to advance.

Reviewed-by: Alvaro Herrera <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CA%2BhUKGJ4VJN8ttxScUFM8dOKX0BrBiboo5uz1cq%3DAovOddfHpA%40mail.gmail.com

5 years agoAllow publishing partition changes via ancestors
Peter Eisentraut [Wed, 8 Apr 2020 07:59:27 +0000 (09:59 +0200)]
Allow publishing partition changes via ancestors

To control whether partition changes are replicated using their own
identity and schema or an ancestor's, add a new parameter that can be
set per publication named 'publish_via_partition_root'.

This allows replicating a partitioned table into a different partition
structure on the subscriber.

Author: Amit Langote <[email protected]>
Reviewed-by: Rafia Sabih <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Reviewed-by: Petr Jelinek <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CA+HiwqH=Y85vRK3mOdjEkqFK+E=ST=eQiHdpj43L=_eJMOOznQ@mail.gmail.com

5 years agoRevert 0f5ca02f53
Alexander Korotkov [Wed, 8 Apr 2020 08:37:27 +0000 (11:37 +0300)]
Revert 0f5ca02f53

0f5ca02f53 introduces 3 new keywords.  It appears to be too much for relatively
small feature.  Given now we past feature freeze, it's already late for
discussion of the new syntax.  So, revert.

Discussion: https://postgr.es/m/28209.1586294824%40sss.pgh.pa.us

5 years agoModify additional power 2 calculations to use new helper functions
David Rowley [Wed, 8 Apr 2020 06:29:51 +0000 (18:29 +1200)]
Modify additional power 2 calculations to use new helper functions

2nd pass of modifying various places which obtain the next power
of 2 of a number and make them use the new functions added in
f0705bb62.

In passing, also modify num_combinations(). This can be implemented
using simple bitshifting rather than looping.

Reviewed-by: John Naylor
Discussion: https://postgr.es/m/20200114173553.GE32763%40fetter.org

5 years agoFix crash when using COLLATE in partition bound expressions
Michael Paquier [Wed, 8 Apr 2020 06:04:51 +0000 (15:04 +0900)]
Fix crash when using COLLATE in partition bound expressions

Attempting to use a COLLATE clause with a type that it not collatable in
a partition bound expression could crash the server.  This commit fixes
the code by adding more checks similar to what is done when computing
index or partition attributes by making sure that there is a collation
iff the type is collatable.

Backpatch down to 12, as 7c079d7 introduced this problem.

Reported-by: Alexander Lakhin
Author: Dmitry Dolgov
Discussion: https://postgr.es/m/16325-809194cf742313ab@postgresql.org
Backpatch-through: 12

5 years agoModify various power 2 calculations to use new helper functions
David Rowley [Wed, 8 Apr 2020 04:55:03 +0000 (16:55 +1200)]
Modify various power 2 calculations to use new helper functions

First pass of modifying various places that obtain the next power of 2 of
a number and make them use the new functions added in pg_bitutils.h
instead.

This also removes the _hash_log2() function. There are no longer any
callers in core. Other users can swap their _hash_log2(n) call to make use
of pg_ceil_log2_32(n).

Author: David Fetter, with some minor adjustments by me
Reviewed-by: John Naylor, Jesse Zhang
Discussion: https://postgr.es/m/20200114173553.GE32763%40fetter.org

5 years agoCreate memory context for HashAgg with a reasonable maxBlockSize.
Jeff Davis [Wed, 8 Apr 2020 03:42:04 +0000 (20:42 -0700)]
Create memory context for HashAgg with a reasonable maxBlockSize.

If the memory context's maxBlockSize is too big, a single block
allocation can suddenly exceed work_mem. For Hash Aggregation, this
can mean spilling to disk too early or reporting a confusing memory
usage number for EXPLAN ANALYZE.

Introduce CreateWorkExprContext(), which is like CreateExprContext(),
except that it creates the AllocSet with a maxBlockSize that is
reasonable in proportion to work_mem.

Right now, CreateWorkExprContext() is only used by Hash Aggregation,
but it may be generally useful in the future.

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

5 years agoAdd functions to calculate the next power of 2
David Rowley [Wed, 8 Apr 2020 04:22:52 +0000 (16:22 +1200)]
Add functions to calculate the next power of 2

There are many areas in the code where we need to determine the next
highest power of 2 of a given number.  We tend to always do that in an
ad-hoc way each time, generally with some tight for loop which performs a
bitshift left once per loop and goes until it finds a number above the
given number.

Here we add two generic functions which make use of the existing
pg_leftmost_one_pos* functions which, when available, will allow us to
calculate the next power of 2 without any looping.

Here we don't add any code which uses these new functions. That will be
done in follow-up commits.

Author: David Fetter, with some minor adjustments by me
Reviewed-by: John Naylor, Jesse Zhang
Discussion: https://postgr.es/m/20200114173553.GE32763%40fetter.org

5 years agoPut back mistakenly removed #include.
Tom Lane [Wed, 8 Apr 2020 04:10:16 +0000 (00:10 -0400)]
Put back mistakenly removed #include.

In commit 4dbcb3f84 I removed some code from parse_coerce.c, and also
removed some apparently-no-longer-needed #includes.  But removing
datum.h broke some not-compiled-by-default code.

Discussion: https://postgr.es/m/20200407205436.pyjhddw5bn5upvsu@development

5 years agoRemove testing for precise LSN/reserved bytes in new TAP test
Alvaro Herrera [Tue, 7 Apr 2020 23:16:37 +0000 (19:16 -0400)]
Remove testing for precise LSN/reserved bytes in new TAP test

Trying to ensure that a slot's restart_lsn or amount of reserved bytes
exactly match some specific values seems unnecessary, and fragile as
shown by failures in multiple buildfarm members.

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

5 years agoSupport PrefetchBuffer() in recovery.
Thomas Munro [Wed, 8 Apr 2020 01:36:45 +0000 (13:36 +1200)]
Support PrefetchBuffer() in recovery.

Provide PrefetchSharedBuffer(), a variant that takes SMgrRelation, for
use in recovery.  Rename LocalPrefetchBuffer() to PrefetchLocalBuffer()
for consistency.

Add a return value to all of these.  In recovery, tolerate and report
missing files, so we can handle relations unlinked before crash recovery
began.  Also report cache hits and misses, so that callers can do faster
buffer lookups and better I/O accounting.

Reviewed-by: Alvaro Herrera <[email protected]>
Reviewed-by: Andres Freund <[email protected]>
Discussion: https://postgr.es/m/CA%2BhUKGJ4VJN8ttxScUFM8dOKX0BrBiboo5uz1cq%3DAovOddfHpA%40mail.gmail.com

5 years agoAllow partitionwise join to handle nested FULL JOIN USING cases.
Tom Lane [Wed, 8 Apr 2020 02:12:14 +0000 (22:12 -0400)]
Allow partitionwise join to handle nested FULL JOIN USING cases.

This case didn't work because columns merged by FULL JOIN USING are
represented in the parse tree by COALESCE expressions, and the logic
for recognizing a partitionable join failed to match upper-level join
clauses to such expressions.  To fix, synthesize suitable COALESCE
expressions and add them to the nullable_partexprs lists.  This is
pretty ugly and brute-force, but it gets the job done.  (I have
ambitions of rethinking the way outer-join output Vars are
represented, so maybe that will provide a cleaner solution someday.
For now, do this.)

Amit Langote, reviewed by Justin Pryzby, Richard Guo, and myself

Discussion: https://postgr.es/m/CA+HiwqG2WVUGmLJqtR0tPFhniO=H=9qQ+Z3L_ZC+Y3-EVQHFGg@mail.gmail.com

5 years agoAllow partitionwise joins in more cases.
Etsuro Fujita [Wed, 8 Apr 2020 01:25:00 +0000 (10:25 +0900)]
Allow partitionwise joins in more cases.

Previously, the partitionwise join technique only allowed partitionwise
join when input partitioned tables had exactly the same partition
bounds.  This commit extends the technique to some cases when the tables
have different partition bounds, by using an advanced partition-matching
algorithm introduced by this commit.  For both the input partitioned
tables, the algorithm checks whether every partition of one input
partitioned table only matches one partition of the other input
partitioned table at most, and vice versa.  In such a case the join
between the tables can be broken down into joins between the matching
partitions, so the algorithm produces the pairs of the matching
partitions, plus the partition bounds for the join relation, to allow
partitionwise join for computing the join.  Currently, the algorithm
works for list-partitioned and range-partitioned tables, but not
hash-partitioned tables.  See comments in partition_bounds_merge().

Ashutosh Bapat and Etsuro Fujita, most of regression tests by Rajkumar
Raghuwanshi, some of the tests by Mark Dilger and Amul Sul, reviewed by
Dmitry Dolgov and Amul Sul, with additional review at various points by
Ashutosh Bapat, Mark Dilger, Robert Haas, Antonin Houska, Amit Langote,
Justin Pryzby, and Tomas Vondra

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

5 years agoFix circle_in to accept "(x,y),r" as it's advertised to do.
Tom Lane [Wed, 8 Apr 2020 00:50:02 +0000 (20:50 -0400)]
Fix circle_in to accept "(x,y),r" as it's advertised to do.

Our documentation describes four allowed input syntaxes for circles,
but the regression tests tried only three ... with predictable
consequences.  Remarkably, this has been wrong since the circle
datatype was added in 1997, but nobody noticed till now.

David Zhang, with some help from me

Discussion: https://postgr.es/m/332c47fa-d951-7574-b5cc-a8f7f7201202@highgo.ca

5 years agosnapshot scalability: Move delayChkpt from PGXACT to PGPROC.
Andres Freund [Wed, 8 Apr 2020 00:36:23 +0000 (17:36 -0700)]
snapshot scalability: Move delayChkpt from PGXACT to PGPROC.

The goal of separating hotly accessed per-backend data from PGPROC
into PGXACT is to make accesses fast (GetSnapshotData() in
particular). But delayChkpt is not actually accessed frequently; only
when starting a checkpoint. As it is frequently modified (multiple
times in the course of a single transaction), storing it in the same
cacheline as hotly accessed data unnecessarily dirties a contended
cacheline.

Therefore move delayChkpt to PGPROC.

This is part of a larger series of patches intending to improve
GetSnapshotData() scalability. It is committed and pushed separately,
as it is independently beneficial (small but measurable win, limited
by the other frequent modifications of PGXACT).

Author: Andres Freund
Reviewed-By: Robert Haas, Thomas Munro, David Rowley
Discussion: https://postgr.es/m/20200301083601[email protected]

5 years agoTrack SLRU page hits in SimpleLruReadPage_ReadOnly
Tomas Vondra [Wed, 8 Apr 2020 00:06:00 +0000 (02:06 +0200)]
Track SLRU page hits in SimpleLruReadPage_ReadOnly

SLRU page hits were tracked only in SimpleLruReadPage, but that's not
enough because we may hit the page in SimpleLruReadPage_ReadOnly in
which case we don't call SimpleLruReadPage at all.

Reported-by: Kuntal Ghosh
Discussion: https://postgr.es/m/20200119143707.gyinppnigokesjok@development

5 years agoFix XLogReader FD leak that makes backends unusable after 2PC usage.
Andres Freund [Tue, 7 Apr 2020 04:28:55 +0000 (21:28 -0700)]
Fix XLogReader FD leak that makes backends unusable after 2PC usage.

Before the fix every 2PC commit/abort leaked a file descriptor. As the
files are opened using BasicOpenFile(), that quickly leads to the
backend running out of file descriptors.

Once enough 2PC abort/commit have caused enough FDs to leak, any IO
in the backend will fail with "Too many open files", as
BasicOpenFilePerm() will have triggered all open files known to fd.c
to be closed.

The leak causing the problem at hand is a consequence of 0dc8ead46,
but is only exascerbated by it. Previously most XLogPageReadCB
callbacks used static variables to cache one open file, but after the
commit the cache is private to each XLogReader instance. There never
was infrastructure to close FDs at the time of XLogReaderFree, but the
way XLogReader was used limited the leak to one FD.

This commit just closes the during XLogReaderFree() if the FD is
stored in XLogReaderState.seg.ws_segno. This may not be the way to
solve this medium/long term, but at least unbreaks 2PC.

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

5 years agoAppease perlcritic
Alvaro Herrera [Tue, 7 Apr 2020 22:58:19 +0000 (18:58 -0400)]
Appease perlcritic

Food for the gods must always be found somehow, even when the land starves.

5 years agoRemove nbtree BTreeTupleSetAltHeapTID() function.
Peter Geoghegan [Tue, 7 Apr 2020 22:56:52 +0000 (15:56 -0700)]
Remove nbtree BTreeTupleSetAltHeapTID() function.

Since heap TID is supposed to be just another key attribute to the
implementation, it doesn't make much sense to have separate
BTreeTupleSetNAtts() and BTreeTupleSetAltHeapTID() functions.  Merge the
two functions together.  This slightly simplifies _bt_truncate().

5 years agoAllow users to limit storage reserved by replication slots
Alvaro Herrera [Tue, 7 Apr 2020 22:35:00 +0000 (18:35 -0400)]
Allow users to limit storage reserved by replication slots

Replication slots are useful to retain data that may be needed by a
replication system.  But experience has shown that allowing them to
retain excessive data can lead to the primary failing because of running
out of space.  This new feature allows the user to configure a maximum
amount of space to be reserved using the new option
max_slot_wal_keep_size.  Slots that overrun that space are invalidated
at checkpoint time, enabling the storage to be released.

Author: Kyotaro HORIGUCHI <[email protected]>
Reviewed-by: Masahiko Sawada <[email protected]>
Reviewed-by: Jehan-Guillaume de Rorthais <[email protected]>
Reviewed-by: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/20170228.122736.123383594[email protected]

5 years agoAllow psql's \g and \gx commands to transiently change \pset options.
Tom Lane [Tue, 7 Apr 2020 21:46:29 +0000 (17:46 -0400)]
Allow psql's \g and \gx commands to transiently change \pset options.

We invented \gx to allow the "\pset expanded" flag to be forced on
for the duration of one command output, but that turns out to not
be nearly enough to satisfy the demand for variant output formats.
Hence, make it possible to change any pset option(s) for the duration
of a single command output, by writing "option=value ..." inside
parentheses, for example
\g (format=csv csv_fieldsep='\t') somefile

\gx can now be understood as a shorthand for including expanded=on
inside the parentheses.

Patch by me, expanding on a proposal by Pavel Stehule

Discussion: https://postgr.es/m/CAFj8pRBx9OnBPRJVtfA5ycUpySge-XootAXAsv_4rrkHxJ8eRg@mail.gmail.com

5 years agoImplement waiting for given lsn at transaction start
Alexander Korotkov [Tue, 7 Apr 2020 20:51:10 +0000 (23:51 +0300)]
Implement waiting for given lsn at transaction start

This commit adds following optional clause to BEGIN and START TRANSACTION
commands.

  WAIT FOR LSN lsn [ TIMEOUT timeout ]

New clause pospones transaction start till given lsn is applied on standby.
This clause allows user be sure, that changes previously made on primary would
be visible on standby.

New shared memory struct is used to track awaited lsn per backend.  Recovery
process wakes up backend once required lsn is applied.

Author: Ivan Kartyshov, Anna Akenteva
Reviewed-by: Craig Ringer, Thomas Munro, Robert Haas, Kyotaro Horiguchi
Reviewed-by: Masahiko Sawada, Ants Aasma, Dmitry Ivanov, Simon Riggs
Reviewed-by: Amit Kapila, Alexander Korotkov
Discussion: https://postgr.es/m/0240c26c-9f84-30ea-fca9-93ab2df5f305%40postgrespro.ru