postgresql.git
3 years agoFix pgbench TAP test.
Tatsuo Ishii [Thu, 24 Mar 2022 04:32:59 +0000 (13:32 +0900)]
Fix pgbench TAP test.

Bildfarm member prairiedog reported a pgbench TAP test failure after
commit: 4a39f87acd6e681e5ded1239391d8a92645b43d6. This commit attempts
to fix some copy&paste errors introduced in the previous commit.

Author: Yugo Nagata
Reported-by: Tom Lane
Discussion: https://postgr.es/m/2775989.1648060014%40sss.pgh.pa.us

3 years agoRefactor code related to pg_hba_file_rules() into new file
Michael Paquier [Thu, 24 Mar 2022 03:42:30 +0000 (12:42 +0900)]
Refactor code related to pg_hba_file_rules() into new file

hba.c is growing big, and more contents are planned for it.  In order to
prepare for this future work, this commit moves all the code related to
the system function processing the contents of pg_hba.conf,
pg_hba_file_rules() to a new file called hbafuncs.c, which will be used
as the location for the SQL portion of the authentication file parsing.
While on it, HbaToken, the structure holding a string token lexed from a
configuration file related to authentication, is renamed to a more
generic AuthToken, as it gets used not only for pg_hba.conf, but also
for pg_ident.conf.  TokenizedLine is now named TokenizedAuthLine.

The size of hba.c is reduced by ~12%.

Author: Julien Rouhaud
Reviewed-by: Aleksander Alekseev, Michael Paquier
Discussion: https://postgr.es/m/20220223045959.35ipdsvbxcstrhya@jrouhaud

3 years agoAdd some basic regression tests for pg_freespacemap
Michael Paquier [Thu, 24 Mar 2022 00:36:30 +0000 (09:36 +0900)]
Add some basic regression tests for pg_freespacemap

The number of relation pages is tricky to get right in a portable way,
particularly across 32b and 64b builds, but checking after the existence
of the FSM and if there is any space available space should be stable
enough with a minimal number of tuples involved.  This commit introduces
checks on a table with some btree, BRIN and hash indexes, as a first
attempt.

Author: Dong Wook Lee, Fabrízio de Royes Mello, Michael Paquier
Discussion: https://postgr.es/m/CAAcByaJ5KW3bd7fJr=jPEyK8M_UzXJFHHBVuOcBe+JHD8txRyQ@mail.gmail.com

3 years agoDon't try to translate NULL in GetConfigOptionByNum().
Andres Freund [Wed, 23 Mar 2022 20:05:59 +0000 (13:05 -0700)]
Don't try to translate NULL in GetConfigOptionByNum().

Noticed via -fsanitize=undefined. Introduced when a few columns in
GetConfigOptionByNum() / pg_settings started to be translated in 72be8c29a /
PG 12.

Backpatch to all affected branches, for the same reasons as 46ab07ffda9.

Discussion: https://postgr.es/m/20220323173537.ll7klrglnp4gn2um@alap3.anarazel.de
Backpatch: 12-

3 years agoDon't call fwrite() with len == 0 when writing out relcache init file.
Andres Freund [Wed, 23 Mar 2022 20:05:25 +0000 (13:05 -0700)]
Don't call fwrite() with len == 0 when writing out relcache init file.

Noticed via -fsanitize=undefined.

Backpatch to all branches, for the same reasons as 46ab07ffda9.

Discussion: https://postgr.es/m/20220323173537.ll7klrglnp4gn2um@alap3.anarazel.de
Backpatch: 10-

3 years agoconfigure: check for dlsym instead of dlopen.
Andres Freund [Wed, 23 Mar 2022 19:43:14 +0000 (12:43 -0700)]
configure: check for dlsym instead of dlopen.

When building with sanitizers the sanitizer library provides dlopen, but not
dlsym(), making configure think that -ldl isn't needed. Just checking for
dlsym() ought to suffice, hard to see dlsym() being provided without dlopen()
also being provided.

Backpatch to all branches, for the same reasons as 46ab07ffda9.

Reviewed-By: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/20220323173537.ll7klrglnp4gn2um@alap3.anarazel.de
Backpatch: 10-

3 years agoClean test_rls_hooks module
Andrew Dunstan [Wed, 23 Mar 2022 19:11:45 +0000 (15:11 -0400)]
Clean test_rls_hooks module

This module isn't an extension and doesn't need to be preloaded.
Adjust the Makefile and remove the extraneous .control and .conf
files accordingly.

Discussion: https://postgr.es/m/43bcaaab-077e-cebe-35be-3cd7f2633449@dunslane.net

3 years agoci: test headerscheck, cpluspluscheck as part of CompilerWarnings task.
Andres Freund [Wed, 23 Mar 2022 18:33:01 +0000 (11:33 -0700)]
ci: test headerscheck, cpluspluscheck as part of CompilerWarnings task.

Discussion: https://postgr.es/m/20220323002024.f2g6tivduzrktgfa@alap3.anarazel.de

3 years agopg_upgrade: Upgrade an Assert to a real 'if' test
Alvaro Herrera [Wed, 23 Mar 2022 18:23:51 +0000 (19:23 +0100)]
pg_upgrade: Upgrade an Assert to a real 'if' test

It seems possible for the condition being tested to be true in
production, and nobody would never know (except when some data
eventually becomes corrupt?).

Author: Álvaro Herrera <alvherre@alvh.no-ip.org>
Discussion: https://postgr.es/m//202109040001.zky3wgv2qeqg@alvherre.pgsql

3 years agopg_basebackup: Try to fix some failures on Windows.
Robert Haas [Wed, 23 Mar 2022 17:25:26 +0000 (13:25 -0400)]
pg_basebackup: Try to fix some failures on Windows.

Commit ffd53659c46a54a6978bcb8c4424c1e157a2c0f1 messed up the
mechanism that was being used to pass parameters to LogStreamerMain()
on Windows. It worked on Linux because only Windows was using threads.
Repair by moving the additional parameters added by that commit into
the 'logstreamer_param' struct.

Along the way, fix a compiler warning on builds without HAVE_LIBZ.

Discussion: http://postgr.es/m/CA+TgmoY5=AmWOtMj3v+cySP2rR=Bt6EGyF_joAq4CfczMddKtw@mail.gmail.com

3 years agoFix "missing continuation record" after standby promotion
Alvaro Herrera [Wed, 23 Mar 2022 17:22:10 +0000 (18:22 +0100)]
Fix "missing continuation record" after standby promotion

Invalidate abortedRecPtr and missingContrecPtr after a missing
continuation record is successfully skipped on a standby. This fixes a
PANIC caused when a recently promoted standby attempts to write an
OVERWRITE_RECORD with an LSN of the previously read aborted record.

Backpatch to 10 (all stable versions).

Author: Sami Imseih <simseih@amazon.com>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@alvh.no-ip.org>
Discussion: https://postgr.es/m/44D259DE-7542-49C4-8A52-2AB01534DCA9@amazon.com

3 years agotest_decoding: Add comments about delaying BEGIN/PREPARE
Alvaro Herrera [Wed, 23 Mar 2022 15:17:00 +0000 (16:17 +0100)]
test_decoding: Add comments about delaying BEGIN/PREPARE

It is not immediately obvious why we return early in these functions;
these comments should make it so.

Reviewed-by: Tomas Vondra <tomas.vondra@enterprisedb.com>
Discussion: https://postgr.es/m/202202141336.xv35beswc6ec@alvherre.pgsql

3 years agoIn get_bc_algorithm_name, add a dummy return statement.
Robert Haas [Wed, 23 Mar 2022 15:37:12 +0000 (11:37 -0400)]
In get_bc_algorithm_name, add a dummy return statement.

This code shouldn't be reached, but having it here might avoid a
compiler warning.

Per CI complaint from Andres Freund.

Discussion: http://postgr.es/m/C6A7643A-582B-47F7-A03D-01736BC0349B@anarazel.de

3 years agoForce NO_LOCALE / UTF8 for test_oat_hooks tests
Andrew Dunstan [Wed, 23 Mar 2022 15:13:33 +0000 (11:13 -0400)]
Force NO_LOCALE / UTF8 for test_oat_hooks tests

This will fix cases like fairywren that have been having issues.

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

3 years agoUse approved style for listing OBJS in test_oat_hooks Makefile
Andrew Dunstan [Wed, 23 Mar 2022 14:42:25 +0000 (10:42 -0400)]
Use approved style for listing OBJS in test_oat_hooks Makefile

3 years agoUnbreak the build.
Robert Haas [Wed, 23 Mar 2022 14:22:54 +0000 (10:22 -0400)]
Unbreak the build.

Commit ffd53659c46a54a6978bcb8c4424c1e157a2c0f1 broke the build for
anyone not compiling with LZ4 and ZSTD enabled. Woops.

3 years agoReplace BASE_BACKUP COMPRESSION_LEVEL option with COMPRESSION_DETAIL.
Robert Haas [Wed, 23 Mar 2022 13:19:14 +0000 (09:19 -0400)]
Replace BASE_BACKUP COMPRESSION_LEVEL option with COMPRESSION_DETAIL.

There are more compression parameters that can be specified than just
an integer compression level, so rename the new COMPRESSION_LEVEL
option to COMPRESSION_DETAIL before it gets released. Introduce a
flexible syntax for that option to allow arbitrary options to be
specified without needing to adjust the main replication grammar,
and common code to parse it that is shared between the client and
the server.

This commit doesn't actually add any new compression parameters,
so the only user-visible change is that you can now type something
like pg_basebackup --compress gzip:level=5 instead of writing just
pg_basebackup --compress gzip:5. However, it should make it easy to
add new options. If for example gzip starts offering fries, we can
support pg_basebackup --compress gzip:level=5,fries=true for the
benefit of users who want fries with that.

Along the way, this fixes a few things in pg_basebackup so that the
pg_basebackup can be used with a server-side compression algorithm
that pg_basebackup itself does not understand. For example,
pg_basebackup --compress server-lz4 could still succeed even if
only the server and not the client has LZ4 support, provided that
the other options to pg_basebackup don't require the client to
decompress the archive.

Patch by me. Reviewed by Justin Pryzby and Dagfinn Ilmari Mannsåker.

Discussion: http://postgr.es/m/CA+TgmoYvpetyRAbbg1M8b3-iHsaN4nsgmWPjOENu5-doHuJ7fA@mail.gmail.com

3 years agoAllow pgbench to retry in some cases.
Tatsuo Ishii [Wed, 23 Mar 2022 09:52:37 +0000 (18:52 +0900)]
Allow pgbench to retry in some cases.

When serialization or deadlock errors are reported by backend, allow
to retry and continue the benchmarking. For this purpose new options
"--max-tries", "--failures-detailed" and "--verbose-errors" are added.

Transactions with serialization errors or deadlock errors will be
repeated after rollbacks until they complete successfully or reach the
maximum number of tries (specified by the --max-tries option), or the
maximum time of tries (specified by the --latency-limit option).
These options can be specified at the same time. It is not possible to
use an unlimited number of tries (--max-tries=0) without the
--latency-limit option or the --time option. By default the option
--max-tries is set to 1, which means transactions with
serialization/deadlock errors are not retried. If the last try fails,
this transaction will be reported as failed, and the client variables
will be set as they were before the first run of this transaction.

Statistics on retries and failures are printed in the progress,
transaction / aggregation logs and in the end with other results (all
and for each script). Also retries and failures are printed
per-command with average latency by using option
(--report-per-command, -r).

Option --failures-detailed prints group failures by basic types
(serialization failures / deadlock failures).

Option --verbose-errors prints distinct reports on errors and failures
(errors without retrying) by type with detailed information like which
limit for retries was violated and how far it was exceeded for the
serialization/deadlock failures.

Patch originally written by Marina Polyakova then Yugo Nagata
inherited the discussion and heavily modified the patch to make it
commitable.

Authors: Yugo Nagata, Marina Polyakova
Reviewed-by: Fabien Coelho, Tatsuo Ishii, Alvaro Herrera, Kevin Grittner, Andres Freund, Arthur Zakirov, Alexander Korotkov, Teodor Sigaev, Ildus Kurbangaliev
Discussion: https://postgr.es/m/flat/72a0d590d6ba06f242d75c2e641820ec%40postgrespro.ru

3 years agoTry to stabilize vacuum test.
Thomas Munro [Wed, 23 Mar 2022 01:31:18 +0000 (14:31 +1300)]
Try to stabilize vacuum test.

As commits b700f96c and 3414099c did for the reloptions test, make
sure VACUUM can always truncate the table as expected.

Back-patch to 12, where vacuum_truncate arrived.

Discussion: https://postgr.es/m/CAD21AoCNoWjYkdEtr%2BVDoF9v__V905AedKZ9iF%3DArgCtrbxZqw%40mail.gmail.com

3 years agoTemporarily disable installcheck for test_oat_hooks module
Andrew Dunstan [Wed, 23 Mar 2022 00:18:30 +0000 (20:18 -0400)]
Temporarily disable installcheck for test_oat_hooks module

Buildfarm members are encountering errors when the test is run under
various locales/encodings. As the buildfarm only does this for
installchecks, disable them for now.

Discussion: https://postgr.es/m/6067945b-960a-ab04-d40f-06b006a1dcd0@dunslane.net

3 years agoRevert "Common SQL/JSON clauses"
Andrew Dunstan [Tue, 22 Mar 2022 23:55:15 +0000 (19:55 -0400)]
Revert "Common SQL/JSON clauses"

This reverts commit 865fe4d5df560a6f5353da652018ff876978ad2d.

This has caused issues with a significant number of buildfarm members

3 years agoAdd missing xlogdefs.h include to pg_subscription.h.
Andres Freund [Tue, 22 Mar 2022 23:46:24 +0000 (16:46 -0700)]
Add missing xlogdefs.h include to pg_subscription.h.

Missed in 208c5d65bbd.

The missing include causes headerscheck to fail. Per buildfarm member crake.

3 years agoCommon SQL/JSON clauses
Andrew Dunstan [Thu, 3 Mar 2022 18:00:49 +0000 (13:00 -0500)]
Common SQL/JSON clauses

This introduces some of the building blocks used by the SQL/JSON
constructor and query functions. Specifically, it provides node
executor and grammar support for the FORMAT JSON [ENCODING foo]
clause, and values decorated with it, and for the RETURNING clause.

The following SQL/JSON patches will leverage these.

Nikita Glukhov (who probably deserves an award for perseverance).

Reviewers have included (in no particular order) Andres Freund, Alexander
Korotkov, Pavel Stehule, Andrew Alsup. Erik Rijkers, Zihong Yu and
Himanshu Upadhyaya.

Discussion: https://postgr.es/m/cd0bb935-0158-78a7-08b5-904886deac4b@postgrespro.ru

3 years agoTidy up Object Access hooks tests
Andrew Dunstan [Tue, 22 Mar 2022 20:18:06 +0000 (16:18 -0400)]
Tidy up Object Access hooks tests

per gripelet from Tom Lane.

3 years agoFix new Object Access hooks test
Andrew Dunstan [Tue, 22 Mar 2022 17:27:26 +0000 (13:27 -0400)]
Fix new Object Access hooks test

Commit 90efa2f556 caused some issues with EXEC_BACKEND builds and with
force_parallel_mode = regress setups. For the first issue we no longer
test if the module has been preloaded, and in fact we don't preload it,
but simply LOAD it in the test script. For the second issue we suppress
error messages emanating from parallel workers.

Mark Dilger

Discussion: https://postgr.es/m/7f6d54a1-4024-3b6e-e3ec-26cd394aac9e@dunslane.net

3 years agoAdd missing dependency of pg_dumpall to WIN32RES.
Andres Freund [Tue, 22 Mar 2022 15:22:02 +0000 (08:22 -0700)]
Add missing dependency of pg_dumpall to WIN32RES.

When cross-building to windows, or building with mingw on windows, the build
could fail with
  x86_64-w64-mingw32-gcc: error: win32ver.o: No such file or director
because pg_dumpall didn't depend on WIN32RES, but it's recipe references
it. The build nevertheless succeeded most of the time, due to
pg_dump/pg_restore having the required dependency, causing win32ver.o to be
built.

Reported-By: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://postgr.es/m/CA+hUKGJeekpUPWW6yCVdf9=oBAcCp86RrBivo4Y4cwazAzGPng@mail.gmail.com
Backpatch: 10-, omission present on all live branches

3 years agopgstat: fix function name in comment.
Andres Freund [Tue, 22 Mar 2022 15:15:40 +0000 (08:15 -0700)]
pgstat: fix function name in comment.

Introduced in 3fa17d37716.

3 years agoAdd a test module for Object Access hooks
Andrew Dunstan [Tue, 22 Mar 2022 14:27:00 +0000 (10:27 -0400)]
Add a test module for Object Access hooks

This includes tests of both the newly added name type object access
hooks and the older Oid type hooks, and provides a useful example
of how to use the hooks.

Mark Dilger, based on some code from Joshua Brindle.

Discussion: https://postgr.es/m/47F87A0E-C0E5-43A6-89F6-D403F2B45175@enterprisedb.com

3 years agoAdd String object access hooks
Andrew Dunstan [Tue, 22 Mar 2022 13:06:15 +0000 (09:06 -0400)]
Add String object access hooks

This caters for cases where the access is to an object identified by
name rather than Oid.

The first user of these is the GUC access controls

Joshua Brindle and Mark Dilger

Discussion: https://postgr.es/m/47F87A0E-C0E5-43A6-89F6-D403F2B45175@enterprisedb.com

3 years agoRevert "graceful shutdown" changes for Windows.
Tom Lane [Tue, 22 Mar 2022 14:19:15 +0000 (10:19 -0400)]
Revert "graceful shutdown" changes for Windows.

This reverts commits 6051857fc and ed52c3707 in HEAD (they were already
reverted in the back branches).  Further testing has shown that while
those changes do fix some things, they also break others; in particular,
it looks like walreceivers fail to detect walsender-initiated connection
close reliably if the walsender shuts down this way.  A proper fix for
this seems possible but won't be done in time for v15.

Discussion: https://postgr.es/m/CA+hUKG+OeoETZQ=Qw5Ub5h3tmwQhBmDA=nuNO3KG=zWfUypFAw@mail.gmail.com
Discussion: https://postgr.es/m/CA+hUKGKkp2XkvSe9nG+bsgkXVKCdTeGSa_TR0Qx1jafc_oqCVA@mail.gmail.com

3 years agoAdd support for security invoker views.
Dean Rasheed [Tue, 22 Mar 2022 10:28:10 +0000 (10:28 +0000)]
Add support for security invoker views.

A security invoker view checks permissions for accessing its
underlying base relations using the privileges of the user of the
view, rather than the privileges of the view owner. Additionally, if
any of the base relations are tables with RLS enabled, the policies of
the user of the view are applied, rather than those of the view owner.

This allows views to be defined without giving away additional
privileges on the underlying base relations, and matches a similar
feature available in other database systems.

It also allows views to operate more naturally with RLS, without
affecting the assignments of policies to users.

Christoph Heiss, with some additional hacking by me. Reviewed by
Laurenz Albe and Wolfgang Walther.

Discussion: https://postgr.es/m/b66dd6d6-ad3e-c6f2-8b90-47be773da240%40cybertec.at

3 years agopgcrypto: Remove internal padding implementation
Peter Eisentraut [Tue, 22 Mar 2022 07:51:05 +0000 (08:51 +0100)]
pgcrypto: Remove internal padding implementation

Use the padding provided by OpenSSL instead of doing it ourselves.
The internal implementation was once applicable to the non-OpenSSL
code paths, but those have since been removed.  The padding algorithm
is still the same.

The OpenSSL padding implementation is stricter than the previous
internal one: Bad padding during decryption is now an error, and
encryption without padding now requires the input size to be a
multiple of the block size, otherwise it is also an error.
Previously, these cases silently proceeded, in spite of the
documentation saying otherwise.

Add some test cases about this, too.  (The test cases are in
rijndael.sql, but they apply to all encryption algorithms.)

Reviewed-by: Jacob Champion <pchampion@vmware.com>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/ba94c26b-0c58-c97e-7a44-f44e08b4cca2%40enterprisedb.com

3 years agoFix failures in SSL tests caused by out-of-tree keys and certificates
Michael Paquier [Tue, 22 Mar 2022 04:20:31 +0000 (13:20 +0900)]
Fix failures in SSL tests caused by out-of-tree keys and certificates

This issue is environment-sensitive, where the SSL tests could fail in
various way by feeding on defaults provided by sslcert, sslkey,
sslrootkey, sslrootcert, sslcrl and sslcrldir coming from a local setup,
as of ~/.postgresql/ by default.  Horiguchi-san has reported two
failures, but more advanced testing from me (aka inclusion of garbage
SSL configuration in ~/.postgresql/ for all the configuration
parameters) has showed dozens of failures that can be triggered in the
whole test suite.

History has showed that we are not good when it comes to address such
issues, fixing them locally like in dd87799, and such problems keep
appearing.  This commit strengthens the entire test suite to put an end
to this set of problems by embedding invalid default values in all the
connection strings used in the tests.  The invalid values are prefixed
in each connection string, relying on the follow-up values passed in the
connection string to enforce any invalid value previously set.  Note
that two tests related to CRLs are required to fail with certain pre-set
configurations, but we can rely on enforcing an empty value instead
after the invalid set of values.

Reported-by: Kyotaro Horiguchi
Reviewed-by: Andrew Dunstan, Daniel Gustafsson, Kyotaro Horiguchi
Discussion: https://postgr.es/m/20220316.163658.1122740600489097632.horikyota.ntt@gmail.com
backpatch-through: 10

3 years agoAdd ALTER SUBSCRIPTION ... SKIP.
Amit Kapila [Tue, 22 Mar 2022 01:41:19 +0000 (07:11 +0530)]
Add ALTER SUBSCRIPTION ... SKIP.

This feature allows skipping the transaction on subscriber nodes.

If incoming change violates any constraint, logical replication stops
until it's resolved. Currently, users need to either manually resolve the
conflict by updating a subscriber-side database or by using function
pg_replication_origin_advance() to skip the conflicting transaction. This
commit introduces a simpler way to skip the conflicting transactions.

The user can specify LSN by ALTER SUBSCRIPTION ... SKIP (lsn = XXX),
which allows the apply worker to skip the transaction finished at
specified LSN. The apply worker skips all data modification changes within
the transaction.

Author: Masahiko Sawada
Reviewed-by: Takamichi Osumi, Hou Zhijie, Peter Eisentraut, Amit Kapila, Shi Yu, Vignesh C, Greg Nancarrow, Haiying Tang, Euler Taveira
Discussion: https://postgr.es/m/CAD21AoDeScrsHhLyEPYqN3sydg6PxAPVBboK=30xJfUVihNZDA@mail.gmail.com

3 years agopgstat: reorder pgstat.[ch] contents.
Andres Freund [Mon, 21 Mar 2022 23:16:42 +0000 (16:16 -0700)]
pgstat: reorder pgstat.[ch] contents.

Now that 13619598f10 has split pgstat up into multiple files it isn't quite as
hard to come up with a sensible order for pgstat.[ch]. Inconsistent naming
makes it still not quite right looking, but that's work for another commit.

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

3 years agoFix assorted missing logic for GroupingFunc nodes.
Tom Lane [Mon, 21 Mar 2022 21:44:29 +0000 (17:44 -0400)]
Fix assorted missing logic for GroupingFunc nodes.

The planner needs to treat GroupingFunc like Aggref for many purposes,
in particular with respect to processing of the argument expressions,
which are not to be evaluated at runtime.  A few places hadn't gotten
that memo, notably including subselect.c's processing of outer-level
aggregates.  This resulted in assertion failures or wrong plans for
cases in which a GROUPING() construct references an outer aggregation
level.

Also fix missing special cases for GroupingFunc in cost_qual_eval
(resulting in wrong cost estimates for GROUPING(), although it's
not clear that that would affect plan shapes in practice) and in
ruleutils.c (resulting in excess parentheses in pretty-print mode).

Per bug #17088 from Yaoguang Chen.  Back-patch to all supported
branches.

Richard Guo, Tom Lane

Discussion: https://postgr.es/m/17088-e33882b387de7f5c@postgresql.org

3 years agopgstat: split different types of stats into separate files.
Andres Freund [Mon, 21 Mar 2022 19:02:25 +0000 (12:02 -0700)]
pgstat: split different types of stats into separate files.

pgstat.c is very long, and it's hard to find an order that makes sense and is
likely to be maintained over time. Splitting the different pieces into
separate files makes that a lot easier.

With a few exceptions, this commit just moves code around. Those exceptions
are:
- adding file headers for new files
- removing 'static' from functions
- adapting pgstat_assert_is_up() to work across TUs
- minor comment adjustments
git diff --color-moved=dimmed-zebra is very helpful separating code movement
from code changes.

The next commit in this series will reorder pgstat.[ch] contents to be a bit
more coherent.

Earlier revisions of this patch had "global" statistics (archiver, bgwriter,
checkpointer, replication slots, SLRU, WAL) in one file, because each seemed
small enough. However later commits will increase their size and their
aggregate size is not insubstantial. It also just seems easier to split each
type of statistic into its own file.

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

3 years agoFix bogus dependency handling for GENERATED expressions.
Tom Lane [Mon, 21 Mar 2022 18:58:49 +0000 (14:58 -0400)]
Fix bogus dependency handling for GENERATED expressions.

For GENERATED columns, we record all dependencies of the generation
expression as AUTO dependencies of the column itself.  This means
that the generated column is silently dropped if any dependency
is removed, even if CASCADE wasn't specified.  This is at least
a POLA violation, but I think it's actually based on a misreading
of the standard.  The standard does say that you can't drop a
dependent GENERATED column in RESTRICT mode; but that's buried down
in a subparagraph, on a different page from some pseudocode that
makes it look like an AUTO drop is being suggested.

Change this to be more like the way that we handle regular default
expressions, ie record the dependencies as NORMAL dependencies of
the pg_attrdef entry.  Also, make the pg_attrdef entry's dependency
on the column itself be INTERNAL not AUTO.  That has two effects:

* the column will go away, not just lose its default, if any
dependency of the expression is dropped with CASCADE.  So we
don't need any special mechanism to make that happen.

* it provides an additional cross-check preventing someone from
dropping the default expression without dropping the column.

catversion bump because of change in the contents of pg_depend
(which also requires a change in one information_schema view).

Per bug #17439 from Kevin Humphreys.  Although this is a longstanding
bug, it seems impractical to back-patch because of the need for
catalog contents changes.

Discussion: https://postgr.es/m/17439-7df4421197e928f0@postgresql.org

3 years agoMove pg_attrdef manipulation code into new file catalog/pg_attrdef.c.
Tom Lane [Mon, 21 Mar 2022 18:38:23 +0000 (14:38 -0400)]
Move pg_attrdef manipulation code into new file catalog/pg_attrdef.c.

This is a pure refactoring commit: there isn't (I hope) any functional
change.

StoreAttrDefault and RemoveAttrDefault[ById] are moved from heap.c,
reducing the size of that overly-large file by about 300 lines.
I took the opportunity to trim unused #includes from heap.c, too.

Two new functions for translating between a pg_attrdef OID and the
relid/attnum of the owning column are created by extracting ad-hoc
code from objectaddress.c.  This already removes one copy of said
code, and a follow-on bug fix will create more callers.

The only other function directly manipulating pg_attrdef is
AttrDefaultFetch.  I judged it was better to leave that in relcache.c,
since it shares special concerns about recursion and error handling
with the rest of that module.

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

3 years agoFix risk of deadlock failure while dropping a partitioned index.
Tom Lane [Mon, 21 Mar 2022 16:22:13 +0000 (12:22 -0400)]
Fix risk of deadlock failure while dropping a partitioned index.

DROP INDEX needs to lock the index's table before the index itself,
else it will deadlock against ordinary queries that acquire the
relation locks in that order.  This is correctly mechanized for
plain indexes by RangeVarCallbackForDropRelation; but in the case of
a partitioned index, we neglected to lock the child tables in advance
of locking the child indexes.  We can fix that by traversing the
inheritance tree and acquiring the needed locks in RemoveRelations,
after we have acquired our locks on the parent partitioned table and
index.

While at it, do some refactoring to eliminate confusion between
the actual and expected relkind in RangeVarCallbackForDropRelation.
We can save a couple of syscache lookups too, by having that function
pass back info that RemoveRelations will need.

Back-patch to v11 where partitioned indexes were added.

Jimmy Yih, Gaurab Dey, Tom Lane

Discussion: https://postgr.es/m/BYAPR05MB645402330042E17D91A70C12BD5F9@BYAPR05MB6454.namprd05.prod.outlook.com

3 years agoRemove workarounds for avoiding [U]INT64_FORMAT in translatable strings.
Tom Lane [Mon, 21 Mar 2022 15:11:55 +0000 (11:11 -0400)]
Remove workarounds for avoiding [U]INT64_FORMAT in translatable strings.

Further code simplification along the same lines as d914eb347
and earlier patches.

Aleksander Alekseev, Japin Li

Discussion: https://postgr.es/m/CAJ7c6TMSKi3Xs8h5MP38XOnQQpBLazJvVxVfPn++roitDJcR7g@mail.gmail.com

3 years agoFix typo in file identification
Magnus Hagander [Mon, 21 Mar 2022 10:33:29 +0000 (12:33 +0200)]
Fix typo in file identification

Clearly a simple copy/paste mistake when the file was created.

3 years agopgstat: separate "xact level" handling out of relation specific functions.
Andres Freund [Mon, 21 Mar 2022 02:12:09 +0000 (19:12 -0700)]
pgstat: separate "xact level" handling out of relation specific functions.

This is in preparation of a later commit moving relation stats handling into
its own file.

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

3 years agopgstat: rename pgstat_initstats() to pgstat_relation_init().
Andres Freund [Mon, 21 Mar 2022 02:12:09 +0000 (19:12 -0700)]
pgstat: rename pgstat_initstats() to pgstat_relation_init().

The old name was overly generic. An upcoming commit moves relation stats
handling into its own file, making pgstat_initstats() look even more out of
place.

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

3 years agopgstat: introduce pgstat_relation_should_count().
Andres Freund [Mon, 21 Mar 2022 02:12:09 +0000 (19:12 -0700)]
pgstat: introduce pgstat_relation_should_count().

A later commit will make the check more complicated than the
current (rel)->pgstat_info != NULL. It also just seems nicer to have a central
copy of the logic, even while still simple.

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

3 years agoBlind fix for uninitialized memory bug in ba9a7e392171
Alvaro Herrera [Sun, 20 Mar 2022 21:10:24 +0000 (22:10 +0100)]
Blind fix for uninitialized memory bug in ba9a7e392171

Valgrind animal skink shows a crash in this new code.  I couldn't
reproduce the problem locally, but going by blind code inspection,
initializing insert_destrel should be sufficient to fix the problem.

3 years agoLog regression.diffs in 027_stream_regress.pl.
Thomas Munro [Sun, 20 Mar 2022 20:31:22 +0000 (09:31 +1300)]
Log regression.diffs in 027_stream_regress.pl.

To help diagnose the reasons for a regression test failure inside this
TAP test, dump the contents of regression.diffs to the log.  While the
CI scripts show it automatically, the build farm client does not.

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

3 years agopsql: handle tab completion of timezone names after "SET TIMEZONE TO".
Tom Lane [Sun, 20 Mar 2022 20:06:41 +0000 (16:06 -0400)]
psql: handle tab completion of timezone names after "SET TIMEZONE TO".

Dagfinn Ilmari Mannsåker and Tom Lane

Discussion: https://postgr.es/m/87k0curq0w.fsf@wibble.ilmari.org

3 years agoEnforce foreign key correctly during cross-partition updates
Alvaro Herrera [Sun, 20 Mar 2022 17:43:40 +0000 (18:43 +0100)]
Enforce foreign key correctly during cross-partition updates

When an update on a partitioned table referenced in foreign key
constraints causes a row to move from one partition to another,
the fact that the move is implemented as a delete followed by an insert
on the target partition causes the foreign key triggers to have
surprising behavior.  For example, a given foreign key's delete trigger
which implements the ON DELETE CASCADE clause of that key will delete
any referencing rows when triggered for that internal DELETE, although
it should not, because the referenced row is simply being moved from one
partition of the referenced root partitioned table into another, not
being deleted from it.

This commit teaches trigger.c to skip queuing such delete trigger events
on the leaf partitions in favor of an UPDATE event fired on the root
target relation.  Doing so is sensible because both the old and the new
tuple "logically" belong to the root relation.

The after trigger event queuing interface now allows passing the source
and the target partitions of a particular cross-partition update when
registering the update event for the root partitioned table.  Along with
the two ctids of the old and the new tuple, the after trigger event now
also stores the OIDs of those partitions. The tuples fetched from the
source and the target partitions are converted into the root table
format, if necessary, before they are passed to the trigger function.

The implementation currently has a limitation that only the foreign keys
pointing into the query's target relation are considered, not those of
its sub-partitioned partitions.  That seems like a reasonable
limitation, because it sounds rare to have distinct foreign keys
pointing to sub-partitioned partitions instead of to the root table.

This misbehavior stems from commit f56f8f8da6af (which added support for
foreign keys to reference partitioned tables) not paying sufficient
attention to commit 2f178441044b (which had introduced cross-partition
updates a year earlier).  Even though the former commit goes back to
Postgres 12, we're not backpatching this fix at this time for fear of
destabilizing things too much, and because there are a few ABI breaks in
it that we'd have to work around in older branches.  It also depends on
commit f4566345cf40, which had its own share of backpatchability issues
as well.

Author: Amit Langote <amitlangote09@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@alvh.no-ip.org>
Reported-by: Eduard Català <eduard.catala@gmail.com>
Discussion: https://postgr.es/m/CA+HiwqFvkBCmfwkQX_yBqv2Wz8ugUGiBDxum8=WvVbfU1TXaNg@mail.gmail.com
Discussion: https://postgr.es/m/CAL54xNZsLwEM1XCk5yW9EqaRzsZYHuWsHQkA2L5MOSKXAwviCQ@mail.gmail.com

3 years agoDoc: fix our example systemd script.
Tom Lane [Sun, 20 Mar 2022 16:39:40 +0000 (12:39 -0400)]
Doc: fix our example systemd script.

The example used "TimeoutSec=0", but systemd's documented way to get
the desired effect is "TimeoutSec=infinity".

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

3 years agoFix global ICU collations for ICU < 54
Peter Eisentraut [Sun, 20 Mar 2022 09:21:45 +0000 (10:21 +0100)]
Fix global ICU collations for ICU < 54

createdb() didn't check for collation attributes validity, which has
to be done explicitly on ICU < 54.  It also forgot to close the ICU collator
opened during the check which leaks some memory.

To fix both, add a new check_icu_locale() that does all the appropriate
verification and close the ICU collator.

initdb also had some partial check for ICU < 54.  To have consistent error
reporting across major ICU versions, and get rid of the need to include ucol.h,
remove the partial check there.  The backend will report an error if needed
during the post-boostrap iniitialization phase.

Author: Julien Rouhaud <julien.rouhaud@free.fr>
Discussion: https://www.postgresql.org/message-id/20220319041459.qqqiqh335sga5ezj@jrouhaud

3 years agoAdd a few recent and not so recent revs to git-blame-ignore-revs.
Andres Freund [Sat, 19 Mar 2022 19:37:28 +0000 (12:37 -0700)]
Add a few recent and not so recent revs to git-blame-ignore-revs.

3 years agopgstat: split out WAL handling from pgstat_{initialize,report_stat}.
Andres Freund [Sat, 19 Mar 2022 18:35:37 +0000 (11:35 -0700)]
pgstat: split out WAL handling from pgstat_{initialize,report_stat}.

A later commit will move the handling of the different kinds of stats into
separate files.  By splitting out WAL handling in this commit that later move
will just move code around without other changes.

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

3 years agopgstat: split relation, database handling out of pgstat_report_stat().
Andres Freund [Sat, 19 Mar 2022 18:32:18 +0000 (11:32 -0700)]
pgstat: split relation, database handling out of pgstat_report_stat().

pgstat_report_stat() handles several types of stats, yet relation stats have
so far been handled directly in pgstat_report_stat().

A later commit will move the handling of the different kinds of stats into
separate files.  By splitting out relation handling in this commit that later
move will just move code around without other changes.

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

3 years agopgstat: run pgindent on pgstat.c/h.
Andres Freund [Sat, 19 Mar 2022 18:32:18 +0000 (11:32 -0700)]
pgstat: run pgindent on pgstat.c/h.

Upcoming commits will touch a lot of the pgstats code. Reindenting separately
makes it easier to keep the code in a well-formatted shape each step.

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

3 years agoci: windows: Use CIRRUS_ESCAPING_PROCESSES, revert 770011e3f39.
Andres Freund [Sat, 19 Mar 2022 18:32:18 +0000 (11:32 -0700)]
ci: windows: Use CIRRUS_ESCAPING_PROCESSES, revert 770011e3f39.

cirrus-ci now defaults to killing processes still running at the end of a
script. Unfortunately we start postgres in the background, which seems
nontrivial to fix. Previously we worked around that in 770011e3f39 by using an
older agent version, but now that CIRRUS_ESCAPING_PROCESSES we should use that.

This reverts commit 770011e3f39f21f2095d3a044b72460c4efac345 "ci: windows:
Work around cirrus-ci bug causing test failures.

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

3 years agoFix an outdated and grammatically wrong comment
Alvaro Herrera [Sat, 19 Mar 2022 18:31:38 +0000 (19:31 +0100)]
Fix an outdated and grammatically wrong comment

Authored by Amit Langote and myself independently
Discussion: https://postgr.es/m/CA+HiwqGCjcH0gG-=tM7hhP7TEDmzrHMHJbPGSHtHgFmx9mnFkg@mail.gmail.com

3 years agoImprove handling of SET ACCESS METHOD for ALTER MATERIALIZED VIEW
Michael Paquier [Sat, 19 Mar 2022 10:13:52 +0000 (19:13 +0900)]
Improve handling of SET ACCESS METHOD for ALTER MATERIALIZED VIEW

b048326 has added support for SET ACCESS METHOD in ALTER TABLE, but it
has missed a few things for materialized views:
- No documentation for this clause on the ALTER MATERIALIZED VIEW page.
- psql tab completion missing.
- No regression tests.

This commit closes the gap on all the points listed above.

Author: Yugo Nagata
Discussion: https://postgr.es/m/20220316133337.5dc9740abfa24c25ec9f67f5@sraoss.co.jp

3 years agoAdd regression tests for ALTER MATERIALIZED VIEW with tablespaces
Michael Paquier [Sat, 19 Mar 2022 08:28:50 +0000 (17:28 +0900)]
Add regression tests for ALTER MATERIALIZED VIEW with tablespaces

The clauses SET TABLESPACE and ALL IN TABLESPACE are supported in ALTER
MATERIALIZED VIEW for a long time, and they behave mostly like ALTER
TABLE by reusing the same code paths, but there were zero tests for
them.  This commit closes the gap with new tests in tablespace.sql.

Author: Yugo Nagata
Discussion: https://postgr.es/m/20220316133337.5dc9740abfa24c25ec9f67f5@sraoss.co.jp

3 years agodoc: Mention SET TABLESPACE clause for ALTER MATERIALIZED VIEW
Michael Paquier [Sat, 19 Mar 2022 07:37:31 +0000 (16:37 +0900)]
doc: Mention SET TABLESPACE clause for ALTER MATERIALIZED VIEW

This command flavor is supported, but there was nothing in the
documentation about it.

Author: Yugo Nagata
Discussion: https://postgr.es/m/20220316133337.5dc9740abfa24c25ec9f67f5@sraoss.co.jp
Backpatch-through: 10

3 years agoSilence -Wmaybe-uninitialized compiler warning in dbcommands.c.
Andres Freund [Sat, 19 Mar 2022 01:48:03 +0000 (18:48 -0700)]
Silence -Wmaybe-uninitialized compiler warning in dbcommands.c.

Introduced in f2553d43060e. See also 3f6b3be39ca9, which did so for nearby
variables.

Discussion: https://postgr.es/m/20220319014707.kgtomqdzm6m2ulro@alap3.anarazel.de

3 years agoClose race condition in slot_creation_error.spec.
Noah Misch [Sat, 19 Mar 2022 01:18:00 +0000 (18:18 -0700)]
Close race condition in slot_creation_error.spec.

Use the pattern from detach-partition-concurrently-3.spec.  Per
buildfarm member wrasse.

Reviewed by Kyotaro Horiguchi and Andres Freund.

Discussion: https://postgr.es/m/20220318072837.GC2739027@rfd.leadboat.com

3 years agoci: compile with -Og where applicable.
Andres Freund [Fri, 18 Mar 2022 22:42:33 +0000 (15:42 -0700)]
ci: compile with -Og where applicable.

To improve performance of check-world, and improve debugging, without
significantly slower builds (they're cached anyway).

This makes freebsd check-world run in 8.5 minutes rather than 15 minutes.

Author: Justin Pryzby <pryzbyj@telsasoft.com>
Reviewed-By: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220310220611.GH28503@telsasoft.com

3 years agoci: include hints how to install OS packages.
Andres Freund [Fri, 18 Mar 2022 22:42:02 +0000 (15:42 -0700)]
ci: include hints how to install OS packages.

This is useful for patches during development, but once a feature is merged,
new libraries should be added to the OS image files, rather than installed
during every CI run forever into the future.

Author: Justin Pryzby <pryzbyj@telsasoft.com>
Reviewed-By: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220310220611.GH28503@telsasoft.com

3 years agoFix incorrect xmlschema output for types timetz and timestamptz.
Tom Lane [Fri, 18 Mar 2022 20:01:42 +0000 (16:01 -0400)]
Fix incorrect xmlschema output for types timetz and timestamptz.

The output of table_to_xmlschema() and allied functions includes
a regex describing valid values for these types ... but the regex
was itself invalid, as it failed to escape a literal "+" sign.

Report and fix by Renan Soares Lopes.  Back-patch to all
supported branches.

Discussion: https://postgr.es/m/7f6fabaa-3f8f-49ab-89ca-59fbfe633105@me.com

3 years agoSpecify database encoding in new ICU test.
Tom Lane [Fri, 18 Mar 2022 17:26:04 +0000 (13:26 -0400)]
Specify database encoding in new ICU test.

Otherwise, the database encoding varies depending on the user's
environment, and so the test might fail depending on whether ICU
likes the encoding.  In particular, the test fails completely
if the prevailing locale is C.

3 years agoDoc: remove bogus instruction to install contrib/hstore.
Tom Lane [Fri, 18 Mar 2022 17:21:47 +0000 (13:21 -0400)]
Doc: remove bogus instruction to install contrib/hstore.

This test suite does not use hstore.  Looks like this text
was copied-and-pasted from src/test/subscription/README.

3 years agoRemove workarounds for avoiding [U]INT64_FORMAT in translatable strings.
Tom Lane [Fri, 18 Mar 2022 17:10:04 +0000 (13:10 -0400)]
Remove workarounds for avoiding [U]INT64_FORMAT in translatable strings.

Update pg_backup_tar.c along the same lines as 62aa2bb29 and
other previous cleanup: we can now rely on %lld or %llu as long
as we explicitly cast to long long or unsigned long long.

Japin Li

Discussion: https://postgr.es/m/MEYP282MB16694F7CC1B119B4ECDD8CBEB6139@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM

3 years agoAdd circular WAL decoding buffer, take II.
Thomas Munro [Fri, 18 Mar 2022 04:45:04 +0000 (17:45 +1300)]
Add circular WAL decoding buffer, take II.

Teach xlogreader.c to decode the WAL into a circular buffer.  This will
support optimizations based on looking ahead, to follow in a later
commit.

 * XLogReadRecord() works as before, decoding records one by one, and
   allowing them to be examined via the traditional XLogRecGetXXX()
   macros and certain traditional members like xlogreader->ReadRecPtr.

 * An alternative new interface XLogReadAhead()/XLogNextRecord() is
   added that returns pointers to DecodedXLogRecord objects so that it's
   now possible to look ahead in the WAL stream while replaying.

 * In order to be able to use the new interface effectively while
   streaming data, support is added for the page_read() callback to
   respond to a new nonblocking mode with XLREAD_WOULDBLOCK instead of
   waiting for more data to arrive.

No direct user of the new interface is included in this commit, though
XLogReadRecord() uses it internally.  Existing code doesn't need to
change, except in a few places where it was accessing reader internals
directly and now needs to go through accessor macros.

Reviewed-by: Julien Rouhaud <rjuju123@gmail.com>
Reviewed-by: Tomas Vondra <tomas.vondra@enterprisedb.com>
Reviewed-by: Andres Freund <andres@anarazel.de> (earlier versions)
Discussion: https://postgr.es/m/CA+hUKGJ4VJN8ttxScUFM8dOKX0BrBiboo5uz1cq=AovOddfHpA@mail.gmail.com

3 years agodoc: Remove mention to in-place tablespaces for pg_tablespace_location()
Michael Paquier [Fri, 18 Mar 2022 01:46:36 +0000 (10:46 +0900)]
doc: Remove mention to in-place tablespaces for pg_tablespace_location()

This paragraph has been added in the documentation by f6f0db4, but after
more discussion we found that this just makes things more confusing,
adding some cross-references between a general feature and something
only aimed at being used by developers.  The original documentation is
not wrong either, and this commit brings back this part of the docs to
the same state as before f6f0db4.

Per discussion with Kyotaro Horiguchi and Thomas Munro.

Discussion: https://postgr.es/m/CA+hUKGL2uaRKu=3+bMBpejHh4k7wqzWC05aiasTsSsHGRCWa8g@mail.gmail.com

3 years agoFix header inclusion order in pg_receivewal.c
Michael Paquier [Fri, 18 Mar 2022 01:38:16 +0000 (10:38 +0900)]
Fix header inclusion order in pg_receivewal.c

lz4frame.h was getting declared after the headers specific to Postgres,
but it needs to be included between postgres_fe.h and the internal
headers.

Issue introduced by babbbb5.

Reported-by: Justin Prysby
Discussion: https://postgr.es/m/20220317111220.GI28503@telsasoft.com

3 years agoDeclare aarch64 has single copy atomicity for 8 byte values.
Thomas Munro [Fri, 18 Mar 2022 00:40:26 +0000 (13:40 +1300)]
Declare aarch64 has single copy atomicity for 8 byte values.

Architecture Reference Manual for ARMv8 B2.2.1 [1]

For explicit memory effects generated from an Exception level the
following rules apply:
- A read that is generated by a load instruction that loads a single
general-purpose register and is aligned to the size of the read in the
instruction is single-copy atomic.
- A write that is generated by a store instruction that stores a single
general-purpose register and is aligned to the size of the write in the
instruction is single-copy atomic.

[1] https://documentation-service.arm.com/static/61fbe8f4fa8173727a1b734e
https://developer.arm.com/documentation/ddi0487/latest

Author: Yura Sokolov <y.sokolov@postgrespro.ru>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Reviewed-by: Alexander Korotkov <aekorotkov@gmail.com>
Discussion: https://postgr.es/m/f7f3f0febe27862711f924a7b0f39e065e547f4b.camel%40postgrespro.ru
Discussion: https://postgr.es/m/CA%2BhUKGKyJf7kwYkqDgzTE26Ra1m9nvM%3Deds2RSSu7WSL-r2wKw%40mail.gmail.com

3 years agoDon't bother to attach column name lists to RowExprs of named types.
Tom Lane [Thu, 17 Mar 2022 22:25:44 +0000 (18:25 -0400)]
Don't bother to attach column name lists to RowExprs of named types.

If a RowExpr is marked as returning a named composite type, we aren't
going to consult its colnames list; we'll use the attribute names
shown for the type in pg_attribute.  Hence, skip storing that list,
to save a few nanoseconds when copying the expression tree around.

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

3 years agoRevert applying column aliases to the output of whole-row Vars.
Tom Lane [Thu, 17 Mar 2022 22:18:05 +0000 (18:18 -0400)]
Revert applying column aliases to the output of whole-row Vars.

In commit bf7ca1587, I had the bright idea that we could make the
result of a whole-row Var (that is, foo.*) track any column aliases
that had been applied to the FROM entry the Var refers to.  However,
that's not terribly logically consistent, because now the output of
the Var is no longer of the named composite type that the Var claims
to emit.  bf7ca1587 tried to handle that by changing the output
tuple values to be labeled with a blessed RECORD type, but that's
really pretty disastrous: we can wind up storing such tuples onto
disk, whereupon they're not readable by other sessions.

The only practical fix I can see is to give up on what bf7ca1587
tried to do, and say that the column names of tuples produced by
a whole-row Var are always those of the underlying named composite
type, query aliases or no.  While this introduces some inconsistencies,
it removes others, so it's not that awful in the abstract.  What *is*
kind of awful is to make such a behavioral change in a back-patched
bug fix.  But corrupt data is worse, so back-patched it will be.

(A workaround available to anyone who's unhappy about this is to
introduce an extra level of sub-SELECT, so that the whole-row Var is
referring to the sub-SELECT's output and not to a named table type.
Then the Var is of type RECORD to begin with and there's no issue.)

Per report from Miles Delahunty.  The faulty commit dates to 9.5,
so back-patch to all supported branches.

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

3 years agoRefactor code for reading and writing relation map files.
Robert Haas [Thu, 17 Mar 2022 17:21:07 +0000 (13:21 -0400)]
Refactor code for reading and writing relation map files.

Restructure things so that the functions which update the global
variables shared_map and local_map are separate from the functions
which just read and write relation map files without touching any
global variables.

In the new structure of things, write_relmap_file() writes a relmap
file but no longer performs global variable updates. A symmetric
function read_relmap_file() that just reads a file without changing
any global variables is added, and load_relmap_file(), which does
change the global variables, uses it as a subroutine.

Because write_relmap_file() no longer updates shared_map and
local_map, that logic is moved to perform_relmap_update(). However,
no similar logic is added to relmap_redo() even though it also calls
write_relmap_file(). That's because recovery must not rely on the
contents of the relation map, and therefore there is no need to
initialize it. In fact, doing so seems like a mistake, because we
might then manage to rely on the in-memory map where we shouldn't.

Patch by me, based on earlier work by Dilip Kumar. Reviewed by
Ashutosh Sharma.

Discussion: http://postgr.es/m/CA+TgmobQLgrt4AXsc0ru7aFFkzv=9fS-Q_yO69=k9WY67RCctg@mail.gmail.com

3 years agoFix row filters with multiple publications
Tomas Vondra [Thu, 17 Mar 2022 16:03:45 +0000 (17:03 +0100)]
Fix row filters with multiple publications

When publishing changes through a artition root, we should use the row
filter for the top-most ancestor. The relation may be added to multiple
publications, using different ancestors, and 52e4f0cd47 handled this
incorrectly. With c91f71b9dc we find the correct top-most ancestor, but
the code tried to fetch the row filter from all publications, including
those using a different ancestor etc. No row filter can be found for
such publications, which was treated as replicating all rows.

Similarly to c91f71b9dc, this seems to be a rare issue in practice. It
requires multiple publications including the same partitioned relation,
through different ancestors.

Fixed by only passing publications containing the top-most ancestor to
pgoutput_row_filter_init(), so that treating a missing row filter as
replicating all rows is correct.

Report and fix by me, test case by Hou zj. Reviews and improvements by
Amit Kapila.

Author: Tomas Vondra, Hou zj, Amit Kapila
Reviewed-by: Amit Kapila, Hou zj
Discussion: https://postgr.es/m/d26d24dd-2fab-3c48-0162-2b7f84a9c893%40enterprisedb.com

3 years agodoc: Add documentation for new field pg_database.daticulocale
Peter Eisentraut [Thu, 17 Mar 2022 13:12:03 +0000 (14:12 +0100)]
doc: Add documentation for new field pg_database.daticulocale

forgotten in f2553d43060edb210b36c63187d52a632448e1d2

Author: Shinoda, Noriyoshi (PN Japan FSIP) <noriyoshi.shinoda@hpe.com>

3 years agoSplit ExecUpdate and ExecDelete into reusable pieces
Alvaro Herrera [Thu, 17 Mar 2022 10:47:04 +0000 (11:47 +0100)]
Split ExecUpdate and ExecDelete into reusable pieces

Create subroutines ExecUpdatePrologue / ExecUpdateAct /
ExecUpdateEpilogue, and similar for ExecDelete.

Introduce a new struct to be used internally in nodeModifyTable.c,
dubbed ModifyTableContext, which contains all context information needed
to perform these operations, as well as ExecInsert and others.

This allows using a different schedule and a different way of evaluating
the results of these operations, which can be exploited by a later
commit introducing support for MERGE.  It also makes ExecUpdate and
ExecDelete proper shorter and (hopefully) simpler.

Author: Álvaro Herrera <alvherre@alvh.no-ip.org>
Reviewed-by: Amit Langote <amitlangote09@gmail.com>
Reviewed-by: Japin Li <japinli@hotmail.com>
Reviewed-by: Zhihong Yu <zyu@yugabyte.com>
Discussion: https://postgr.es/m/202202271724.4z7xv3cf46kv@alvherre.pgsql

3 years agoAdd option to use ICU as global locale provider
Peter Eisentraut [Thu, 17 Mar 2022 10:11:21 +0000 (11:11 +0100)]
Add option to use ICU as global locale provider

This adds the option to use ICU as the default locale provider for
either the whole cluster or a database.  New options for initdb,
createdb, and CREATE DATABASE are used to select this.

Since some (legacy) code still uses the libc locale facilities
directly, we still need to set the libc global locale settings even if
ICU is otherwise selected.  So pg_database now has three
locale-related fields: the existing datcollate and datctype, which are
always set, and a new daticulocale, which is only set if ICU is
selected.  A similar change is made in pg_collation for consistency,
but in that case, only the libc-related fields or the ICU-related
field is set, never both.

Reviewed-by: Julien Rouhaud <rjuju123@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/5e756dd6-0e91-d778-96fd-b1bcb06c161a%402ndquadrant.com

3 years agoFix pg_tablespace_location() with in-place tablespaces
Michael Paquier [Thu, 17 Mar 2022 02:25:02 +0000 (11:25 +0900)]
Fix pg_tablespace_location() with in-place tablespaces

Using this system function with an in-place tablespace (created when
allow_in_place_tablespaces is enabled by specifying an empty string as
location) caused a failure when using readlink(), as the tablespace is,
in this case, not a symbolic link in pg_tblspc/ but a directory.

Rather than getting a failure, the commit changes
pg_tablespace_location() so as a relative path to the data directory is
returned for in-place tablespaces, to make a difference between
tablespaces created when allow_in_place_tablespaces is enabled or not.
Getting a path rather than an empty string that would match the CREATE
TABLESPACE command in this case is more useful for tests that would like
to rely on this function.

While on it, a regression test is added for this case.  This is simple
to add in the main regression test suite thanks to regexp_replace() to
mask the part of the tablespace location dependent on its OID.

Author: Michael Paquier
Reviewed-by: Kyotaro Horiguchi, Thomas Munro
Discussion: https://postgr.es/m/YiG1RleON1WBcLnX@paquier.xyz

3 years agoFix publish_as_relid with multiple publications
Tomas Vondra [Wed, 16 Mar 2022 15:42:47 +0000 (16:42 +0100)]
Fix publish_as_relid with multiple publications

Commit 83fd4532a7 allowed publishing of changes via ancestors, for
publications defined with publish_via_partition_root. But the way
the ancestor was determined in get_rel_sync_entry() was incorrect,
simply updating the same variable. So with multiple publications,
replicating different ancestors, the outcome depended on the order
of publications in the list - the value from the last loop was used,
even if it wasn't the top-most ancestor.

This is a probably rare situation, as in most cases publications do
not overlap, so each partition has exactly one candidate ancestor
to replicate as and there's no ambiguity.

Fixed by tracking the "ancestor level" for each publication, and
picking the top-most ancestor. Adds a test case, verifying the
correct ancestor is used for publishing the changes and that this
does not depend on order of publications in the list.

Older releases have another bug in this loop - once all actions are
replicated, the loop is terminated, on the assumption that inspecting
additional publications is unecessary. But that misses the fact that
those additional applications may replicate different ancestors.

Fixed by removal of this break condition. We might still terminate the
loop in some cases (e.g. when replicating all actions and the ancestor
is the partition root).

Backpatch to 13, where publish_via_partition_root was introduced.

Initial report and fix by me, test added by Hou zj. Reviews and
improvements by Amit Kapila.

Author: Tomas Vondra, Hou zj, Amit Kapila
Reviewed-by: Amit Kapila, Hou zj
Discussion: https://postgr.es/m/d26d24dd-2fab-3c48-0162-2b7f84a9c893%40enterprisedb.com

3 years agoSuppress compiler warnings.
Robert Haas [Wed, 16 Mar 2022 13:26:48 +0000 (09:26 -0400)]
Suppress compiler warnings.

Michael Paquier

Discussion: http://postgr.es/m/YjGvq4zPDT6j15go@paquier.xyz

3 years agodoc: Ensure intermediate path creation with mkdir
Daniel Gustafsson [Wed, 16 Mar 2022 10:38:29 +0000 (11:38 +0100)]
doc: Ensure intermediate path creation with mkdir

The mkdir command in the Installation from Source Short Version docs
didn't use the -p intermediate path creation parameter which likely
would cause the command to fail.  At the time of writing, -p wasn't
universally available but it can now be relied upon existing. The -p
parameter is defined by POSIX, at least since posix-2004.

Reported-by: Daniel Westermann <daniel.westermann@dbi-services.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/ZR0P278MB0920263E7F2D546A33E50079D20E9@ZR0P278MB0920.CHEP278.PROD.OUTLOOK.COM

3 years agoFix default signature length for gist_ltree_ops
Alexander Korotkov [Wed, 16 Mar 2022 08:41:18 +0000 (11:41 +0300)]
Fix default signature length for gist_ltree_ops

911e702077 implemented operator class parameters including the signature length
in ltree.  Previously, the signature length for gist_ltree_ops was 8.  Because
of bug 911e702077 the default signature length for gist_ltree_ops became 28 for
ltree 1.1 (where options method is NOT provided) and 8 for ltree 1.2 (where
options method is provided).  This commit changes the default signature length
for ltree 1.1 to 8.

Existing gist_ltree_ops indexes might be corrupted in various scenarios.
Thus, we have to recommend reindexing all the gist_ltree_ops indexes after
the upgrade.

Reported-by: Victor Yegorov
Reviewed-by: Tomas Vondra, Tom Lane, Andres Freund, Nikita Glukhov
Reviewed-by: Andrew Dunstan
Author: Tomas Vondra, Alexander Korotkov
Discussion: https://postgr.es/m/17406-71e02820ae79bb40%40postgresql.org
Discussion: https://postgr.es/m/d80e0a55-6c3e-5b26-53e3-3c4f973f737c%40enterprisedb.com

3 years agoFix race between DROP TABLESPACE and checkpointing.
Thomas Munro [Wed, 16 Mar 2022 04:20:24 +0000 (17:20 +1300)]
Fix race between DROP TABLESPACE and checkpointing.

Commands like ALTER TABLE SET TABLESPACE may leave files for the next
checkpoint to clean up.  If such files are not removed by the time DROP
TABLESPACE is called, we request a checkpoint so that they are deleted.
However, there is presently a window before checkpoint start where new
unlink requests won't be scheduled until the following checkpoint.  This
means that the checkpoint forced by DROP TABLESPACE might not remove the
files we expect it to remove, and the following ERROR will be emitted:

ERROR:  tablespace "mytblspc" is not empty

To fix, add a call to AbsorbSyncRequests() just before advancing the
unlink cycle counter.  This ensures that any unlink requests forwarded
prior to checkpoint start (i.e., when ckpt_started is incremented) will
be processed by the current checkpoint.  Since AbsorbSyncRequests()
performs memory allocations, it cannot be called within a critical
section, so we also need to move SyncPreCheckpoint() to before
CreateCheckPoint()'s critical section.

This is an old bug, so back-patch to all supported versions.

Author: Nathan Bossart <nathandbossart@gmail.com>
Reported-by: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220215235845.GA2665318%40nathanxps13

3 years agopageinspect: Fix memory context allocation of page in brin_revmap_data()
Michael Paquier [Wed, 16 Mar 2022 03:29:39 +0000 (12:29 +0900)]
pageinspect: Fix memory context allocation of page in brin_revmap_data()

This caused the function to fail, as the aligned copy of the raw page
given by the function caller was not saved in the correct memory
context, which needs to be multi_call_memory_ctx in this case.

Issue introduced by 076f4d9.

Per buildfarm members sifika, mylodon and longfin.  I have reproduced
that locally with macos.

Discussion: https://postgr.es/m/YjFPOtfCW6yLXUeM@paquier.xyz
Backpatch-through: 10

3 years agoFix documentation typo in commit 5e6368b4.
Thomas Munro [Wed, 16 Mar 2022 02:53:28 +0000 (15:53 +1300)]
Fix documentation typo in commit 5e6368b4.

Back-patch to 14.

3 years agoFix waiting in RegisterSyncRequest().
Thomas Munro [Wed, 16 Mar 2022 02:35:16 +0000 (15:35 +1300)]
Fix waiting in RegisterSyncRequest().

If we run out of space in the checkpointer sync request queue (which is
hopefully rare on real systems, but common with very small buffer pool),
we wait for it to drain.  While waiting, we should report that as a wait
event so that users know what is going on, and also handle postmaster
death, since otherwise the loop might never terminate if the
checkpointer has exited.

Back-patch to 12.  Although the problem exists in earlier releases too,
the code is structured differently before 12 so I haven't gone any
further for now, in the absence of field complaints.

Reported-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220226213942.nb7uvb2pamyu26dj%40alap3.anarazel.de

3 years agopageinspect: Fix handling of page sizes and AM types
Michael Paquier [Wed, 16 Mar 2022 02:19:39 +0000 (11:19 +0900)]
pageinspect: Fix handling of page sizes and AM types

This commit fixes a set of issues related to the use of the SQL
functions in this module when the caller is able to pass down raw page
data as input argument:
- The page size check was fuzzy in a couple of places, sometimes
looking after only a sub-range, but what we are looking for is an exact
match on BLCKSZ.  After considering a few options here, I have settled
down to do a generalization of get_page_from_raw().  Most of the SQL
functions already used that, and this is not strictly required if not
accessing an 8-byte-wide value from a raw page, but this feels safer in
the long run for alignment-picky environment, particularly if a code
path begins to access such values.  This also reduces the number of
strings that need to be translated.
- The BRIN function brin_page_items() uses a Relation but it did not
check the access method of the opened index, potentially leading to
crashes.  All the other functions in need of a Relation already did
that.
- Some code paths could fail on elog(), but we should to use ereport()
for failures that can be triggered by the user.

Tests are added to stress all the cases that are fixed as of this
commit, with some junk raw pages (\set VERBOSITY ensures that this works
across all page sizes) and unexpected index types when functions open
relations.

Author: Michael Paquier, Justin Prysby
Discussion: https://postgr.es/m/20220218030020.GA1137@telsasoft.com
Backpatch-through: 10

3 years agoWake up for latches in CheckpointWriteDelay().
Thomas Munro [Wed, 16 Mar 2022 00:37:58 +0000 (13:37 +1300)]
Wake up for latches in CheckpointWriteDelay().

The checkpointer shouldn't ignore its latch.  Other backends may be
waiting for it to drain the request queue.  Hopefully real systems don't
have a full queue often, but the condition is reached easily when
shared_buffers is small.

This involves defining a new wait event, which will appear in the
pg_stat_activity view often due to spread checkpoints.

Back-patch only to 14.  Even though the problem exists in earlier
branches too, it's hard to hit there.  In 14 we stopped using signal
handlers for latches on Linux, *BSD and macOS, which were previously
hiding this problem by interrupting the sleep (though not reliably, as
the signal could arrive before the sleep begins; precisely the problem
latches address).

Reported-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20220226213942.nb7uvb2pamyu26dj%40alap3.anarazel.de

3 years agoSilence LLVM 14 API deprecation warnings.
Thomas Munro [Tue, 15 Mar 2022 21:30:55 +0000 (10:30 +1300)]
Silence LLVM 14 API deprecation warnings.

We are going to need to handle the upcoming opaque pointer API
changes[1], possibly in time for LLVM 15, but in the meantime let's
silence the warnings produced by LLVM 14.

[1] https://llvm.org/docs/OpaquePointers.html

Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CA%2BhUKG%2Bp%3DfaBQR2PSAqWoWa%2B_tJdKPT0wjZPQe7XcDEttUCgdQ%40mail.gmail.com

3 years agoRemove accidentally-committed file.
Robert Haas [Tue, 15 Mar 2022 17:41:36 +0000 (13:41 -0400)]
Remove accidentally-committed file.

3 years agoAdd 'basebackup_to_shell' contrib module.
Robert Haas [Tue, 15 Mar 2022 17:24:23 +0000 (13:24 -0400)]
Add 'basebackup_to_shell' contrib module.

As a demonstration of the sort of thing that can be done by adding a
custom backup target, this defines a 'shell' target which executes a
command defined by the system administrator. The command is executed
once for each tar archive generate by the backup and once for the
backup manifest, if any. Each time the command is executed, it
receives the contents of th file for which it is executed via standard
input.

The configured command can use %f to refer to the name of the archive
(e.g. base.tar, $TABLESPACE_OID.tar, backup_manifest) and %d to refer
to the target detail (pg_basebackup --target shell:DETAIL). A target
detail is required if %d appears in the configured command and
forbidden if it does not.

Patch by me, reviewed by Abhijit Menon-Sen.

Discussion: http://postgr.es/m/CA+TgmoaqvdT-u3nt+_kkZ7bgDAyqDB0i-+XOMmr5JN2Rd37hxw@mail.gmail.com

3 years agoAllow extensions to add new backup targets.
Robert Haas [Tue, 15 Mar 2022 17:22:04 +0000 (13:22 -0400)]
Allow extensions to add new backup targets.

Commit 3500ccc39b0dadd1068a03938e4b8ff562587ccc allowed for base backup
targets, meaning that we could do something with the backup other than
send it to the client, but all of those targets had to be baked in to
the core code. This commit makes it possible for extensions to define
additional backup targets.

Patch by me, reviewed by Abhijit Menon-Sen.

Discussion: http://postgr.es/m/CA+TgmoaqvdT-u3nt+_kkZ7bgDAyqDB0i-+XOMmr5JN2Rd37hxw@mail.gmail.com

3 years agoChange HAVE_LIBLZ4 and HAVE_LIBZSTD tests to USE_LZ4 and USE_ZSTD.
Robert Haas [Tue, 15 Mar 2022 17:06:25 +0000 (13:06 -0400)]
Change HAVE_LIBLZ4 and HAVE_LIBZSTD tests to USE_LZ4 and USE_ZSTD.

These tests were added recently, but older code tests USE_LZ4 rathr
than HAVE_LIBLZ4, so let's follow the established precedent. It
also seems more consistent with the intent of the configure tests,
since I think that the USE_* symbols are intended to correspond to
what the user requested, and the HAVE_* symbols to what configure
found while probing.

Discussion: http://postgr.es/m/CA+Tgmoap+hTD2-QNPJLH4tffeFE8MX5+xkbFKMU3FKBy=ZSNKA@mail.gmail.com

3 years agoFix compiler warning introduced in commit 705e20f855.
Amit Kapila [Tue, 15 Mar 2022 02:41:17 +0000 (08:11 +0530)]
Fix compiler warning introduced in commit 705e20f855.

Reported-by: Nathan Bossart
Author: Nathan Bossart
Reviewed-by: Osumi Takamichi
Discussion : https://postgr.es/m/20220314230424.GA1085716@nathanxps13

3 years agoFix collection of typos in the code and the documentation
Michael Paquier [Tue, 15 Mar 2022 02:29:23 +0000 (11:29 +0900)]
Fix collection of typos in the code and the documentation

Some words were duplicated while other places were grammatically
incorrect, including one variable name in the code.

Author: Otto Kekalainen, Justin Pryzby
Discussion: https://postgr.es/m/7DDBEFC5-09B6-4325-B942-B563D1A24BDC@amazon.com

3 years agoAdd more regression tests for pg_ls_dir()
Michael Paquier [Tue, 15 Mar 2022 01:52:19 +0000 (10:52 +0900)]
Add more regression tests for pg_ls_dir()

This system function was being triggered once in the main regression
test suite to check its SRF configuration, and more in other test
modules but nothing checked the behavior of the options missing_ok and
include_dot_dirs.  This commit adds some tests for both options, to
avoid mistakes if this code is manipulated in the future.

Extracted from a larger patch by the same author, with a few tweaks by
me.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20191227170220.GE12890@telsasoft.com

3 years agoFix pg_basebackup with in-place tablespaces.
Thomas Munro [Tue, 15 Mar 2022 00:38:41 +0000 (13:38 +1300)]
Fix pg_basebackup with in-place tablespaces.

Previously, pg_basebackup from a cluster that contained an 'in-place'
tablespace, as introduced by commit 7170f215, would produce a harmless
warning on Unix and fail completely on Windows.

Reported-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/20220304.165449.1200020258723305904.horikyota.ntt%40gmail.com

3 years agoSupport "of", "tzh", and "tzm" format codes.
Robert Haas [Mon, 14 Mar 2022 20:46:46 +0000 (16:46 -0400)]
Support "of", "tzh", and "tzm" format codes.

The upper case versions "OF", "TZH", and "TZM" are already supported,
and all other format codes that are supported in upper case are also
supported in lower case, so we should support these as well for
consistency.

Nitin Jadhav, with a tiny cosmetic change by me. Reviewed by Suraj
Kharage and David Zhang.

Discussion: http://postgr.es/m/CAMm1aWZ-oZyKd75+8D=VJ0sAoSwtdXWLP-MAWD4D8R1Dgandzw@mail.gmail.com