postgresql.git
4 years agoDoc: get rid of <foreignphrase> tags.
Tom Lane [Wed, 10 Mar 2021 17:38:43 +0000 (12:38 -0500)]
Doc: get rid of <foreignphrase> tags.

We italicized some, but not all, instances of "per se", "pro forma", and
"ad hoc". These phrases are widespread in formal registers of English,
so it"s debatable whether they even qualify as foreign. We could instead
try to be more consistent in the use of <foreignphrase>, but that"s
difficult to enforce, so let"s just remove the tags for those words.

The one case that seems to deserve the tag is "voilà". Instead of keeping
just one instance of the tag, change that to a more standard phrase.

John Naylor

Discussion: https://postgr.es/m/CAFBsxsHtWs_NsccAVgQ=tTUKkXHpHdkjZXtp_Cd9dGWyBDxfbQ@mail.gmail.com

4 years agoDoc: improve introductory information about procedures.
Tom Lane [Wed, 10 Mar 2021 16:33:50 +0000 (11:33 -0500)]
Doc: improve introductory information about procedures.

Clarify the discussion in "User-Defined Procedures", by laying out
the key differences between functions and procedures in a bulleted
list.  Notably, this avoids burying the lede about procedures being
able to do transaction control.  Make the back-link in the CREATE
FUNCTION reference page more prominent, and add one in CREATE
PROCEDURE.

Per gripe from Guyren Howe.  Thanks to David Johnston for discussion.

Discussion: https://postgr.es/m/BYAPR03MB4903C53A8BB7EFF5EA289674A6949@BYAPR03MB4903.namprd03.prod.outlook.com

4 years agoDoc: fix missing mention of procedure OUT parameters.
Tom Lane [Wed, 10 Mar 2021 15:59:48 +0000 (10:59 -0500)]
Doc: fix missing mention of procedure OUT parameters.

Small oversight in commit 2453ea142.

4 years agoAdd bound check before bsearch() for performance
Peter Eisentraut [Wed, 10 Mar 2021 14:19:37 +0000 (15:19 +0100)]
Add bound check before bsearch() for performance

In the current lazy vacuum implementation, some index AMs such as
btree indexes call lazy_tid_reaped() for each index tuple during
ambulkdelete to check if the index tuple points to the (collected)
garbage tuple.  In that function, we simply call bsearch(), but we
should be able to know the result without bsearch() if the index tuple
points to the heap tuple that is out of range of the collected garbage
tuples.  Therefore, add a simple bound check before resorting to
bsearch().  Testing has shown that this can give significant
performance benefits.

Author: Masahiko Sawada <masahiko.sawada@2ndquadrant.com>
Discussion: https://www.postgresql.org/message-id/flat/CA+fd4k76j8jKzJzcx8UqEugvayaMSnQz0iLUt_XgBp-_-bd22A@mail.gmail.com

4 years agoFix another portability bug in recent pgbench commit.
Thomas Munro [Wed, 10 Mar 2021 09:22:12 +0000 (22:22 +1300)]
Fix another portability bug in recent pgbench commit.

Commit 547f04e7 produced errors on AIX/xlc while building plpython.  The
new code appears to be incompatible with the hack installed by commit
a11cf433.  Without access to an AIX system to check, my guess is that
_POSIX_C_SOURCE may be required for <time.h> to declare the things the
header needs to see, but plpython.h undefines it.

For now, to unbreak build farm animal hoverfly, just move the new
pg_time_usec_t support into pgbench.c.  Perhaps later we could figure
out what to rearrange to put it back into a header for wider use.

Discussion: https://postgr.es/m/CA%2BhUKG%2BP%2BjcD%3Dx9%2BagyTdWtjpOT64MYiGic%2Bcbu_TD8CV%3D6A3w%40mail.gmail.com

4 years agoTry to fix portability bugs in recent pgbench commits.
Thomas Munro [Wed, 10 Mar 2021 07:18:15 +0000 (20:18 +1300)]
Try to fix portability bugs in recent pgbench commits.

1.  pg_time_usec_t needs to be printed with INT64_FORMAT, not %ld, or 32
bit systems complain, per lapwing.

2.  Some Windows compilers didn't like a thread function not marked with
__stdcall, per whelk; let's see if this fixes the problem.

4 years agoSmall debug message tweak
Peter Eisentraut [Wed, 10 Mar 2021 07:16:38 +0000 (08:16 +0100)]
Small debug message tweak

This makes the wording of the delete case match the update case.

4 years agoMove tablespace path re-creation from the makefiles to pg_regress
Michael Paquier [Wed, 10 Mar 2021 05:50:00 +0000 (14:50 +0900)]
Move tablespace path re-creation from the makefiles to pg_regress

Moving this logic into pg_regress fixes a potential failure with
parallel tests when pg_upgrade and the main regression test suite both
trigger the makefile rule that cleaned up testtablespace/ under
src/test/regress.  Even if pg_upgrade was triggering this rule, it has
no need to do so as it uses a different tablespace path.  So if
pg_upgrade triggered the makefile rule for the tablespace setup while
the main regression test suite ran the tablespace cases, it would fail.

61be85a was a similar attempt at achieving that, but that broke cases
where the regression tests require to run under an Administrator
account, like with Appveyor.

Reported-by: Andres Freund, Kyotaro Horiguchi
Reviewed-by: Peter Eisentraut
Discussion: https://postgr.es/m/20201209012911.uk4d6nxcnkp7ehrx@alap3.anarazel.de

4 years agopgbench: Synchronize client threads.
Thomas Munro [Wed, 10 Mar 2021 03:17:34 +0000 (16:17 +1300)]
pgbench: Synchronize client threads.

Wait until all pgbench threads are connected before benchmarking begins.
This fixes a problem where some connections could take a very long time
to be established because of lock contention from earlier connections,
making results unstable and bogus with high connection counts.

Author: Andres Freund <andres@anarazel.de>
Author: Fabien COELHO <coelho@cri.ensmp.fr>
Reviewed-by: Marina Polyakova <m.polyakova@postgrespro.ru>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Reviewed-by: David Rowley <dgrowleyml@gmail.com>
Discussion: https://postgr.es/m/20200227180100.zyvjwzcpiokfsqm2%40alap3.anarazel.de

4 years agoAdd missing pthread_barrier_t.
Thomas Munro [Wed, 10 Mar 2021 02:40:17 +0000 (15:40 +1300)]
Add missing pthread_barrier_t.

Supply a simple implementation of the missing pthread_barrier_t type and
functions, for macOS.

Discussion: https://postgr.es/m/20200227180100.zyvjwzcpiokfsqm2%40alap3.anarazel.de

4 years agopgbench: Improve time logic.
Thomas Munro [Wed, 10 Mar 2021 03:09:50 +0000 (16:09 +1300)]
pgbench: Improve time logic.

Instead of instr_time (struct timespec) and the INSTR_XXX macros,
introduce pg_time_usec_t and use integer arithmetic.  Don't include the
connection time in TPS unless using -C mode, but report it separately.

Author: Fabien COELHO <coelho@cri.ensmp.fr>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Discussion: https://postgr.es/m/20200227180100.zyvjwzcpiokfsqm2%40alap3.anarazel.de

4 years agopgbench: Refactor thread portability support.
Thomas Munro [Wed, 10 Mar 2021 02:39:08 +0000 (15:39 +1300)]
pgbench: Refactor thread portability support.

Instead of maintaining an incomplete emulation of POSIX threads for
Windows, let's use an extremely minimalist macro-based abstraction for
now.  A later patch will extend this, without the need to supply more
complicated pthread emulation code.  (There may be a need for a more
serious portable thread abstraction in later projects, but this is not
it.)

Minor incidental problems fixed: it wasn't OK to use (pthread_t) 0 as a
special value, it wasn't OK to compare thread_t values with ==, and we
incorrectly assumed that pthread functions set errno.

Discussion: https://postgr.es/m/20200227180100.zyvjwzcpiokfsqm2%40alap3.anarazel.de

4 years agoFix valgrind issue in commit 05c8482f7f.
Amit Kapila [Wed, 10 Mar 2021 04:34:20 +0000 (10:04 +0530)]
Fix valgrind issue in commit 05c8482f7f.

Initialize other newly added variables in max_parallel_hazard_context via
is_parallel_safe() because we don't check the parallel-safety of target
relations in that function.

Reported-by: Tom Lane as per buildfarm
Author: Amit Kapila
Discussion: https://postgr.es/m/2060179.1615347455@sss.pgh.pa.us

4 years agoEnable parallel SELECT for "INSERT INTO ... SELECT ...".
Amit Kapila [Wed, 10 Mar 2021 02:08:58 +0000 (07:38 +0530)]
Enable parallel SELECT for "INSERT INTO ... SELECT ...".

Parallel SELECT can't be utilized for INSERT in the following cases:
- INSERT statement uses the ON CONFLICT DO UPDATE clause
- Target table has a parallel-unsafe: trigger, index expression or
  predicate, column default expression or check constraint
- Target table has a parallel-unsafe domain constraint on any column
- Target table is a partitioned table with a parallel-unsafe partition key
  expression or support function

The planner is updated to perform additional parallel-safety checks for
the cases listed above, for determining whether it is safe to run INSERT
in parallel-mode with an underlying parallel SELECT. The planner will
consider using parallel SELECT for "INSERT INTO ... SELECT ...", provided
nothing unsafe is found from the additional parallel-safety checks, or
from the existing parallel-safety checks for SELECT.

While checking parallel-safety, we need to check it for all the partitions
on the table which can be costly especially when we decide not to use a
parallel plan. So, in a separate patch, we will introduce a GUC and or a
reloption to enable/disable parallelism for Insert statements.

Prior to entering parallel-mode for the execution of INSERT with parallel
SELECT, a TransactionId is acquired and assigned to the current
transaction state. This is necessary to prevent the INSERT from attempting
to assign the TransactionId whilst in parallel-mode, which is not allowed.
This approach has a disadvantage in that if the underlying SELECT does not
return any rows, then the TransactionId is not used, however that
shouldn't happen in practice in many cases.

Author: Greg Nancarrow, Amit Langote, Amit Kapila
Reviewed-by: Amit Langote, Hou Zhijie, Takayuki Tsunakawa, Antonin Houska, Bharath Rupireddy, Dilip Kumar, Vignesh C, Zhihong Yu, Amit Kapila
Tested-by: Tang, Haiying
Discussion: https://postgr.es/m/CAJcOf-cXnB5cnMKqWEp2E2z7Mvcd04iLVmV=qpFJrR3AcrTS3g@mail.gmail.com
Discussion: https://postgr.es/m/CAJcOf-fAdj=nDKMsRhQzndm-O13NY4dL6xGcEvdX5Xvbbi0V7g@mail.gmail.com

4 years agoRevert changes for SSL compression in libpq
Michael Paquier [Wed, 10 Mar 2021 00:35:42 +0000 (09:35 +0900)]
Revert changes for SSL compression in libpq

This partially reverts 096bbf7 and 9d2d457, undoing the libpq changes as
it could cause breakages in distributions that share one single libpq
version across multiple major versions of Postgres for extensions and
applications linking to that.

Note that the backend is unchanged here, and it still disables SSL
compression while simplifying the underlying catalogs that tracked if
compression was enabled or not for a SSL connection.

Per discussion with Tom Lane and Daniel Gustafsson.

Discussion: https://postgr.es/m/YEbq15JKJwIX+S6m@paquier.xyz

4 years agoFix vague comment in jsonb documentation
Alexander Korotkov [Tue, 9 Mar 2021 15:16:03 +0000 (18:16 +0300)]
Fix vague comment in jsonb documentation

The sample query fails because of an attempt to update the key of a numeric.
But the comment says it's just because of the missing object key.  That's not
correct because jsonb subscription automatically adds missing keys.

Reported-by: Nikita Konev
4 years agolibpq: Remove deprecated connection parameters authtype and tty
Peter Eisentraut [Tue, 9 Mar 2021 14:01:22 +0000 (15:01 +0100)]
libpq: Remove deprecated connection parameters authtype and tty

The authtype parameter was deprecated and made inactive in commit
d5bbe2aca55bc8, but the environment variable was left defined and thus
tested with a getenv call even though the value is of no use.  Also,
if it would exist it would be copied but never freed as the cleanup
code had been removed.

tty was deprecated in commit cb7fb3ca958ec8bd5a14e7 but most of the
infrastructure around it remained in place.

Author: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/DDDF36F3-582A-4C02-8598-9B464CC42B34@yesql.se

4 years agoSwitch back sslcompression to be a normal input field in libpq
Michael Paquier [Tue, 9 Mar 2021 10:52:36 +0000 (19:52 +0900)]
Switch back sslcompression to be a normal input field in libpq

Per buildfarm member crake, any servers including a postgres_fdw server
with this option set would fail to do a pg_upgrade properly as the
option got hidden in f9264d1 by becoming a debug option, making the
restore of the FDW server fail.

This changes back the option in libpq to be visible, but still inactive
to fix this upgrade issue.

Discussion: https://postgr.es/m/YEbq15JKJwIX+S6m@paquier.xyz

4 years agoTrack total amounts of times spent writing and syncing WAL data to disk.
Fujii Masao [Tue, 9 Mar 2021 07:52:06 +0000 (16:52 +0900)]
Track total amounts of times spent writing and syncing WAL data to disk.

This commit adds new GUC track_wal_io_timing. When this is enabled,
the total amounts of time XLogWrite writes and issue_xlog_fsync syncs
WAL data to disk are counted in pg_stat_wal. This information would be
useful to check how much WAL write and sync affect the performance.

Enabling track_wal_io_timing will make the server query the operating
system for the current time every time WAL is written or synced,
which may cause significant overhead on some platforms. To avoid such
additional overhead in the server with track_io_timing enabled,
this commit introduces track_wal_io_timing as a separate parameter from
track_io_timing.

Note that WAL write and sync activity by walreceiver has not been tracked yet.

This commit makes the server also track the numbers of times XLogWrite
writes and issue_xlog_fsync syncs WAL data to disk, in pg_stat_wal,
regardless of the setting of track_wal_io_timing. This counters can be
used to calculate the WAL write and sync time per request, for example.

Bump PGSTAT_FILE_FORMAT_ID.

Bump catalog version.

Author: Masahiro Ikeda
Reviewed-By: Japin Li, Hayato Kuroda, Masahiko Sawada, David Johnston, Fujii Masao
Discussion: https://postgr.es/m/0509ad67b585a5b86a83d445dfa75392@oss.nttdata.com

4 years agoAdd support for more progress reporting in COPY
Michael Paquier [Tue, 9 Mar 2021 05:21:03 +0000 (14:21 +0900)]
Add support for more progress reporting in COPY

The command (TO or FROM), its type (file, pipe, program or callback),
and the number of tuples excluded by a WHERE clause in COPY FROM are
added to the progress reporting already available.

The column "lines_processed" is renamed to "tuples_processed" to
disambiguate the meaning of this column in the cases of CSV and BINARY
COPY and to be more consistent with the other catalog progress views.

Bump catalog version, again.

Author: Matthias van de Meent
Reviewed-by: Michael Paquier, Justin Pryzby, Bharath Rupireddy, Josef
Šimánek, Tomas Vondra
Discussion: https://postgr.es/m/CAEze2WiOcgdH4aQA8NtZq-4dgvnJzp8PohdeKchPkhMY-jWZXA@mail.gmail.com

4 years agoRemove support for SSL compression
Michael Paquier [Tue, 9 Mar 2021 02:16:47 +0000 (11:16 +0900)]
Remove support for SSL compression

PostgreSQL disabled compression as of e3bdb2d and the documentation
recommends against using it since.  Additionally, SSL compression has
been disabled in OpenSSL since version 1.1.0, and was disabled in many
distributions long before that.  The most recent TLS version, TLSv1.3,
disallows compression at the protocol level.

This commit removes the feature itself, removing support for the libpq
parameter sslcompression (parameter still listed for compatibility
reasons with existing connection strings, just ignored), and removes
the equivalent field in pg_stat_ssl and de facto PgBackendSSLStatus.

Note that, on top of removing the ability to activate compression by
configuration, compression is actively disabled in both frontend and
backend to avoid overrides from local configurations.

A TAP test is added for deprecated SSL parameters to check after
backwards compatibility.

Bump catalog version.

Author: Daniel Gustafsson
Reviewed-by: Peter Eisentraut, Magnus Hagander, Michael Paquier
Discussion:  https://postgr.es/m/7E384D48-11C5-441B-9EC3-F7DB1F8518F6@yesql.se

4 years agoComplain if a function-in-FROM returns a set when it shouldn't.
Tom Lane [Mon, 8 Mar 2021 23:54:55 +0000 (18:54 -0500)]
Complain if a function-in-FROM returns a set when it shouldn't.

Throw a "function protocol violation" error if a function in FROM
tries to return a set though it wasn't marked proretset.  Although
such cases work at the moment, it doesn't seem like something we
want to guarantee will keep working.  Besides, there are other
negative consequences of not setting the proretset flag, such as
potentially bad plans.

No back-patch, since if there is any third-party code violating
this expectation, people wouldn't appreciate us breaking it in
a minor release.

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

4 years agoProperly mark pg_stat_get_subscription() as returning a set.
Tom Lane [Mon, 8 Mar 2021 23:47:23 +0000 (18:47 -0500)]
Properly mark pg_stat_get_subscription() as returning a set.

The initial catalog data for this function failed to set proretset
or provide a prorows estimate.  It accidentally worked anyway when
invoked in the FROM clause, because the executor isn't too picky
about this; but the planner didn't expect the function to return
multiple rows, which could lead to bad plans.  Also the function
would fail if invoked in the SELECT list.

We can't easily back-patch this fix, but fortunately the bug's
consequences aren't awful in most cases.  Getting this right is
mainly an exercise in future-proofing.

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

4 years agoValidate the OID argument of pg_import_system_collations().
Tom Lane [Mon, 8 Mar 2021 23:21:51 +0000 (18:21 -0500)]
Validate the OID argument of pg_import_system_collations().

"SELECT pg_import_system_collations(0)" caused an assertion failure.
With a random nonzero argument --- or indeed with zero, in non-assert
builds --- it would happily make pg_collation entries with garbage
values of collnamespace.  These are harmless as far as I can tell
(unless maybe the OID happens to become used for a schema, later on?).
In any case this isn't a security issue, since the function is
superuser-only.  But it seems like a gotcha for unwary DBAs, so let's
add a check that the given OID belongs to some schema.

Back-patch to v10 where this function was introduced.

4 years agoFurther tweak memory management for regex DFAs.
Tom Lane [Mon, 8 Mar 2021 21:32:29 +0000 (16:32 -0500)]
Further tweak memory management for regex DFAs.

Coverity is still unhappy after commit 190c79884, and after looking
closer I think it might be onto something.  The callers of newdfa()
typically drop out if v->err has been set nonzero, which newdfa()
is faithfully doing if it fails.  However, what if v->err was already
nonzero before we entered newdfa()?  Then newdfa() could succeed and
the caller would promptly leak its result.

I don't think this scenario can actually happen, but the predicate
"v->err is always zero when newdfa() is called" seems difficult to be
entirely sure of; there's a good deal of code that potentially could
get that wrong.

It seems better to adjust the callers to directly check for a null
result instead of relying on ISERR() tests.  This is slightly cheaper
than the previous coding anyway.

Lacking evidence that there's any real bug, no back-patch.

4 years agoTrack replication origin progress for rollbacks.
Amit Kapila [Mon, 8 Mar 2021 02:24:03 +0000 (07:54 +0530)]
Track replication origin progress for rollbacks.

Commit 1eb6d6527a allowed to track replica origin replay progress for 2PC
but it was not complete. It misses to properly track the progress for
rollback prepared especially it missed updating the code for recovery.
Additionally, we need to allow tracking it on subscriber nodes where
wal_level might not be logical.

It is required to track decoding of 2PC which is committed in PG14
(a271a1b50e) and also nobody complained about this till now so not
backpatching it.

Author: Amit Kapila
Reviewed-by: Michael Paquier and Ajin Cherian
Discussion: https://postgr.es/m/CAA4eK1L-kHmMnSdrRW6UhRbCjR7cgh04c+6psY15qzT6ktcd+g@mail.gmail.com

4 years agoAdd bit_xor aggregate function
Peter Eisentraut [Sat, 6 Mar 2021 18:25:45 +0000 (19:25 +0100)]
Add bit_xor aggregate function

This can be used as a checksum for unordered sets.  bit_and and bit_or
already exist.

Author: Alexey Bashtanov <bashtanov@imap.cc>
Reviewed-by: Ibrar Ahmed <ibrar.ahmad@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/9d4582ae-ecfc-3a13-2238-6ab5a37c1f41@imap.cc

4 years agoClarify that CREATEROLE roles are considered Administrators
Magnus Hagander [Sat, 6 Mar 2021 17:11:00 +0000 (18:11 +0100)]
Clarify that CREATEROLE roles are considered Administrators

Author: Michael Banck
Reviewed-By: Robert Treat
Discussion: https://postgr.es/m/2160a5071a7bb5339055b04a8cad81a822be9d8d.camel@credativ.de

4 years agoAdd binary I/O capability for cube datatype.
Tom Lane [Sat, 6 Mar 2021 17:04:00 +0000 (12:04 -0500)]
Add binary I/O capability for cube datatype.

We can adjust the not-yet-released cube--1.4--1.5.sql upgrade
rather than making a whole new version.

KaiGai Kohei

Discussion: https://postgr.es/m/CAOP8fzZO4y60QPTK=RGDXeVeVHV9tLHKOsh7voUOoUouVCPV8A@mail.gmail.com

4 years agoImprove docs on updatable views
Magnus Hagander [Sat, 6 Mar 2021 16:36:48 +0000 (17:36 +0100)]
Improve docs on updatable views

Introduce the options before going into details, and add a link to the
CREATE TRIGGER documentation.

Author: David Johnston
Reviewed-By: Anastasia Lubennikova
Discussion: https://postgr.es/m/CAKFQuwYLLRhheo0_Y4Jp=vJ_YDsz1KoRuTpX1A_bUxmHTmLe-A@mail.gmail.com

4 years agopgbench: Simplify some port, host, user and dbname assignments
Michael Paquier [Sat, 6 Mar 2021 12:26:34 +0000 (21:26 +0900)]
pgbench: Simplify some port, host, user and dbname assignments

Using pgbench in an environment with both PGPORT and PGUSER set would
have caused the generation of a debug log with an incorrect database
name due to an oversight in 412893b.  Not specifying user, port and/or
database using the option switches, without their respective environment
variables, generated a log entry with empty strings, which was
rather useless.

This commit fixes this set of issues by simplifying the logic grabbing
the connection information, removing a set of getenv() calls that
emulated what libpq already does.  The faulty debug log now directly
uses the information from the libpq connection, and it gets generated
after the connection to the backend is completed, not before it (in the
event of a failure libpq would complain with more information about the
connection attempt so the log is not really useful before anyway).

Author: Kota Miyake
Reviewed-by: Fujii Masao, Michael Paquier
Discussion: https://postgr.es/m/026b3ae6fc339a18394d053c32a4463d@oss.nttdata.com

4 years agoDoc: remove obsolete entries in table of BRIN strategy numbers.
Tom Lane [Fri, 5 Mar 2021 15:59:23 +0000 (10:59 -0500)]
Doc: remove obsolete entries in table of BRIN strategy numbers.

See commit 591d282e8.

Noted by Justin Pryzby

Discussion: https://postgr.es/m/20201027032511.GF9241@telsasoft.com

4 years agoRemove deprecated containment operators for contrib types.
Tom Lane [Fri, 5 Mar 2021 15:45:41 +0000 (10:45 -0500)]
Remove deprecated containment operators for contrib types.

Since PG 8.2, @ and ~ have been deprecated aliases for the containment
operators @> and <@.  It seems like enough time has passed to actually
remove them, so do so.

This completes the project begun in commit 2f70fdb06.  Note that in
the core types, the relation to the preferred operator names was
reversed from what it is in these contrib modules.  The confusion
that induced was a large part of the reason for deprecation.

Justin Pryzby

Discussion: https://postgr.es/m/20201027032511.GF9241@telsasoft.com

4 years agodoc: Add backlinks to progress reporting documentation
Michael Paquier [Fri, 5 Mar 2021 05:58:16 +0000 (14:58 +0900)]
doc: Add backlinks to progress reporting documentation

Previously, the only place where progress reports were mentioned is in
the section for monitoring dedicated to its catalogs.  This makes the
progress reporting more discoverable, by adding links from the pages of
the commands supporting progress reports to their related catalog
views.

Author: Matthias van de Meent
Reviewed-by: Justin Pryzby, Bharath Rupireddy, Josef Šimánek, Tomas
Vondra
Discussion: https://postgr.es/m/CAEze2WiOcgdH4aQA8NtZq-4dgvnJzp8PohdeKchPkhMY-jWZXA@mail.gmail.com

4 years agoAdd support for PROVE_TESTS and PROVE_FLAGS in MSVC scripts
Michael Paquier [Fri, 5 Mar 2021 01:12:49 +0000 (10:12 +0900)]
Add support for PROVE_TESTS and PROVE_FLAGS in MSVC scripts

These can be set in buildenv.pl or a "set" command within a Windows
terminal.  The MSVC script vcregress.pl parses the values available in
the environment to build the resulting prove commands, and the parsing
of PROVE_TESTS is able to handle name patterns in the same way as other
platforms.

Not specifying those environment values makes vcregress.pl fall back to
the previous default, with no extra flags for the prove command, and all
the tests run within t/.

Author: Michael Paquier
Reviewed-by: Juan José Santamaría Flecha, Julien Rouhaud
Discussion: https://postgr.es/m/YD9GigwHoL6lFY2y@paquier.xyz

4 years agoClose psql processes gracefully in recovery tests
Andrew Dunstan [Thu, 4 Mar 2021 18:13:10 +0000 (13:13 -0500)]
Close psql processes gracefully in recovery tests

Under windows, psql processes need to be ended explicitly, or the TAP
tests hang. However, the recovery tests were doing this via
IPC::Run::kill_kill(), which causes other major problems on Windows.

We solve this by instead sending '\q' to psql so it quits of its own
accord, and then simply waiting for it. This means we can now run almost
all the recovery tests on all Windows platforms.

Discussion: https://postgr.es/m/20210301200715.tdjpuesfzebpffgn@alap3.anarazel.de

4 years agopg_upgrade: Fix oversight in version checking
Peter Eisentraut [Thu, 4 Mar 2021 07:21:59 +0000 (08:21 +0100)]
pg_upgrade: Fix oversight in version checking

Mistake in f06b1c598254f8adb2b7f51d6a7685618a7fb121: We should only
check the version of the binaries in the target installation.  The
source installation can of course be of a different version.

Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://www.postgresql.org/message-id/flat/E1lHNKN-0005IC-V6%40gemulon.postgresql.org

4 years agoRemove redundant getenv() for PGUSER, in psql help.
Fujii Masao [Thu, 4 Mar 2021 09:23:22 +0000 (18:23 +0900)]
Remove redundant getenv() for PGUSER, in psql help.

Previously psql obtained the value of PGUSER twice to display
a default user in its help message.

Author: Kota Miyake
Reviewed-by: Nitin Jadhav, Fujii Masao
Discussion: https://postgr.es/m/2a3c612babdd6ed63a9d877bb575d793@oss.nttdata.com

4 years agoAvoid extra newline in errors received in FE protocol version 2.
Heikki Linnakangas [Thu, 4 Mar 2021 08:56:33 +0000 (10:56 +0200)]
Avoid extra newline in errors received in FE protocol version 2.

Contrary to what the comment said, the postmaster does in fact end all
its messages in a newline, since server version 7.2. Be tidy and don't
add an extra newline if the error message already has one.

Discussion: https://www.postgresql.org/message-id/CAFBsxsEdgMXc%2BtGfEy9Y41i%3D5pMMjKeH8t8vSAypR3ZnAoQnHg%40mail.gmail.com

4 years agoRemove server and libpq support for old FE/BE protocol version 2.
Heikki Linnakangas [Thu, 4 Mar 2021 08:45:55 +0000 (10:45 +0200)]
Remove server and libpq support for old FE/BE protocol version 2.

Protocol version 3 was introduced in PostgreSQL 7.4. There shouldn't be
many clients or servers left out there without version 3 support. But as
a courtesy, I kept just enough of the old protocol support that we can
still send the "unsupported protocol version" error in v2 format, so that
old clients can display the message properly. Likewise, libpq still
understands v2 ErrorResponse messages when establishing a connection.

The impetus to do this now is that I'm working on a patch to COPY
FROM, to always prefetch some data. We cannot do that safely with the
old protocol, because it requires parsing the input one byte at a time
to detect the end-of-copy marker.

Reviewed-by: Tom Lane, Alvaro Herrera, John Naylor
Discussion: https://www.postgresql.org/message-id/9ec25819-0a8a-d51a-17dc-4150bb3cca3b%40iki.fi

4 years agoAdd trim_array() function.
Tom Lane [Wed, 3 Mar 2021 21:39:57 +0000 (16:39 -0500)]
Add trim_array() function.

This has been in the SQL spec since 2008.  It's a pretty thin
wrapper around the array slice functionality, but the spec
says we should have it, so here it is.

Vik Fearing, reviewed by Dian Fay

Discussion: https://postgr.es/m/fc92ce17-9655-8ff1-c62a-4dc4c8ccd815@postgresfriends.org

4 years agoMake test_target_session_attrs more robust against connection failure.
Tom Lane [Wed, 3 Mar 2021 18:51:43 +0000 (13:51 -0500)]
Make test_target_session_attrs more robust against connection failure.

Feed the desired command to psql via "-c" not stdin, else Perl
may complain that it can't push stdin to an already-failed psql
process, as seen in intermittent buildfarm failures.

Make some minor cosmetic improvements while at it.

Before commit ee28cacf6 we had no tests here that expected failure
to connect, so there seems no need for a back-patch.

Discussion: https://postgr.es/m/CALDaNm2mo8YED=M2ZJKGf1U3F3mw6SaQuLXWCK8rZP6sECYcrA@mail.gmail.com

4 years agopg_upgrade: Check version of target cluster binaries
Peter Eisentraut [Wed, 3 Mar 2021 08:44:46 +0000 (09:44 +0100)]
pg_upgrade: Check version of target cluster binaries

This expands the binary validation in pg_upgrade with a version
check per binary to ensure that the target cluster installation
only contains binaries from the target version.

In order to reduce duplication, validate_exec is exported from
port.h and the local copy in pg_upgrade is removed.

Author: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://www.postgresql.org/message-id/flat/9328.1552952117@sss.pgh.pa.us

4 years agoClarify the usage of max_replication_slots on the subscriber side.
Amit Kapila [Wed, 3 Mar 2021 06:31:56 +0000 (12:01 +0530)]
Clarify the usage of max_replication_slots on the subscriber side.

It was not clear in the docs that the max_replication_slots is also used
to track replication origins on the subscriber side.

Author: Paul Martinez
Reviewed-by: Amit Kapila
Backpatch-through: 10 where logical replication was introduced
Discussion: https://postgr.es/m/CACqFVBZgwCN_pHnW6dMNCrOS7tiHCw6Retf_=U2Vvj3aUSeATw@mail.gmail.com

4 years agoSome copy-editing of GUC descriptions
Peter Eisentraut [Wed, 3 Mar 2021 06:14:35 +0000 (07:14 +0100)]
Some copy-editing of GUC descriptions

4 years agoSilence perlcritic warning in commit ee28cacf6.
Tom Lane [Wed, 3 Mar 2021 04:32:43 +0000 (23:32 -0500)]
Silence perlcritic warning in commit ee28cacf6.

Per buildfarm; this fix is from Michael Paquier (vignesh C
proposed nearly the same).

Discussion: https://postgr.es/m/YD8IZ9OKfUf9X1eF@paquier.xyz

4 years agoUse sort_template.h for qsort_tuple() and qsort_ssup().
Thomas Munro [Wed, 3 Mar 2021 03:57:42 +0000 (16:57 +1300)]
Use sort_template.h for qsort_tuple() and qsort_ssup().

Replace the Perl code previously used to generate specialized sort
functions with sort_template.h.

Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/CA%2BhUKGJ2-eaDqAum5bxhpMNhvuJmRDZxB_Tow0n-gse%2BHG0Yig%40mail.gmail.com

4 years agoUse sort_template.h for qsort() and qsort_arg().
Thomas Munro [Wed, 3 Mar 2021 03:57:26 +0000 (16:57 +1300)]
Use sort_template.h for qsort() and qsort_arg().

Reduce duplication by using the new template.

Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/CA%2BhUKGJ2-eaDqAum5bxhpMNhvuJmRDZxB_Tow0n-gse%2BHG0Yig%40mail.gmail.com

4 years agoAdd sort_template.h for making sort functions.
Thomas Munro [Wed, 3 Mar 2021 03:57:14 +0000 (16:57 +1300)]
Add sort_template.h for making sort functions.

Move our qsort implementation into a header that can be used to define
specialized functions for better performance and reduced duplication.

Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/CA%2BhUKGJ2-eaDqAum5bxhpMNhvuJmRDZxB_Tow0n-gse%2BHG0Yig%40mail.gmail.com

4 years agoAdd option to enable two_phase commits via pg_create_logical_replication_slot.
Amit Kapila [Wed, 3 Mar 2021 01:58:43 +0000 (07:28 +0530)]
Add option to enable two_phase commits via pg_create_logical_replication_slot.

Commit 0aa8a01d04 extends the output plugin API to allow decoding of
prepared xacts and allowed the user to enable/disable the two-phase option
via pg_logical_slot_get_changes(). This can lead to a problem such that
the first time when it gets changes via pg_logical_slot_get_changes()
without two_phase option enabled it will not get the prepared even though
prepare is after consistent snapshot. Now next time during getting changes,
if the two_phase option is enabled it can skip prepare because by that
time start decoding point has been moved. So the user will only get commit
prepared.

Allow to enable/disable this option at the create slot time and default
will be false. It will break the existing slots which is fine in a major
release.

Author: Ajin Cherian
Reviewed-by: Amit Kapila and Vignesh C
Discussion: https://postgr.es/m/d0f60d60-133d-bf8d-bd70-47784d8fabf3@enterprisedb.com

4 years agoExtend the abilities of libpq's target_session_attrs parameter.
Tom Lane [Wed, 3 Mar 2021 01:17:45 +0000 (20:17 -0500)]
Extend the abilities of libpq's target_session_attrs parameter.

In addition to the existing options of "any" and "read-write", we
now support "read-only", "primary", "standby", and "prefer-standby".
"read-write" retains its previous meaning of "transactions are
read-write by default", and "read-only" inverts that.  The other
three modes test specifically for hot-standby status, which is not
quite the same thing.  (Setting default_transaction_read_only on
a primary server renders it read-only to this logic, but not a
standby.)

Furthermore, if talking to a v14 or later server, no extra network
round trip is needed to detect the session's status; the GUC_REPORT
variables delivered by the server are enough.  When talking to an
older server, a SHOW or SELECT query is issued to detect session
read-only-ness or server hot-standby state, as needed.

Haribabu Kommi, Greg Nancarrow, Vignesh C, Tom Lane; reviewed at
various times by Laurenz Albe, Takayuki Tsunakawa, Peter Smith.

Discussion: https://postgr.es/m/CAF3+xM+8-ztOkaV9gHiJ3wfgENTq97QcjXQt+rbFQ6F7oNzt9A@mail.gmail.com

4 years agoAdd --tablespace option to reindexdb
Michael Paquier [Wed, 3 Mar 2021 01:14:21 +0000 (10:14 +0900)]
Add --tablespace option to reindexdb

This option provides REINDEX (TABLESPACE) for reindexdb, applying the
tablespace value given by the caller to all the REINDEX queries
generated.

While on it, this commit adds some tests for REINDEX TABLESPACE, with
and without CONCURRENTLY, when run on toast indexes and tables.  Such
operations are not allowed, and toast relation names are not stable
enough to be part of the main regression test suite (even if using a PL
function with a TRY/CATCH logic, as CONCURRENTLY could not be tested).

Author: Michael Paquier
Reviewed-by: Mark Dilger, Daniel Gustafsson
Discussion: https://postgr.es/m/YDiaDMnzLICqeukl@paquier.xyz

4 years agonbtree page deletion: Add leaftopparent assertion.
Peter Geoghegan [Tue, 2 Mar 2021 22:06:07 +0000 (14:06 -0800)]
nbtree page deletion: Add leaftopparent assertion.

Add documenting assertion.  This makes it easier to follow how we
maintain the top parent link in target subtree's half-dead/leaf level
page.

4 years agoFix nbtree page deletion error messages.
Peter Geoghegan [Tue, 2 Mar 2021 21:02:24 +0000 (13:02 -0800)]
Fix nbtree page deletion error messages.

Adjust some "can't happen" error messages that assumed that the page
deletion target page must be a half-dead page.  This assumption was
wrong in the case of an internal target page.  Simply refer to these
pages as the target page instead.

Internal pages are never marked half-dead.  There is exactly one
half-dead page for each subtree undergoing deletion.  The half-dead page
is also the target subtree's leaf-level page.  This has been the case
since commit efada2b8, which totally overhauled nbtree page deletion.

4 years agoMark default_transaction_read_only as GUC_REPORT.
Tom Lane [Tue, 2 Mar 2021 18:53:46 +0000 (13:53 -0500)]
Mark default_transaction_read_only as GUC_REPORT.

This allows clients to find out the setting at connection time without
having to expend a query round trip to do so; which is helpful when
trying to identify read/write servers.  (One must also look at
in_hot_standby, but that's already GUC_REPORT, cf bf8a662c9.)
Modifying libpq to make use of this will come soon, but I felt it
cleaner to push the server change separately.

Haribabu Kommi, Greg Nancarrow, Vignesh C; reviewed at various times
by Laurenz Albe, Takayuki Tsunakawa, Peter Smith.

Discussion: https://postgr.es/m/CAF3+xM+8-ztOkaV9gHiJ3wfgENTq97QcjXQt+rbFQ6F7oNzt9A@mail.gmail.com

4 years agoUse native path separators to pg_ctl in initdb
Alvaro Herrera [Tue, 2 Mar 2021 18:39:34 +0000 (15:39 -0300)]
Use native path separators to pg_ctl in initdb

On Windows, CMD.EXE allegedly does not run a command that uses forward slashes,
so let's convert the path to use backslashes instead.

Backpatch to 10.

Author: Nitin Jadhav <nitinjadhavpostgres@gmail.com>
Reviewed-by: Juan José Santamaría Flecha <juanjo.santamaria@gmail.com>
Discussion: https://postgr.es/m/CAMm1aWaNDuaPYFYMAqDeJrZmPtNvLcJRS++CcZWY8LT6KcoBZw@mail.gmail.com

4 years agoSuppress unnecessary regex subre nodes in a couple more cases.
Tom Lane [Tue, 2 Mar 2021 17:14:14 +0000 (12:14 -0500)]
Suppress unnecessary regex subre nodes in a couple more cases.

This extends the changes made in commit cebc1d34e, teaching
parseqatom() to generate fewer or cheaper subre nodes in some edge
cases.  The case of interest here is a quantified atom that is "messy"
only because it has greediness opposite to what preceded it (whereas
captures and backrefs are intrinsically messy).  In this case we don't
need an iteration node, since we don't care where the sub-matches of
the quantifier are; and we might also not need a second concatenation
node.  This seems of only marginal real-world use according to my
testing, but I wanted to get it in before wrapping up this series of
regex performance fixes.

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

4 years agoImprove performance of regular expression back-references.
Tom Lane [Tue, 2 Mar 2021 16:55:12 +0000 (11:55 -0500)]
Improve performance of regular expression back-references.

In some cases, at the time that we're doing an NFA-based precheck
of whether a backref subexpression can match at a particular place
in the string, we already know which substring the referenced
subexpression matched.  If so, we might as well forget about the NFA
and just compare the substring; this is faster and it gives an exact
rather than approximate answer.

In general, this optimization can help while we are prechecking within
the second child expression of a concat node, while the capture was
within the first child expression; then the substring was saved during
cdissect() of the first child and will be available to NFA checks done
while cdissect() recurses into the second child.  It can help quite a
lot if the tree looks like

              concat
             /      \
      capture        concat
                    /      \
     expensive stuff        backref

as we will be able to avoid recursively dissecting the "expensive
stuff" before discovering that the backref isn't satisfied with a
particular midpoint that the lower concat node is testing.  This
doesn't help if the concat tree is left-deep, as the capture node
won't get set soon enough (and it's hard to fix that without changing
the engine's match behavior).  Fortunately, right-deep concat trees
are the common case.

Patch by me, reviewed by Joel Jacobson

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

4 years agoFix semantics of regular expression back-references.
Tom Lane [Tue, 2 Mar 2021 16:34:53 +0000 (11:34 -0500)]
Fix semantics of regular expression back-references.

POSIX defines the behavior of back-references thus:

    The back-reference expression '\n' shall match the same (possibly
    empty) string of characters as was matched by a subexpression
    enclosed between "\(" and "\)" preceding the '\n'.

As far as I can see, the back-reference is supposed to consider only
the data characters matched by the referenced subexpression.  However,
because our engine copies the NFA constructed from the referenced
subexpression, it effectively enforces any constraints therein, too.
As an example, '(^.)\1' ought to match 'xx', or any other string
starting with two occurrences of the same character; but in our code
it does not, and indeed can't match anything, because the '^' anchor
constraint is included in the backref's copied NFA.  If POSIX intended
that, you'd think they'd mention it.  Perl for one doesn't act that
way, so it's hard to conclude that this isn't a bug.

Fix by modifying the backref's NFA immediately after it's copied from
the reference, replacing all constraint arcs by EMPTY arcs so that the
constraints are treated as automatically satisfied.  This still allows
us to enforce matching rules that depend only on the data characters;
for example, in '(^\d+).*\1' the NFA matching step will still know
that the backref can only match strings of digits.

Perhaps surprisingly, this change does not affect the results of any
of a rather large corpus of real-world regexes.  Nonetheless, I would
not consider back-patching it, since it's a clear compatibility break.

Patch by me, reviewed by Joel Jacobson

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

4 years agoFix duplicated test case in TAP tests of reindexdb
Michael Paquier [Tue, 2 Mar 2021 04:18:06 +0000 (13:18 +0900)]
Fix duplicated test case in TAP tests of reindexdb

The same test for REINDEX (VERBOSE) was done twice, while it is clear
that the second test should use --concurrently.  Issue introduced in
5dc92b8, for what looks like a copy-paste mistake.

Reviewed-by: Mark Dilger
Discussion: https://postgr.es/m/A7AE97EA-F4B0-4CAB-8FFF-3FECD31F9D63@enterprisedb.com
Backpatch-through: 12

4 years agoSimplify code to switch pg_class.relrowsecurity in tablecmds.c
Michael Paquier [Tue, 2 Mar 2021 03:30:21 +0000 (12:30 +0900)]
Simplify code to switch pg_class.relrowsecurity in tablecmds.c

The same code pattern was repeated twice to enable or disable ROW LEVEL
SECURITY with an ALTER TABLE command.  This makes the code slightly
cleaner.

Author: Justin Pryzby
Reviewed-by: Zhihong Yu
Discussion: https://postgr.es/m/20210228211854.GC20769@telsasoft.com

4 years agodoc: Improve description of data checksums
Michael Paquier [Tue, 2 Mar 2021 01:50:13 +0000 (10:50 +0900)]
doc: Improve description of data checksums

This partially reverts bcf2667 that got incorrectly merged, and this
improves the wording of the documentation that existed before that.

Per discussion with Justin Pryzby.

Discussion: https://postgr.es/m/20210301004647.GF20769@telsasoft.com

4 years agodoc: Mention archive_command failure handling on signals
Michael Paquier [Tue, 2 Mar 2021 01:25:47 +0000 (10:25 +0900)]
doc: Mention archive_command failure handling on signals

The behavior is similar to restore_command, which was already documented
for the restore part, but not the archive part.

Author: Benoit Lobréau
Reviewed-by: Julien Rouhaud
Discussion: https://postgr.es/m/CAPE8EZ7akCzc1hWohA4AcbmKtHh9rcWAB5MStOeZD2+9jC+hLQ@mail.gmail.com

4 years agoImprove reporting for syntax errors in multi-line JSON data.
Tom Lane [Mon, 1 Mar 2021 21:44:17 +0000 (16:44 -0500)]
Improve reporting for syntax errors in multi-line JSON data.

Point to the specific line where the error was detected; the
previous code tended to include several preceding lines as well.
Avoid re-scanning the entire input to recompute which line that
was.  Simplify the logic a bit.  Add test cases.

Simon Riggs and Hamid Akhtar, reviewed by Daniel Gustafsson and myself

Discussion: https://postgr.es/m/CANbhV-EPBnXm3MF_TTWBwwqgn1a1Ghmep9VHfqmNBQ8BT0f+_g@mail.gmail.com

4 years agoRemove obsolete comment for WaitForProcSignalBarrier().
Thomas Munro [Mon, 1 Mar 2021 20:15:15 +0000 (09:15 +1300)]
Remove obsolete comment for WaitForProcSignalBarrier().

Commit 814f1d8b removed the behavior described.

Reported-by: Amit Kapila <amit.kapila16@gmail.com>
4 years agoFix recovery test hang in 021_row_visibility.pl on windows.
Andres Freund [Mon, 1 Mar 2021 17:52:15 +0000 (09:52 -0800)]
Fix recovery test hang in 021_row_visibility.pl on windows.

The psql processes were not explicitly killed (but would eventually
exit due postgres shutting down). For some reason windows perl doesn't
like that, resulting in errors like
Warning: unable to close filehandle GEN20 properly: Bad file descriptor during global destruction.

The test was introduced in d6734a897e3, so no backpatching necessary.

4 years agoAllow condition variables to be used in interrupt code.
Thomas Munro [Mon, 1 Mar 2021 03:28:12 +0000 (16:28 +1300)]
Allow condition variables to be used in interrupt code.

Adjust the condition variable sleep loop to work correctly when code
reached by its internal CHECK_FOR_INTERRUPTS() call interacts with
another condition variable.

There are no such cases currently, but a proposed patch would do this.

Discussion: https://postgr.es/m/CA+hUKGLdemy2gBm80kz20GTe6hNVwoErE8KwcJk6-U56oStjtg@mail.gmail.com

4 years agoUse condition variables for ProcSignalBarriers.
Thomas Munro [Mon, 1 Mar 2021 03:26:22 +0000 (16:26 +1300)]
Use condition variables for ProcSignalBarriers.

Instead of a poll/sleep loop, use a condition variable for precise
wake-up whenever a backend's pss_barrierGeneration advances.

Discussion: https://postgr.es/m/CA+hUKGLdemy2gBm80kz20GTe6hNVwoErE8KwcJk6-U56oStjtg@mail.gmail.com

4 years agoAvoid repeated decoding of prepared transactions after a restart.
Amit Kapila [Mon, 1 Mar 2021 03:41:18 +0000 (09:11 +0530)]
Avoid repeated decoding of prepared transactions after a restart.

In commit a271a1b50e, we allowed decoding at prepare time and the prepare
was decoded again if there is a restart after decoding it. It was done
that way because we can't distinguish between the cases where we have not
decoded the prepare because it was prior to consistent snapshot or we have
decoded it earlier but restarted. To distinguish between these two cases,
we have introduced an initial_consistent_point at the slot level which is
an LSN at which we found a consistent point at the time of slot creation.
This is also the point where we have exported a snapshot for the initial
copy. So, prepare transaction prior to this point are sent along with
commit prepared.

This commit bumps SNAPBUILD_VERSION because of change in SnapBuild. It
will break existing slots which is fine in a major release.

Author: Ajin Cherian, based on idea by Andres Freund
Reviewed-by: Amit Kapila and Vignesh C
Discussion: https://postgr.es/m/d0f60d60-133d-bf8d-bd70-47784d8fabf3@enterprisedb.com

4 years agoUse FeBeWaitSet for walsender.c.
Thomas Munro [Mon, 1 Mar 2021 02:17:28 +0000 (15:17 +1300)]
Use FeBeWaitSet for walsender.c.

This avoids the need to set up and tear down a fresh WaitEventSet every
time we need need to wait.  We have to add an explicit exit on
postmaster exit (FeBeWaitSet isn't set up to do that automatically), so
move the code to do that into a new function to avoid repetition.

Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com> (earlier version)
Discussion: https://postgr.es/m/CA%2BhUKGJAC4Oqao%3DqforhNey20J8CiG2R%3DoBPqvfR0vOJrFysGw%40mail.gmail.com

4 years agoIntroduce symbolic names for FeBeWaitSet positions.
Thomas Munro [Mon, 1 Mar 2021 02:16:56 +0000 (15:16 +1300)]
Introduce symbolic names for FeBeWaitSet positions.

Previously we used 0 and 1 to refer to the socket and latch in far flung
parts of the tree, without any explanation.  Also use PGINVALID_SOCKET
rather than -1 in a couple of places that didn't already do that.

Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Discussion: https://postgr.es/m/CA%2BhUKGJAC4Oqao%3DqforhNey20J8CiG2R%3DoBPqvfR0vOJrFysGw%40mail.gmail.com

4 years agoUpdate docs of logical replication for commit ce0fdbfe97.
Amit Kapila [Mon, 1 Mar 2021 02:53:41 +0000 (08:23 +0530)]
Update docs of logical replication for commit ce0fdbfe97.

Forgot to update the logical replication configuration settings page.
After commit ce0fdbfe97, table synchronization workers also started using
replication origins to track the progress and the same should be reflected
in docs.

Author: Amit Kapila
Discussion: https://postgr.es/m/CAA4eK1KkbppndxxRKbaT2sXrLkdPwy44F4pjEZ0EDrVjD9MPjQ@mail.gmail.com

4 years agoUpdate the docs and comments for decoding of prepared xacts.
Amit Kapila [Mon, 1 Mar 2021 02:44:33 +0000 (08:14 +0530)]
Update the docs and comments for decoding of prepared xacts.

Commit a271a1b50e introduced decoding at prepare time in ReorderBuffer.
This can lead to deadlock for out-of-core logical replication solutions
that uses this feature to build distributed 2PC in case such transactions
lock [user] catalog tables exclusively. They need to inform users to not
have locks on catalog tables (via explicit LOCK command) in such
transactions.

Reported-by: Andres Freund
Discussion: https://postgr.es/m/20210222222847.tpnb6eg3yiykzpky@alap3.anarazel.de

4 years agoUse EVFILT_SIGNAL for kqueue latches.
Thomas Munro [Sun, 28 Feb 2021 23:28:43 +0000 (12:28 +1300)]
Use EVFILT_SIGNAL for kqueue latches.

Cut down on system calls and other overheads by waiting for SIGURG
explicitly with kqueue instead of using a signal handler and self-pipe.
Affects *BSD and macOS systems.

This leaves only the poll implementation with a signal handler and the
traditional self-pipe trick.

Discussion: https://postgr.es/m/CA+hUKGJjxPDpzBE0a3hyUywBvaZuC89yx3jK9RFZgfv_KHU7gg@mail.gmail.com

4 years agoUse signalfd(2) for epoll latches.
Thomas Munro [Sun, 28 Feb 2021 23:06:09 +0000 (12:06 +1300)]
Use signalfd(2) for epoll latches.

Cut down on system calls and other overheads by reading from a signalfd
instead of using a signal handler and self-pipe.  Affects Linux sytems,
and possibly others including illumos that implement the Linux epoll and
signalfd interfaces.

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

4 years agoUse SIGURG rather than SIGUSR1 for latches.
Thomas Munro [Sun, 28 Feb 2021 22:58:10 +0000 (11:58 +1300)]
Use SIGURG rather than SIGUSR1 for latches.

Traditionally, SIGUSR1 has been overloaded for ad-hoc signals,
procsignal.c signals and latch.c wakeups.  Move that last use over to a
new dedicated signal.  SIGURG is normally used to report out-of-band
socket data, but PostgreSQL doesn't use that facility.

The signal handler is now installed in all postmaster children by
InitializeLatchSupport().  Those wishing to disconnect from it should
call ShutdownLatchSupport().

Future patches will use this separation of signals to avoid the need for
a signal handler on some operating systems.

Discussion: https://postgr.es/m/CA+hUKGJjxPDpzBE0a3hyUywBvaZuC89yx3jK9RFZgfv_KHU7gg@mail.gmail.com

4 years agoOptimize latches to send fewer signals.
Thomas Munro [Sun, 28 Feb 2021 22:51:15 +0000 (11:51 +1300)]
Optimize latches to send fewer signals.

Don't send signals to processes that aren't sleeping.

Author: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA+hUKGJjxPDpzBE0a3hyUywBvaZuC89yx3jK9RFZgfv_KHU7gg@mail.gmail.com

4 years agoRemove latch.c workaround for Linux < 2.6.27.
Thomas Munro [Sun, 28 Feb 2021 21:44:21 +0000 (10:44 +1300)]
Remove latch.c workaround for Linux < 2.6.27.

Commit 82ebbeb0 added a workaround for systems with no epoll_create1()
and EPOLL_CLOEXEC.  Linux < 2.6.27 and glibc < 2.9 are long gone.  Now
seems like a good time to drop the extra code, because otherwise we'd
have to add similar already-dead workaround code to new patches using
XXX_CLOEXEC flags that arrived in the same kernel release.

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

4 years agopgbench: Remove now-dead CState->ecnt
Michael Paquier [Sat, 27 Feb 2021 22:50:26 +0000 (07:50 +0900)]
pgbench: Remove now-dead CState->ecnt

The last use of ecnt was in 12788ae.  It was getting incremented after a
backend error without any purpose since then, so let's get rid of it.

Author: Kota Miyake
Reviewed-by: Álvaro Herrera
Discussion: https://postgr.es/m/786c3d9fbe067763d899e78c296f9f0f@oss.nttdata.com

4 years agoFix use-after-free bug with AfterTriggersTableData.storeslot
Alvaro Herrera [Sat, 27 Feb 2021 21:09:15 +0000 (18:09 -0300)]
Fix use-after-free bug with AfterTriggersTableData.storeslot

AfterTriggerSaveEvent() wrongly allocates the slot in execution-span
memory context, whereas the correct thing is to allocate it in
a transaction-span context, because that's where the enclosing
AfterTriggersTableData instance belongs into.

Backpatch to 12 (the test back to 11, where it works well with no code
changes, and it's good to have to confirm that the case was previously
well supported); this bug seems introduced by commit ff11e7f4b9ae.

Reported-by: Bertrand Drouvot <bdrouvot@amazon.com>
Author: Amit Langote <amitlangote09@gmail.com>
Discussion: https://postgr.es/m/39a71864-b120-5a5c-8cc5-c632b6f16761@amazon.com

4 years agoRaise a timeout to 180s, in contrib/test_decoding.
Noah Misch [Sat, 27 Feb 2021 15:02:56 +0000 (07:02 -0800)]
Raise a timeout to 180s, in contrib/test_decoding.

Per buildfarm member hornet.  The test is new in v14, so no back-patch.

4 years agoAdd missing TidRangeScan readfunc
David Rowley [Sat, 27 Feb 2021 10:21:21 +0000 (23:21 +1300)]
Add missing TidRangeScan readfunc

Mistakenly forgotten in bb437f995

4 years agoAdd TID Range Scans to support efficient scanning ranges of TIDs
David Rowley [Sat, 27 Feb 2021 09:59:36 +0000 (22:59 +1300)]
Add TID Range Scans to support efficient scanning ranges of TIDs

This adds a new executor node named TID Range Scan.  The query planner
will generate paths for TID Range scans when quals are discovered on base
relations which search for ranges on the table's ctid column.  These
ranges may be open at either end. For example, WHERE ctid >= '(10,0)';
will return all tuples on page 10 and over.

To support this, two new optional callback functions have been added to
table AM.  scan_set_tidrange is used to set the scan range to just the
given range of TIDs.  scan_getnextslot_tidrange fetches the next tuple
in the given range.

For AMs were scanning ranges of TIDs would not make sense, these functions
can be set to NULL in the TableAmRoutine.  The query planner won't
generate TID Range Scan Paths in that case.

Author: Edmund Horner, David Rowley
Reviewed-by: David Rowley, Tomas Vondra, Tom Lane, Andres Freund, Zhihong Yu
Discussion: https://postgr.es/m/CAMyN-kB-nFTkF=VA_JPwFNo08S0d-Yk0F741S2B7LDmYAi8eyA@mail.gmail.com

4 years agoEnhanced cycle mark values
Peter Eisentraut [Sat, 27 Feb 2021 07:11:14 +0000 (08:11 +0100)]
Enhanced cycle mark values

Per SQL:202x draft, in the CYCLE clause of a recursive query, the
cycle mark values can be of type boolean and can be omitted, in which
case they default to TRUE and FALSE.

Reviewed-by: Vik Fearing <vik@postgresfriends.org>
Discussion: https://www.postgresql.org/message-id/flat/db80ceee-6f97-9b4a-8ee8-3ba0c58e5be2@2ndquadrant.com

4 years agoDoc: further clarify libpq's description of connection string URIs.
Tom Lane [Fri, 26 Feb 2021 20:24:00 +0000 (15:24 -0500)]
Doc: further clarify libpq's description of connection string URIs.

Break the synopsis into named parts to make it less confusing.
Make more than zero effort at applying SGML markup.  Do a bit
of copy-editing of nearby text.

The synopsis revision is by Alvaro Herrera and Paul Förster,
the rest is my fault.  Back-patch to v10 where multi-host
connection strings appeared.

Discussion: https://postgr.es/m/6E752D6B-487C-463E-B6E2-C32E7FB007EA@gmail.com

4 years agoImprove memory management in regex compiler.
Tom Lane [Fri, 26 Feb 2021 18:52:10 +0000 (13:52 -0500)]
Improve memory management in regex compiler.

The previous logic here created a separate pool of arcs for each
state, so that the out-arcs of each state were physically stored
within it.  Perhaps this choice was driven by trying to not include
a "from" pointer within each arc; but Spencer gave up on that idea
long ago, and it's hard to see what the value is now.  The approach
turns out to be fairly disastrous in terms of memory consumption,
though.  In the first place, NFAs built by this engine seem to have
about 4 arcs per state on average, with a majority having only one
or two out-arcs.  So pre-allocating 10 out-arcs for each state is
already cause for a factor of two or more bloat.  Worse, the NFA
optimization phase moves arcs around with abandon.  In a large NFA,
some of the states will have hundreds of out-arcs, so towards the
end of the optimization phase we have a significant number of states
whose arc pools have room for hundreds of arcs each, even though only
a few of those arcs are in use.  We have seen real-world regexes in
which this effect bloats the memory requirement by 25X or even more.

Hence, get rid of the per-state arc pools in favor of a single arc
pool for the whole NFA, with variable-sized allocation batches
instead of always asking for 10 at a time.  While we're at it,
let's batch the allocations of state structs too, to further reduce
the malloc traffic.

This incidentally allows moveouts() to be optimized in a similar
way to moveins(): when moving an arc to another state, it's now
valid to just re-link the same arc struct into a different outchain,
where before the code invariants required us to make a physically
new arc and then free the old one.

These changes reduce the regex compiler's typical space consumption
for average-size regexes by about a factor of two, and much more for
large or complicated regexes.  In a large test set of real-world
regexes, we formerly had half a dozen cases that failed with "regular
expression too complex" due to exceeding the REG_MAX_COMPILE_SPACE
limit (about 150MB); we would have had to raise that limit to
something close to 400MB to make them work with the old code.  Now,
none of those cases need more than 13MB to compile.  Furthermore,
the test set is about 10% faster overall due to less malloc traffic.

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

4 years agoExtend a test case a little
Peter Eisentraut [Fri, 26 Feb 2021 08:11:15 +0000 (09:11 +0100)]
Extend a test case a little

This will possibly help a subsequent patch by making sure the notice
messages are distinct so that it's clear that they come out in the
right order.

Author: Fabien COELHO <coelho@cri.ensmp.fr>
Discussion: https://www.postgresql.org/message-id/alpine.DEB.2.21.1904240654120.3407%40lancre

4 years agodoc: Improve {archive,restore}_command for compressed logs
Michael Paquier [Fri, 26 Feb 2021 05:39:03 +0000 (14:39 +0900)]
doc: Improve {archive,restore}_command for compressed logs

The commands mentioned in the docs with gzip and gunzip did not prefix
the archives with ".gz" and used inconsistent paths for the archives,
which can be confusing.

Reported-by: Philipp Gramzow
Reviewed-by: Fujii Masao
Discussion: https://postgr.es/m/161397938841.15451.13129264141285167267@wrigleys.postgresql.org

4 years agoRevert "pg_collation_actual_version() -> pg_collation_current_version()."
Thomas Munro [Fri, 26 Feb 2021 02:29:27 +0000 (15:29 +1300)]
Revert "pg_collation_actual_version() -> pg_collation_current_version()."

This reverts commit 9cf184cc0599b6e65e7e5ecd9d91cd42e278bcd8.  Name
change less well received than anticipated.

Discussion: https://postgr.es/m/afcfb97e-88a1-a540-db95-6c573b93bc2b%40eisentraut.org

4 years agoFix list-manipulation bug in WITH RECURSIVE processing.
Tom Lane [Fri, 26 Feb 2021 01:47:32 +0000 (20:47 -0500)]
Fix list-manipulation bug in WITH RECURSIVE processing.

makeDependencyGraphWalker and checkWellFormedRecursionWalker
thought they could hold onto a pointer to a list's first
cons cell while the list was modified by recursive calls.
That was okay when the cons cell was actually separately
palloc'd ... but since commit 1cff1b95a, it's quite unsafe,
leading to core dumps or incorrect complaints of faulty
WITH nesting.

In the field this'd require at least a seven-deep WITH nest
to cause an issue, but enabling DEBUG_LIST_MEMORY_USAGE
allows the bug to be seen with lesser nesting depths.

Per bug #16801 from Alexander Lakhin.  Back-patch to v13.

Michael Paquier and Tom Lane

Discussion: https://postgr.es/m/16801-393c7922143eaa4d@postgresql.org

4 years agoVACUUM VERBOSE: Count "newly deleted" index pages.
Peter Geoghegan [Thu, 25 Feb 2021 22:32:18 +0000 (14:32 -0800)]
VACUUM VERBOSE: Count "newly deleted" index pages.

Teach VACUUM VERBOSE to report on pages deleted by the _current_ VACUUM
operation -- these are newly deleted pages.  VACUUM VERBOSE continues to
report on the total number of deleted pages in the entire index (no
change there).  The former is a subset of the latter.

The distinction between each category of deleted index page only arises
with index AMs where page deletion is supported and is decoupled from
page recycling for performance reasons.

This is follow-up work to commit e5d8a999, which made nbtree store
64-bit XIDs (not 32-bit XIDs) in pages at the point at which they're
deleted.  Note that the btm_last_cleanup_num_delpages metapage field
added by that commit usually gets set to pages_newly_deleted.  The
exceptions (the scenarios in which they're not equal) all seem to be
tricky cases for the implementation (of page deletion and recycling) in
general.

Author: Peter Geoghegan <pg@bowt.ie>
Discussion: https://postgr.es/m/CAH2-WznpdHvujGUwYZ8sihX%3Dd5u-tRYhi-F4wnV2uN2zHpMUXw%40mail.gmail.com

4 years agoDoc: remove src/backend/regex/re_syntax.n.
Tom Lane [Thu, 25 Feb 2021 18:33:27 +0000 (13:33 -0500)]
Doc: remove src/backend/regex/re_syntax.n.

We aren't publishing this file as documentation, and it's been
much more haphazardly maintained than the real docs in func.sgml,
so let's just drop it.  I think the only reason I included it in
commit 7bcc6d98f was that the Berkeley-era sources had had a man
page in this directory.

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

4 years agoChange regex \D and \W shorthands to always match newlines.
Tom Lane [Thu, 25 Feb 2021 18:29:06 +0000 (13:29 -0500)]
Change regex \D and \W shorthands to always match newlines.

Newline is certainly not a digit, nor a word character, so it is
sensible that it should match these complemented character classes.
Previously, \D and \W acted that way by default, but in
newline-sensitive mode ('n' or 'p' flag) they did not match newlines.

This behavior was previously forced because explicit complemented
character classes don't match newlines in newline-sensitive mode;
but as of the previous commit that implementation constraint no
longer exists.  It seems useful to change this because the primary
real-world use for newline-sensitive mode seems to be to match the
default behavior of other regex engines such as Perl and Javascript
... and their default behavior is that these match newlines.

The old behavior can be kept by writing an explicit complemented
character class, i.e. [^[:digit:]] or [^[:word:]].  (This means
that \D and \W are not exactly equivalent to those strings, but
they weren't anyway.)

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

4 years agoAllow complemented character class escapes within regex brackets.
Tom Lane [Thu, 25 Feb 2021 18:00:40 +0000 (13:00 -0500)]
Allow complemented character class escapes within regex brackets.

The complement-class escapes \D, \S, \W are now allowed within
bracket expressions.  There is no semantic difficulty with doing
that, but the rather hokey macro-expansion-based implementation
previously used here couldn't cope.

Also, invent "word" as an allowed character class name, thus "\w"
is now equivalent to "[[:word:]]" outside brackets, or "[:word:]"
within brackets.  POSIX allows such implementation-specific
extensions, and the same name is used in e.g. bash.

One surprising compatibility issue this raises is that constructs
such as "[\w-_]" are now disallowed, as our documentation has always
said they should be: character classes can't be endpoints of a range.
Previously, because \w was just a macro for "[:alnum:]_", such a
construct was read as "[[:alnum:]_-_]", so it was accepted so long as
the character after "-" was numerically greater than or equal to "_".

Some implementation cleanup along the way:

* Remove the lexnest() hack, and in consequence clean up wordchrs()
to not interact with the lexer.

* Fix colorcomplement() to not be O(N^2) in the number of colors
involved.

* Get rid of useless-as-far-as-I-can-see calls of element()
on single-character character element names in brackpart().
element() always maps these to the character itself, and things
would be quite broken if it didn't --- should "[a]" match something
different than "a" does?  Besides, the shortcut path in brackpart()
wasn't doing this anyway, making it even more inconsistent.

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

4 years agoImprove tab-completion for TRUNCATE.
Fujii Masao [Thu, 25 Feb 2021 09:20:57 +0000 (18:20 +0900)]
Improve tab-completion for TRUNCATE.

Author: Kota Miyake
Reviewed-by: Muhammad Usama
Discussion: https://postgr.es/m/f5d30053d00dcafda3280c9e267ecb0f@oss.nttdata.com

4 years agodoc: Mention PGDATABASE as supported by pgbench
Michael Paquier [Thu, 25 Feb 2021 07:06:54 +0000 (16:06 +0900)]
doc: Mention PGDATABASE as supported by pgbench

PGHOST, PGPORT and PGUSER were already mentioned, but not PGDATABASE.
Like 5aaa584, backpatch down to 12.

Reported-by: Christophe Courtois
Discussion: https://postgr.es/m/161399398648.21711.15387267201764682579@wrigleys.postgresql.org
Backpatch-through: 12

4 years agoUse full 64-bit XIDs in deleted nbtree pages.
Peter Geoghegan [Thu, 25 Feb 2021 02:41:34 +0000 (18:41 -0800)]
Use full 64-bit XIDs in deleted nbtree pages.

Otherwise we risk "leaking" deleted pages by making them non-recyclable
indefinitely.  Commit 6655a729 did the same thing for deleted pages in
GiST indexes.  That work was used as a starting point here.

Stop storing an XID indicating the oldest bpto.xact across all deleted
though unrecycled pages in nbtree metapages.  There is no longer any
reason to care about that condition/the oldest XID.  It only ever made
sense when wraparound was something _bt_vacuum_needs_cleanup() had to
consider.

The btm_oldest_btpo_xact metapage field has been repurposed and renamed.
It is now btm_last_cleanup_num_delpages, which is used to remember how
many non-recycled deleted pages remain from the last VACUUM (in practice
its value is usually the precise number of pages that were _newly
deleted_ during the specific VACUUM operation that last set the field).

The general idea behind storing btm_last_cleanup_num_delpages is to use
it to give _some_ consideration to non-recycled deleted pages inside
_bt_vacuum_needs_cleanup() -- though never too much.  We only really
need to avoid leaving a truly excessive number of deleted pages in an
unrecycled state forever.  We only do this to cover certain narrow cases
where no other factor makes VACUUM do a full scan, and yet the index
continues to grow (and so actually misses out on recycling existing
deleted pages).

These metapage changes result in a clear user-visible benefit: We no
longer trigger full index scans during VACUUM operations solely due to
the presence of only 1 or 2 known deleted (though unrecycled) blocks
from a very large index.  All that matters now is keeping the costs and
benefits in balance over time.

Fix an issue that has been around since commit 857f9c36, which added the
"skip full scan of index" mechanism (i.e. the _bt_vacuum_needs_cleanup()
logic).  The accuracy of btm_last_cleanup_num_heap_tuples accidentally
hinged upon _when_ the source value gets stored.  We now always store
btm_last_cleanup_num_heap_tuples in btvacuumcleanup().  This fixes the
issue because IndexVacuumInfo.num_heap_tuples (the source field) is
expected to accurately indicate the state of the table _after_ the
VACUUM completes inside btvacuumcleanup().

A backpatchable fix cannot easily be extracted from this commit.  A
targeted fix for the issue will follow in a later commit, though that
won't happen today.

I (pgeoghegan) have chosen to remove any mention of deleted pages in the
documentation of the vacuum_cleanup_index_scale_factor GUC/param, since
the presence of deleted (though unrecycled) pages is no longer of much
concern to users.  The vacuum_cleanup_index_scale_factor description in
the docs now seems rather unclear in any case, and it should probably be
rewritten in the near future.  Perhaps some passing mention of page
deletion will be added back at the same time.

Bump XLOG_PAGE_MAGIC due to nbtree WAL records using full XIDs now.

Author: Peter Geoghegan <pg@bowt.ie>
Reviewed-By: Masahiko Sawada <sawada.mshk@gmail.com>
Discussion: https://postgr.es/m/CAH2-WznpdHvujGUwYZ8sihX=d5u-tRYhi-F4wnV2uN2zHpMUXw@mail.gmail.com

4 years agoFix relcache reference leak introduced by ce0fdbfe97.
Amit Kapila [Thu, 25 Feb 2021 02:18:24 +0000 (07:48 +0530)]
Fix relcache reference leak introduced by ce0fdbfe97.

Author: Sawada Masahiko
Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/CAD21AoA7ZEfsOXQ9HQqMv3QYGsEm2H5Wk5ic5S=mvzDf-3a3SA@mail.gmail.com

4 years agoFix some typos, grammar and style in docs and comments
Michael Paquier [Wed, 24 Feb 2021 07:13:17 +0000 (16:13 +0900)]
Fix some typos, grammar and style in docs and comments

The portions fixing the documentation are backpatched where needed.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20210210235557.GQ20012@telsasoft.com
backpatch-through: 9.6

4 years agoMessage style fix
Peter Eisentraut [Wed, 24 Feb 2021 06:00:49 +0000 (07:00 +0100)]
Message style fix

Don't quote type name placeholders.