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

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

Richard Guo, with some editorialization by me

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

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

Erik Rijkers and Justin Pryzby

Backpatch to v14

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

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

Per suggestion from Robert Haas

Backpatch to v14

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2 years agoRemove duplicated wait for subscription sync from 007_ddl.pl.
Amit Kapila [Tue, 2 Aug 2022 03:50:38 +0000 (09:20 +0530)]
Remove duplicated wait for subscription sync from 007_ddl.pl.

An oversight in 8f2e2bbf14.

Author: Masahiko Sawada
Reviewed by: Amit Kapila
Backpatch-through: 15, where it was introduced
Discussion: https://postgr.es/m/CAD21AoC-fvAkaKHa4t1urupwL8xbAcWRePeETvshvy80f6WV1A@mail.gmail.com

2 years agoCheck maximum number of columns in function RTEs, too.
Tom Lane [Mon, 1 Aug 2022 16:22:35 +0000 (12:22 -0400)]
Check maximum number of columns in function RTEs, too.

I thought commit fd96d14d9 had plugged all the holes of this sort,
but no, function RTEs could produce oversize tuples too, either
via long coldeflists or just from multiple functions in one RTE.
(I'm pretty sure the other variants of base RTEs aren't a problem,
because they ultimately refer to either a table or a sub-SELECT,
whose widths are enforced elsewhere.  But we explicitly allow join
RTEs to be overwidth, as long as you don't try to form their
tuple result.)

Per further discussion of bug #17561.  As before, patch all branches.

Discussion: https://postgr.es/m/17561-80350151b9ad2ad4@postgresql.org

2 years agoFix error reporting after ioctl() call with pg_upgrade --clone
Michael Paquier [Mon, 1 Aug 2022 07:39:16 +0000 (16:39 +0900)]
Fix error reporting after ioctl() call with pg_upgrade --clone

errno was not reported correctly after attempting to clone a file,
leading to incorrect error reports.  While scanning through the code, I
have not noticed any similar mistakes.

Error introduced in 3a769d8.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20220731134135[email protected]
Backpatch-through: 12

2 years agoci: remove minor version from freebsd image name
Andres Freund [Mon, 1 Aug 2022 00:40:42 +0000 (17:40 -0700)]
ci: remove minor version from freebsd image name

This way .cirrus.yml does not need to be changed just because freebsd releases
a new minor version.

Discussion: https://postgr.es/m/20220728095704[email protected]
Backpatch: 15-, just like the CI support

2 years agoRemove test_oat_hooks.c's nodetag_to_string().
Tom Lane [Sun, 31 Jul 2022 20:58:20 +0000 (16:58 -0400)]
Remove test_oat_hooks.c's nodetag_to_string().

In the short time this function has existed, it's already proven to be
a nontrivial maintenance burden, since it has to be updated whenever a
node tag is added or removed.  Although in principle we could now
automate that, I see little justification for having such functionality
here at all.  The function is only being applied to utility statements,
for which we already have infrastructure for obtaining string names.
Moreover, that infrastructure produces already-familiar-to-users names,
unlike nodetag_to_string().

So, remove this function and use the existing infrastructure instead.
That saves over a thousand lines of largely-unreachable code.

Back-patch to v15 where this code came in.  Although it seems unlikely
that v15's nodetag list will change anymore, we might as well keep the
two branches looking and acting alike; otherwise back-patching any
test-results changes in this area will be painful.

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

2 years agoci: switch to freebsd 13.1
Andres Freund [Sun, 31 Jul 2022 19:31:40 +0000 (12:31 -0700)]
ci: switch to freebsd 13.1

freebsd 13.0 is out of support, switch to 13.1. It might be a good idea to
remove the minor version number from the image name, but there's not been a
response to that so far...

Discussion: https://postgr.es/m/20220728095704[email protected]
Backpatch: 15-, just like the CI support

2 years agoFix trim_array() for zero-dimensional array argument.
Tom Lane [Sun, 31 Jul 2022 17:43:17 +0000 (13:43 -0400)]
Fix trim_array() for zero-dimensional array argument.

The code tried to access ARR_DIMS(v)[0] and ARR_LBOUND(v)[0]
whether or not those values exist.  This made the range check
on the "n" argument unstable --- it might or might not fail, and
if it did it would report garbage for the allowed upper limit.
These bogus accesses would probably annoy Valgrind, and if you
were very unlucky even lead to SIGSEGV.

Report and fix by Martin Kalcher.  Back-patch to v14 where this
function was added.

Discussion: https://postgr.es/m/baaeb413-b8a8-4656-5757-ef347e5ec11f@aboutsource.net

2 years agoMake new auto_explain test safe for log_error_verbosity = verbose.
Tom Lane [Sun, 31 Jul 2022 16:29:44 +0000 (12:29 -0400)]
Make new auto_explain test safe for log_error_verbosity = verbose.

Allow for the possible presence of a SQLSTATE code in the expected
warning message, similarly to b998196bb and 19408aae7 (although
here I see no need to allow more than one specific SQLSTATE).
Per gripe from Andrew Dunstan.

Discussion: https://postgr.es/m/c550ac53-5db5-3958-1798-50bae3d9af71@dunslane.net

2 years agoFix incorrect is-this-the-topmost-join tests in parallel planning.
Tom Lane [Sat, 30 Jul 2022 17:05:15 +0000 (13:05 -0400)]
Fix incorrect is-this-the-topmost-join tests in parallel planning.

Two callers of generate_useful_gather_paths were testing the wrong
thing when deciding whether to call that function: they checked for
being at the top of the current join subproblem, rather than being at
the actual top join.  This'd result in failing to construct parallel
paths for a sub-join for which they might be useful.

While set_rel_pathlist() isn't actively broken, it seems best to
make its identical-in-intention test for this be like the other two.

This has been wrong all along, but given the lack of field complaints
I'm hesitant to back-patch into stable branches; we usually prefer
to avoid non-bug-fix changes in plan choices in minor releases.
It seems not too late for v15 though.

Richard Guo, reviewed by Antonin Houska and Tom Lane

Discussion: https://postgr.es/m/CAMbWs4-mH8Zf87-w+3P2J=nJB+5OyicO28ia9q_9o=Lamf_VHg@mail.gmail.com

2 years agoRevise test case added in 43746996399541ecb5c7b188725a5f097c15ceae.
Robert Haas [Sat, 30 Jul 2022 03:24:39 +0000 (23:24 -0400)]
Revise test case added in 43746996399541ecb5c7b188725a5f097c15ceae.

Instead of using command_ok() to run psql, use safe_psql(). wrasse
isn't happy, and it be because of failure to pass -X to the psql
invocation, which safe_psql() will do automatically.

Since safe_psql() returns standard output instead of writing it to
a file, this requires some changes to the incantation for running
'diff'.

Test against the 'regression' database rather than 'postgres' so
we test more than just one table. That also means we need to record
the horizons later, after the test does "VACUUM FULL pg_largeobject".

Add an ORDER BY clause to the horizon query for stability.

Patch by me, reviewed by Tom Lane.

Discussion: http://postgr.es/m/CA+TgmoaGBbpzgu3=du1f9zDUbkfycO0y=_uWrLFy=KKEqXWeLQ@mail.gmail.com

2 years agoFix new recovery test for log_error_verbosity=verbose case
Andrew Dunstan [Fri, 29 Jul 2022 21:43:34 +0000 (17:43 -0400)]
Fix new recovery test for log_error_verbosity=verbose case

The new test is from commit 9e4f914b5e.

With this setting messages have SQL error numbers included, so that
needs to be provided for in the pattern looked for.

Backpatch to all live branches like the original.

2 years agoFix brown paper bag bug in bbe08b8869bd29d587f24ef18eb45c7d4d14afca.
Robert Haas [Fri, 29 Jul 2022 20:31:57 +0000 (16:31 -0400)]
Fix brown paper bag bug in bbe08b8869bd29d587f24ef18eb45c7d4d14afca.

We must issue the TRUNCATE command first and update relfrozenxid
and relminmxid afterward; otherwise, TRUNCATE overwrites the
previously-set values.

Add a test case like I should have done the first time.

Per buildfarm report from TestUpgradeXversion.pm, by way of Tom
Lane.

2 years agoIn transformRowExpr(), check for too many columns in the row.
Tom Lane [Fri, 29 Jul 2022 17:30:50 +0000 (13:30 -0400)]
In transformRowExpr(), check for too many columns in the row.

A RowExpr with more than MaxTupleAttributeNumber columns would fail at
execution anyway, since we cannot form a tuple datum with more than that
many columns.  While heap_form_tuple() has a check for too many columns,
it emerges that there are some intermediate bits of code that don't
check and can be driven to failure with sufficiently many columns.
Checking this at parse time seems like the most appropriate place to
install a defense, since we already check SELECT list length there.

While at it, make the SELECT-list-length error use the same errcode
(TOO_MANY_COLUMNS) as heap_form_tuple does, rather than the generic
PROGRAM_LIMIT_EXCEEDED.

Per bug #17561 from Egor Chindyaskin.  The given test case crashes
in all supported branches (and probably a lot further back),
so patch all.

Discussion: https://postgr.es/m/17561-80350151b9ad2ad4@postgresql.org

2 years agoFix mistake in bbe08b8869bd29d587f24ef18eb45c7d4d14afca.
Robert Haas [Fri, 29 Jul 2022 15:20:07 +0000 (11:20 -0400)]
Fix mistake in bbe08b8869bd29d587f24ef18eb45c7d4d14afca.

The earlier commit used pg_class.relfilenode where it should have
used pg_class.oid. This could lead to emitting an UPDATE statement
into the dump that would update nothing (or the wrong thing) when
executed in the new cluster, resulting in relfrozenxid and
relminmxid being improperly carried forward for pg_largeobject.

Noticed by Dilip Kumar.

Discussion: http://postgr.es/m/CAFiTN-ty1Gzs6stk2vt9BJiq0m0hzf=aPnh3a-4Z3Tk5GzoENw@mail.gmail.com

2 years agoFix test instability
Alvaro Herrera [Fri, 29 Jul 2022 10:50:47 +0000 (12:50 +0200)]
Fix test instability

On FreeBSD, the new test fails due to a WAL file being removed before
the standby has had the chance to copy it.  Fix by adding a replication
slot to prevent the removal until after the standby has connected.

Author: Kyotaro Horiguchi 
Reported-by: Matthias van de Meent
Discussion: https://postgr.es/m/CAEze2Wj5nau_qpjbwihvmXLfkAWOZ5TKdbnqOc6nKSiRJEoPyQ@mail.gmail.com

2 years agoUse TRUNCATE to preserve relfilenode for pg_largeobject + index.
Robert Haas [Thu, 28 Jul 2022 19:32:24 +0000 (15:32 -0400)]
Use TRUNCATE to preserve relfilenode for pg_largeobject + index.

Commit 9a974cbcba005256a19991203583a94b4f9a21a9 arranged to preserve
the relfilenode of user tables across pg_upgrade, but failed to notice
that pg_upgrade treats pg_largeobject as a user table and thus it needs
the same treatment. Otherwise, large objects will appear to vanish
after a  pg_upgrade.

Commit d498e052b4b84ae21b3b68d5b3fda6ead65d1d4d fixed this problem
by teaching pg_dump to UPDATE pg_class.relfilenode for pg_largeobject
and its index. However, because an UPDATE on the catalog rows doesn't
change anything on disk, this can leave stray files behind in the new
cluster. They will normally be empty, but it's a little bit untidy.

Hence, this commit arranges to do the same thing using DDL. Specifically,
it makes TRUNCATE work for the pg_largeobject catalog when in
binary-upgrade mode, and it then uses that command in binary-upgrade
dumps as a way of setting pg_class.relfilenode for pg_largeobject and
its index. That way, the old files are removed from the new cluster.

Discussion: http://postgr.es/m/CA+TgmoYYMXGUJO5GZk1-MByJGu_bB8CbOL6GJQC8=Bzt6x6vDg@mail.gmail.com

2 years agodoc: avoid saying "inheritance" ...
Alvaro Herrera [Thu, 28 Jul 2022 16:21:56 +0000 (18:21 +0200)]
doc: avoid saying "inheritance" ...

... when it applies to partitioned relations.  This is almost the
opposite of 0c06534bd63b, which removed references to "partition" in
favour of "child".

Author: Justin Pryzby 
Reviewed-by: Ashutosh Bapat
Reviewed-by: Amit Langote
Discussion: https://postgr.es/m/20220525013248[email protected]

2 years agoFix replay of create database records on standby
Alvaro Herrera [Thu, 28 Jul 2022 06:26:05 +0000 (08:26 +0200)]
Fix replay of create database records on standby

Crash recovery on standby may encounter missing directories
when replaying database-creation WAL records.  Prior to this
patch, the standby would fail to recover in such a case;
however, the directories could be legitimately missing.
Consider the following sequence of commands:

    CREATE DATABASE
    DROP DATABASE
    DROP TABLESPACE

If, after replaying the last WAL record and removing the
tablespace directory, the standby crashes and has to replay the
create database record again, crash recovery must be able to continue.

A fix for this problem was already attempted in 49d9cfc68bf4, but it
was reverted because of design issues.  This new version is based
on Robert Haas' proposal: any missing tablespaces are created
during recovery before reaching consistency.  Tablespaces
are created as real directories, and should be deleted
by later replay.  CheckRecoveryConsistency ensures
they have disappeared.

The problems detected by this new code are reported as PANIC,
except when allow_in_place_tablespaces is set to ON, in which
case they are WARNING.  Apart from making tests possible, this
gives users an escape hatch in case things don't go as planned.

Author: Kyotaro Horiguchi 
Author: Asim R Praveen 
Author: Paul Guo 
Reviewed-by: Anastasia Lubennikova (older versions)
Reviewed-by: Fujii Masao (older versions)
Reviewed-by: Michaël Paquier
Diagnosed-by: Paul Guo
Discussion: https://postgr.es/m/CAEET0ZGx9AvioViLf7nbR_8tH9-=27DN5xWJ2P9-ROH16e4JUA@mail.gmail.com

2 years agoFix get_dirent_type() for symlinks on MinGW/MSYS.
Thomas Munro [Thu, 28 Jul 2022 02:13:37 +0000 (14:13 +1200)]
Fix get_dirent_type() for symlinks on MinGW/MSYS.

On Windows with MSVC, get_dirent_type() was recently made to return
DT_LNK for junction points by commit 9d3444dc, which fixed some
defective dirent.c code.

On Windows with Cygwin, get_dirent_type() already worked for symlinks,
as it does on POSIX systems, because Cygwin has its own fake symlinks
that behave like POSIX (on closer inspection, Cygwin's dirent has the
BSD d_type extension but it's probably always DT_UNKNOWN, so we fall
back to lstat(), which understands Cygwin symlinks with S_ISLNK()).

On Windows with MinGW/MSYS, we need extra code, because the MinGW
runtime has its own readdir() without d_type, and the lstat()-based
fallback has no knowledge of our convention for treating junctions as
symlinks.

Back-patch to 14, where get_dirent_type() landed.

Reported-by: Andrew Dunstan
Discussion: https://postgr.es/m/b9ddf605-6b36-f90d-7c30-7b3e95c46276%40dunslane.net

2 years agoFix new auto_explain test case for Windows.
Tom Lane [Wed, 27 Jul 2022 22:58:20 +0000 (18:58 -0400)]
Fix new auto_explain test case for Windows.

In commit 7c34555f8, I overlooked the need to configure SSPI
on Windows to allow login as the non-superuser role.
Fix that by adding auth_extra/--create-role incantation
(which, oddly enough, doesn't actually create the role).
Per buildfarm.

While here, upgrade the mechanism for temporarily setting
$ENV{PGUSER}, as per recommendation from ilmari.

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

2 years agoForce immediate commit after CREATE DATABASE etc in extended protocol.
Tom Lane [Tue, 26 Jul 2022 17:07:03 +0000 (13:07 -0400)]
Force immediate commit after CREATE DATABASE etc in extended protocol.

We have a few commands that "can't run in a transaction block",
meaning that if they complete their processing but then we fail
to COMMIT, we'll be left with inconsistent on-disk state.
However, the existing defenses for this are only watertight for
simple query protocol.  In extended protocol, we didn't commit
until receiving a Sync message.  Since the client is allowed to
issue another command instead of Sync, we're in trouble if that
command fails or is an explicit ROLLBACK.  In any case, sitting
in an inconsistent state while waiting for a client message
that might not come seems pretty risky.

This case wasn't reachable via libpq before we introduced pipeline
mode, but it's always been an intended aspect of extended query
protocol, and likely there are other clients that could reach it
before.

To fix, set a flag in PreventInTransactionBlock that tells
exec_execute_message to force an immediate commit.  This seems
to be the approach that does least damage to existing working
cases while still preventing the undesirable outcomes.

While here, add some documentation to protocol.sgml that explicitly
says how to use pipelining.  That's latent in the existing docs if
you know what to look for, but it's better to spell it out; and it
provides a place to document this new behavior.

Per bug #17434 from Yugo Nagata.  It's been wrong for ages,
so back-patch to all supported branches.

Discussion: https://postgr.es/m/17434-d9f7a064ce2a88a3@postgresql.org

2 years agoFix path reference when parsing pg_ident.conf for pg_ident_file_mappings
Michael Paquier [Tue, 26 Jul 2022 06:57:33 +0000 (15:57 +0900)]
Fix path reference when parsing pg_ident.conf for pg_ident_file_mappings

Since a2c8499, HbaFileName (default pg_hba.conf) was getting used
instead of IdentFileName (default pg_ident.conf) as the parent file to
use as reference when parsing the contents of pg_ident.conf, with
pg_ident.conf correctly opened, when feeding this information to
pg_ident_file_mappings.  This had two consequences:
- On an I/O error when reading pg_ident.conf, the user would get an
ERROR message referring to pg_hba.conf and not pg_ident.conf.
- When reading an external file with a relative path using '@' in
pg_ident.conf, the directory used to look at the file to load would be
the base directory of pg_hba.conf rather than the one of pg_ident.conf,
leading to errors in pg_ident_file_mappings inconsistent with what gets
loaded at startup when pg_ident.conf and pg_hba.conf are located in
different directories.

This error only impacted the SQL view pg_ident_file_mappings that uses a
logic new to v15 to fill the view with the parsed information, not the
code paths loading these authentication files at startup.

Author: Julien Rouhaud
Discussion: https://postgr.es/m/20220726050402.vsr6fmz7rsgpmdz3@jrouhaud
Backpatch-through: 15

2 years agoAdd test for session_preload_libraries and parameter permissions checks.
Tom Lane [Mon, 25 Jul 2022 19:45:24 +0000 (15:45 -0400)]
Add test for session_preload_libraries and parameter permissions checks.

We weren't exercising the session_preload_libraries option in any
meaningful way.  auto_explain is a good testbed for doing so, since
it's one of the primary use-cases for session_preload_libraries.
Hence, adjust its TAP test to load the library via
session_preload_libraries not shared_preload_libraries.  While at it,
feed test-specific settings to the backend via PGOPTIONS rather than
tediously rewriting postgresql.conf.

Also, since auto_explain has some PGC_SUSET parameters, we can use it
to provide a test case for the permissions-checking bug just fixed
by commit b35617de3.

Back-patch to v15 so that we have coverage for the permissions issue
in that branch too.  To do that, I back-patched the refactoring
recently done by commit 550bc0a6c.

Dagfinn Ilmari Mannsåker and Tom Lane

Discussion: https://postgr.es/m/CABwTF4VEpwTHhRQ+q5MiC5ucngN-whN-PdcKeufX7eLSoAfbZA@mail.gmail.com

2 years agoProcess session_preload_libraries within InitPostgres's transaction.
Tom Lane [Mon, 25 Jul 2022 14:27:43 +0000 (10:27 -0400)]
Process session_preload_libraries within InitPostgres's transaction.

Previously we did this after InitPostgres, at a somewhat randomly chosen
place within PostgresMain.  However, since commit a0ffa885e doing this
outside a transaction can cause a crash, if we need to check permissions
while replacing a placeholder GUC.  (Besides which, a preloaded library
could itself want to do database access within _PG_init.)

To avoid needing an additional transaction start/end in every session,
move the process_session_preload_libraries call to within InitPostgres's
transaction.  That requires teaching the code not to call it when
InitPostgres is called from somewhere other than PostgresMain, since
we don't want session_preload_libraries to affect background workers.
The most future-proof solution here seems to be to add an additional
flag parameter to InitPostgres; fortunately, we're not yet very worried
about API stability for v15.

Doing this also exposed the fact that we're currently honoring
session_preload_libraries in walsenders, even those not connected to
any database.  This seems, at minimum, a POLA violation: walsenders
are not interactive sessions.  Let's stop doing that.

(All these comments also apply to local_preload_libraries, of course.)

Per report from Gurjeet Singh (thanks also to Nathan Bossart and Kyotaro
Horiguchi for review).  Backpatch to v15 where a0ffa885e came in.

Discussion: https://postgr.es/m/CABwTF4VEpwTHhRQ+q5MiC5ucngN-whN-PdcKeufX7eLSoAfbZA@mail.gmail.com

2 years agoFix ReadRecentBuffer for local buffers.
Heikki Linnakangas [Mon, 25 Jul 2022 05:48:38 +0000 (08:48 +0300)]
Fix ReadRecentBuffer for local buffers.

It incorrectly used GetBufferDescriptor instead of
GetLocalBufferDescriptor, causing it to not find the correct buffer in
most cases, and performing an out-of-bounds memory read in the corner
case that temp_buffers > shared_buffers.

It also bumped the usage-count on the buffer, even if it was
previously pinned. That won't lead to crashes or incorrect results,
but it's different from what the shared-buffer case does, and
different from the usual code in LocalBufferAlloc. Fix that too, and
make the code ordering match LocalBufferAlloc() more closely, so that
it's easier to verify that it's doing the same thing.

Currently, ReadRecentBuffer() is only used with non-temp relations, in
WAL redo, so the broken code is currently dead code. However, it could
be used by extensions.

Backpatch-through: 14
Discussion: https://www.postgresql.org/message-id/2d74b46f-27c9-fb31-7f99-327a87184cc0%40iki.fi
Reviewed-by: Thomas Munro, Zhang Mingli, Richard Guo
2 years agoDoc: improve documentation about random().
Tom Lane [Sat, 23 Jul 2022 23:00:30 +0000 (19:00 -0400)]
Doc: improve documentation about random().

We didn't explicitly say that random() uses a randomly-chosen seed
if you haven't called setseed().  Do so.

Also, remove ref/set.sgml's no-longer-accurate (and never very
relevant) statement that the seed value is multiplied by 2^31-1.

Back-patch to v12 where set.sgml's claim stopped being true.
The claim that we use a source of random bits as seed was debatable
before 4203842a1, too, so v12 seems like a good place to stop.

Per question from Carl Sopchak.

Discussion: https://postgr.es/m/f37bb937-9d99-08f0-4de7-80c91a3cfc2e@sopchak.me

2 years agoDoc: update recovery/README.
Tom Lane [Sat, 23 Jul 2022 20:10:14 +0000 (16:10 -0400)]
Doc: update recovery/README.

Commit e2f65f425 added contrib/pg_prewarm to the prerequisites for
running the src/test/recovery suite, but did not bother to update
the documentation about that.

2 years agoIncrease minimum supported GNU make version to 3.81.
Tom Lane [Sat, 23 Jul 2022 16:12:42 +0000 (12:12 -0400)]
Increase minimum supported GNU make version to 3.81.

We've long held the minimum at 3.80, but that's required more than
one workaround.  Commit 0f39b70a6 broke it again, because it turns
out that exporting a target-specific variable didn't work in 3.80.
Considering that 3.81 is now old enough to get a driver's license,
and that the only remaining buildfarm member testing 3.80 (prairiedog)
is likely to be retired soon, let's just stop supporting 3.80.

Adjust docs and Makefile.global's minimum-version check to match.
There are a couple of comments in the Makefiles suggesting that
random things could be done differently after we desupport 3.80,
but I couldn't get excited about changing any of them right now.

Back-patch to v15, as 0f39b70a6 was.

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

2 years agoFix [install]check in interfaces/libpq/Makefile
Alvaro Herrera [Fri, 22 Jul 2022 18:15:11 +0000 (20:15 +0200)]
Fix [install]check in interfaces/libpq/Makefile

The common recipe when TAP tests are disabled doesn't work, because the
libpq-specific recipe wants to define the PATH environment variable, so
the starting '@' is misinterpreted as part of the command instead of
silencing said command.

Fix by setting the environment variable in a way that doesn't interfere
with the recipe.

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20220720172321[email protected]

2 years agoClose old gap in dependency checks for functions returning composite.
Tom Lane [Fri, 22 Jul 2022 16:46:42 +0000 (12:46 -0400)]
Close old gap in dependency checks for functions returning composite.

The dependency logic failed to register a column-level dependency
when a view or rule contains a reference to a specific column of
the result of a function-returning-composite.  That meant you could
drop the column from the composite type, causing trouble for future
executions of the view.  We've known about this for years, but never
summoned the energy to actually fix it, instead installing various
low-level defenses to prevent crashing on references to dropped columns.
We had to do that to plug the hole in stable branches, where there might
be pre-existing broken references; but let's fix the root cause today.

To do that, add some logic (borrowed from get_rte_attribute_is_dropped)
to find_expr_references_walker, to check whether a Var referencing an
RTE_FUNCTION RTE is referencing a column of a composite type, and if
so add the proper dependency.

However ... it seems mighty unwise to remove said low-level defenses,
since there could be other bugs now or in the future that allow
reaching them.  By the same token, letting those defenses go untested
seems unwise.  Hence, rather than just dropping the associated test
cases, hack them to continue working by the expedient of manually
dropping the pg_depend entries that this fix installs.

Back-patch into v15.  I don't want to risk changing this behavior
in stable branches, but it seems not too late for v15.  (Since
we have already forced initdb for beta3, we can be sure that all
production v15 installations will have these added dependencies.)

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

2 years agoFix minor memory leaks in psql's tab completion.
Tom Lane [Fri, 22 Jul 2022 14:53:26 +0000 (10:53 -0400)]
Fix minor memory leaks in psql's tab completion.

Tang Haiying and Tom Lane

Discussion: https://postgr.es/m/OS0PR01MB6113EA19F05E217C823B4CCAFB909@OS0PR01MB6113.jpnprd01.prod.outlook.com

2 years agoRemove unnecessary Windows-specific basebackup code.
Thomas Munro [Fri, 22 Jul 2022 05:37:39 +0000 (17:37 +1200)]
Remove unnecessary Windows-specific basebackup code.

Commit c6f2f016 added an explicit check for a Windows "junction point".
That turned out to be needed only because get_dirent_type() was busted
on Windows.  It's been fixed by commit 9d3444dc, so remove it.

Add a TAP-test to demonstrate that in-place tablespaces are copied by
pg_basebackup.  This exercises the codepath that would fail before
c6f2f016 on Windows, and shows that it still doesn't fail now that we're
using get_dirent_type() on both Windows and Unix.

Back-patch to 15, where in-place tablespaces arrived and caused this
problem (ie directories where previously only symlinks were expected).

Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/CA%2BhUKGLzLK4PUPx0_AwXEWXOYAejU%3D7XpxnYE55Y%2Be7hB2N3FA%40mail.gmail.com

2 years agoFix get_dirent_type() for Windows junction points.
Thomas Munro [Fri, 22 Jul 2022 04:57:12 +0000 (16:57 +1200)]
Fix get_dirent_type() for Windows junction points.

Commit 87e6ed7c8 added code that intended to report Windows "junction
points" as DT_LNK (the same way we report symlinks on Unix).  Windows
junction points are *also* directories according to the Windows
attributes API, and we were reporting them as as DT_DIR.  Change the
order we check the attribute flags, to prioritize DT_LNK.

If at some point we start using Windows' recently added real symlinks
and need to distinguish them from junction points, we may need to
rethink this, but for now this continues the tradition of wrapper
functions that treat junction points as symlinks.

Back-patch to 14, where get_dirent_type() landed.

Reviewed-by: Michael Paquier
Reviewed-by: Alvaro Herrera
Discussion: https://postgr.es/m/CA%2BhUKGLzLK4PUPx0_AwXEWXOYAejU%3D7XpxnYE55Y%2Be7hB2N3FA%40mail.gmail.com
Discussion: https://postgr.es/m/20220721111751.x7hod2xgrd76xr5c%40alvherre.pgsql

2 years agopostgres_fdw: Fix bug in checking of return value of PQsendQuery().
Fujii Masao [Thu, 21 Jul 2022 13:52:50 +0000 (22:52 +0900)]
postgres_fdw: Fix bug in checking of return value of PQsendQuery().

When postgres_fdw begins an asynchronous data fetch, it submits FETCH query
by using PQsendQuery(). If PQsendQuery() fails and returns 0, postgres_fdw
should report an error. But, previously, postgres_fdw reported an error
only when the return value is less than 0, though PQsendQuery() never return
the values other than 0 and 1. Therefore postgres_fdw could not handle
the failure to send FETCH query in an asynchronous data fetch.

This commit fixes postgres_fdw so that it reports an error
when PQsendQuery() returns 0.

Back-patch to v14 where asynchronous execution was supported in postgres_fdw.

Author: Fujii Masao
Reviewed-by: Japin Li, Tom Lane
Discussion: https://postgr.es/m/b187a7cf-d4e3-5a32-4d01-8383677797f3@oss.nttdata.com

2 years agodoc: use wording "restore" instead of "reload" of dumps
Bruce Momjian [Thu, 21 Jul 2022 18:55:23 +0000 (14:55 -0400)]
doc:  use wording "restore" instead of "reload" of dumps

Reported-by: [email protected]
Discussion: https://postgr.es/m/164736074430.660.3645615289283943146@wrigleys.postgresql.org

Backpatch-through: 11

2 years agodoc: clarify that auth. names are lower case and case-sensitive
Bruce Momjian [Thu, 21 Jul 2022 17:58:20 +0000 (13:58 -0400)]
doc:  clarify that auth. names are lower case and case-sensitive

This is true even for acronyms that are usually upper case, like LDAP.

Reported-by: Alvaro Herrera
Discussion: https://postgr.es/m/202205141521[email protected]

Backpatch-through: 10

2 years agoFix ruleutils issues with dropped cols in functions-returning-composite.
Tom Lane [Thu, 21 Jul 2022 17:56:02 +0000 (13:56 -0400)]
Fix ruleutils issues with dropped cols in functions-returning-composite.

Due to lack of concern for the case in the dependency code, it's
possible to drop a column of a composite type even though stored
queries have references to the dropped column via functions-in-FROM
that return the composite type.  There are "soft" references,
namely FROM-clause aliases for such columns, and "hard" references,
that is actual Vars referring to them.  The right fix for hard
references is to add dependencies preventing the drop; something
we've known for many years and not done (and this commit still doesn't
address it).  A "soft" reference shouldn't prevent a drop though.
We've been around on this before (cf. 9b35ddce92c4debbd0), but
nobody had noticed that the current behavior can result in dump/reload
failures, because ruleutils.c can print more column aliases than the
underlying composite type now has.  So we need to rejigger the
column-alias-handling code to treat such columns as dropped and not
print aliases for them.

Rather than writing new code for this, I used expandRTE() which already
knows how to figure out which function result columns are dropped.
I'd initially thought maybe we could use expandRTE() in all cases, but
that fails for EXPLAIN's purposes, because the planner strips a lot of
RTE infrastructure that expandRTE() needs.  So this patch just uses it
for unplanned function RTEs and otherwise does things the old way.

If there is a hard reference (Var), then removing the column alias
causes us to fail to print the Var, since there's no longer a name
to print.  Failing seems less desirable than printing a made-up
name, so I made it print "?dropped?column?" instead.

Per report from Timo Stolz.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/5c91267e-3b6d-5795-189c-d15a55d61dbb@nullachtvierzehn.de

2 years agorelnotes: improve PG 15 schema permission change wording
Bruce Momjian [Thu, 21 Jul 2022 17:43:13 +0000 (13:43 -0400)]
relnotes:  improve PG 15 schema permission change wording

Reported-by: Noah Misch
Discussion: https://postgr.es/m/20220630050808[email protected]

Backpatch-through: 15 only

2 years agoCorrect some uses of e.g. and i.e. in message strings and documentation
John Naylor [Thu, 14 Jul 2022 02:38:06 +0000 (09:38 +0700)]
Correct some uses of e.g. and i.e. in message strings and documentation

E.g. means "for example" and i.e. means "that is". Fix a couple uses
that don't match the intended meaning.

Kyotaro Horiguchi

Reviewed by Junwang Zhao and Aleksander Alekseev, with one addition by me
Discussion: https://www.postgresql.org/message-id/flat/20220713.180943.589079824955875739.horikyota.ntt%40gmail.com

This is a backpatch of 82785effc0 to v15

2 years agoFix various memory leaks in psql's describe commands \d*
Michael Paquier [Thu, 21 Jul 2022 01:42:07 +0000 (10:42 +0900)]
Fix various memory leaks in psql's describe commands \d*

Most of these have been introduced in d2d3547 with the new pattern
validation logic, and would leak memory worth an amount of one
PQExpBuffer each time (as of 256 bytes at minimum, possibly more).

Most of the patch has been written by Tang Haiying, with a few tweaks
coming from Álvaro Herrera.

Reported-by: Tang Haiying
Author: Tang Haiying, Álvaro Herrera
Reviewed-by: Mark Dilger, Andres Freund, Álvaro Herrera, Tom Lane, Japin
Li, Michael Paquier, Junwang Zhao
Backpatch-through: 15

2 years agoProcess shared_preload_libraries in single-user mode.
Jeff Davis [Fri, 15 Jul 2022 19:24:10 +0000 (12:24 -0700)]
Process shared_preload_libraries in single-user mode.

Without processing shared_preload_libraries, it's impossible to
recover if custom WAL resource managers are needed. It may also pose a
problem running VACUUM on a table with a custom AM, if the module
implementing the AM is expecting to be loaded by
shared_preload_libraries.

The reason this wasn't done before was just the general principle to
do fewer things in single-user mode. But it's easy enough to just set
shared_preload_libraries to empty, for the same effect.

Discussion: https://postgr.es/m/9decc18a42634f8a2f15c97a385a0f51a752f396.camel%40j-davis.com
Reviewed-by: Tom Lane, Andres Freund
Backpatch-through: 15

2 years agoFix assertion failure and segmentation fault in backup code.
Fujii Masao [Tue, 12 Jul 2022 02:53:29 +0000 (11:53 +0900)]
Fix assertion failure and segmentation fault in backup code.

When a non-exclusive backup is canceled, do_pg_abort_backup() is called
and resets some variables set by pg_backup_start (pg_start_backup in v14
or before). But previously it forgot to reset the session state indicating
whether a non-exclusive backup is in progress or not in this session.

This issue could cause an assertion failure when the session running
BASE_BACKUP is terminated after it executed pg_backup_start and
pg_backup_stop (pg_stop_backup in v14 or before). Also it could cause
a segmentation fault when pg_backup_stop is called after BASE_BACKUP
in the same session is canceled.

This commit fixes the issue by making do_pg_abort_backup reset
that session state.

Back-patch to all supported branches.

Author: Fujii Masao
Reviewed-by: Kyotaro Horiguchi, Masahiko Sawada, Michael Paquier, Robert Haas
Discussion: https://postgr.es/m/3374718f-9fbf-a950-6d66-d973e027f44c@oss.nttdata.com

2 years agoPrevent BASE_BACKUP in the middle of another backup in the same session.
Fujii Masao [Tue, 12 Jul 2022 00:31:57 +0000 (09:31 +0900)]
Prevent BASE_BACKUP in the middle of another backup in the same session.

Multiple non-exclusive backups are able to be run conrrently in different
sessions. But, in the same session, only one non-exclusive backup can be
run at the same moment. If pg_backup_start (pg_start_backup in v14 or before)
is called in the middle of another non-exclusive backup in the same session,
an error is thrown.

However, previously, in logical replication walsender mode, even if that
walsender session had already called pg_backup_start and started
a non-exclusive backup, it could execute BASE_BACKUP command and
start another non-exclusive backup. Which caused subsequent pg_backup_stop
to throw an error because BASE_BACKUP unexpectedly reset the session state
marked by pg_backup_start.

This commit prevents BASE_BACKUP command in the middle of another
non-exclusive backup in the same session.

Back-patch to all supported branches.

Author: Fujii Masao
Reviewed-by: Kyotaro Horiguchi, Masahiko Sawada, Michael Paquier, Robert Haas
Discussion: https://postgr.es/m/3374718f-9fbf-a950-6d66-d973e027f44c@oss.nttdata.com

2 years agoTweak detail and hint messages to be consistent with project policy
Michael Paquier [Wed, 20 Jul 2022 00:50:57 +0000 (09:50 +0900)]
Tweak detail and hint messages to be consistent with project policy

Detail and hint messages should be full sentences and should end with a
period, but some of the messages newly-introduced in v15 did not follow
that.

Author: Justin Pryzby
Reviewed-by: Álvaro Herrera
Discussion: https://postgr.es/m/20220719120948[email protected]
Backpatch-through: 15

2 years agoFix missed corner cases for grantable permissions on GUCs.
Tom Lane [Tue, 19 Jul 2022 21:22:03 +0000 (17:22 -0400)]
Fix missed corner cases for grantable permissions on GUCs.

We allow users to set the values of not-yet-loaded extension GUCs,
remembering those values in "placeholder" GUC entries.  When/if
the extension is loaded later in the session, we need to verify that
the user had permissions to set the GUC.  That was done correctly
before commit a0ffa885e, but as of that commit, we'd check the
permissions of the active role when the LOAD happens, not the role
that had set the value.  (This'd be a security bug if it had made it
into a released version.)

In principle this is simple enough to fix: we just need to remember
the exact role OID that set each GUC value, and use that not
GetUserID() when verifying permissions.  Maintaining that data in
the guc.c data structures is slightly tedious, but fortunately it's
all basically just copy-n-paste of the logic for tracking the
GucSource of each setting, as we were already doing.

Another oversight is that validate_option_array_item() hadn't
been taught to check for granted GUC privileges.  This appears
to manifest only in that ALTER ROLE/DATABASE RESET ALL will
fail to reset settings that the user should be allowed to reset.

Patch by myself and Nathan Bossart, per report from Nathan Bossart.
Back-patch to v15 where the faulty code came in.

Discussion: https://postgr.es/m/20220706224727.GA2158260@nathanxps13

2 years agorelnotes: clarify pg_basebackup compression options
Bruce Momjian [Tue, 19 Jul 2022 20:45:25 +0000 (16:45 -0400)]
relnotes:  clarify pg_basebackup compression options

Also, a few wording improvements

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20220719181307[email protected]

Backpatch-through: 15 only

2 years agorelnotes: improve wording of several PG 15 items
Bruce Momjian [Tue, 19 Jul 2022 17:35:00 +0000 (13:35 -0400)]
relnotes:  improve wording of several PG 15 items

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20220719012322[email protected]

Backpatch-through: 15 only

2 years agoUse STDOUT/STDERR_FILENO in most of syslogger.
Andres Freund [Tue, 19 Jul 2022 00:06:34 +0000 (17:06 -0700)]
Use STDOUT/STDERR_FILENO in most of syslogger.

This fixes problems on windows when logging collector is used in a service,
failing with:
FATAL:  could not redirect stderr: Bad file descriptor

This is triggered by 76e38b37a5. The problem is that STDOUT/STDERR_FILENO
aren't defined on windows, which lead us to use _fileno(stdout) etc, but that
doesn't work if stdout/stderr are closed.

Author: Andres Freund 
Reported-By: Sandeep Thakkar
Message-Id: 20220520164558[email protected] (on pgsql-packagers)
Backpatch: 15-, where 76e38b37a5 came in

2 years agowindows: msvc: Define STDIN/OUT/ERR_FILENO.
Andres Freund [Tue, 19 Jul 2022 00:06:34 +0000 (17:06 -0700)]
windows: msvc: Define STDIN/OUT/ERR_FILENO.

Because they are not available we've used _fileno(stdin) in some places, but
that doesn't reliably work, because stdin might be closed. This is the
prerequisite of the subsequent commit, fixing a failure introduced in
76e38b37a5.

Author: Andres Freund 
Reported-By: Sandeep Thakkar
Message-Id: 20220520164558[email protected] (on pgsql-packagers)
Backpatch: 15-, where 76e38b37a5 came in

2 years agoDeal with paths containing \ and spaces in basebackup_to_shell tests
Andres Freund [Mon, 18 Jul 2022 17:14:43 +0000 (10:14 -0700)]
Deal with paths containing \ and spaces in basebackup_to_shell tests

As $gzip is embedded in postgresql.conf \ needs to be escaped, otherwise guc.c
will take it as a string escape. Similarly, if "$gzip" contains spaces, the
prior incantation will fail. Both of these are common on windows.

Reviewed-by: Peter Eisentraut
Discussion: https://postgr.es/m/ce1b6eb3-5736-6f38-9775-b7020128b8d8@enterprisedb.com
Backpatch: 15-, where the test was added in 027fa0fd726

2 years agopg_upgrade: Adjust quoting style in message to match guidelines
Peter Eisentraut [Mon, 18 Jul 2022 12:53:00 +0000 (14:53 +0200)]
pg_upgrade: Adjust quoting style in message to match guidelines

2 years agoAdd another SQL/JSON error code
Peter Eisentraut [Mon, 18 Jul 2022 12:26:43 +0000 (14:26 +0200)]
Add another SQL/JSON error code

A code comment said that the standard does not define a number for
ERRCODE_SQL_JSON_ITEM_CANNOT_BE_CAST_TO_TARGET_TYPE, but this was
fixed in a later draft version of the standard, so use that number
now.

2 years agoFix omissions in support for the "regcollation" type.
Tom Lane [Sun, 17 Jul 2022 21:43:28 +0000 (17:43 -0400)]
Fix omissions in support for the "regcollation" type.

The patch that added regcollation doesn't seem to have been too
thorough about supporting it everywhere that other reg* types
are supported.  Fix that.  (The find_expr_references omission
is moderately serious, since it could result in missing expression
dependencies.  The others are less exciting.)

Noted while fixing bug #17483.  Back-patch to v13 where
regcollation was added.

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

2 years agopostgres_fdw: set search_path to 'pg_catalog' while deparsing constants.
Tom Lane [Sun, 17 Jul 2022 21:27:50 +0000 (17:27 -0400)]
postgres_fdw: set search_path to 'pg_catalog' while deparsing constants.

The motivation for this is to ensure successful transmission of the
values of constants of regconfig and other reg* types.  The remote
will be reading them with search_path = 'pg_catalog', so schema
qualification is necessary when referencing objects in other schemas.

Per bug #17483 from Emmanuel Quincerot.  Back-patch to all supported
versions.  (There's some other stuff to do here, but it's less
back-patchable.)

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

2 years agoMake dsm_impl_posix_resize more future-proof.
Thomas Munro [Fri, 15 Jul 2022 22:59:52 +0000 (10:59 +1200)]
Make dsm_impl_posix_resize more future-proof.

Commit 4518c798 blocks signals for a short region of code, but it
assumed that whatever called it had the signal mask set to UnBlockSig on
entry.  That may be true today (or may even not be, in extensions in the
wild), but it would be better not to make that assumption.  We should
save-and-restore the caller's signal mask.

The PG_SETMASK() portability macro couldn't be used for that, which is
why it wasn't done before.  But... considering that commit a65e0864
established back in 9.6 that supported POSIX systems have sigprocmask(),
and that this is POSIX-only code, there is no reason not to use standard
sigprocmask() directly to achieve that.

Back-patch to all supported releases, like 4518c798 and 80845b7c.

Reviewed-by: Alvaro Herrera
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/CA%2BhUKGKx6Biq7_UuV0kn9DW%2B8QWcpJC1qwhizdtD9tN-fn0H0g%40mail.gmail.com

2 years agoFix inconsistent parameter names between prototype and declaration
David Rowley [Fri, 15 Jul 2022 03:27:14 +0000 (15:27 +1200)]
Fix inconsistent parameter names between prototype and declaration

Noticed while working in this area.  This code was introduced in PG15,
which is still in beta, so backpatch to there for consistency.

Backpatch-through: 15

2 years agoClarify that pg_dump takes ACCESS SHARE lock
John Naylor [Fri, 1 Jul 2022 04:41:36 +0000 (11:41 +0700)]
Clarify that pg_dump takes ACCESS SHARE lock

Add link to the description of lock levels to avoid confusing "shared locks"
with SHARE locks.

Florin Irion

Reviewed-by: Álvaro Herrera, Tom Lane, and Nathan Bossart
Discussion: https://www.postgresql.org/message-id/flat/d0f30cc2-3c76-1d43-f291-7c4b2872d653@gmail.com

This is a backpatch of 4e2e8d71f, applied through version 14

2 years agodocs: make monitoring "phases" table titles consistent
Bruce Momjian [Fri, 15 Jul 2022 00:01:11 +0000 (20:01 -0400)]
docs:  make monitoring "phases" table titles consistent

Reported-by: Nitin Jadhav
Discussion: https://postgr.es/m/CAMm1aWbmTHwHKC2PERH0CCaFVPoxrtLeS8=wNuoge94qdSp3vA@mail.gmail.com

Author: Nitin Jadhav

Backpatch-through: 13

2 years agodoc: clarify how dropping of extensions affects dependent objs.
Bruce Momjian [Thu, 14 Jul 2022 21:41:03 +0000 (17:41 -0400)]
doc:  clarify how dropping of extensions affects dependent objs.

Clarify that functions/procedures are dropped when any extension that
depends on them is dropped.

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwbPSHMDGkisRUmewopweC1bFvytVqB=a=X4GFg=4ZWxPA@mail.gmail.com

Backpatch-through: 13

2 years agopg_upgrade doc: mention that replication slots must be recreated
Bruce Momjian [Thu, 14 Jul 2022 20:34:30 +0000 (16:34 -0400)]
pg_upgrade doc: mention that replication slots must be recreated

Reported-by: Nikhil Shetty
Discussion: https://postgr.es/m/CAFpL5Vxastip0Jei-K-=7cKXTg=5sahSe5g=om=x68NOX8+PUA@mail.gmail.com

Backpatch-through: 10

2 years agodoc: add documentation about ecpg Oracle-compatibility mode
Bruce Momjian [Thu, 14 Jul 2022 20:19:45 +0000 (16:19 -0400)]
doc:  add documentation about ecpg Oracle-compatibility mode

Reported-by: Takeshi Ideriha
Discussion: https://postgr.es/m/TYCPR01MB7041A157067208327D8DAAF9EAA59@TYCPR01MB7041.jpnprd01.prod.outlook.com

Backpatch-through: 11

2 years agodoc: move system views section to its own chapter
Bruce Momjian [Thu, 14 Jul 2022 20:07:12 +0000 (16:07 -0400)]
doc:  move system views section to its own chapter

Previously it was inside the system catalogs chapter.

Reported-by: Peter Smith
Discussion: https://postgr.es/m/CAHut+PsMc18QP60D+L0hJBOXrLQT5m88yVaCDyxLq34gfPHsow@mail.gmail.com

Backpatch-through: 15

2 years agodoc: clarify the behavior of identically-named savepoints
Bruce Momjian [Thu, 14 Jul 2022 19:44:22 +0000 (15:44 -0400)]
doc:  clarify the behavior of identically-named savepoints

Original patch by David G. Johnston.

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwYQCxSSuSL18skCWG8QHFswOJ3hjovHsOZUE346i4OpVQ@mail.gmail.com

Backpatch-through: 10

2 years agodoc: clarify that "excluded" ON CONFLICT is a single row
Bruce Momjian [Thu, 14 Jul 2022 19:33:28 +0000 (15:33 -0400)]
doc:  clarify that "excluded" ON CONFLICT is a single row

Original patch by David G. Johnston.

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwa4J0+WuO7kW1PLbjoEvzPN+Q_j+P2bXxNnCLaszY7ZdQ@mail.gmail.com

Backpatch-through: 10

2 years agodoc: mention that INSERT can block because of unique indexes
Bruce Momjian [Thu, 14 Jul 2022 19:17:19 +0000 (15:17 -0400)]
doc:  mention that INSERT can block because of unique indexes

Initial patch by David G. Johnston.

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwZpbdzceO41VE-xt1Xh8rWRRfgopTAK1wL9EhCo0Am-Sw@mail.gmail.com

Backpatch-through: 10

2 years agodoc: mention the pg_locks lock names in parentheses
Bruce Momjian [Thu, 14 Jul 2022 16:08:55 +0000 (12:08 -0400)]
doc:  mention the pg_locks lock names in parentheses

Reported-by: Troy Frericks
Discussion: https://postgr.es/m/165653551130.665.8240515669521441325@wrigleys.postgresql.org

Backpatch-through: 10

2 years agoDon't clobber postmaster sigmask in dsm_impl_resize.
Thomas Munro [Thu, 14 Jul 2022 13:23:29 +0000 (01:23 +1200)]
Don't clobber postmaster sigmask in dsm_impl_resize.

Commit 4518c798 intended to block signals in regular backends that
allocate DSM segments, but dsm_impl_resize() is also reached by
dsm_postmaster_startup().  It's not OK to clobber the postmaster's
signal mask, so only manipulate the signal mask when under the
postmaster.

Back-patch to all releases, like 4518c798.

Discussion: https://postgr.es/m/CA%2BhUKGKNpK%3D2OMeea_AZwpLg7Bm4%3DgYWk7eDjZ5F6YbozfOf8w%40mail.gmail.com

2 years agoBlock signals while allocating DSM memory.
Thomas Munro [Wed, 13 Jul 2022 04:16:07 +0000 (16:16 +1200)]
Block signals while allocating DSM memory.

On Linux, we call posix_fallocate() on shm_open()'d memory to avoid
later potential SIGBUS (see commit 899bd785).

Based on field reports of systems stuck in an EINTR retry loop there,
there, we made it possible to break out of that loop via slightly odd
coding where the CHECK_FOR_INTERRUPTS() call was somewhat removed from
the loop (see commit 422952ee).

On further reflection, that was not a great choice for at least two
reasons:

1.  If interrupts were held, the CHECK_FOR_INTERRUPTS() would do nothing
and the EINTR error would be surfaced to the user.

2.  If EINTR was reported but neither QueryCancelPending nor
ProcDiePending was set, then we'd dutifully retry, but with a bit more
understanding of how posix_fallocate() works, it's now clear that you
can get into a loop that never terminates.  posix_fallocate() is not a
function that can do some of the job and tell you about progress if it's
interrupted, it has to undo what it's done so far and report EINTR, and
if signals keep arriving faster than it can complete (cf recovery
conflict signals), you're stuck.

Therefore, for now, we'll simply block most signals to guarantee
progress.  SIGQUIT is not blocked (see InitPostmasterChild()), because
its expected handler doesn't return, and unblockable signals like
SIGCONT are not expected to arrive at a high rate.  For good measure,
we'll include the ftruncate() call in the blocked region, and add a
retry loop.

Back-patch to all supported releases.

Reported-by: Alvaro Herrera
Reported-by: Nicola Contu
Reviewed-by: Alvaro Herrera
Reviewed-by: Andres Freund
Discussion: https://postgr.es/m/20220701154105.jjfutmngoedgiad3%40alvherre.pgsql

2 years agoPlug memory leak
Alvaro Herrera [Wed, 13 Jul 2022 10:10:03 +0000 (12:10 +0200)]
Plug memory leak

Commit 054325c5eeb3 created a memory leak in PQsendQueryInternal in case
an error occurs while sending the message.  Repair.

Backpatch to 14, like that commit.  Reported by Coverity.

2 years agoSmall cleanup of create_list_bounds()
David Rowley [Wed, 13 Jul 2022 05:01:39 +0000 (17:01 +1200)]
Small cleanup of create_list_bounds()

When checking for interleaved partitions, we mark the partition as
interleaved when;

1. we find an earlier partition index when looping over the
sorted-by-Datum indexes[] array, or;

2. we find that the NULL partition allows some non-NULL Datum value.

In the code, as it was written in db632fbca we'll continue to check for
case 2 when we've already marked the partition as interleaved for case 1.
Here we make it so we don't bother marking the partition as interleaved
for case 2 when it's already been marked due to case 1.

Really all this saves is a useless call to bms_add_member(), but since
this code is new to PG15, it seems worth fixing it now to save anyone the
trouble of complaining at some time in the future.  We have the
opportunity to improve this now before PG15 is out.  This might ease some
future back-patching pain.

Per report and patch by Zhihong Yu.  However, I slightly revised the
comments and altered the bms_add_member() code to match in both locations.
We already know that index is equal to boundinfo->null_index from the if
condition.

Author: Zhihong Yu
Discussion: https://postgr.es/m/CALNJ-vQbZR0pYxz9zQ5bqXVcwtGgNgVupeEpNT65HZ+yWZnc4g@mail.gmail.com
Backpatch-through: 15, same as db632fbca.

2 years agoTidy up code in get_cheapest_group_keys_order()
David Rowley [Wed, 13 Jul 2022 02:03:24 +0000 (14:03 +1200)]
Tidy up code in get_cheapest_group_keys_order()

There are a few things that we could do a little better within
get_cheapest_group_keys_order():

1. We should be using list_free() rather than pfree() on a List.

2. We should use for_each_from() instead of manually coding a for loop to
skip the first n elements of a List

3. list_truncate(list_copy(...), n) is not a great way to copy the first n
elements of a list. Let's invent list_copy_head() for that.  That way we
don't need to copy the entire list just to truncate it directly
afterwards.

4. We can simplify finding the cheapest cost by setting the cheapest cost
variable to DBL_MAX.  That allows us to skip special-casing the initial
iteration of the loop.

Author: David Rowley
Discussion: https://postgr.es/m/CAApHDvrGyL3ft8waEkncG9y5HDMu5TFFJB1paoTC8zi9YK97Nw@mail.gmail.com
Backpatch-through: 15, where get_cheapest_group_keys_order was added.

2 years agoInvent qsort_interruptible().
Tom Lane [Tue, 12 Jul 2022 20:30:36 +0000 (16:30 -0400)]
Invent qsort_interruptible().

Justin Pryzby reported that some scenarios could cause gathering
of extended statistics to spend many seconds in an un-cancelable
qsort() operation.  To fix, invent qsort_interruptible(), which is
just like qsort_arg() except that it will also do CHECK_FOR_INTERRUPTS
every so often.  This bloats the backend by a couple of kB, which
seems like a good investment.  (We considered just enabling
CHECK_FOR_INTERRUPTS in the existing qsort and qsort_arg functions,
but there are some callers for which that'd demonstrably be unsafe.
Opt-in seems like a better way.)

For now, just apply qsort_interruptible() in statistics collection.
There's probably more places where it could be useful, but we can
always change other call sites as we find problems.

Back-patch to v14.  Before that we didn't have extended stats on
expressions, so that the problem was less severe.  Also, this patch
depends on the sort_template infrastructure introduced in v14.

Tom Lane and Justin Pryzby

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

2 years agorelnotes: updates "cumulative statistics system" mention
Bruce Momjian [Mon, 11 Jul 2022 18:21:24 +0000 (14:21 -0400)]
relnotes:  updates "cumulative statistics system" mention

Also add "the".

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20220711173923[email protected]

Backpatch-through: 15 only

2 years agoFix lock assertions in dshash.c.
Thomas Munro [Mon, 11 Jul 2022 02:47:16 +0000 (14:47 +1200)]
Fix lock assertions in dshash.c.

dshash.c previously maintained flags to be able to assert that you
didn't hold any partition lock.  These flags could get out of sync with
reality in error scenarios.

Get rid of all that, and make assertions about the locks themselves
instead.  Since LWLockHeldByMe() loops internally, we don't want to put
that inside another loop over all partition locks.  Introduce a new
debugging-only interface LWLockAnyHeldByMe() to avoid that.

This problem was noted by Tom and Andres while reviewing changes to
support the new shared memory stats system, and later showed up in
reality while working on commit 389869af.

Back-patch to 11, where dshash.c arrived.

Reported-by: Tom Lane
Reported-by: Andres Freund
Reviewed-by: Kyotaro HORIGUCHI
Reviewed-by: Zhihong Yu
Reviewed-by: Andres Freund
Discussion: https://postgr.es/m/20220311012712[email protected]
Discussion: https://postgr.es/m/CA%2BhUKGJ31Wce6HJ7xnVTKWjFUWQZPBngxfJVx4q0E98pDr3kAw%40mail.gmail.com

2 years agoFix two portability issues with the tests of test_oat_hooks
Michael Paquier [Mon, 11 Jul 2022 03:48:06 +0000 (12:48 +0900)]
Fix two portability issues with the tests of test_oat_hooks

This addresses two issues in the tests of test_oat_hooks:
- The role regress_test_user was being left behind, preventing the test
to succeed on repeated runs.  It makes sense to leave some objects
behind to have more coverage for pg_upgrade (as does test_pg_dump), but
the role dropped here does not own any objects so there is no reason to
keep it.
- GRANT SET ON PARAMETER is issued, creating an entry in
pg_parameter_acl without cleaning up the entry created.  This causes
an overlap with unsafe_tests as both use work_mem, making the latter
fail.  This commit adds an extra REVOKE SET ON PARAMETER to clean the
contents of pg_parameter_acl, switching to maintenance_work_mem rather
than work_mem to avoid an overlap between both tests.

The tests of test_oat_hooks cannot use installcheck yet as these are
proving to be unstable with caching and the namespace search hooks, so
the issues fixed here cannot be reached yet, but they would be once the
hook issue is addressed and installcheck is allowed again in
test_oat_hooks.

Discussion: https://postgr.es/m/[email protected]
Backpatch-through: 15

2 years agoImprove error message with JSON_SERIALIZE()
Michael Paquier [Mon, 11 Jul 2022 02:20:52 +0000 (11:20 +0900)]
Improve error message with JSON_SERIALIZE()

The error message introduced in 3c633f3 can share the same format string
with an existing message used for JSON(), reducing the translation
effort.

Author: Kyotaro Horiguchi
Discussion: https://postgr.es/m/20220708.154135.2123613118233840495[email protected]
Backpatch-through: 15

2 years agodoc: Fix inconsistent quotes in some jsonb fields
Michael Paquier [Mon, 11 Jul 2022 01:56:42 +0000 (10:56 +0900)]
doc: Fix inconsistent quotes in some jsonb fields

Single quotes are not allowed in json internals, double quotes are.

Reported-by: Eric Mutta
Discussion: https://postgr.es/m/165715362165.665.3875113264927503997@wrigleys.postgresql.org
Backpatch-through: 14

2 years agoFix \watch's interaction with libedit on ^C.
Thomas Munro [Sun, 10 Jul 2022 04:30:03 +0000 (16:30 +1200)]
Fix \watch's interaction with libedit on ^C.

When you hit ^C, the terminal driver in Unix-like systems echoes "^C" as
well as sending an interrupt signal (depending on stty settings).  At
least libedit (but maybe also libreadline) is then confused about the
current cursor location, and corrupts the display if you try to scroll
back.  Fix, by moving to a new line before the next prompt is displayed.

Back-patch to all supported released.

Author: Pavel Stehule 
Reported-by: Tom Lane
Discussion: https://postgr.es/m/3278793.1626198638%40sss.pgh.pa.us

2 years agodoc: add examples for array_length() and jsonb_array_length()
Bruce Momjian [Sat, 9 Jul 2022 00:23:35 +0000 (20:23 -0400)]
doc:  add examples for array_length() and jsonb_array_length()

The examples show the output of array_length() and jsonb_array_length()
for empty arrays.

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

Author: David G. Johnston

Backpatch-through: 13

2 years agodoc: add pg_prewarm example
Bruce Momjian [Fri, 8 Jul 2022 22:36:27 +0000 (18:36 -0400)]
doc:  add pg_prewarm example

Discussion: https://postgr.es/m/20220618085541.ezxdaljlpo6x7msc@home-desktop

Author: Dong Wook Lee

Backpatch-through: 11

2 years agoPreserve relfilenode of pg_largeobject and its index across pg_upgrade.
Robert Haas [Fri, 8 Jul 2022 14:15:19 +0000 (10:15 -0400)]
Preserve relfilenode of pg_largeobject and its index across pg_upgrade.

Commit 9a974cbcba005256a19991203583a94b4f9a21a9 did this for user
tables, but pg_upgrade treats pg_largeobject as a user table, and so
needs the same treatment. Without this fix, if you rewrite the
pg_largeobject table and then perform an upgrade with pg_upgrade, the
table will apparently be empty on the new cluster, while all of your
objects will end up with an orphaned file.

With this fix, instead of the old cluster's pg_largeobject files ending
up orphaned, the original files fro the new cluster do. That's mostly
harmless because we expect the table to be empty, but we might want
to arrange to remove the as part of the upgrade. Since we're still
debating the best way of doing that, I (rhaas) have decided to postpone
dealing with that problem and get the basic fix committed.

Justin Pryzby, reviewed by Shruthi Gowda and by me.

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

2 years agoOnly allow returning string types or bytea from json_serialize
Andrew Dunstan [Thu, 7 Jul 2022 21:40:02 +0000 (17:40 -0400)]
Only allow returning string types or bytea from json_serialize

These are documented to be the allowed types for the RETURNING clause,
but the restriction was not being enforced, which caused a segfault if
another type was specified. Add some testing for this.

Per report from a.kozhemyakin

Backpatch to release 15.

2 years agoFix alias matching in transformLockingClause().
Dean Rasheed [Thu, 7 Jul 2022 12:08:06 +0000 (13:08 +0100)]
Fix alias matching in transformLockingClause().

When locking a specific named relation for a FOR [KEY] UPDATE/SHARE
clause, transformLockingClause() finds the relation to lock by
scanning the rangetable for an RTE with a matching eref->aliasname.
However, it failed to account for the visibility rules of a join RTE.

If a join RTE doesn't have a user-supplied alias, it will have a
generated eref->aliasname of "unnamed_join" that is not visible as a
relation name in the parse namespace. Such an RTE needs to be skipped,
otherwise it might be found in preference to a regular base relation
with a user-supplied alias of "unnamed_join", preventing it from being
locked.

In addition, if a join RTE doesn't have a user-supplied alias, but
does have a join_using_alias, then the RTE needs to be matched using
that alias rather than the generated eref->aliasname, otherwise a
misleading "relation not found" error will be reported rather than a
"join cannot be locked" error.

Backpatch all the way, except for the second part which only goes back
to 14, where JOIN USING aliases were added.

Dean Rasheed, reviewed by Tom Lane.

Discussion: https://postgr.es/m/CAEZATCUY_KOBnqxbTSPf=7fz9HWPnZ5Xgb9SwYzZ8rFXe7nb=w@mail.gmail.com

2 years agopostgres_fdw: Fix grammar.
Etsuro Fujita [Thu, 7 Jul 2022 07:25:00 +0000 (16:25 +0900)]
postgres_fdw: Fix grammar.

Oversight in commit 4036bcbbb; back-patch to v15 where that appeared.

2 years agoRe-order disable_on_error in tab-complete.
Amit Kapila [Thu, 7 Jul 2022 03:45:52 +0000 (09:15 +0530)]
Re-order disable_on_error in tab-complete.

By convention, the tab-complete subscription parameters are listed in the
COMPLETE_WITH lists in alphabetical order, but when the "disable_on_error"
parameter was introduced this was not done.

This patch just tidies that up.

Reported-by: Peter Smith
Author: Peter Smith
Reviewed-by: Euler Taveira, Takamichi Osumi
Backpatch-through: 15, where it was introduced
Discussion: https://postgr.es/m/CAHut+PucvKZgg_eJzUW--iL6DXHg1Jwj6F09tQziE3kUF67uLg@mail.gmail.com

2 years agopgstat: slru: remove outdated comment
Andres Freund [Wed, 6 Jul 2022 22:50:38 +0000 (15:50 -0700)]
pgstat: slru: remove outdated comment

That comment might have been true at some point during development, but
definitely isn't anymore.

Reported-By: Melanie Plageman
Backpatch: 15-

2 years agoFix wrong field order in _readMergeWhenClause().
Tom Lane [Wed, 6 Jul 2022 21:26:27 +0000 (17:26 -0400)]
Fix wrong field order in _readMergeWhenClause().

We hadn't noticed this because it's dead code: there is no
situation where we read raw parse trees from text format.
So maybe the right fix is to remove the function altogether,
but I'll forbear for now; it's not the only dead code in
readfuncs.c, I think.

Noted while comparing existing code to the results of
Peter's auto-generation script.

2 years agoOverload index_form_tuple to allow the memory context to be supplied
David Rowley [Wed, 6 Jul 2022 20:14:32 +0000 (08:14 +1200)]
Overload index_form_tuple to allow the memory context to be supplied

40af10b57 changed things so we make use of a generation memory context for
storing tuples to be sorted by tuplesort.c. That change does not play
nicely with the changes made in 9f03ca915 (back in 2014). That commit
changed things so that index_form_tuple() is called while switched into
the tuplestore's tuplecontext. In order to fetch the tuple from the index,
index_form_tuple() must do various memory allocations which are unrelated
to the storage of the final returned tuple. Although all of these
allocations are pfree'd, the fact that we now use a generation context
means that the memory for these pfree'd allocations won't be used again by
any other allocation due to generation.c's lack of freelists.  This could
result in sorts used for building indexes exceeding maintenance_work_mem
by a very large amount.

Here we fix it so we no longer allocate anything apart from the tuple
itself into the generation context by adding a new version of
index_form_tuple named index_form_tuple_context, which can be called to
specify the MemoryContext to allocate the tuple into.

Discussion: https://postgr.es/m/CAApHDvrHQkiFRHiGiAS-LMOvJN-eK-s762=tVzBz8ZqUea-a_A@mail.gmail.com
Backpatch-through: 15, where 40af10b57 was added.

2 years agopgstat: drop subscription stats regardless of slot, fix comment
Andres Freund [Wed, 6 Jul 2022 15:46:04 +0000 (08:46 -0700)]
pgstat: drop subscription stats regardless of slot, fix comment

There's no reason anymore to only drop subscription stats if associated with a
slot, now that stats drops are transactional. Additionally, the comment
referring to autovacuum cleaning up stats was clearly outdated.

Author: Masahiko Sawada 
Discussion: https://postgr.es/m/CAD21AoAwiby3HeJE7vJe16Gr75RFfJ640dyHqvsiUhyKJTXPtw@mail.gmail.com
Backpatch: 15-

2 years agoRemove size increase in ExprEvalStep caused by hashed saops
David Rowley [Wed, 6 Jul 2022 07:41:09 +0000 (19:41 +1200)]
Remove size increase in ExprEvalStep caused by hashed saops

50e17ad28 increased the size of ExprEvalStep from 64 bytes up to 88 bytes.
Lots of effort was spent during the development of the current expression
evaluation code to make an instance of this struct as small as possible.
Making this struct larger than needed reduces CPU cache efficiency during
expression evaluation which causes noticeable slowdowns during query
execution.

In order to reduce the size of the struct, here we remove the fn_addr
field. The values from this field can be obtained via fcinfo, just with
some extra pointer dereferencing. The extra indirection does not seem to
cause any noticeable slowdowns.

Various other fields have been moved into the ScalarArrayOpExprHashTable
struct. These fields are only used when the ScalarArrayOpExprHashTable
pointer has already been dereferenced, so no additional pointer
dereferences occur for these. Here we also make hash_fcinfo_data the last
field in ScalarArrayOpExprHashTable so that we can avoid a further pointer
dereference to get the FunctionCallInfoBaseData. This also saves a call to
palloc().

50e17ad28 was added in 14, but it's too late to adjust the size of the
ExprEvalStep in that version, so here we just backpatch to 15, which is
currently in beta.

Author: Andres Freund, David Rowley
Discussion: https://postgr.es/m/20220616233130[email protected]
Backpatch-through: 15

2 years agoTighten pg_upgrade's new check for non-upgradable anyarray usages.
Tom Lane [Tue, 5 Jul 2022 22:23:19 +0000 (18:23 -0400)]
Tighten pg_upgrade's new check for non-upgradable anyarray usages.

We only need to reject cases when the aggregate or operator is
itself declared with a polymorphic type.  Per buildfarm.

Discussion: https://postgr.es/m/3383880.QJadu78ljV@vejsadalnx

2 years agopgstat: reduce timer overhead by leaving timer running.
Andres Freund [Fri, 17 Jun 2022 19:48:34 +0000 (12:48 -0700)]
pgstat: reduce timer overhead by leaving timer running.

Previously the timer was enabled whenever there were any pending stats after
executing a statement, just to then be disabled again when not idle
anymore. That lead to an increase in GetCurrentTimestamp() calls from within
timeout.c compared to 14.

To avoid that increase, leave the timer enabled until stats are reported,
rather than until idle. The timer is only disabled once the pending stats have
been reported.

For me this fixes the increase in GetCurrentTimestamp() calls, there now are
fewer calls in 15 than in 14, in the previously slowed down workload.

While at it, also update assertion in pgstat_report_stat() to be more precise.

Author: Andres Freund 
Discussion: https://postgr.es/m/20220616233130[email protected]
Backpatch: 15-