postgresql.git
2 years agoAdd missing fields to _outConstraint()
Peter Eisentraut [Sat, 13 Aug 2022 08:32:38 +0000 (10:32 +0200)]
Add missing fields to _outConstraint()

As of 897795240cfaaed724af2f53ed2c50c9862f951f, check constraints can
be declared invalid.  But that patch didn't update _outConstraint() to
also show the relevant struct fields (which were only applicable to
foreign keys before that).  This currently only affects debugging
output, so no impact in practice.

2 years agopg_upgrade: Fix some minor code issues
Peter Eisentraut [Fri, 12 Aug 2022 22:00:41 +0000 (00:00 +0200)]
pg_upgrade: Fix some minor code issues

96ef3b8ff1cf1950e897fd2f766d4bd9ef0d5d56 accidentally copied a not
applicable comment from the float8_pass_by_value code to the
data_checksums code.  Remove that.

87d3b35a1ca31a9d947a8f919a6006679216dff0 changed pg_upgrade to
checking the checksum version rather than just the Boolean presence of
checksums, but didn't change the field type in its ControlData struct
from bool.  So this would not work correctly if there ever is a
checksum version larger than 1.

2 years agopg_upgrade: Remove unused typedef
Peter Eisentraut [Fri, 12 Aug 2022 21:45:38 +0000 (23:45 +0200)]
pg_upgrade: Remove unused typedef

pgpid_t has been unused in pg_upgrade for a long time.

2 years agodoc: add missing role attributes to user management section
Bruce Momjian [Fri, 12 Aug 2022 19:43:23 +0000 (15:43 -0400)]
doc:  add missing role attributes to user management section

Reported-by: Shinya Kato
Discussion: https://postgr.es/m/1ecdb1ff78e9b03dfce37e85eaca725a@oss.nttdata.com

Author: Shinya Kato

Backpatch-through: 10

2 years agodoc: add section about heap-only tuples (HOT)
Bruce Momjian [Fri, 12 Aug 2022 19:05:13 +0000 (15:05 -0400)]
doc:  add section about heap-only tuples (HOT)

Reported-by: Jonathan S. Katz
Discussion: https://postgr.es/m/c59ffbd5-96ac-a5a5-a401-14f627ca1405@postgresql.org

Backpatch-through: 11

2 years agodoc: warn about security issues around log files
Bruce Momjian [Fri, 12 Aug 2022 16:02:21 +0000 (12:02 -0400)]
doc:  warn about security issues around log files

Reported-by: Simon Riggs
Discussion: https://postgr.es/m/CANP8+jJESuuXYq9Djvf-+tx2vY2OFLmfEuu+UvwHNJ1RT7iJCQ@mail.gmail.com

Author: Simon Riggs

Backpatch-through: 10

2 years agodoc: clarify configuration file for Windows builds
Bruce Momjian [Fri, 12 Aug 2022 15:35:23 +0000 (11:35 -0400)]
doc:  clarify configuration file for Windows builds

The use of file 'config.pl' was not clearly explained.

Reported-by: liambowen@gmail.com
Discussion: https://postgr.es/m/164246013804.31952.4958087335645367498@wrigleys.postgresql.org

Backpatch-through: 10

2 years agodoc: document the CREATE INDEX "USING" clause
Bruce Momjian [Fri, 12 Aug 2022 15:26:03 +0000 (11:26 -0400)]
doc:  document the CREATE INDEX "USING" clause

Somehow this was in the syntax but had no description.

Reported-by: robertcorrington@gmail.com
Discussion: https://postgr.es/m/164228771825.31954.2719791849363756957@wrigleys.postgresql.org

Backpatch-through: 10

2 years agodoc: clarify CREATE TABLE AS ... IF NOT EXISTS
Bruce Momjian [Fri, 12 Aug 2022 14:59:00 +0000 (10:59 -0400)]
doc:  clarify CREATE TABLE AS ... IF NOT EXISTS

Mention that the table is not modified if it already exists.

Reported-by: frank_limpert@yahoo.com
Discussion: https://postgr.es/m/164441177106.9677.5991676148704507229@wrigleys.postgresql.org

Backpatch-through: 10

2 years agodoc: improve wal_level docs for the 'minimal' level
Bruce Momjian [Fri, 12 Aug 2022 14:30:01 +0000 (10:30 -0400)]
doc:  improve wal_level docs for the 'minimal' level

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwZ24UcfkoyLLSW3PMGQATomOcw1nuYFRuMev-NoOF+mYw@mail.gmail.com

Author: David G. Johnston

Backpatch-through: 14, partial to 13

2 years agodoc: clarify DROP EXTENSION dependent members text
Bruce Momjian [Fri, 12 Aug 2022 13:06:48 +0000 (09:06 -0400)]
doc:  clarify DROP EXTENSION dependent members text

Member tracking was added in PG 13.

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwY1YtxQHVWUFYvSnOjZ5VPpXjF33V52bSKEwFjK2K=1Aw@mail.gmail.com

Author: David G. Johnston

Backpatch-through: 13

2 years agoAvoid using a fake relcache entry to own an SmgrRelation.
Robert Haas [Fri, 12 Aug 2022 12:25:41 +0000 (08:25 -0400)]
Avoid using a fake relcache entry to own an SmgrRelation.

If an error occurs before we close the fake relcache entry, the the
fake relcache entry will be destroyed by the SmgrRelation will
survive until end of transaction. Its smgr_owner pointer ends up
pointing to already-freed memory.

The original reason for using a fake relcache entry here was to try
to avoid reusing an SMgrRelation across a relevant invalidation. To
avoid that problem, just call smgropen() again each time we need a
reference to it. Hopefully someday we will come up with a more
elegant approach, but accessing uninitialized memory is bad so let's
do this for now.

Dilip Kumar, reviewed by Andres Freund and Tom Lane. Report by
Justin Pryzby.

Discussion: http://postgr.es/m/20220802175043.GA13682@telsasoft.com
Discussion: http://postgr.es/m/CAFiTN-vSFeE6_W9z698XNtFROOA_nSqUXWqLcG0emob_kJ+dEQ@mail.gmail.com

2 years agoMERGE docs adjustments
Alvaro Herrera [Fri, 12 Aug 2022 11:16:50 +0000 (13:16 +0200)]
MERGE docs adjustments

Per Justin Pryzby

Discussion: https://postgr.es/m/20220801145257.GA15006@telsasoft.com
Discussion: https://postgr.es/m/20220714162618.GH18011@telsasoft.com

2 years agoReject MERGE in CTEs and COPY
Alvaro Herrera [Fri, 12 Aug 2022 10:05:50 +0000 (12:05 +0200)]
Reject MERGE in CTEs and COPY

The grammar added for MERGE inadvertently made it accepted syntax in
places that were not prepared to deal with it -- namely COPY and inside
CTEs, but invoking these things with MERGE currently causes assertion
failures or weird misbehavior in non-assertion builds.  Protect those
places by checking for it explicitly until somebody decides to implement
it.

Reported-by: Alexey Borzov <borz_off@cs.msu.su>
Discussion: https://postgr.es/m/17579-82482cd7b267b862@postgresql.org

2 years agoFix _outConstraint() for "identity" constraints
Peter Eisentraut [Fri, 12 Aug 2022 06:17:30 +0000 (08:17 +0200)]
Fix _outConstraint() for "identity" constraints

The set of fields printed by _outConstraint() in the CONSTR_IDENTITY
case didn't match the set of fields actually used in that case.  (The
code was probably uncarefully copied from the CONSTR_DEFAULT case.)
Fix that by using the right set of fields.  Since there is no read
support for this node type, this is really just for debugging output
right now, so it doesn't affect anything important.

2 years agoFix non-specific error message.
Robert Haas [Thu, 11 Aug 2022 18:12:11 +0000 (14:12 -0400)]
Fix non-specific error message.

"something has gone wrong" is not helpful. Make this elog()
consistent with the other one in the same function.

Discussion: http://postgr.es/m/CA+Tgmoa_AZ2jUWSA_noiqOqnxBaWDR+t3bHjSygZi6+wqDBCXQ@mail.gmail.com

2 years agostruct PQWalReceiverFunctions: use designated initializers
Alvaro Herrera [Thu, 11 Aug 2022 10:07:05 +0000 (12:07 +0200)]
struct PQWalReceiverFunctions: use designated initializers

We now require that compilers support this, and it makes the code easier
to trace, so change it.  I'm fixated on this particular struct because
I've had to navigate around it a number of times, but there are others
elsewhere that could use the same treatment.

Discussion: https://postgr.es/m/20220810140300.ixhbmm4svo5yypv6@alvherre.pgsql

2 years agoAdd missing space in _outA_Const() output
Peter Eisentraut [Thu, 11 Aug 2022 08:35:39 +0000 (10:35 +0200)]
Add missing space in _outA_Const() output

Mistake introduced by 639a86e36aaecb84faaf941dcd0b183ba0aba9e9.

2 years agoFix catalog lookup with the wrong snapshot during logical decoding.
Amit Kapila [Thu, 11 Aug 2022 04:39:24 +0000 (10:09 +0530)]
Fix catalog lookup with the wrong snapshot during logical decoding.

Previously, we relied on HEAP2_NEW_CID records and XACT_INVALIDATION
records to know if the transaction has modified the catalog, and that
information is not serialized to snapshot. Therefore, after the restart,
if the logical decoding decodes only the commit record of the transaction
that has actually modified a catalog, we will miss adding its XID to the
snapshot. Thus, we will end up looking at catalogs with the wrong
snapshot.

To fix this problem, this change adds the list of transaction IDs and
sub-transaction IDs, that have modified catalogs and are running during
snapshot serialization, to the serialized snapshot. After restart or
otherwise, when we restore from such a serialized snapshot, the
corresponding list is restored in memory. Now, when decoding a COMMIT
record, we check both the list and the ReorderBuffer to see if the
transaction has modified catalogs.

Since this adds additional information to the serialized snapshot, we
cannot backpatch it. For back branches, we took another approach.
We remember the last-running-xacts list of the decoded RUNNING_XACTS
record after restoring the previously serialized snapshot. Then, we mark
the transaction as containing catalog changes if it's in the list of
initial running transactions and its commit record has
XACT_XINFO_HAS_INVALS. This doesn't require any file format changes but
the transaction will end up being added to the snapshot even if it has
only relcache invalidations. But that won't be a problem since we use
snapshot built during decoding only to read system catalogs.

This commit bumps SNAPBUILD_VERSION because of a change in SnapBuild.

Reported-by: Mike Oh
Author: Masahiko Sawada
Reviewed-by: Amit Kapila, Shi yu, Takamichi Osumi, Kyotaro Horiguchi, Bertrand Drouvot, Ahsan Hadi
Backpatch-through: 10
Discussion: https://postgr.es/m/81D0D8B0-E7C4-4999-B616-1E5004DBDCD2%40amazon.com

2 years agoOptimize xid/subxid searches in XidInMVCCSnapshot().
John Naylor [Wed, 3 Aug 2022 16:59:28 +0000 (09:59 -0700)]
Optimize xid/subxid searches in XidInMVCCSnapshot().

As reported by Yura Sokolov, scanning the snapshot->xip array has
noticeable impact on scalability when there are a large number of
concurrent writers. Use the optimized (on x86-64) routine from b6ef16756
to speed up searches through the [sub]xip arrays. One benchmark showed
a 5% increase in transaction throughput with 128 concurrent writers,
and a 50% increase in a pathological case of 1024 writers. While a hash
table would have scaled even better, it was ultimately rejected because
of concerns around code complexity and memory allocation. Credit to Andres
Freund for the idea to optimize linear search using SIMD instructions.

Nathan Bossart

Reviewed by: Andres Freund, John Naylor, Bharath Rupireddy, Masahiko Sawada
Discussion: https://postgr.es/m/20220713170950.GA3116318%40nathanxps13

2 years agoMove basebackup code to new directory src/backend/backup
Robert Haas [Wed, 10 Aug 2022 18:03:23 +0000 (14:03 -0400)]
Move basebackup code to new directory src/backend/backup

Reviewed by David Steele and Justin Pryzby

Discussion: http://postgr.es/m/CA+TgmoafqboATDSoXHz8VLrSwK_MDhjthK4hEpYjqf9_1Fmczw%40mail.gmail.com

2 years agoFix handling of R/W expanded datums that are passed to SQL functions.
Tom Lane [Wed, 10 Aug 2022 17:37:25 +0000 (13:37 -0400)]
Fix handling of R/W expanded datums that are passed to SQL functions.

fmgr_sql must make expanded-datum arguments read-only, because
it's possible that the function body will pass the argument to
more than one callee function.  If one of those functions takes
the datum's R/W property as license to scribble on it, then later
callees will see an unexpected value, leading to wrong answers.

From a performance standpoint, it'd be nice to skip this in the
common case that the argument value is passed to only one callee.
However, detecting that seems fairly hard, and certainly not
something that I care to attempt in a back-patched bug fix.

Per report from Adam Mackler.  This has been broken since we
invented expanded datums, so back-patch to all supported branches.

Discussion: https://postgr.es/m/WScDU5qfoZ7PB2gXwNqwGGgDPmWzz08VdydcPFLhOwUKZcdWbblbo-0Lku-qhuEiZoXJ82jpiQU4hOjOcrevYEDeoAvz6nR0IU4IHhXnaCA=@mackler.email
Discussion: https://postgr.es/m/187436.1660143060@sss.pgh.pa.us

2 years agoFix typo in test_oat_hooks README
Daniel Gustafsson [Wed, 10 Aug 2022 11:49:48 +0000 (13:49 +0200)]
Fix typo in test_oat_hooks README

Discussion: https://postgr.es/m/3F066AFE-19F9-4DF5-A498-B09643857A39@yesql.se

2 years agoImprove the protocol message descriptions for 2PC logical replication.
Amit Kapila [Wed, 10 Aug 2022 11:11:31 +0000 (16:41 +0530)]
Improve the protocol message descriptions for 2PC logical replication.

The messages were using 'two-phase transaction' at some places and
'prepared transaction' at other places. Make them consistently use
'prepared transaction'.

Reported-by: Ekaterina Kiryanova
Author: Peter Smith
Reviewed by: Amit Kapila
Backpatch-through: 15
Discussion: https://postgr.es/m/745414e7-efb2-a6ae-5b83-fcbdf35aabc8@postgrespro.ru

2 years agoRemove unused short option from getopt_long() call
Peter Eisentraut [Wed, 10 Aug 2022 09:02:32 +0000 (12:02 +0300)]
Remove unused short option from getopt_long() call

The option was removed in 3ce7f72529 but the letter was left in the
getopt_long() call.

2 years agoIntroduce optimized routine for linear searches of arrays
John Naylor [Wed, 3 Aug 2022 16:49:04 +0000 (09:49 -0700)]
Introduce optimized routine for linear searches of arrays

Use SSE2 intrinsics to speed up the search, where available.  Otherwise,
use a simple 'for' loop.  The motivation to add this now is to speed up
XidInMVCCSnapshot(), which is the reason only unsigned 32-bit integer
arrays are optimized. Other types are left for future work, as is the
extension of this technique to non-x86 platforms.

Nathan Bossart

Reviewed by: Andres Freund, Bharath Rupireddy, Masahiko Sawada
Discussion: https://postgr.es/m/20220713170950.GA3116318%40nathanxps13

2 years agodoc: mention that COPY MATCH requires columns _in_ _order_
Bruce Momjian [Wed, 10 Aug 2022 00:37:53 +0000 (20:37 -0400)]
doc: mention that COPY MATCH requires columns _in_ _order_

Question asked at SCaLE conference.

Reported-by: doc suggestion by Stephen Frost
Backpatch-through: 15

2 years agoFix some inconsistencies with GUC categories
Michael Paquier [Tue, 9 Aug 2022 11:01:44 +0000 (20:01 +0900)]
Fix some inconsistencies with GUC categories

This commit addresses a few things around GUCs:
- The TCP-related parameters (the four tcp_keepalives_* and
client_connection_check_interval are listed in postgresql.conf.sample in
a subsection called "TCP settings" of "CONNECTIONS AND AUTHENTICATION",
but they did not have their own group name in guc.c.
- enable_group_by_reordering, stats_fetch_consistency and
recovery_prefetch had an inconsistent description, missing a dot at the
end.
- In postgresql.conf.sample, "Process title" should not have a section
of its own, but it should be a subsection of "REPORTING AND LOGGING".

This impacts the contents of pg_settings, which could be seen as a
compatibility break, so no backpatch is done.  This is similar to the
cleanup done in a55a984.

Author: Shinya Kato
Discussion: https://postgr.es/m/5e0c9c608624eafbba910c344282cb14@oss.nttdata.com

2 years agoFix mismatched file identifications
John Naylor [Tue, 9 Aug 2022 02:21:37 +0000 (09:21 +0700)]
Fix mismatched file identifications

Masahiko Sawada
Discussion: https://www.postgresql.org/message-id/CAD21AoASq93KPiNxipPaTCzEdsnxT9665UesOnWcKhmX9Qfx6A@mail.gmail.com

2 years agoFix obsolete comment in commit_ts.c.
Thomas Munro [Tue, 9 Aug 2022 00:55:45 +0000 (12:55 +1200)]
Fix obsolete comment in commit_ts.c.

Commit 08aa89b removed COMMIT_TS_SETTS, but left a reference in a
comment.

Author: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://postgr.es/m/20220726173343.GA154110%40nathanxps13

2 years agoFix obsolete comments in instr_time.h.
Thomas Munro [Mon, 8 Aug 2022 23:50:03 +0000 (11:50 +1200)]
Fix obsolete comments in instr_time.h.

Commit 623cc673 removed gettimeofday(), and commits 24c3ce8f and
495ed0ef removed support for very old Windows releases with low accuracy
timers, but references to those things were left behind in comments.

Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/295419.1659918447%40sss.pgh.pa.us

2 years agoFix MSVC build script's check for obsolete node support functions.
Tom Lane [Mon, 8 Aug 2022 18:43:35 +0000 (14:43 -0400)]
Fix MSVC build script's check for obsolete node support functions.

Commit 964d01ae9 was a few bricks shy of a load here: the script
checked whether gen_node_support.pl itself had been updated since it
was last run, but not whether any of its input files had been updated.
Fix that.  While here, scrape the list of input files from the
Makefiles rather than having a duplicate copy, as we do for most
other lists of source files.

In passing, improve gen_node_support.pl's error report for an
incorrect file list.

Per gripe from Amit Kapila.

Discussion: https://postgr.es/m/CAA4eK1KQk4vP-3mTAz26h-PRUZaGu8Fc=q-ZKSajsAthH0A15w@mail.gmail.com

2 years agoStabilize output of new regression test.
Tom Lane [Mon, 8 Aug 2022 16:16:01 +0000 (12:16 -0400)]
Stabilize output of new regression test.

Per buildfarm, the output order of \dx+ isn't consistent across
locales.  Apply NO_LOCALE to force C locale.  There might be a
more localized way, but I'm not seeing it offhand, and anyway
there is nothing in this test module that particularly cares
about locales.

Security: CVE-2022-2625

2 years agoIn extensions, don't replace objects not belonging to the extension.
Tom Lane [Mon, 8 Aug 2022 15:12:31 +0000 (11:12 -0400)]
In extensions, don't replace objects not belonging to the extension.

Previously, if an extension script did CREATE OR REPLACE and there was
an existing object not belonging to the extension, it would overwrite
the object and adopt it into the extension.  This is problematic, first
because the overwrite is probably unintentional, and second because we
didn't change the object's ownership.  Thus a hostile user could create
an object in advance of an expected CREATE EXTENSION command, and would
then have ownership rights on an extension object, which could be
modified for trojan-horse-type attacks.

Hence, forbid CREATE OR REPLACE of an existing object unless it already
belongs to the extension.  (Note that we've always forbidden replacing
an object that belongs to some other extension; only the behavior for
previously-free-standing objects changes here.)

For the same reason, also fail CREATE IF NOT EXISTS when there is
an existing object that doesn't belong to the extension.

Our thanks to Sven Klemm for reporting this problem.

Security: CVE-2022-2625

2 years agoaix: fix misreading of condition in 8f12a4e7add
Andres Freund [Sun, 7 Aug 2022 18:34:42 +0000 (11:34 -0700)]
aix: fix misreading of condition in 8f12a4e7add

This lead to choosing the aix4.1 specific way of building the export file for
the backend, rather than the modern one.

Per buildfarm member hoverfly.

Discussion: https://postgr.es/m/20220807182707.gi7pirwbz5etprfo@awork3.anarazel.de

2 years agoTrust a few system headers to stand on their own
Andres Freund [Sun, 7 Aug 2022 16:36:01 +0000 (09:36 -0700)]
Trust a few system headers to stand on their own

At some point in the past some headers (net/if.h on some BSDs in 2009,
netinet/tcp.h on IRIX in 2000, sys/ucred.h in 2013 on then older openbsd),
only compiled if other heades were included first, complicating configure
tests. More recent tests indicate that that's not required anymore.

Reviewed-By: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/20220807012914.ydz73yte6j3coulo@awork3.anarazel.de

2 years agosolaris: Remove unnecessary gcc / gnu ld vs sun studio differences
Andres Freund [Sun, 7 Aug 2022 16:36:01 +0000 (09:36 -0700)]
solaris: Remove unnecessary gcc / gnu ld vs sun studio differences

Unfortunately one with_gnu_ld reference remains, otherwise we could remove the
configure support for determining with_gnu_ld.

Reviewed-By: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/20220807012914.ydz73yte6j3coulo@awork3.anarazel.de

2 years agoaix: Remove checks for very old OS versions
Andres Freund [Sun, 7 Aug 2022 16:36:01 +0000 (09:36 -0700)]
aix: Remove checks for very old OS versions

Reviewed-By: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/20220807012914.ydz73yte6j3coulo@awork3.anarazel.de

2 years agowindows: Remove HAVE_MINIDUMP_TYPE test
Andres Freund [Sun, 7 Aug 2022 16:36:01 +0000 (09:36 -0700)]
windows: Remove HAVE_MINIDUMP_TYPE test

We've relied on it being present for msvc for ages...

Reviewed-By: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/20220807012914.ydz73yte6j3coulo@awork3.anarazel.de

2 years agoRely on __func__ being supported
Andres Freund [Sun, 7 Aug 2022 16:36:01 +0000 (09:36 -0700)]
Rely on __func__ being supported

Previously we fell back to __FUNCTION__ and then NULL. As __func__ is in C99
that shouldn't be necessary anymore.

Solution.pm defined HAVE_FUNCNAME__FUNCTION instead of
HAVE_FUNCNAME__FUNC (originating in 4164e6636e2), as at some point in the past
MSVC only supported __FUNCTION__. Our minimum version supports __func__.

Reviewed-By: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/20220807012914.ydz73yte6j3coulo@awork3.anarazel.de

2 years agoRemove unportable use of timezone in recent test
Alvaro Herrera [Sun, 7 Aug 2022 08:19:40 +0000 (10:19 +0200)]
Remove unportable use of timezone in recent test

Per buildfarm member snapper

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

2 years agoSimplify replacement code for strtof.
Thomas Munro [Sun, 7 Aug 2022 00:42:11 +0000 (12:42 +1200)]
Simplify replacement code for strtof.

strtof() is in C99 and all targeted systems have it.  We can remove the
configure probe and some dead code, but we still need replacement code
for a couple of systems that have known buggy implementations selected
via platform template.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/152683.1659830125%40sss.pgh.pa.us

2 years agoSimplify gettimeofday for Windows.
Thomas Munro [Sun, 7 Aug 2022 00:35:11 +0000 (12:35 +1200)]
Simplify gettimeofday for Windows.

Previously we bothered to forward-declare struct timezone, following man
pages on typical systems, but POSIX actually says the argument (which we
ignore anyway) is void *.  Drop a line.

While here, add an assertion that nobody actually uses the tzp argument.

Previously we did extra work to select between Windows APIs needed on
older releases, but now we can just use the higher resolution function
directly.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CA%2BhUKGKwRpvGfcfq2qNVAQS2Wg1B9eA9QRhAmVSyJt1zsCN2sQ%40mail.gmail.com

2 years agoFix function-defined-but-not-used warning.
Tom Lane [Sat, 6 Aug 2022 17:32:29 +0000 (13:32 -0400)]
Fix function-defined-but-not-used warning.

Buildfarm member jacana (MinGW) has been complaining that
get_iso_localename is defined but not used.  This is evidently
fallout from the recent removal of VS2013 support in pg_locale.c.
Rearrange the #ifs so that get_iso_localename and its subroutine
search_locale_enum won't get built on MinGW.

I also noticed that a comment in get_iso_localename cross-
referenced a comment in IsoLocaleName that isn't there anymore.
Put back what I think is the referenced material.

2 years agoFix data-corruption hazard in WAL-logged CREATE DATABASE.
Tom Lane [Sat, 6 Aug 2022 15:50:23 +0000 (11:50 -0400)]
Fix data-corruption hazard in WAL-logged CREATE DATABASE.

RelationCopyStorageUsingBuffer thought it could skip copying
empty pages, but of course that does not work at all, because
subsequent blocks will be out of place.

Also fix it to acquire share lock on the source buffer.  It *might*
be safe to not do that, but it's not very certain, and I don't think
this code deserves any benefit of the doubt.

Dilip Kumar, per complaint from me

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

2 years agoSimplify gettimeofday() fallback logic.
Andres Freund [Sat, 6 Aug 2022 15:34:56 +0000 (08:34 -0700)]
Simplify gettimeofday() fallback logic.

There's no known supported system needing 1 argument gettimeofday()
support. The test for it was added a long time ago (92c6bf9775b). Remove.

Until now we tested whether a gettimeofday() fallback is needed when
targetting windows. Which lead to the odd result that HAVE_GETTIMEOFDAY only
being defined when targetting MinGW (which has gettimeofday() since at least
2007). As the fallback is specific to msvc, remove the configure code and
rename src/port/gettimeofday.c to src/port/win32gettimeofday.c.

While at it, also remove the definition of struct timezone, a forward
declaration of the struct is sufficient.

Reviewed-By: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-By: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/20220806000311.ywx65iuchvj4qn2k@awork3.anarazel.de

2 years agoImprove recently-added test reliability
Alvaro Herrera [Sat, 6 Aug 2022 13:52:10 +0000 (15:52 +0200)]
Improve recently-added test reliability

Commit 59be1c942a47 already tried to make
src/test/recovery/t/033_replay_tsp_drops more reliable, but it wasn't
enough.  Try to improve on that by making this use of a replication slot
to be more like others.  Also, don't drop the slot.

Make a few other stylistic changes while at it.  It's still quite slow,
which is another thing that we need to fix in this script.

Backpatch to all supported branches.

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

2 years agoFix comment in copyfrom_internal.h
Michael Paquier [Sat, 6 Aug 2022 12:13:45 +0000 (21:13 +0900)]
Fix comment in copyfrom_internal.h

COPY_NEW_FE has become COPY_FRONTEND in 3174d69, that has removed the
frontend-backend protocol v2.

Author: Zhang Mingli
Discussion: https://postgr.es/m/aeec12a3-501e-449a-8d25-901c4ff706cf@Spark

2 years agoReplace pgwin32_is_junction() with lstat().
Thomas Munro [Sat, 6 Aug 2022 00:02:43 +0000 (12:02 +1200)]
Replace pgwin32_is_junction() with lstat().

Now that lstat() reports junction points with S_IFLNK/S_ISLINK(), and
unlink() can unlink them, there is no need for conditional code for
Windows in a few places.  That was expressed by testing for WIN32 or
S_ISLNK, which we can now constant-fold.

The coding around pgwin32_is_junction() was a bit suspect anyway, as we
never checked for errors, and we also know that errors can be spuriously
reported because of transient sharing violations on this OS.  The
lstat()-based code has handling for that.

This also reverts 4fc6b6ee on master only.  That was done because
lstat() didn't previously work for symlinks (junction points), but now
it does.

Tested-by: Andrew Dunstan <andrew@dunslane.net>
Discussion: https://postgr.es/m/CA%2BhUKGLfOOeyZpm5ByVcAt7x5Pn-%3DxGRNCvgiUPVVzjFLtnY0w%40mail.gmail.com

2 years agoMake unlink() work for junction points on Windows.
Thomas Munro [Sat, 6 Aug 2022 00:01:42 +0000 (12:01 +1200)]
Make unlink() work for junction points on Windows.

To support harmonization of Windows and Unix code, teach our unlink()
wrapper that junction points need to be unlinked with rmdir() on
Windows.

Tested-by: Andrew Dunstan <andrew@dunslane.net>
Discussion: https://postgr.es/m/CA%2BhUKGLfOOeyZpm5ByVcAt7x5Pn-%3DxGRNCvgiUPVVzjFLtnY0w%40mail.gmail.com

2 years agoProvide lstat() for Windows.
Thomas Munro [Sat, 6 Aug 2022 00:00:57 +0000 (12:00 +1200)]
Provide lstat() for Windows.

Junction points will be reported with S_ISLNK(x.st_mode), simulating
POSIX lstat().  stat() will follow pseudo-symlinks, like in POSIX (but
only one level before giving up, unlike in POSIX).

This completes a TODO left by commit bed90759fcb.

Tested-by: Andrew Dunstan <andrew@dunslane.net> (earlier version)
Discussion: https://postgr.es/m/CA%2BhUKGLfOOeyZpm5ByVcAt7x5Pn-%3DxGRNCvgiUPVVzjFLtnY0w%40mail.gmail.com

2 years agoRemove fallbacks for strtoll, strtoull.
Thomas Munro [Fri, 5 Aug 2022 21:59:45 +0000 (09:59 +1200)]
Remove fallbacks for strtoll, strtoull.

strtoll was backfilled with either __strtoll or strtoq on systems without
strtoll. The last such system on the buildfarm was an ancient HP-UX animal. We
don't support HP-UX anymore, so remove.

On other systems strtoll was present, but did not have a declaration. The last
known instance on the buildfarm was running an ancient OSX and shut down in
2019.

Author: Andres Freund <andres@anarazel.de>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/20220804013546.h65najrzig764jar@awork3.anarazel.de

2 years agoFix comments about deduplication updating page.
Peter Geoghegan [Fri, 5 Aug 2022 21:25:49 +0000 (14:25 -0700)]
Fix comments about deduplication updating page.

nbtree deduplication passes add tuples from the original/target page to
a temp page, merging as necessary.  The temp page is copied back to the
target permanent page in the critical section.  This is similar to the
approach taken by nbtree page splits.

Adjust comments that referred to updating the original page in-place as
tuples were merged.  These were left over from earlier versions of the
deduplication patch that didn't yet use a temp page.

2 years agoAdd missing parenthesis to max item size macro.
Peter Geoghegan [Fri, 5 Aug 2022 20:06:19 +0000 (13:06 -0700)]
Add missing parenthesis to max item size macro.

Oversight in commit 92f37505, per buildfarm.

2 years agoPartially undo commit 94da73281.
Tom Lane [Fri, 5 Aug 2022 19:57:46 +0000 (15:57 -0400)]
Partially undo commit 94da73281.

On closer inspection, mcv.c isn't as broken for ScalarArrayOpExpr
as I thought.  The Var-on-right issue is real enough, but actually
it does cope fine with a NULL array constant --- I was misled by
an XXX comment suggesting it didn't.  Undo that part of the code
change, and replace the XXX comment with something less misleading.

2 years agoFix handling of bare boolean expressions in mcv_get_match_bitmap.
Tom Lane [Fri, 5 Aug 2022 19:00:03 +0000 (15:00 -0400)]
Fix handling of bare boolean expressions in mcv_get_match_bitmap.

Since v14, the extended stats machinery will try to estimate for
otherwise-unsupported boolean expressions if they match an expression
available from an extended stats object.  mcv.c did not get the memo
about this, and would spit up with "unknown clause type".  Fortunately
the case is easy to handle, since we can expect the expression yields
boolean.

While here, replace some not-terribly-on-point assertions with
simpler runtime tests for lookup failure.  That seems appropriate
so that we get an elog not a crash if we somehow get to the new
it-should-be-a-bool-expression code with a subexpression that
doesn't match any stats column.

Per report from Danny Shemesh.  Thanks to Justin Pryzby for
preliminary investigation.

Discussion: https://postgr.es/m/CAFZC=QqD6=27wQPOW1pbRa98KPyuyn+7cL_Ay_Ck-roZV84vHg@mail.gmail.com

2 years agoFix non-bulletproof ScalarArrayOpExpr code for extended statistics.
Tom Lane [Fri, 5 Aug 2022 17:58:37 +0000 (13:58 -0400)]
Fix non-bulletproof ScalarArrayOpExpr code for extended statistics.

statext_is_compatible_clause_internal() checked that the arguments
of a ScalarArrayOpExpr are one Var and one Const, but it would allow
cases where the Const was on the left.  Subsequent uses of the clause
are not expecting that and would suffer assertion failures or core
dumps.  mcv.c also had not bothered to cope with the case of a NULL
array constant, which seems really unacceptably sloppy of somebody.
(Although our tools failed us there too, since AFAIK neither Coverity
nor any compiler warned of the obvious use-of-uninitialized-variable
condition.)  It seems best to handle that by having
statext_is_compatible_clause_internal() reject it.

Noted while fixing bug #17570.  Back-patch to v13 where the
extended stats code grew some awareness of ScalarArrayOpExpr.

2 years agoBackpatch addition of .git-blame-ignore-revs
Alvaro Herrera [Fri, 5 Aug 2022 17:36:24 +0000 (19:36 +0200)]
Backpatch addition of .git-blame-ignore-revs

This makes it more convenient for git config to contain the
blame.ignoreRevsFile setting; otherwise current git versions complain if
the file is not present.

I constructed the file for each branch by scraping the file in branch
master for commits that appear in that branch.  Because a few additional
pgindent commits have been added to the list in master since the list
was first created, this also propagates those to branches 14 and 15
where the file already existed.  Also, some entries appear to have been
made using author-date rather than committer-date in the format string,
so some timestamps are changed.  Also remove bogus whitespace in the
suggested `git log` format string.

Backpatch to all supported branches.

Discussion: https://postgr.es/m/20220711163138.o72evdeus5f5yy5z@alvherre.pgsql

2 years agoFix incorrect permissions-checking code for extended statistics.
Tom Lane [Fri, 5 Aug 2022 16:46:34 +0000 (12:46 -0400)]
Fix incorrect permissions-checking code for extended statistics.

Commit a4d75c86b improved the extended-stats logic to allow extended
stats to be collected on expressions not just bare Vars.  To apply
such stats, we first verify that the user has permissions to read all
columns used in the stats.  (If not, the query will likely fail at
runtime, but the planner ought not do so.)  That had to get extended
to check permissions of columns appearing within such expressions,
but the code for that was completely wrong: it applied pull_varattnos
to the wrong pointer, leading to "unrecognized node type" failures.
Furthermore, although you couldn't get to this because of that bug,
it failed to account for the attnum offset applied by pull_varattnos.

This escaped recognition so far because the code in question is not
reached when the user has whole-table SELECT privilege (which is the
common case), and because only subexpressions not specially handled
by statext_is_compatible_clause_internal() are at risk.

I think a large part of the reason for this bug is under-documentation
of what statext_is_compatible_clause() is doing and what its arguments
are, so do some work on the comments to try to improve that.

Per bug #17570 from Alexander Kozhemyakin.  Patch by Richard Guo;
comments and other cosmetic improvements by me.  (Thanks also to
Japin Li for diagnosis.)  Back-patch to v14 where the bug came in.

Discussion: https://postgr.es/m/17570-f2f2e0f4bccf0965@postgresql.org

2 years agoBRIN: mask BRIN_EVACUATE_PAGE for WAL consistency checking
Alvaro Herrera [Fri, 5 Aug 2022 16:00:17 +0000 (18:00 +0200)]
BRIN: mask BRIN_EVACUATE_PAGE for WAL consistency checking

That bit is unlogged and therefore it's wrong to consider it in WAL page
comparison.

Add a test that tickles the case, as branch testing technology allows.

This has been a problem ever since wal consistency checking was
introduced (commit a507b86900f6 for pg10), so backpatch to all supported
branches.

Author: 王海洋 (Haiyang Wang) <wanghaiyang.001@bytedance.com>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Discussion: https://postgr.es/m/CACciXAD2UvLMOhc4jX9VvOKt7DtYLr3OYRBhvOZ-jRxtzc_7Jg@mail.gmail.com
Discussion: https://postgr.es/m/CACciXADOfErX9Bx0nzE_SkdfXr6Bbpo5R=v_B6MUTEYW4ya+cg@mail.gmail.com

2 years agoBe more prescriptive in new doc about re-archiving of same WAL file.
Noah Misch [Fri, 5 Aug 2022 15:30:55 +0000 (08:30 -0700)]
Be more prescriptive in new doc about re-archiving of same WAL file.

Nathan Bossart, reviewed by David Steele.

Discussion: https://postgr.es/m/20220731065156.GA3694276@rfd.leadboat.com

2 years agoregress: fix test instability
Alvaro Herrera [Fri, 5 Aug 2022 09:55:52 +0000 (11:55 +0200)]
regress: fix test instability

Having additional triggers in a test table made the ORDER BY clauses in
old queries underspecified.  Add another column there for stability.

Per sporadic buildfarm pink.

2 years agoSimplify coding style of is_valid_ascii()
John Naylor [Fri, 5 Aug 2022 06:07:31 +0000 (13:07 +0700)]
Simplify coding style of is_valid_ascii()

Calculate end of input rather than maintaining length,
per prior suggestion from Heikki Linnakangas. In passing,
use more natural language in a comment.

Discussion: https://www.postgresql.org/message-id/b4648cc2-5e9c-c93a-52cc-51e5c658a4f6%40iki.fi

2 years agopostgres_fdw: Disable batch insertion when there are WCO constraints.
Etsuro Fujita [Fri, 5 Aug 2022 08:15:00 +0000 (17:15 +0900)]
postgres_fdw: Disable batch insertion when there are WCO constraints.

When inserting a view referencing a foreign table that has WITH CHECK
OPTION constraints, in single-insert mode postgres_fdw retrieves the
data that was actually inserted on the remote side so that the WITH
CHECK OPTION constraints are enforced with the data locally, but in
batch-insert mode it cannot currently retrieve the data (except for the
row first inserted through the view), resulting in enforcing the WITH
CHECK OPTION constraints with the data passed from the core (except for
the first-inserted row), which led to incorrect results when inserting
into a view referencing a foreign table in which a remote BEFORE ROW
INSERT trigger changes the rows inserted through the view so that they
violate the view's WITH CHECK OPTION constraint.  Also, the query
inserting into the view caused an assertion failure in assert-enabled
builds.

Fix these by disabling batch insertion when inserting into such a view.

Back-patch to v14 where batch insertion was added.

Discussion: https://postgr.es/m/CAPmGK17LpbTZs4m4a_6THP54UBeK9fHvX8aVVA%2BC6yEZDZwQcg%40mail.gmail.com

2 years agoFix ENABLE/DISABLE TRIGGER to handle recursion correctly
Alvaro Herrera [Thu, 4 Aug 2022 18:02:02 +0000 (20:02 +0200)]
Fix ENABLE/DISABLE TRIGGER to handle recursion correctly

Using ATSimpleRecursion() in ATPrepCmd() to do so as bbb927b4db9b did is
not correct, because ATPrepCmd() can't distinguish between triggers that
may be cloned and those that may not, so would wrongly try to recurse
for the latter category of triggers.

So this commit restores the code in EnableDisableTrigger() that
86f575948c77 had added to do the recursion, which would do it only for
triggers that may be cloned, that is, row-level triggers.  This also
changes tablecmds.c such that ATExecCmd() is able to pass the value of
ONLY flag down to EnableDisableTrigger() using its new 'recurse'
parameter.

This also fixes what seems like an oversight of 86f575948c77 that the
recursion to partition triggers would only occur if EnableDisableTrigger()
had actually changed the trigger.  It is more apt to recurse to inspect
partition triggers even if the parent's trigger didn't need to be
changed: only then can we be certain that all descendants share the same
state afterwards.

Backpatch all the way back to 11, like bbb927b4db9b.  Care is taken not
to break ABI compatibility (and that no catversion bump is needed.)

Co-authored-by: Amit Langote <amitlangote09@gmail.com>
Reviewed-by: Dmitry Koval <d.koval@postgrespro.ru>
Discussion: https://postgr.es/m/CA+HiwqG-cZT3XzGAnEgZQLoQbyfJApVwOTQaCaas1mhpf+4V5A@mail.gmail.com

2 years agoRemove configure probe for fdatasync.
Thomas Munro [Fri, 5 Aug 2022 04:10:05 +0000 (16:10 +1200)]
Remove configure probe for fdatasync.

fdatasync() is in SUSv2, and all targeted Unix systems have it.  We have
a replacement function for Windows.

We retain the probe for the function declaration, which allows us to
supply the mysteriously missing declaration for macOS, and also for
Windows.  No need to keep a HAVE_FDATASYNC macro around.

Also rename src/port/fdatasync.c to win32fdatasync.c since it's only for
Windows.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com
Discussion: https://postgr.es/m/CA%2BhUKGJZJVO%3DiX%2Beb-PXi2_XS9ZRqnn_4URh0NUQOwt6-_51xQ%40mail.gmail.com

2 years agoRemove configure probe for clock_gettime.
Thomas Munro [Fri, 5 Aug 2022 03:56:36 +0000 (15:56 +1200)]
Remove configure probe for clock_gettime.

clock_gettime() is in SUSv2 and all targeted Unix systems have it.
Remove a chunk of fallback code for old Unix is no longer reachable on
modern systems, and untested as of the retirement of build farm animal
prairiedog.

There is no need to retain a HAVE_CLOCK_GETTIME macro here, because it
is already used in a context with Unix and Windows code paths.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoFix nbtree maximum item size macro.
Peter Geoghegan [Fri, 5 Aug 2022 03:55:02 +0000 (20:55 -0700)]
Fix nbtree maximum item size macro.

Commit dd299df8189, which made heap TID a tiebreaker nbtree index
column, introduced new rules on page space management to make suffix
truncation safe for v4+ indexes.  New pivot tuples (generated by suffix
truncation during leaf page splits) sometimes require dedicated extra
space at the end of a new leaf page high key/pivot to store a heap TID
using a special representation (a representation only used in pivot
tuples).

The definition of "1/3 of a page" was reduced by a single MAXALIGN()
quantum for v4 indexes to make sure that the final enlarged pivot tuple
always fit, even with a split point whose firstright tuple happened to
already be at the "1/3 of a page" limit (limit for non-pivot tuples).
Internal pages (which only contain pivot tuples) stuck with the original
"1/3 of a page" definition.  This scheme made it impossible for any page
split to fail to free enough space for its newitem, which is never okay.

The macro that determines whether non-pivot tuples exceed their "1/3 of
a leaf page" restriction was structured as if space was needed for all
three tuples during a leaf page split (the new pivot plus two very large
adjoining non-pivots that are separated by the split).  This was subtly
wrong, in that it accidentally relied on implementation details that
could (at least in theory) change in the future.

To fix, make the macro subtract a single MAXALIGN() quantum, once.  The
macro evaluates to exactly the same value as before in practice.  But it
no longer depends on the current layout of nbtree's special area struct.

No backpatch, since this isn't a live bug.

Author: Peter Geoghegan <pg@bowt.ie>
Reported-By: Robert Haas <robertmhaas@gmail.com>
Diagnosed-By: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/CA+Tgmoa7UBxivM7f6Ocx_qbq4=ky3uXc+WZNOBcVX+kvJvWOEA@mail.gmail.com

2 years agoSimplify replacement code for preadv and pwritev.
Thomas Munro [Thu, 4 Aug 2022 23:43:14 +0000 (11:43 +1200)]
Simplify replacement code for preadv and pwritev.

preadv() and pwritev() are not standardized by POSIX, but appeared in
NetBSD in 1999 and were adopted by at least OpenBSD, FreeBSD,
DragonFlyBSD, Linux, AIX, illumos and macOS.  We don't use them much
yet, but an active proposal uses them heavily.

In 15, we had two replacement implementations for other OSes: one based
on lseek() + -v function if available for true vector I/O, and the other
based on a loop over p- function.

The former would be an obstacle to hypothetical future multi-threaded
code sharing file descriptors, while the latter would not, since commit
cf112c12.  Furthermore, the number of targeted systems that could
benefit from the former's potential upside has dwindled to just one
niche OS, since macOS added the functions and we de-supported HP-UX.
That doesn't seem like a good trade-off.

Therefore, drop the lseek()-based variant, and also the pg_ prefix now
that the file position portability hazard is gone.

At the time of writing, the only systems in our build farm that lack
native preadv/pwritev and thus use fallback code are:

 * Solaris (but not illumos)
 * macOS before release 11.0
 * Windows

With this commit, the above systems will now use the *same* fallback
code, the version that loops over pread()/pwrite().  Windows already
used that (though a later proposal may include true vector I/O for
Windows), so this decision really only affects Solaris, until it gets
around to adding these system calls.

Also remove some useless includes while here.

Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoMake consistent a couple of log messages when parsing HBA files
Michael Paquier [Fri, 5 Aug 2022 00:50:27 +0000 (09:50 +0900)]
Make consistent a couple of log messages when parsing HBA files

This commit adjusts two log messages:
- When a field in pg_ident.conf is not populated, report the line of the
configuration file in an error context message instead of the main
entry.
- When parsing pg_ident.conf and finding an invalid regexp, add some
information about the line of the configuration file involved within an
error context message.

Author: Julien Rouhaud
Discussion: https://postgr.es/m/20220223045959.35ipdsvbxcstrhya@jrouhaud

2 years agoUse hba_file/ident_file GUCs rather than pg_hba.conf/pg_ident.conf in logs
Michael Paquier [Fri, 5 Aug 2022 00:36:42 +0000 (09:36 +0900)]
Use hba_file/ident_file GUCs rather than pg_hba.conf/pg_ident.conf in logs

This is particularly useful when log_min_messages is set to FATAL, so as
one can know which file was not getting loaded whether hba_file or
ident_file are set to some non-default values.  If using the default
values of these GUC parameters, the same reports are generated.

This commit changes the load (startup) and reload (SIGHUP) messages.

Author: Julien Rouhaud
Discussion: https://postgr.es/m/20220223045959.35ipdsvbxcstrhya@jrouhaud

2 years agoFix failure to set correct operator in window run condition
David Rowley [Thu, 4 Aug 2022 22:14:00 +0000 (10:14 +1200)]
Fix failure to set correct operator in window run condition

This was a simple omission in 9d9c02ccd where the code didn't correctly
set the operator to use in the run condition OpExpr when the window
function was both monotonically increasing and decreasing.

Bug discovered by Julien Roze, although he did not report it.

Reported-by: Phil Florent
Discussion: https://postgr.es/m/PA4P191MB160009A09B9D0624359278CFBA9F9@PA4P191MB1600.EURP191.PROD.OUTLOOK.COM
Backpatch-through: 15, where 9d9c02ccd was added

2 years agoRemove dead pread and pwrite replacement code.
Thomas Munro [Thu, 4 Aug 2022 21:42:31 +0000 (09:42 +1200)]
Remove dead pread and pwrite replacement code.

pread() and pwrite() are in SUSv2, and all targeted Unix systems have
them.

Previously, we defined pg_pread and pg_pwrite to emulate these function
with lseek() on old Unixen.  The names with a pg_ prefix were a reminder
of a portability hazard: they might change the current file position.
That hazard is gone, so we can drop the prefixes.

Since the remaining replacement code is Windows-only, move it into
src/port/win32p{read,write}.c, and move the declarations into
src/include/port/win32_port.h.

No need for vestigial HAVE_PREAD, HAVE_PWRITE macros as they were only
used for declarations in port.h which have now moved into win32_port.h.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Greg Stark <stark@mit.edu>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove dead setenv, unsetenv replacement code.
Thomas Munro [Thu, 4 Aug 2022 21:38:36 +0000 (09:38 +1200)]
Remove dead setenv, unsetenv replacement code.

setenv() and unsetenv() are in SUSv3 and targeted Unix systems have
them.  We still need special code for these on Windows, but that doesn't
require a configure probe.

This marks the first time we require a SUSv3 (POSIX.1-2001) facility
(rather than SUSv2).  The replacement code removed here was not needed
on any targeted system or any known non-EOL'd Unix system, and was
therefore dead and untested.

No need for vestigial HAVE_SETENV and HAVE_UNSETENV macros, because we
provide a replacement for Windows, and we didn't previously test the
macros.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Greg Stark <stark@mit.edu>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove configure probes for poll and poll.h.
Thomas Munro [Thu, 4 Aug 2022 21:37:53 +0000 (09:37 +1200)]
Remove configure probes for poll and poll.h.

poll() and <poll.h> are in SUSv2 and all targeted Unix systems have
them.

Retain HAVE_POLL and HAVE_POLL_H macros for readability.  There's an
error in latch.c that is now unreachable (since we always have one of
WIN32 or HAVE_POLL defined), but that falls out of a decision to keep
using defined(HAVE_POLL) instead of !defined(WIN32) to guard the poll()
code.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove configure probe for link.
Thomas Munro [Thu, 4 Aug 2022 21:36:50 +0000 (09:36 +1200)]
Remove configure probe for link.

link() is in SUSv2 and all targeted Unix systems have it.  We have
replacement code for Windows that doesn't require a configure probe.
Since only Windows needs it, rename src/port/link.c to win32link.c like
other similar things.

There is no need for a vestigial HAVE_LINK macro, because we expect all
Unix and, with our replacement function, Windows systems to have it, so
we didn't have any tests around link() usage.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove configure probes for symlink/readlink, and dead code.
Thomas Munro [Thu, 4 Aug 2022 21:22:56 +0000 (09:22 +1200)]
Remove configure probes for symlink/readlink, and dead code.

symlink() and readlink() are in SUSv2 and all targeted Unix systems have
them.  We have partial emulation on Windows.  Code that raised runtime
errors on systems without it has been dead for years, so we can remove
that and also references to such systems in the documentation.

Define HAVE_READLINK and HAVE_SYMLINK macros on Unix.  Our Windows
replacement functions based on junction points can't be used for
relative paths or for non-directories, so the macros can be used to
check for full symlink support.  The places that deal with tablespaces
can just use symlink functions without checking the macros.  (If they
did check the macros, they'd need to provide an #else branch with a
runtime or compile time error, and it'd be dead code.)

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove configure probe for setsid.
Thomas Munro [Thu, 4 Aug 2022 21:21:51 +0000 (09:21 +1200)]
Remove configure probe for setsid.

setsid() is in SUSv2 and all targeted Unix systems have it.  Retain a
HAVE_SETSID macro, defined on Unix only.  That's easier to understand
than !defined(WIN32), for the optional code it governs.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove configure probe for shm_open.
Thomas Munro [Thu, 4 Aug 2022 21:19:36 +0000 (09:19 +1200)]
Remove configure probe for shm_open.

shm_open() is in SUSv2 and all targeted Unix systems have it.

We retain a HAVE_SHM_OPEN macro, because it's clearer to readers than
something like !defined(WIN32).

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove configure probe and related tests for getrlimit.
Thomas Munro [Thu, 4 Aug 2022 21:18:34 +0000 (09:18 +1200)]
Remove configure probe and related tests for getrlimit.

getrlimit() is in SUSv2 and all targeted systems have it.

Windows doesn't have it.  We could just use #ifndef WIN32, but for a
little more explanation about why we're making things conditional, let's
retain the HAVE_GETRLIMIT macro.  It's defined in port.h for Unix systems.

On systems that have it, it's not necessary to test for RLIMIT_CORE,
RLIMIT_STACK or RLIMIT_NOFILE macros, since SUSv2 requires those and all
targeted systems have them.  Also remove references to a pre-historic
alternative spelling of RLIMIT_NOFILE, and coding that seemed to believe
that Cygwin didn't have it.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRemove configure probe for dlopen, and refactor.
Thomas Munro [Thu, 4 Aug 2022 21:12:45 +0000 (09:12 +1200)]
Remove configure probe for dlopen, and refactor.

dlopen() is in SUSv2 and all targeted Unix systems have it.  We still
need replacement functions for Windows, but we don't need a configure
probe for that.

Since it's no longer needed by other operating systems, rename dlopen.c
to win32dlopen.c and move the declarations into win32_port.h.

Likewise, the macros RTLD_NOW and RTLD_GLOBAL now only need to be
defined on Windows, since all targeted Unix systems have 'em.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJ3LHeP9w5Fgzdr4G8AnEtJ=z=p6hGDEm4qYGEUX5B6fQ@mail.gmail.com

2 years agoRevert recent changes to 002_pg_upgrade.pl.
Robert Haas [Thu, 4 Aug 2022 19:17:14 +0000 (15:17 -0400)]
Revert recent changes to 002_pg_upgrade.pl.

The test is proving to be unreliable in the buildfarm, and we neither
agree on how best to fix it nor have time to do so before the upcoming
release. So for now, put things back to the way they were before commit
d498e052b4b84ae21b3b68d5b3fda6ead65d1d4d.

Discussion: http://postgr.es/m/3628089.1659640252@sss.pgh.pa.us

2 years agoFix check_exclusion_or_unique_constraint for UNIQUE NULLS NOT DISTINCT.
Tom Lane [Thu, 4 Aug 2022 18:16:26 +0000 (14:16 -0400)]
Fix check_exclusion_or_unique_constraint for UNIQUE NULLS NOT DISTINCT.

Adjusting this function was overlooked in commit 94aa7cc5f.  The only
visible symptom (so far) is that INSERT ... ON CONFLICT could go into
an endless loop when inserting a null that has a conflict.

Richard Guo and Tom Lane, per bug #17558 from Andrew Kesper

Discussion: https://postgr.es/m/17558-3f6599ffcf52fd4a@postgresql.org

2 years agoAdd CHECK_FOR_INTERRUPTS in ExecInsert's speculative insertion loop.
Tom Lane [Thu, 4 Aug 2022 18:10:06 +0000 (14:10 -0400)]
Add CHECK_FOR_INTERRUPTS in ExecInsert's speculative insertion loop.

Ordinarily the functions called in this loop ought to have plenty
of CFIs themselves; but we've now seen a case where no such CFI is
reached, making the loop uninterruptible.  Even though that's from
a recently-introduced bug, it seems prudent to install a CFI at
the loop level in all branches.

Per discussion of bug #17558 from Andrew Kesper (an actual fix for
that bug will follow).

Discussion: https://postgr.es/m/17558-3f6599ffcf52fd4a@postgresql.org

2 years agoAdd proper regression test for the recent SRFs-in-pathkeys problem.
Tom Lane [Thu, 4 Aug 2022 15:11:22 +0000 (11:11 -0400)]
Add proper regression test for the recent SRFs-in-pathkeys problem.

Remove the test case added by commit fac1b470a, which never actually
worked to expose the problem it claimed to test.  Replace it with
a case that does expose the problem, and also covers the SRF-not-
at-the-top deficiency repaired in 1aa8dad41.

Richard Guo, with some editorialization by me

Discussion: https://postgr.es/m/17564-c7472c2f90ef2da3@postgresql.org

2 years agoRephrase comments to make them clearer
Daniel Gustafsson [Thu, 4 Aug 2022 14:30:06 +0000 (16:30 +0200)]
Rephrase comments to make them clearer

The use of "we" when referring to the active backend might be
misunderstood, so rephrase to make it clearer who is performing
the actions discussed in the comment.

Author: Junwang Zhao <zhjwpku@gmail.com>
Reviewed-by: Erikjan Rijkers <er@xs4all.nl>
Reviewed-by: Robert Treat <rob@xzilla.net>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAEG8a3LRSMqkvjiURiJoSi4aGWORpiXUmUfQQK5PaD6WfPzu3w@mail.gmail.com

2 years agoFix formatting and comment typos
John Naylor [Thu, 4 Aug 2022 09:41:29 +0000 (16:41 +0700)]
Fix formatting and comment typos

Justin Pryzby

Discussion: https://www.postgresql.org/message-id/20220801181136.GJ15006%40telsasoft.com

2 years agoFix assorted doc typos
John Naylor [Thu, 4 Aug 2022 08:59:32 +0000 (15:59 +0700)]
Fix assorted doc typos

Erik Rijkers and Justin Pryzby

Backpatch to v14

Discussion: https://www.postgresql.org/message-id/b79bfeff-d0e3-29a3-2576-0e325848dede%40xs4all.nl

2 years agoClarify DROP EXTENSION docs regarding explicitly dependent routines
John Naylor [Thu, 4 Aug 2022 08:29:25 +0000 (15:29 +0700)]
Clarify DROP EXTENSION docs regarding explicitly dependent routines

Per suggestion from Robert Haas

Backpatch to v14

Discussion: https://www.postgresql.org/message-id/CA%2BTgmoZ1QvHquYHLkMy1oHKqz4-E7QQctj6e0ocq_GP1B5%2B9bA%40mail.gmail.com

2 years agoFix inconsistent comments for some function declarations in headers
Michael Paquier [Thu, 4 Aug 2022 08:36:21 +0000 (17:36 +0900)]
Fix inconsistent comments for some function declarations in headers

Some of the headers list a couple of function prototypes located in a
different file than what is referred to.  This fixes a couple of
places where this inconsistency exists.

Author: Richard Guo
Discussion: https://postgr.es/m/CAMbWs4__RdcSNXPa7L62Ozvo_Q4LvT60o3Bnp8yrQ_m9y5CKvg@mail.gmail.com

2 years agoSupport SSE2 intrinsics where available
John Naylor [Wed, 3 Aug 2022 04:07:40 +0000 (11:07 +0700)]
Support SSE2 intrinsics where available

SSE2 vector instructions are part of the spec for the 64-bit x86
architecture. Until now we have relied on the compiler to autovectorize
in some limited situations, but some useful coding idioms can only be
expressed explicitly via compiler intrinsics. To this end, add a header
that defines USE_SSE2 where available. While x86-only for now, we can
add other architectures in the future. This will also be the intended
place for helper functions that use vector operations.

Reviewed by Nathan Bossart and Masahiko Sawada

Discussion: https://www.postgresql.org/message-id/CAFBsxsE2G_H_5Wbw%2BNOPm70-BK4xxKf86-mRzY%3DL2sLoQqM%2B-Q%40mail.gmail.com

2 years agoFix incorrect tests for SRFs in relation_can_be_sorted_early().
Tom Lane [Wed, 3 Aug 2022 21:33:42 +0000 (17:33 -0400)]
Fix incorrect tests for SRFs in relation_can_be_sorted_early().

Commit fac1b470a thought we could check for set-returning functions
by testing only the top-level node in an expression tree.  This is
wrong in itself, and to make matters worse it encouraged others
to make the same mistake, by exporting tlist.c's special-purpose
IS_SRF_CALL() as a widely-visible macro.  I can't find any evidence
that anyone's taken the bait, but it was only a matter of time.

Use expression_returns_set() instead, and stuff the IS_SRF_CALL()
genie back in its bottle, this time with a warning label.  I also
added a couple of cross-reference comments.

After a fair amount of fooling around, I've despaired of making
a robust test case that exposes the bug reliably, so no test case
here.  (Note that the test case added by fac1b470a is itself
broken, in that it doesn't notice if you remove the code change.
The repro given by the bug submitter currently doesn't fail either
in v15 or HEAD, though I suspect that may indicate an unrelated bug.)

Per bug #17564 from Martijn van Oosterhout.  Back-patch to v13,
as the faulty patch was.

Discussion: https://postgr.es/m/17564-c7472c2f90ef2da3@postgresql.org

2 years agoAdd another old commit to git-blame-ignore-revs.
Peter Geoghegan [Wed, 3 Aug 2022 16:28:27 +0000 (09:28 -0700)]
Add another old commit to git-blame-ignore-revs.

2 years agoReduce test runtime of src/test/modules/snapshot_too_old.
Tom Lane [Wed, 3 Aug 2022 15:14:55 +0000 (11:14 -0400)]
Reduce test runtime of src/test/modules/snapshot_too_old.

The sto_using_cursor and sto_using_select tests were coded to exercise
every permutation of their test steps, but AFAICS there is no value in
exercising more than one.  This matters because each permutation costs
about six seconds, thanks to the "pg_sleep(6)".  Perhaps we could
reduce that, but the useless permutations seem worth getting rid of
in any case.  (Note that sto_using_hash_index got it right already.)

While here, clean up some other sloppiness such as an unused table.

This doesn't make too much difference in interactive testing, since the
wasted time is typically masked by parallelization with other tests.
However, the buildfarm runs this as a serial step, which means we can
expect to shave ~40 seconds from every buildfarm run.  That makes it
worth back-patching.

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

2 years agoAdd wait_for_subscription_sync for TAP tests.
Amit Kapila [Wed, 3 Aug 2022 10:01:17 +0000 (15:31 +0530)]
Add wait_for_subscription_sync for TAP tests.

The TAP tests for logical replication in src/test/subscription are using
the following code in many places to make sure that the subscription is
synchronized with the publisher:

  $node_publisher->wait_for_catchup('tap_sub');
  $node_subscriber->poll_query_until('postgres',
    qq[SELECT count(1) = 0
       FROM pg_subscription_rel
       WHERE srsubstate NOT IN ('r', 's')]);

The new function wait_for_subscription_sync() can be used to replace the
above code. This eliminates duplicated code and makes it easier to write
future tests.

Author: Masahiko Sawada
Reviewed by: Amit Kapila, Shi yu
Discussion: https://postgr.es/m/CAD21AoC-fvAkaKHa4t1urupwL8xbAcWRePeETvshvy80f6WV1A@mail.gmail.com

2 years agoBe more wary about 32-bit integer overflow in pg_stat_statements.
Tom Lane [Tue, 2 Aug 2022 22:05:34 +0000 (18:05 -0400)]
Be more wary about 32-bit integer overflow in pg_stat_statements.

We've heard a couple of reports of people having trouble with
multi-gigabyte-sized query-texts files.  It occurred to me that on
32-bit platforms, there could be an issue with integer overflow
of calculations associated with the total query text size.
Address that with several changes:

1. Limit pg_stat_statements.max to INT_MAX / 2 not INT_MAX.
The hashtable code will bound it to that anyway unless "long"
is 64 bits.  We still need overflow guards on its use, but
this helps.

2. Add a check to prevent extending the query-texts file to
more than MaxAllocHugeSize.  If it got that big, qtext_load_file
would certainly fail, so there's not much point in allowing it.
Without this, we'd need to consider whether extent, query_offset,
and related variables shouldn't be off_t not size_t.

3. Adjust the comparisons in need_gc_qtexts() to be done in 64-bit
arithmetic on all platforms.  It appears possible that under duress
those multiplications could overflow 32 bits, yielding a false
conclusion that we need to garbage-collect the texts file, which
could lead to repeatedly garbage-collecting after every hash table
insertion.

Per report from Bruno da Silva.  I'm not convinced that these
issues fully explain his problem; there may be some other bug that's
contributing to the query-texts file becoming so large in the first
place.  But it did get that big, so #2 is a reasonable defense,
and #3 could explain the reported performance difficulties.

(See also commit 8bbe4cbd9, which addressed some related bugs.
The second Discussion: link is the thread that led up to that.)

This issue is old, and is primarily a problem for old platforms,
so back-patch.

Discussion: https://postgr.es/m/CAB+Nuk93fL1Q9eLOCotvLP07g7RAv4vbdrkm0cVQohDVMpAb9A@mail.gmail.com
Discussion: https://postgr.es/m/5601D354.5000703@BlueTreble.com

2 years agoRemove unused fields from ExprEvalStep
David Rowley [Tue, 2 Aug 2022 21:46:02 +0000 (09:46 +1200)]
Remove unused fields from ExprEvalStep

These were added recently by 1349d2790.

Reported-by: Zhihong Yu
Discussion: https://postgr.es/m/CALNJ-vTi+YDuAWKp4Z_Dv=mrz=aq81qTg0D7wzc8y7rS_+i_cw@mail.gmail.com

2 years agoChange type "char"'s I/O format for non-ASCII characters.
Tom Lane [Tue, 2 Aug 2022 14:29:35 +0000 (10:29 -0400)]
Change type "char"'s I/O format for non-ASCII characters.

Previously, a byte with the high bit set was just transmitted
as-is by charin() and charout().  This is problematic if the
database encoding is multibyte, because the result of charout()
won't be validly encoded, which breaks various stuff that
expects all text strings to be validly encoded.  We've
previously decided to enforce encoding validity rather than try
to individually harden each place that might have a problem with
such strings, so it's time to do something about "char".

To fix, represent high-bit-set characters as \ooo (backslash
and three octal digits), following the ancient "escape" format
for bytea.  charin() will continue to accept the old way as well,
though that is only reachable in single-byte encodings.

Add some test cases just so there is coverage for this code.
We'll otherwise leave this question undocumented as it was before,
because we don't really want to encourage end-user use of "char".

For the moment, back-patch into v15 so that this change appears
in 15beta3.  If there's not great pushback we should consider
absorbing this change into the older branches.

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

2 years agoImprove performance of ORDER BY / DISTINCT aggregates
David Rowley [Tue, 2 Aug 2022 11:11:45 +0000 (23:11 +1200)]
Improve performance of ORDER BY / DISTINCT aggregates

ORDER BY / DISTINCT aggreagtes have, since implemented in Postgres, been
executed by always performing a sort in nodeAgg.c to sort the tuples in
the current group into the correct order before calling the transition
function on the sorted tuples.  This was not great as often there might be
an index that could have provided pre-sorted input and allowed the
transition functions to be called as the rows come in, rather than having
to store them in a tuplestore in order to sort them once all the tuples
for the group have arrived.

Here we change the planner so it requests a path with a sort order which
supports the most amount of ORDER BY / DISTINCT aggregate functions and
add new code to the executor to allow it to support the processing of
ORDER BY / DISTINCT aggregates where the tuples are already sorted in the
correct order.

Since there can be many ORDER BY / DISTINCT aggregates in any given query
level, it's very possible that we can't find an order that suits all of
these aggregates.  The sort order that the planner chooses is simply the
one that suits the most aggregate functions.  We take the most strictly
sorted variation of each order and see how many aggregate functions can
use that, then we try again with the order of the remaining aggregates to
see if another order would suit more aggregate functions.  For example:

SELECT agg(a ORDER BY a),agg2(a ORDER BY a,b) ...

would request the sort order to be {a, b} because {a} is a subset of the
sort order of {a,b}, but;

SELECT agg(a ORDER BY a),agg2(a ORDER BY c) ...

would just pick a plan ordered by {a} (we give precedence to aggregates
which are earlier in the targetlist).

SELECT agg(a ORDER BY a),agg2(a ORDER BY b),agg3(a ORDER BY b) ...

would choose to order by {b} since two aggregates suit that vs just one
that requires input ordered by {a}.

Author: David Rowley
Reviewed-by: Ronan Dunklau, James Coleman, Ranier Vilela, Richard Guo, Tom Lane
Discussion: https://postgr.es/m/CAApHDvpHzfo92%3DR4W0%2BxVua3BUYCKMckWAmo-2t_KiXN-wYH%3Dw%40mail.gmail.com

2 years agodoc: Fix typos in protocol.sgml
Michael Paquier [Tue, 2 Aug 2022 10:55:59 +0000 (19:55 +0900)]
doc: Fix typos in protocol.sgml

Author: Ekaterina Kiryanova
Discussion: https://postgr.es/m/745414e7-efb2-a6ae-5b83-fcbdf35aabc8@postgrespro.ru
Backpatch-through: 15