postgresql.git
21 months agoSimplify determining logical replication worker types.
Amit Kapila [Mon, 14 Aug 2023 03:08:03 +0000 (08:38 +0530)]
Simplify determining logical replication worker types.

We deduce a LogicalRepWorker's type from the values of several different
fields ('relid' and 'leader_pid') whenever logic needs to know it.

In fact, the logical replication worker type is already known at the time
of launching the LogicalRepWorker and it never changes for the lifetime of
that process. Instead of deducing the type, it is simpler to just store it
one time, and access it directly thereafter.

Author: Peter Smith
Reviewed-by: Amit Kapila, Bharath Rupireddy
Discussion: http://postgr.es/m/CAHut+PttPSuP0yoZ=9zLDXKqTJ=d0bhxwKaEaNcaym1XqcvDEg@mail.gmail.com

21 months agoci: macos: Remove use of -Dsegsize_blocks=6
Andres Freund [Sat, 12 Aug 2023 20:09:45 +0000 (13:09 -0700)]
ci: macos: Remove use of -Dsegsize_blocks=6

The option causes a measurable slowdown. Macos is, by far, the most expensive
platform for CI, therefore it doesn't make sense to run such a test there.

d3b111e3205 used a small segment size for two tasks, one with autoconf, one
with meson. In hindsight that is a bit overkill, it's unlikely that the option
would silently break. Thus don't move the -Dsegsize_blocks=6, just remove
it. I did however change the autoconf test to use 6 instead of 8 blocks, as
long as we allow it, a non-power-of-two test seems like a good idea.

While at it, add a comment explaining why we use a small segment size for CI.

Author: Andres Freund <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Discussion: https://postgr.es/m/20230808021541[email protected]
Back: 16-, where d3b111e3205 introduced the use of -Dsegsize_blocks=6

21 months agoci: macos: Remove use of -DRANDOMIZE_ALLOCATED_MEMORY
Andres Freund [Sat, 12 Aug 2023 20:06:04 +0000 (13:06 -0700)]
ci: macos: Remove use of -DRANDOMIZE_ALLOCATED_MEMORY

RANDOMIZE_ALLOCATED_MEMORY causes a measurable slowdown. Macos is, by far, the
most expensive platform for CI, therefore it doesn't make sense to run such a
test there.

Ubsan and asan on linux should detect most of the the cases of uninitialized
memory, so it doesn't really seem worth using -DRANDOMIZE_ALLOCATED_MEMORY in
another instance type.

Author: Andres Freund <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Discussion: https://postgr.es/m/20230808021541[email protected]
Back: 16-, where 89d16b635 added the use of -DRANDOMIZE_ALLOCATED_MEMORY

21 months agoFix off-by-one in XLogRecordMaxSize check.
Noah Misch [Sat, 12 Aug 2023 21:37:05 +0000 (14:37 -0700)]
Fix off-by-one in XLogRecordMaxSize check.

pg_logical_emit_message(false, '_', repeat('x', 1069547465)) failed with
self-contradictory message "WAL record would be 1069547520 bytes (of
maximum 1069547520 bytes)".  There's no particular benefit from allowing
or denying one byte in either direction; XLogRecordMaxSize could rise a
few megabytes without trouble.  Hence, this is just for cleanliness.
Back- to v16, where this check first appeared.

21 months agoShow GIDs of two-phase commit commands as constants in pg_stat_statements
Michael Paquier [Sat, 12 Aug 2023 01:44:15 +0000 (10:44 +0900)]
Show GIDs of two-phase commit commands as constants in pg_stat_statements

This relies on the "location" field added to TransactionStmt in 31de7e6,
now applied to the "gid" field used by 2PC commands.  These commands are
now reported like:
COMMIT PREPARED $1
PREPARE TRANSACTION $1
ROLLBACK PREPARED $1

Applying constants for these commands is a huge advantage for workloads
that rely a lot on 2PC commands with different GIDs.  Some tests are
added to track the new behavior.

Reviewed-by: Julien Rouhaud
Discussion: https://postgr.es/m/[email protected]

21 months agoFix code indentation violations introduced by recent commit
Michael Paquier [Fri, 11 Aug 2023 11:43:34 +0000 (20:43 +0900)]
Fix code indentation violations introduced by recent commit

The two culprit commits are 5765cfe and 5e0c761.

Per buildfarm member koel for the first commit, while I have noticed the
second one in passing.

21 months agoTransform proconfig for faster execution.
Jeff Davis [Thu, 10 Aug 2023 19:43:53 +0000 (12:43 -0700)]
Transform proconfig for faster execution.

Store function config settings in lists to avoid the need to parse and
allocate for each function execution.

Speedup is modest but significant. Additionally, this change also
seems cleaner and supports some other performance improvements under
discussion.

Discussion: https://postgr.es/m/04c8592dbd694e4114a3ed87139a7a04e4363030[email protected]
Reviewed-by: Nathan Bossart
21 months agoRemove test from commit fa2e874946.
Jeff Davis [Thu, 10 Aug 2023 17:16:59 +0000 (10:16 -0700)]
Remove test from commit fa2e874946.

The fix itself is fine, but the test revealed other problems related
to parallel query that are not easily fixable. Remove the test for
now to fix the buildfarm.

Discussion: https://postgr.es/m/88825.1691665432@sss.pgh.pa.us
Back-through: 11

21 months agoFix erroneous -Werror=missing-braces on old GCC
Peter Eisentraut [Thu, 10 Aug 2023 14:55:07 +0000 (16:55 +0200)]
Fix erroneous -Werror=missing-braces on old GCC

The buildfarm reports that this is an error on gcc (Debian 4.7.2-5)
4.7.2, 32-bit. The bug seems to be GCC bug 53119, which has obviously
been fixed for years.

Author: Tristan Partin <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CT6HJ3U8068R.3A8SJMV02D9BC@gonk

21 months agoUpdate Solution.pm for new LoongArch CRC symbol
John Naylor [Thu, 10 Aug 2023 11:37:46 +0000 (18:37 +0700)]
Update Solution.pm for new LoongArch CRC symbol

Oversight in 4d14ccd6a, per report from Amit Kapila
and Michael Paquier.

Discussion: https://postgr.es/m/CAA4eK1LsV3KuyUt8tzZDjPcUds1XfVVeW3Wpeju_59DtRV0%3DxQ%40mail.gmail.com

21 months agoDocument RelationGetIndexAttrBitmap better
Alvaro Herrera [Thu, 10 Aug 2023 10:04:07 +0000 (12:04 +0200)]
Document RelationGetIndexAttrBitmap better

Commit 19d8e2308bc5 changed the list of set-of-columns that can be
returned by RelationGetIndexAttrBitmap, but didn't update its
"documentation".  That was pretty hard to read already, so rewrite to
make it more comprehensible, adding the missing values while at it.

Back to 16, like that commit.

Discussion: https://postgr.es/m/20230809091155[email protected]
Reviewed-by: Tomas Vondra <[email protected]>
21 months agoUse native CRC instructions on 64-bit LoongArch
John Naylor [Thu, 10 Aug 2023 04:36:15 +0000 (11:36 +0700)]
Use native CRC instructions on 64-bit LoongArch

As with the Intel and Arm CRC instructions, compiler intrinsics for
them must be supported by the compiler. In contrast, no runtime check
is needed. Aligned memory access is faster, so use the Arm coding as
a model.

YANG Xudong

Discussion: https://postgr.es/m/b522a0c5-e3b2-99cc-6387-58134fb88cbe%40ymatrix.cn

21 months agoRecalculate search_path after ALTER ROLE.
Jeff Davis [Mon, 7 Aug 2023 22:13:24 +0000 (15:13 -0700)]
Recalculate search_path after ALTER ROLE.

Renaming a role can affect the meaning of the special string $user, so
must cause search_path to be recalculated.

Discussion: https://postgr.es/m/186761d32c0255debbdf50b6310b581b9c973e6c[email protected]
Reviewed-by: Nathan Bossart, Michael Paquier
Back-through: 11

21 months agostruct PQcommMethods: use C99 designated initializers
Alvaro Herrera [Wed, 9 Aug 2023 09:30:59 +0000 (11:30 +0200)]
struct PQcommMethods: use C99 designated initializers

As in 98afa68d93522c860777656a, et al.

21 months agoFix last remaining uninitialized memory warnings
Peter Eisentraut [Wed, 9 Aug 2023 08:00:50 +0000 (10:00 +0200)]
Fix last remaining uninitialized memory warnings

gcc (version 13) fails to properly analyze the code due to the loop
stop condition including `l != NULL`. Let's just help it out.

Author: Tristan Partin <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/CT6HJ3U8068R.3A8SJMV02D9BC@gonk

21 months agoFix pg_dumpall with in-place tablespaces
Michael Paquier [Tue, 8 Aug 2023 23:56:05 +0000 (08:56 +0900)]
Fix pg_dumpall with in-place tablespaces

In-place tablespaces would be dumped with the path produced by
pg_tablespace_location(), which is in this case a relative path built as
pg_tblspc/OID, but this would fail to restore as such tablespaces need
to use an empty string as location.  In order to detect if an in-place
tablespace is used, this commit checks if the path returned is relative
and adapts the dump contents in consequence.

Like the other changes related to in-place tablespaces, no back is
done as these are only intended for development purposes.  Rui Zhao has
fixed the code, while the test is from me.

Author: Rui Zhao, Michael Paquier
Discussion: https://postgr.es/m/80c80b4a-b87b-456f-bd46-1ae326601d79[email protected]

21 months agodoc: Fix incorrect entries generated from wait_event_names.txt
Michael Paquier [Mon, 7 Aug 2023 23:17:53 +0000 (08:17 +0900)]
doc: Fix incorrect entries generated from wait_event_names.txt

fa88928 has introduced wait_event_names.txt, and some of its entries had
some documentation fields with more information than necessary.

This commit brings back the description of all the wait events to be
consistent with the older stable branches.  Five descriptions were
incorrect.

Author: Bertrand Drouvot
Discussion: https://postgr.es/m/e378989e-1899-643a-dec1-10f691a0a105@gmail.com

21 months agoReject substituting extension schemas or owners matching ["$'\].
Noah Misch [Mon, 7 Aug 2023 13:05:56 +0000 (06:05 -0700)]
Reject substituting extension schemas or owners matching ["$'\].

Substituting such values in extension scripts facilitated SQL injection
when @extowner@, @extschema@, or @extschema:...@ appeared inside a
quoting construct (dollar quoting, '', or "").  No bundled extension was
vulnerable.  Vulnerable uses do appear in a documentation example and in
non-bundled extensions.  Hence, the attack prerequisite was an
administrator having installed files of a vulnerable, trusted,
non-bundled extension.  Subject to that prerequisite, this enabled an
attacker having database-level CREATE privilege to execute arbitrary
code as the bootstrap superuser.  By blocking this attack in the core
server, there's no need to modify individual extensions.  Back- to
v11 (all supported versions).

Reported by Micah Gate, Valerie Woolard, Tim Carey-Smith, and Christoph
Berg.

Security: CVE-2023-39417

21 months agoTranslation updates
Peter Eisentraut [Mon, 7 Aug 2023 10:06:49 +0000 (12:06 +0200)]
Translation updates

Source-Git-URL: https://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 97398d714ace69f0c919984e160f429b6fd2300e

21 months agoDon't Memoize lateral joins with volatile join conditions
David Rowley [Mon, 7 Aug 2023 10:14:21 +0000 (22:14 +1200)]
Don't Memoize lateral joins with volatile join conditions

The use of Memoize was already disabled in normal joins when the join
conditions had volatile functions per the code in
match_opclause_to_indexcol().  Ordinarily, the parameterization for the
inner side of a nested loop will be an Index Scan or at least eventually
lead to an index scan (perhaps nested several joins deep). However, for
lateral joins, that's not the case and seq scans can be parameterized
too, so we can't rely on match_opclause_to_indexcol().

Here we explicitly check the parameterization for volatile functions and
don't consider the generation of a Memoize path when such functions
are present.

Author: Richard Guo
Discussion: https://postgr.es/m/CAMbWs49nHFnHbpepLsv_yF3qkpCS4BdB-v8HoJVv8_=Oat0u_w@mail.gmail.com
Back-through: 14, where Memoize was introduced

21 months agoFix RLS policy usage in MERGE.
Dean Rasheed [Mon, 7 Aug 2023 08:28:47 +0000 (09:28 +0100)]
Fix RLS policy usage in MERGE.

If MERGE executes an UPDATE action on a table with row-level security,
the code incorrectly applied the WITH CHECK clauses from the target
table's INSERT policies to new rows, instead of the clauses from the
table's UPDATE policies. In addition, it failed to check new rows
against the target table's SELECT policies, if SELECT permissions were
required (likely to always be the case).

In addition, if MERGE executes a DO NOTHING action for matched rows,
the code incorrectly applied the USING clauses from the target table's
DELETE policies to existing target tuples. These policies were applied
as checks that would throw an error, if they did not pass.

Fix this, so that a MERGE UPDATE action applies the same RLS policies
as a plain UPDATE query with a WHERE clause, and a DO NOTHING action
does not apply any RLS checks (other than adding clauses from SELECT
policies to the join).

Back- to v15, where MERGE was introduced.

Dean Rasheed, reviewed by Stephen Frost.

Security: CVE-2023-39418

21 months agoRemove configure check for z_streamp
Peter Eisentraut [Mon, 7 Aug 2023 07:06:52 +0000 (09:06 +0200)]
Remove configure check for z_streamp

This is surely obsolete.  zlib version 1.0.4, which includes
z_streamp, was released 1996-07-24.  When this check was put in in
2001 (19c97b8579), the commit was already labeling that release as
ancient.

Reviewed-by: Tristan Partin <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/33462926-bb1e-7cc9-8d92-d86318e8ed1d%40eisentraut.org

21 months agoImprove const use in zlib-using code
Peter Eisentraut [Mon, 7 Aug 2023 07:06:52 +0000 (09:06 +0200)]
Improve const use in zlib-using code

If we define ZLIB_CONST before including zlib.h, zlib augments some
interfaces with const decorations.  By doing that we can keep our own
interfaces cleaner and can remove some unconstify calls.

ZLIB_CONST was introduced in zlib 1.2.5.2 (17 Dec 2011).  When
compiling with older zlib releases, you might now get compiler
warnings about discarding qualifiers.

CentOS 6 has zlib 1.2.3, but in 8e278b6576, we removed support for the
OpenSSL release in CentOS 6, so it seems ok to de-support the zlib
release in CentOS 6 as well.

Reviewed-by: Tristan Partin <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/33462926-bb1e-7cc9-8d92-d86318e8ed1d%40eisentraut.org

21 months agoFix misleading comment in paraminfo_get_equal_hashops
David Rowley [Mon, 7 Aug 2023 06:16:46 +0000 (18:16 +1200)]
Fix misleading comment in paraminfo_get_equal_hashops

The comment mistakenly claimed the code was checking PlaceHolderVars for
volatile functions when the code was actually checking lateral vars.

Update the comment to reflect the reality of the code.

Author: Richard Guo
Discussion: https://postgr.es/m/CAMbWs48HZGZOV85g0fx8z1qDx6NNKHexJPT2FCnKnZhxBWkd-A@mail.gmail.com

21 months agoTidy up join_search_one_level code
David Rowley [Sun, 6 Aug 2023 09:51:54 +0000 (21:51 +1200)]
Tidy up join_search_one_level code

The code in join_search_one_level was a bit convoluted.  With a casual
glance, you might think that other_rels_list was being set to something
other than joinrels[1] when level == 2, however, joinrels[level - 1] is
joinrels[1] when level == 2, so nothing special needs to happen to set
other_rels_list.  Let's clean that up to avoid confusing anyone.

In passing, we may as well modernize the loop in
make_rels_by_clause_joins() and instead of passing in the ListCell to
start looping from, let's just pass in the index where to start from and
make use of for_each_from().  Ever since 1cff1b95a, Lists are arrays
under the hood. lnext() and list_head() both seem a little too linked-list
like.

Author: Alex Hsieh, David Rowley, Richard Guo
Reviewed-by: Julien Rouhaud
Discussion: https://postgr.es/m/CANWNU8x9P9aCXGF%3DaT-A_8mLTAT0LkcZ_ySYrGbcuHzMQw2-1g%40mail.gmail.com

21 months agoSimplify some of the logical replication worker-type checks.
Amit Kapila [Fri, 4 Aug 2023 02:45:07 +0000 (08:15 +0530)]
Simplify some of the logical replication worker-type checks.

Author: Peter Smith
Reviewed-by: Hou Zhijie
Discussion: http://postgr.es/m/CAHut+Pv-xkEpuPzbEJ=ZSi7Hp2RoGJf=VA-uDRxLi1KHSneFjg@mail.gmail.com

21 months agoAttempt to stabilize new window agg regression test
David Rowley [Fri, 4 Aug 2023 01:27:19 +0000 (13:27 +1200)]
Attempt to stabilize new window agg regression test

This test was recently added in 3900a02c9.  It appears to be unstable in
regards to the join order presumably due to the relations at either side
of the join being equal in side.  Here we add a qual to make one of them
smaller so the planner is more likely to choose to hash the smaller of the
two.

Reported-by: Nathan Bossart, Tom Lane
Discussion: https://www.postgr.es/m/20230803235403.GC1238296@nathanxps13

21 months agoMinor adjustments to WindowAgg startup cost code
David Rowley [Thu, 3 Aug 2023 22:47:54 +0000 (10:47 +1200)]
Minor adjustments to WindowAgg startup cost code

This is a follow-on of 3900a02c9 containing some changes which I forgot
to commit locally before forming a  with git format-.

Discussion: https://postgr.es/m/CAApHDvrB0S5BMv+0-wTTqWFE-BJ0noWqTnDu9QQfjZ2VSpLv_g@mail.gmail.com

21 months agoAccount for startup rows when costing WindowAggs
David Rowley [Thu, 3 Aug 2023 21:27:38 +0000 (09:27 +1200)]
Account for startup rows when costing WindowAggs

Here we adjust the costs for WindowAggs so that they properly take into
account how much of their subnode they must read before outputting the
first row.  Without this, we always assumed that the startup cost for the
WindowAgg was not much more expensive than the startup cost of its
subnode, however, that's going to be completely wrong in many cases.  The
WindowAgg may have to read *all* of its subnode to output a single row
with certain window bound options.

Here we estimate how many rows we'll need to read from the WindowAgg's
subnode and proportionally add more of the subnode's run costs onto the
WindowAgg's startup costs according to how much of it we expect to have to
read in order to produce the first WindowAgg row.

The reason this is more important than we might have initially thought is
that we may end up making use of a path from the lower planner that works
well as a cheap startup plan when the query has a LIMIT clause, however,
the WindowAgg might mean we need to read far more rows than what the LIMIT
specifies.

No back on this so as not to cause plan changes in released
versions.

Bug: #17862
Reported-by: Tim Palmer
Author: David Rowley
Reviewed-by: Andy Fan
Discussion: https://postgr.es/m/17862-1ab8f74b0f7b0611@postgresql.org
Discussion: https://postgr.es/m/CAApHDvrB0S5BMv+0-wTTqWFE-BJ0noWqTnDu9QQfjZ2VSpLv_g@mail.gmail.com

21 months agoDoc: update documentation for creating custom scan paths.
Etsuro Fujita [Thu, 3 Aug 2023 08:45:00 +0000 (17:45 +0900)]
Doc: update documentation for creating custom scan paths.

Commit f49842d1e added a new callback for custom scan paths, but missed
updating the documentation.

Back- to all supported branches.

Discussion: https://postgr.es/m/CAPmGK15ODkN%2B%3DhkBCufj1HBW0x5OTb65Xuy7ryXchMdiCMpx_g%40mail.gmail.com

21 months agoUpdate comments on CustomPath struct.
Etsuro Fujita [Thu, 3 Aug 2023 08:15:00 +0000 (17:15 +0900)]
Update comments on CustomPath struct.

Commit e7cb7ee14 allowed custom scan providers to create CustomPath
paths for join relations as well, but missed updating the comments.

Back- to all supported branches.

Discussion: https://postgr.es/m/CAPmGK15ODkN%2B%3DhkBCufj1HBW0x5OTb65Xuy7ryXchMdiCMpx_g%40mail.gmail.com

21 months agoRefactor to split Apply and Tablesync Workers code.
Amit Kapila [Thu, 3 Aug 2023 03:29:50 +0000 (08:59 +0530)]
Refactor to split Apply and Tablesync Workers code.

Both apply and tablesync workers were using ApplyWorkerMain() as entry
point. As the name implies, ApplyWorkerMain() should be considered as
the main function for apply workers. Tablesync worker's path was hidden
and does not have enough in common to share the same main function with
apply worker.

Also, most of the code shared by both worker types is already combined
in LogicalRepApplyLoop(). There is no need to combine the rest in
ApplyWorkerMain() anymore.

This  introduces TablesyncWorkerMain() as a new entry point for
tablesync workers. This aims to increase code readability and would help
with future improvements like the reuse of tablesync workers in the
initial synchronization.

Author: Melih Mutlu based on suggestions by Melanie Plageman
Reviewed-by: Peter Smith, Kuroda Hayato, Amit Kapila
Discussion: http://postgr.es/m/CAGPVpCTq=rUDd4JUdaRc1XUWf4BrH2gdSNf3rtOMUGj9rPpfzQ@mail.gmail.com

21 months agoFix ReorderBufferCheckMemoryLimit() comment.
Masahiko Sawada [Wed, 2 Aug 2023 06:01:13 +0000 (15:01 +0900)]
Fix ReorderBufferCheckMemoryLimit() comment.

Commit 7259736a6 updated the comment but it was not correct since
ReorderBufferLargestStreamableTopTXN() returns only top-level
transactions.

Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/CAD21AoA9XB7OR86BqvrCe2dMYX%2BZv3-BvVmjF%3DGY2z6jN-kqjg%40mail.gmail.com
Back-through: 14

21 months agoFix performance regression in pg_strtointNN_safe functions
David Rowley [Wed, 2 Aug 2023 00:05:41 +0000 (12:05 +1200)]
Fix performance regression in pg_strtointNN_safe functions

Between 6fcda9aba and 1b6f632a3, the pg_strtoint functions became quite
a bit slower in v16, despite efforts in 6b423ec67 to speed these up.

Since the majority of cases for these functions will only contain
base-10 digits, perhaps prefixed by a '-', it makes sense to have a
special case for this and just fall back on the more complex version
which processes hex, octal, binary and underscores if the fast path
version fails to parse the string.

While we're here, update the header comments for these functions to
mention that hex, octal and binary formats along with underscore
separators are now supported.

Author: Andres Freund, David Rowley
Reported-by: Masahiko Sawada
Reviewed-by: Dean Rasheed, John Naylor
Discussion: https://postgr.es/m/CAD21AoDvDmUQeJtZrau1ovnT_smN940%3DKp6mszNGK3bq9yRN6g%40mail.gmail.com
Back-through: 16, where 6fcda9aba and 1b6f632a3 were added

21 months agoFix pg_stat_io buffer reuse test instability
Andres Freund [Tue, 1 Aug 2023 18:22:03 +0000 (11:22 -0700)]
Fix pg_stat_io buffer reuse test instability

The stats regression test attempts to ensure that Buffer Access Strategy
"reuses" are being counted in pg_stat_io by vacuuming a table which is larger
than the size of the strategy ring. However, when shared buffers are in
sufficiently high demand, another backend could evict one of the blocks in the
strategy ring before the first backend has a chance to reuse the buffer. The
backend using the strategy would then evict another shared buffer and add that
buffer to the strategy ring. This counts as an eviction and not a reuse in
pg_stat_io. Count both evictions and reuses in the test to ensure it does not
fail incorrectly.

Reported-by: Jeff Davis <[email protected]>,
Author: Melanie Plageman <[email protected]>
Reviewed-by: Alexander Lakhin <[email protected]>
Reviewed-by: Masahiko Sawada <[email protected]>
Discussion: https://postgr.es/m/CAAKRu_bNG27AxG9TdPtwsL6wg8AWbVckjmTL2t1HF=miDQuNtw@mail.gmail.com

21 months agoAdd and use symbolic constants for tar header offsets and file types.
Robert Haas [Tue, 1 Aug 2023 17:50:42 +0000 (13:50 -0400)]
Add and use symbolic constants for tar header offsets and file types.

Because symbolic constants in a header file are better than magic
constants embedded in the code.

 by me, reviewed by Tom Lane, Dagfinn Ilmari Mannsåker, and
Tristan Partin.

Discussion: http://postgr.es/m/CA+TgmoZNbLwhmCrNtkJAvi8FLkwFdMeVU3myV2HQQpA5bvbRZg@mail.gmail.com

21 months agoFix overly strict Assert in jsonpath code
David Rowley [Tue, 1 Aug 2023 13:39:47 +0000 (01:39 +1200)]
Fix overly strict Assert in jsonpath code

This was failing for queries which try to get the .type() of a
jpiLikeRegex.  For example:

select jsonb_path_query('["string", "string"]',
                        '($[0] like_regex ".{7}").type()');

Reported-by: Alexander Kozhemyakin
Bug: #18035
Discussion: https://postgr.es/m/18035-64af5cdcb5adf2a9@postgresql.org
Back-through: 12, where SQL/JSON path was added.

21 months agoRename OverrideSearchPath to SearchPathMatcher.
Noah Misch [Tue, 1 Aug 2023 00:04:47 +0000 (17:04 -0700)]
Rename OverrideSearchPath to SearchPathMatcher.

The previous commit removed the "override" APIs.  Surviving APIs facilitate
plancache.c to snapshot search_path and test whether the current value equals
a remembered snapshot.

Aleksander Alekseev.  Reported by Alexander Lakhin and Noah Misch.

Discussion: https://postgr.es/m/8ffb4650-52c4-6a81-38fc-8f99be981130@gmail.com

21 months agoRemove PushOverrideSearchPath() and PopOverrideSearchPath().
Noah Misch [Tue, 1 Aug 2023 00:04:47 +0000 (17:04 -0700)]
Remove PushOverrideSearchPath() and PopOverrideSearchPath().

Since commit 681d9e4621aac0a9c71364b6f54f00f6d8c4337f, they have no in-tree
calls.  Any new calls would introduce security vulnerabilities like the one
fixed in that commit.

Alexander Lakhin, reviewed by Aleksander Alekseev.

Discussion: https://postgr.es/m/8ffb4650-52c4-6a81-38fc-8f99be981130@gmail.com

21 months agoSupport custom wait events for wait event type "Extension"
Michael Paquier [Mon, 31 Jul 2023 08:09:24 +0000 (17:09 +0900)]
Support custom wait events for wait event type "Extension"

Two backend routines are added to allow extension to allocate and define
custom wait events, all of these being allocated in the type
"Extension":
* WaitEventExtensionNew(), that allocates a wait event ID computed from
a counter in shared memory.
* WaitEventExtensionRegisterName(), to associate a custom string to the
wait event ID allocated.

Note that this includes an example of how to use this new facility in
worker_spi with tests in TAP for various scenarios, and some
documentation about how to use them.

Any code in the tree that currently uses WAIT_EVENT_EXTENSION could
switch to this new facility to define custom wait events.  This is left
as work for future es.

Author: Masahiro Ikeda
Reviewed-by: Andres Freund, Michael Paquier, Tristan Partin, Bharath
Rupireddy
Discussion: https://postgr.es/m/b9f5411acda0cf15c8fbb767702ff43e@oss.nttdata.com

21 months agoBring some MSVC asserts in line with other platforms
John Naylor [Mon, 31 Jul 2023 06:34:29 +0000 (13:34 +0700)]
Bring some MSVC asserts in line with other platforms

MSVC's _BitScan* functions return a boolean indicating whether any
bits were set in the input, and we were previously asserting that
they returned true, per our API. This is correct. However, other
platforms simply assert that the input is non-zero, so do that to be
more consistent.

Noted while investigating a hypothesis from Ranier Vilela about
undefined behavior, but this is not his proposed .

Discussion: https://www.postgresql.org/message-id/CAEudQAoDhUZyKGJ1vbMGcgVUOcsixe-%3DjcVaDWarqkUg163D2w%40mail.gmail.com

21 months agoAdd WAIT_EVENT_{CLASS,ID}_MASK in wait_event.c
Michael Paquier [Mon, 31 Jul 2023 07:14:47 +0000 (16:14 +0900)]
Add WAIT_EVENT_{CLASS,ID}_MASK in wait_event.c

These are useful to extract the class ID and the event ID associated to
a single uint32 wait_event_info.  Only two code paths use them now, but
an upcoming  will extend their use.

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

21 months agoAvoid memory in rmtree() when path cannot be opened
Michael Paquier [Mon, 31 Jul 2023 02:36:44 +0000 (11:36 +0900)]
Avoid memory  in rmtree() when path cannot be opened

An allocation done for the directory names to recurse into for their
deletion was done before OPENDIR(), so, assuming that a failure happens,
this could  a bit of memory.

Author: Ranier Vilela
Reviewed-by: Daniel Gustafsson
Discussion: https://postgr.es/m/CAEudQAoN3-2ZKBALThnEk_q2hu8En5A0WG9O+5siJTQKVZzoWQ@mail.gmail.com

21 months agoFix pg_rewind with in-place tablespaces when source is remote
Michael Paquier [Sun, 30 Jul 2023 06:26:25 +0000 (15:26 +0900)]
Fix pg_rewind with in-place tablespaces when source is remote

libpq_source.c would consider any result returned by
pg_tablespace_location() as a symlink, resulting in run-time errors like
that:
pg_rewind: error: file "pg_tblspc/NN" is of different type in source and target

In-place tablespaces are directories located in pg_tblspc/, returned as
relative paths instead of absolute paths, so rely on that to make the
difference with a normal tablespace and an in-place one.  If the path is
relative, the tablespace is handled as a directory.  If the path is
absolute, consider it as a symlink.

In-place tablespaces are only intended for development purposes, so like
363e8f9 no back is done.  A test is added in pg_rewind with an
in-place tablespace and some data in it.

Author: Rui Zhao, Michael Paquier
Discussion: https://postgr.es/m/2b79d2a8-b2d5-4bd7-a15b-31e485100980[email protected]

21 months agoworker_spi: Fix race condition in newly-added TAP tests
Michael Paquier [Sat, 29 Jul 2023 02:34:53 +0000 (11:34 +0900)]
worker_spi: Fix race condition in newly-added TAP tests

The second portion of the tests had a race condition where it would be
possible for the startup of the dynamic workers to fail, in the event
where the static workers started before them with the library loading in
shared_preload_libraries did not finish to create their respective
schemas.  The conflict is caused by the fact that the dynamic and static
workers used the same IDs, overlapping each other, so, for now, switch
the dynamic workers to use different IDs, leading to different schemas
created.

Reported-by: Andres Freund
Discussion: https://postgr.es/m/20230728022332[email protected]

21 months agoHarmonize password reuse in vacuumdb, clusterdb, and reindexdb.
Nathan Bossart [Fri, 28 Jul 2023 17:07:44 +0000 (10:07 -0700)]
Harmonize password reuse in vacuumdb, clusterdb, and reindexdb.

Commits 83dec5a712 and ff402ae11b taught vacuumdb to reuse
passwords instead of prompting repeatedly.  However, the docs still
warn about repeated prompts, and this improvement was not applied
to clusterdb and reindexdb.  This commit allows clusterdb and
reindexdb to reuse passwords just like vacuumdb does, and it
expunges the aforementioned warnings from the docs.

Reviewed-by: Gurjeet Singh, Zhang Mingli
Discussion: https://postgr.es/m/20230628045741.GA1813397%40nathanxps13

21 months agodoc: add missing <returnvalue> and whitespace
Amit Langote [Fri, 28 Jul 2023 07:05:44 +0000 (16:05 +0900)]
doc: add missing <returnvalue> and whitespace

Missed in commit 03734a7fed.

Author: Shinoda, Noriyoshi <[email protected]>
Discussion: https://postgr.es/m/DM4PR84MB1734E58BB4DC0E1B6E2990EBEE01A%40DM4PR84MB1734.NAMPRD84.PROD.OUTLOOK.COM

21 months agoDisallow replacing joins with scans in problematic cases.
Etsuro Fujita [Fri, 28 Jul 2023 06:45:00 +0000 (15:45 +0900)]
Disallow replacing joins with scans in problematic cases.

Commit e7cb7ee14, which introduced the infrastructure for FDWs and
custom scan providers to replace joins with scans, failed to add support
handling of pseudoconstant quals assigned to replaced joins in
createplan.c, leading to an incorrect plan without a gating Result node
when postgres_fdw replaced a join with such a qual.

To fix, we could add the support by 1) modifying the ForeignPath and
CustomPath structs to store the list of RestrictInfo nodes to apply to
the join, as in JoinPaths, if they represent foreign and custom scans
replacing a join with a scan, and by 2) modifying create_scan_plan() in
createplan.c to use that list in that case, instead of the
baserestrictinfo list, to get pseudoconstant quals assigned to the join;
but #1 would cause an ABI break.  So fix by modifying the infrastructure
to just disallow replacing joins with such quals.

Back- to all supported branches.

Reported by Nishant Sharma.   by me, reviewed by Nishant Sharma and
Richard Guo.

Discussion: https://postgr.es/m/CADrsxdbcN1vejBaf8a%2BQhrZY5PXL-04mCd4GDu6qm6FigDZd6Q%40mail.gmail.com

21 months agoEliminate fixed token-length limit in hba.c.
Tom Lane [Thu, 27 Jul 2023 15:56:35 +0000 (11:56 -0400)]
Eliminate fixed token-length limit in hba.c.

Historically, hba.c limited tokens in the authentication configuration
files (pg_hba.conf and pg_ident.conf) to less than 256 bytes.  We have
seen a few reports of this limit causing problems; notably, for
moderately-complex LDAP configurations.  Let's get rid of the fixed
limit by using a StringInfo instead of a fixed-size buffer.
This actually takes less code than before, since we can get rid of
a nontrivial error recovery stanza.  It's doubtless a hair slower,
but parsing the content of the HBA files should in no way be
performance-critical.

Although this is a pretty straightforward , it doesn't seem
worth the risk to back- given the small number of complaints
to date.  In released branches, we'll just raise MAX_TOKEN to
ameliorate the problem.

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

21 months agoworker_spi: Switch to TAP tests
Michael Paquier [Thu, 27 Jul 2023 04:30:07 +0000 (13:30 +0900)]
worker_spi: Switch to TAP tests

This commit moves worker_spi to use TAP tests.  sql/worker_spi.sql is
gone, replaced by an equivalent set of queries in a TAP script, without
worker_spi loaded in shared_preload_libraries:
- One query to launch a worker dynamically, relying now on "postgres" as
the default database to connect to.
- Two wait queries with poll_query_until(), one to wait for the worker
schema to be initialized and a second to wait for a tuple processed by
the worker.
- Server reload to accelerate the main loop of the spawned worker.

More coverage is added for workers registered when the library is loaded
with shared_preload_libraries, while on it, checking that these are
connecting to the database set in the GUC worker_spi.database.

A local run of these test is showing that TAP is slightly faster than
the original, while providing more coverage (3.7s vs 4.4s).  There was
also some discussions about keeping the SQL tests, but this would
require initializing twice a cluster, increasing the runtime of the
tests up to 5.6s here.

These tests will be expanded more in an upcoming  aimed at adding
support for custom wait events for the Extension class, still under
discussion, to check the new in-core APIs with and without a library set
in shared_preload_libraries.

Bharath has written the part where shared_preload_libraries is used,
while I have migrated the existing SQL tests to TAP.

Author: Bharath Rupireddy, Michael Paquier
Reviewed-by: Masahiro Ikeda
Discussion: https://postgr.es/m/CALj2ACWR9ncAiDF73unqdJF1dmsA2R0efGXX2624X+YVxcAVWg@mail.gmail.com

21 months agoFix performance problem with new COPY DEFAULT code
David Rowley [Thu, 27 Jul 2023 02:47:05 +0000 (14:47 +1200)]
Fix performance problem with new COPY DEFAULT code

9f8377f7a added code to allow COPY FROM insert a column's default value
when the input matches the DEFAULT string specified in the COPY command.

Here we fix some inefficient code which needlessly palloc0'd an array to
store if we should use the default value or input value for the given
column.  This array was being palloc0'd and pfree'd once per row.  It's
much more efficient to allocate this once and just reset the values once
per row.

Reported-by: Masahiko Sawada
Author: Masahiko Sawada
Discussion: https://postgr.es/m/CAD21AoDvDmUQeJtZrau1ovnT_smN940%3DKp6mszNGK3bq9yRN6g%40mail.gmail.com
Back-through: 16, where 9f8377f7a was introduced.

21 months agoAdd sanity asserts for index OID and attnums during cache init
Michael Paquier [Thu, 27 Jul 2023 01:55:16 +0000 (10:55 +0900)]
Add sanity asserts for index OID and attnums during cache init

There was already a check on the relation OID, but not its index OID and
the attributes that can be used during the syscache lookups.  The two
assertions added by this commit are cheap, and actually useful for
developers to fasten the detection of incorrect data in a new entry
added in the syscache list, as these assertions are triggered during the
initial cache loading (initdb, or just backend startup), not requiring a
syscache that uses the new entry.

While on it, the relation OID check is switched to use OidIsValid().

Author: Aleksander Alekseev
Reviewed-by: Dagfinn Ilmari Mannsåker, Zhang Mingli, Michael Paquier
Discussion: https://postgr.es/m/CAJ7c6TOjUTJ0jxvWY6oJeP2-840OF8ch7qscZQsuVuotXTOS_g@mail.gmail.com

21 months agoShow savepoint names as constants in pg_stat_statements
Michael Paquier [Thu, 27 Jul 2023 00:42:33 +0000 (09:42 +0900)]
Show savepoint names as constants in pg_stat_statements

In pg_stat_statements, savepoint names now show up as constants with a
parameter symbol, using as base query string the one added as a new
entry to the PGSS hash table, leading to:
RELEASE $1
ROLLBACK TO $1
SAVEPOINT $1

Applying constants to these query parts is a huge advantage for
workloads that generate randomly savepoint points, like ORMs (Django is
at the origin of this ).  The ODBC driver is a second layer that
likes a lot savepoints, though it does not use a random naming pattern.

A "location" field is added to TransactionStmt, now set only for
savepoints.  The savepoint name is ignored by the query jumbling.  The
location can be extended to other query patterns, if required, like 2PC
commands.  Some tests are added to pg_stat_statements for all the query
patterns supported by the parser.

ROLLBACK, ROLLBACK TO SAVEPOINT and ROLLBACK TRANSACTION TO SAVEPOINT
have the same Node representation, so all these are equivalents.  The
same happens for RELEASE and RELEASE SAVEPOINT.

Author: Greg Sabino Mullane
Discussion: https://postgr.es/m/CAKAnmm+2s9PA4OaumwMJReWHk8qvJ_-g1WqxDRDAN1BSUfxyTw@mail.gmail.com

21 months agoAdjust extra lines generated by psql to be valid SQL comments.
Nathan Bossart [Thu, 27 Jul 2023 00:02:39 +0000 (17:02 -0700)]
Adjust extra lines generated by psql to be valid SQL comments.

psql's --echo-hidden, --log-file, and --single-step options
generate extra lines to clearly separate queries from other output.
Presently, these extra lines are not valid SQL comments, which
makes them a hazard for anyone trying to copy/paste the decorated
queries into a client or query editor.  This commit replaces the
starting and ending asterisks in these extra lines with forward
slashes so that they are valid SQL comments that can be copy/pasted
without incident.

Author: Kirk Wolak
Reviewed-by: Pavel Stehule, Laurenz Albe, Tom Lane, Alvaro Herrera, Andrey Borodin
Discussion: https://postgr.es/m/CACLU5mTFJRJYtbvmZ26txGgmXWQo0hkGhH2o3hEquUPmSbGtBw%40mail.gmail.com

21 months agoAdd more SQL/JSON constructor functions
Amit Langote [Thu, 20 Jul 2023 13:21:43 +0000 (22:21 +0900)]
Add more SQL/JSON constructor functions

This  introduces three SQL standard JSON functions:

JSON()
JSON_SCALAR()
JSON_SERIALIZE()

JSON() produces json values from text, bytea, json or jsonb values,
and has facilitites for handling duplicate keys.

JSON_SCALAR() produces a json value from any scalar sql value,
including json and jsonb.

JSON_SERIALIZE() produces text or bytea from input which containis
or represents json or jsonb;

For the most part these functions don't add any significant new
capabilities, but they will be of use to users wanting standard
compliant JSON handling.

Catversion bumped as this changes ruleutils.c.

Author: Nikita Glukhov <[email protected]>
Author: Teodor Sigaev <[email protected]>
Author: Oleg Bartunov <[email protected]>
Author: Alexander Korotkov <[email protected]>
Author: Andrew Dunstan <[email protected]>
Author: Amit Langote <[email protected]>

Reviewers have included (in no particular order) Andres Freund, Alexander
Korotkov, Pavel Stehule, Andrew Alsup, Erik Rijkers, Zihong Yu,
Himanshu Upadhyaya, Daniel Gustafsson, Justin Pryzby, Álvaro Herrera,
Peter Eisentraut

Discussion: https://postgr.es/m/cd0bb935-0158-78a7-08b5-904886deac4b@postgrespro.ru
Discussion: https://postgr.es/m/20220616233130[email protected]
Discussion: https://postgr.es/m/abd9b83b-aa66-f230-3d6d-734817f0995d%40postgresql.org
Discussion: https://postgr.es/m/CA+HiwqE4XTdfb1nW=Ojoy_tQSRhYt-q_kb6i5d4xcKyrLC1Nbg@mail.gmail.com

21 months agoRename a nonterminal used in SQL/JSON grammar
Amit Langote [Thu, 20 Jul 2023 13:21:43 +0000 (22:21 +0900)]
Rename a nonterminal used in SQL/JSON grammar

This renames json_output_clause_opt to json_returning_clause_opt,
because the new name makes more sense given that the governing
keyword is RETURNING.

Per suggestion from Álvaro Herrera.

Discussion: https://postgr.es/m/20230707122820.wy5zlmhn4tdzbojl%40alvherre.pgsql

21 months agoSome refactoring to export json(b) conversion functions
Amit Langote [Fri, 21 Jul 2023 02:46:56 +0000 (11:46 +0900)]
Some refactoring to export json(b) conversion functions

This is to export datum_to_json(), datum_to_jsonb(), and
jsonb_from_cstring(), though the last one is exported as
jsonb_from_text().

A subsequent commit to add new SQL/JSON constructor functions will
need them for calling from the executor.

Discussion: https://postgr.es/m/20230720160252.ldk7jy6jqclxfxkq%40alvherre.pgsql

21 months agoFix crash with RemoveFromWaitQueue() when detecting a deadlock.
Masahiko Sawada [Wed, 26 Jul 2023 05:41:26 +0000 (14:41 +0900)]
Fix crash with RemoveFromWaitQueue() when detecting a deadlock.

Commit 5764f611e used dclist_delete_from() to remove the proc from the
wait queue. However, since it doesn't clear dist_node's next/prev to
NULL, it could call RemoveFromWaitQueue() twice: when the process
detects a deadlock and then when cleaning up locks on aborting the
transaction. The waiting lock information is cleared in the first
call, so it led to a crash in the second call.

Back to v16, where the change was introduced.

Bug: #18031
Reported-by: Justin Pryzby, Alexander Lakhin
Reviewed-by: Andres Freund
Discussion: https://postgr.es/m/ZKy4AdrLEfbqrxGJ%40telsasoft.com
Discussion: https://postgr.es/m/18031-ebe2d08cb405f6cc@postgresql.org
Back-through: 16

21 months agoworker_spi: Use term "dynamic" for bgworkers launched with worker_spi_launch()
Michael Paquier [Wed, 26 Jul 2023 03:43:26 +0000 (12:43 +0900)]
worker_spi: Use term "dynamic" for bgworkers launched with worker_spi_launch()

This gives a way to make a difference between workers registered when
the library is loaded with shared_preload_libraries and when these are
launched dynamically, in ps output or pg_stat_activity.

Extracted from a larger  by the same author.

Author: Bharath Rupireddy
Reviewed-by: Masahiro Ikeda
Discussion: https://postgr.es/m/CALj2ACWR9ncAiDF73unqdJF1dmsA2R0efGXX2624X+YVxcAVWg@mail.gmail.com

21 months agoDocument more assumptions of LWLock variable changes with WAL inserts
Michael Paquier [Wed, 26 Jul 2023 03:06:04 +0000 (12:06 +0900)]
Document more assumptions of LWLock variable changes with WAL inserts

This commit adds a few comments about what LWLockWaitForVar() relies on
when a backend waits for a variable update on its LWLocks for WAL
insertions up to an expected LSN.

First, LWLockWaitForVar() does not include a memory barrier, relying on
a spinlock taken at the beginning of WaitXLogInsertionsToFinish().  This
was hidden behind two layers of routines in lwlock.c.  This assumption
is now documented at the top of LWLockWaitForVar(), and detailed at bit
more within LWLockConflictsWithVar().

Second, document why WaitXLogInsertionsToFinish() does not include
memory barriers, relying on a spinlock at its top, which is, per Andres'
input, fine for two different reasons, both depending on the fact that
the caller of WaitXLogInsertionsToFinish() is waiting for a LSN up to a
certain value.

This area's documentation and assumptions could be improved more in the
future, but at least that's a beginning.

Author: Bharath Rupireddy, Andres Freund
Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/CALj2ACVF+6jLvqKe6xhDzCCkr=rfd6upaGc3477Pji1Ke9G7Bg@mail.gmail.com

21 months agoFix code indentation vioaltion introduced in commit d38ad8e31d.
Amit Kapila [Tue, 25 Jul 2023 07:05:58 +0000 (12:35 +0530)]
Fix code indentation vioaltion introduced in commit d38ad8e31d.

Per buildfarm member koel

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

21 months agoRemove unnecessary checks for indexes for REPLICA IDENTITY FULL tables.
Masahiko Sawada [Tue, 25 Jul 2023 06:09:34 +0000 (15:09 +0900)]
Remove unnecessary checks for indexes for REPLICA IDENTITY FULL tables.

Previously, when selecting an usable index for update/delete for the
REPLICA IDENTITY FULL table, in IsIndexOnlyExpression(), we used to
check if all index fields are not expressions. However, it was not
necessary, because it is enough to check if only the leftmost index
field is not an expression (and references the remote table column)
and this check has already been done by
RemoteRelContainsLeftMostColumnOnIdx().

This commit removes IsIndexOnlyExpression() and
RemoteRelContainsLeftMostColumnOnIdx() and all checks for usable
indexes for REPLICA IDENTITY FULL tables are now performed by
IsIndexUsableForReplicaIdentityFull().

Back this to remain the code consistent.

Reported-by: Peter Smith
Reviewed-by: Amit Kapila, Önder Kalacı
Discussion: https://postgr.es/m/CAHut%2BPsGRE5WSsY0jcLHJEoA17MrbP9yy8FxdjC_ZOAACxbt%2BQ%40mail.gmail.com
Back-through: 16

21 months agoOptimize WAL insertion lock acquisition and release with some atomics
Michael Paquier [Tue, 25 Jul 2023 04:38:58 +0000 (13:38 +0900)]
Optimize WAL insertion lock acquisition and release with some atomics

The WAL insertion lock variable insertingAt is currently being read
and written with the help of the LWLock wait list lock to avoid any read
of torn values.  This wait list lock can become a point of contention on
a highly concurrent write workloads.

This commit switches insertingAt to a 64b atomic variable that provides
torn-free reads/writes.  On platforms without 64b atomic support, the
fallback implementation uses spinlocks to provide the same guarantees
for the values read.  LWLockWaitForVar(), through
LWLockConflictsWithVar(), reads the new value to check if it still needs
to wait with a u64 atomic operation.  LWLockUpdateVar() updates the
variable before waking up the waiters with an exchange_u64 (full memory
barrier).  LWLockReleaseClearVar() now uses also an exchange_u64 to
reset the variable.  Before this commit, all these steps relied on
LWLockWaitListLock() and LWLockWaitListUnlock().

This reduces contention on LWLock wait list lock and improves
performance of highly-concurrent write workloads.  Here are some
numbers using pg_logical_emit_message() (HEAD at d6677b93) with various
arbitrary record lengths and clients up to 1k on a rather-large machine
(64 vCPUs, 512GB of RAM, 16 cores per sockets, 2 sockets), in terms of
TPS numbers coming from pgbench:
 message_size_b     |     16 |     64 |    256 |   1024
--------------------+--------+--------+--------+-------
 _4_clients    |  83830 |  82929 |  80478 |  73131
 _16_clients   | 267655 | 264973 | 250566 | 213985
 _64_clients   | 380423 | 378318 | 356907 | 294248
 _256_clients  | 360915 | 354436 | 326209 | 263664
 _512_clients  | 332654 | 321199 | 287521 | 240128
 _1024_clients | 288263 | 276614 | 258220 | 217063
 _2048_clients | 252280 | 243558 | 230062 | 192429
 _4096_clients | 212566 | 213654 | 205951 | 166955
 head_4_clients     |  83686 |  83766 |  81233 |  73749
 head_16_clients    | 266503 | 265546 | 249261 | 213645
 head_64_clients    | 366122 | 363462 | 341078 | 261707
 head_256_clients   | 132600 | 132573 | 134392 | 165799
 head_512_clients   | 118937 | 114332 | 116860 | 150672
 head_1024_clients  | 133546 | 115256 | 125236 | 151390
 head_2048_clients  | 137877 | 117802 | 120909 | 138165
 head_4096_clients  | 113440 | 115611 | 120635 | 114361

Bharath has been measuring similar improvements, where the limit of the
WAL insertion lock begins to be felt when more than 256 concurrent
clients are involved in this specific workload.

An extra  has been discussed to introduce a fast-exit path in
LWLockUpdateVar() when there are no waiters, still this does not
influence the write-heavy workload cases discussed as there are always
waiters.  This will be considered separately.

Author: Bharath Rupireddy
Reviewed-by: Nathan Bossart, Andres Freund, Michael Paquier
Discussion: https://postgr.es/m/CALj2ACVF+6jLvqKe6xhDzCCkr=rfd6upaGc3477Pji1Ke9G7Bg@mail.gmail.com

21 months agoFix the display of UNKNOWN message type in apply worker.
Amit Kapila [Tue, 25 Jul 2023 03:42:29 +0000 (09:12 +0530)]
Fix the display of UNKNOWN message type in apply worker.

We include the message type while displaying an error context in the
apply worker. Now, while retrieving the message type string if the
message type is unknown we throw an error that will hide the original
error. So, instead, we need to simply return the string indicating an
unknown message type.

Reported-by: Ashutosh Bapat
Author: Euler Taveira, Amit Kapila
Reviewed-by: Ashutosh Bapat
Back-through: 15
Discussion: https://postgr.es/m/CAExHW5suAEDW-mBZt_qu4RVxWZ1vL54-L+ci2zreYWebpzxYsA@mail.gmail.com

21 months agoFix off-by-one in LimitAdditionalPins()
Andres Freund [Tue, 25 Jul 2023 02:07:52 +0000 (19:07 -0700)]
Fix off-by-one in LimitAdditionalPins()

Due to the bug LimitAdditionalPins() could return 0, violating
LimitAdditionalPins()'s API ("One additional pin is always allowed"). This
could be hit when setting shared_buffers very low and using a fair amount of
concurrency.

This bug was introduced in 31966b151e6a.

Author: "Anton A. Melnikov" <[email protected]>
Reported-by: "Anton A. Melnikov" <[email protected]>
Reported-by: Victoria Shepard
Discussion: https://postgr.es/m/ae46f2fb-5586-3de0-b54b-1bb0f6410ebd@inbox.ru
Back: 16-

21 months agoMake test_decoding ddl.out shorter
Alvaro Herrera [Mon, 24 Jul 2023 15:48:06 +0000 (17:48 +0200)]
Make test_decoding ddl.out shorter

Some of the test_decoding test output was extremely wide, because it
deals with massive toasted values, and the aligned mode causes psql to
produce 200kB of whitespace and dashes. Change to unaligned mode
temporarily to avoid that behavior.

Back to 14, where it applies cleanly.

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

21 months agoCompare only major versions in AdjustUpgrade.pm
Alvaro Herrera [Mon, 24 Jul 2023 15:14:22 +0000 (17:14 +0200)]
Compare only major versions in AdjustUpgrade.pm

Because PostgreSQL::Version is very nuanced about development version
numbers, the comparison to 16beta2 makes it think that that release is
older than 16, therefore applying a database tweak that doesn't work
there (the comparison is only supposed to match when run on version 15).
As suggested by Andrew Dunstan, fix by having AdjustUpgrade.pm public
methods create a separate PostgreSQL::Version object to use for these
comparisons, that only carries the major version number.

While at it, have the same methods ensure that the objects given are of
the expected type.

Back to 16.  This module goes all the way back to 9.2, but there's
probably no need for this fix except where betas still live.

Co-authored-by: Andrew Dunstan <[email protected]>
Discussion: https://postgr.es/m/20230719110504[email protected]

21 months agopgbench: Use COPY for client-side data generation
Michael Paquier [Mon, 24 Jul 2023 04:48:22 +0000 (13:48 +0900)]
pgbench: Use COPY for client-side data generation

This commit switches the client-side data generation from INSERT queries
to COPY for the two tables pgbench_branches and pgbench_tellers.
pgbench_accounts was already using COPY.

COPY is a better interface for bulk loading or high latency connections
(this point can be countered with the option for server-side data
generation, still client-side is the default), and measurements have
proved that using it for these two other tables can lead to improvements
during initialization.  I did not notice slowdowns at large scale
numbers on a local setup, either, most of the work happening for the
accounts table.

Previously COPY was only used for the pgbench_accounts table because the
amount of data was much larger than the two other tables.  The code is
refactored so as all three tables use the same code path to execute the
COPY queries, with a callback to build data rows.

Author: Tristan Partin
Discussion: https://postgr.es/m/CSTU5P82ONZ1.19XFUGHMXHBRY@c3po

21 months agopgbench: Add TAP tests to check consistency of data generated
Michael Paquier [Sun, 23 Jul 2023 11:03:35 +0000 (20:03 +0900)]
pgbench: Add TAP tests to check consistency of data generated

The tables created by pgbench rely on a few assumptions for TPC-B, where
the "filler" attribute is used to comply with this benchmark's rules as
well as pgbencn historical behavior.  The data generated for each table
uses this filler in a different way:
- pgbench_accounts uses it as a blank-padded empty string.
- pgbench_tellers and pgbench_branches use it as a NULL value.

There were no checks done about the consistency of the data initialized,
and this has showed up while discussing a  that changes the logic
in charge of the client-side data generation (pgbench documents all that
already in its comments).  This commit adds some checks on the data
generated for both the server-side and client-side logic.

Reviewed-by: Tristan Partin
Discussion: https://postgr.es/m/[email protected]

21 months agoAvoid compiler warning in non-assert builds.
Tom Lane [Sat, 22 Jul 2023 14:32:52 +0000 (10:32 -0400)]
Avoid compiler warning in non-assert builds.

After 3c90dcd03, try_partitionwise_join's child_joinrelids
variable is read only in an Assert, provoking a compiler
warning in non-assert builds.  Rearrange code to avoid the
warning and eliminate unnecessary work in the non-assert case.

Per CI testing (via Jeff Davis and Bharath Rupireddy)

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

21 months agoICU: remove negative test that fails to fail.
Jeff Davis [Fri, 21 Jul 2023 22:24:19 +0000 (15:24 -0700)]
ICU: remove negative test that fails to fail.

On OpenBSD, setlocale() does not fail on an ICU-specific
locale. Remove the test.

Reported-by: Andres Freund
Discussion: https://postgr.es/m/20230702165615[email protected]

21 months agoFix calculation of relid sets for partitionwise child joins.
Tom Lane [Fri, 21 Jul 2023 16:00:14 +0000 (12:00 -0400)]
Fix calculation of relid sets for partitionwise child joins.

Applying add_outer_joins_to_relids() to a child join doesn't actually
work, even if we've built a SpecialJoinInfo specialized to the child,
because that function will also compare the join's relids to elements
of the main join_info_list, which only deal in regular relids not
child relids.  This mistake escaped detection by the existing
partitionwise join tests because they didn't test any cases where
add_outer_joins_to_relids() needs to add additional OJ relids (that
is, any cases where join reordering per identity 3 is possible).

Instead, let's apply adjust_child_relids() to the relids of the parent
join.  This requires minor code reordering to collect the relevant
AppendRelInfo structures first, but that's work we'd do shortly anyway.

Report and fix by Richard Guo; cosmetic changes by me

Discussion: https://postgr.es/m/CAMbWs49NCNbyubZWgci3o=_OTY=snCfAPtMnM-32f3mm-K-Ckw@mail.gmail.com

21 months agoCode review for commit b6e1157e7d
Amit Langote [Fri, 21 Jul 2023 10:15:34 +0000 (19:15 +0900)]
Code review for commit b6e1157e7d

b6e1157e7d made some changes to enforce that
JsonValueExpr.formatted_expr is always set and is the expression that
gives a JsonValueExpr its runtime value, but that's not really
apparent from the comments about and the code manipulating
formatted_expr.  This commit fixes that.

Per suggestion from Álvaro Herrera.

Discussion: https://postgr.es/m/20230718155313.3wqg6encgt32adqb%40alvherre.pgsql

21 months agoFix worker_spi when launching workers without shared_preload_libraries
Michael Paquier [Fri, 21 Jul 2023 03:07:52 +0000 (12:07 +0900)]
Fix worker_spi when launching workers without shared_preload_libraries

Currently, the database name to connect is initialized only when the
module is loaded with shared_preload_libraries, causing any call of
worker_spi_launch() to fail if the library is not loaded for a dynamic
bgworker launch.  Rather than making the GUC defining the database to
connect to a PGC_POSTMASTER, this commit switches worker_spi.database to
PGC_SIGHUP, loaded even if the module's library is loaded dynamically
for a worker.

We have been discussing about the integration of more advanced tests in
this module, with and without shared_preload_libraries set, so this
eases a bit the work planned in this area.

No back is done as, while this is a bug, it changes the definition
of worker_spi.database.

Author: Masahiro Ikeda
Reviewed-by: Bharath Rupireddy
Discussion: https://postgr.es/m/d30d3ea7d21cb7c9e1e3cc47e301f1b6@oss.nttdata.com

21 months agoGuard against null plan pointer in CachedPlanIsSimplyValid().
Tom Lane [Thu, 20 Jul 2023 18:23:46 +0000 (14:23 -0400)]
Guard against null plan pointer in CachedPlanIsSimplyValid().

If both the passed-in plan pointer and plansource->gplan are
NULL, CachedPlanIsSimplyValid would think that the plan pointer
is possibly-valid and try to dereference it.  For the one extant
call site in plpgsql, this situation doesn't normally happen
which is why we've not noticed. However, it appears to be possible
if the previous use of the cached plan failed, as per report from
Justin Pryzby.  Add an extra check to prevent crashing.
Back- to v13 where this code was added.

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

21 months agoRevert "Add notBefore and notAfter to SSL cert info display"
Daniel Gustafsson [Thu, 20 Jul 2023 15:18:12 +0000 (17:18 +0200)]
Revert "Add notBefore and notAfter to SSL cert info display"

Due to an oversight in reviewing, this used functionality not
compatible with old versions of OpenSSL.

This reverts commit 75ec5e7bec700577d39d653c316e3ae6c505842c.

21 months agoAdd notBefore and notAfter to SSL cert info display
Daniel Gustafsson [Thu, 20 Jul 2023 15:07:32 +0000 (17:07 +0200)]
Add notBefore and notAfter to SSL cert info display

This adds the X509 attributes notBefore and notAfter to sslinfo
as well as pg_stat_ssl to allow verifying and identifying the
validity period of the current client certificate.

Author: Cary Huang <[email protected]>
Discussion: https://postgr.es/m/182b8565486.10af1a86f158715.2387262617218380588@highgo.ca

21 months agoSet fixed dates for test certificates validity
Daniel Gustafsson [Thu, 20 Jul 2023 14:04:27 +0000 (16:04 +0200)]
Set fixed dates for test certificates validity

Rather than specifying a validity of 10 000 days into the future
during test certificate generation, this hardcodes the notBefore
and notAfter attributes to known values. This will allow writing
tests on the validity of the certificates without knowing when a
specific certificate was regenerated.

This is done as a prerequisite for an upcoming  which adds
notBefore and notAfter to pg_stat_ssl and sslinfo.

Discussion: https://postgr.es/m/EE288A58-947E-479A-9D99-C46C273D7A23@yesql.se

21 months agopg_upgrade: include additional detail in cluster check
Daniel Gustafsson [Thu, 20 Jul 2023 12:55:50 +0000 (14:55 +0200)]
pg_upgrade: include additional detail in cluster check

When the cluster failed the pg_controldata check for clean shut
down we only reported that it did so, not why. The state of the
cluster can be important information when diagnosing the failed
upgrade attempt, so instead include it in the error message.

Discussion: https://postgr.es/m/E0D5EA16-A085-4753-8DDC-C7055048B439@yesql.se

21 months agoUnify JSON categorize type API and export for external use
Amit Langote [Thu, 20 Jul 2023 07:19:56 +0000 (16:19 +0900)]
Unify JSON categorize type API and export for external use

This essentially removes the JsonbTypeCategory enum and
jsonb_categorize_type() and integrates any jsonb-specific logic that
was in jsonb_categorize_type() into json_categorize_type(), now
moved to jsonfuncs.c.  The remaining JsonTypeCategory enum and
json_categorize_type() cover the needs of the callers in both json.c
and jsonb.c.  json_categorize_type() has grown a new parameter named
is_jsonb for callers to engage the jsonb-specific behavior of
json_categorize_type().

One notable change in the now exported API of json_categorize_type()
is that it now always returns *outfuncoid even though a caller may
have no need currently to see one.

This is in preparation of later commits to implement additional
SQL/JSON functions.

Co-authored-by: Álvaro Herrera <[email protected]>
Reviewed-by: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/CA+HiwqE4XTdfb1nW=Ojoy_tQSRhYt-q_kb6i5d4xcKyrLC1Nbg@mail.gmail.com

21 months agoAdd missing ObjectIdGetDatum() in syscache lookup calls for Oids
Michael Paquier [Thu, 20 Jul 2023 06:18:25 +0000 (15:18 +0900)]
Add missing ObjectIdGetDatum() in syscache lookup calls for Oids

Based on how postgres.h foes the Oid <-> Datum conversion, there is no
existing bugs but let's be consistent.  17 spots have been noticed as
incorrectly passing down Oids rather than Datums.  Aleksander got one,
Zhang two and I the rest.

Author: Michael Paquier, Aleksander Alekseev, Zhang Mingli
Discussion: https://postgr.es/m/[email protected]

21 months agoFix pg_recvlogical upon signal termination
Michael Paquier [Thu, 20 Jul 2023 01:22:46 +0000 (10:22 +0900)]
Fix pg_recvlogical upon signal termination

When pg_recvlogical needs to abort on a signal like SIGINT/SIGTERM, it
is expected to exit cleanly as the code documents.  However, the code
forgot to clean up the state of the connection before leaving.  This
would cause the tool to emit messages like "unexpected termination of
replication stream" error, which is meant for really unexpected
termination or a crash.

The code is refactored to apply the same termination abort operations for
signals, end LSN and keepalive cases, registering a "reason" for the
termination with a message printed under --verbose adapted to the reason
used.

This is arguably a bug, but this has been this way since the tool exists
and the signal termination can now become slower depending on the change
being decoded when the signal is received.

Reported-by: Andres Freund
Author: Bharath Rupireddy
Reviewed-by: Andres Freund, Kyotaro Horiguchi, Cary Huang, Michael
Paquier
Discussion: https://postgr.es/m/20221019213953[email protected]

21 months agoDoc: move unparenthesized syntaxes for a few commands.
Nathan Bossart [Wed, 19 Jul 2023 22:26:59 +0000 (15:26 -0700)]
Doc: move unparenthesized syntaxes for a few commands.

Move documentation of the unparenthesized syntaxes for VACUUM,
ANALYZE, EXPLAIN, and CLUSTER to the "Compatibility" section of
their documentation to improve readability of the preferred,
parenthesized syntaxes.

Author: Melanie Plageman
Discussion: https://postgr.es/m/CAAKRu_bc5uHieG1976kGqJKxyWtyQt9yvktjsVX%2Bi7NOigDjOA%40mail.gmail.com

21 months agoSupport parenthesized syntax for CLUSTER without a table name.
Nathan Bossart [Wed, 19 Jul 2023 22:26:52 +0000 (15:26 -0700)]
Support parenthesized syntax for CLUSTER without a table name.

b5913f6120 added a parenthesized syntax for CLUSTER, but it
requires specifying a table name.  This is unlike commands such as
VACUUM and ANALYZE, which do not require specifying a table in the
parenthesized syntax.  This change resolves this inconsistency.
This is preparatory work for a follow-up commit that will move the
unparenthesized syntax to the "Compatibility" section of the
CLUSTER documentation.

Reviewed-by: Melanie Plageman, Michael Paquier
Discussion: https://postgr.es/m/CAAKRu_bc5uHieG1976kGqJKxyWtyQt9yvktjsVX%2Bi7NOigDjOA%40mail.gmail.com

21 months agoRearrange CLUSTER rules in gram.y.
Nathan Bossart [Wed, 19 Jul 2023 22:26:43 +0000 (15:26 -0700)]
Rearrange CLUSTER rules in gram.y.

This change moves the unparenthesized syntax for CLUSTER to the end
of the ClusterStmt rules in preparation for a follow-up commit that
will move this syntax to the "Compatibility" section of the CLUSTER
documentation.  The documentation for the CLUSTER syntaxes has also
been consolidated.

Suggested-by: Melanie Plageman
Discussion https://postgr.es/m/CAAKRu_bc5uHieG1976kGqJKxyWtyQt9yvktjsVX%2Bi7NOigDjOA%40mail.gmail.com

22 months agoAdd psql \drg command to display role grants.
Tom Lane [Wed, 19 Jul 2023 16:46:30 +0000 (12:46 -0400)]
Add psql \drg command to display role grants.

With the addition of INHERIT and SET options for role grants,
the historical display of role memberships in \du/\dg is woefully
inadequate.  Besides those options, there are pre-existing
shortcomings that you can't see the ADMIN option nor the grantor.

To fix this, remove the "Member of" column from \du/\dg altogether
(making that output usefully narrower), and invent a new meta-command
"\drg" that is specifically for displaying role memberships.  It
shows one row for each role granted to the selected role(s), with
the grant options and grantor.

We would not normally back- such a feature addition post
feature freeze, but in this case the change is mainly driven by
v16 changes in the server, so it seems appropriate to include it
in v16.

Pavel Luzanov, with bikeshedding and review from a lot of people,
but particularly David Johnston

Discussion: https://postgr.es/m/b9be2d0e-a9bc-0a30-492f-a4f68e4f7740@postgrespro.ru

22 months agoDoc: improve description of IN and row-constructor comparisons.
Tom Lane [Wed, 19 Jul 2023 15:00:34 +0000 (11:00 -0400)]
Doc: improve description of IN and row-constructor comparisons.

IN and NOT IN work fine on records and arrays, so just say that
they accept "expressions" not "scalar expressions".  I think that
that phrasing was meant to say that they don't work on set-returning
expressions, but that's not the common meaning of "scalar".

Revise the description of row-constructor comparisons to make it
perhaps a bit less confusing.  (This partially reverts some
dubious wording changes made by commit f56651519.)

Per gripe from Ilya Nenashev.  Back- to supported branches.
In HEAD and v16, also drop a NOTE about pre-8.2 behavior, which
is hopefully no longer of interest to anybody.

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

22 months agopg_archivecleanup: Add --clean-backup-history
Michael Paquier [Wed, 19 Jul 2023 04:41:22 +0000 (13:41 +0900)]
pg_archivecleanup: Add --clean-backup-history

By default, pg_archivecleanup does not remove backup history files.
These are just few bytes useful for debugging purposes, still keeping
them around can bloat an archive path history files mixed with the WAL
segments if the path has a long history.

This  adds a new option to control if backup history files are
removed, depending on the oldest segment name to keep around.

While on it, the TAP tests are refactored so as these are now able to
handle lists of files.  Each file has a flag to track if it should still
exist or not depending on the oldest segment defined with the command
run.

Author: Atsushi Torikoshi
Reviewed-by: Kyotaro Horiguchi, Fujii Masao, Michael Paquier
Discussion: https://postgr.es/m/d660ef741ce3d82f3b4283f1cafd576c@oss.nttdata.com

22 months agopg_archivecleanup: Refactor loop doing old segment removals
Michael Paquier [Wed, 19 Jul 2023 03:23:53 +0000 (12:23 +0900)]
pg_archivecleanup: Refactor loop doing old segment removals

This commit refactors a bit the main loop of pg_archivecleanup that
handles the removal of old segments, reducing by one its level of
indentation.  This will help an incoming  that adds a new option
related to the segment filtering logic.

Author: Atsushi Torikoshi
Reviewed-by: Kyotaro Horiguchi, Fujii Masao, Michael Paquier
Discussion: https://postgr.es/m/d660ef741ce3d82f3b4283f1cafd576c@oss.nttdata.com

22 months agoDoc: Update the logical replication restriction w.r.t Replica Identity Full.
Amit Kapila [Wed, 19 Jul 2023 02:41:44 +0000 (08:11 +0530)]
Doc: Update the logical replication restriction w.r.t Replica Identity Full.

Author: Kuroda Hayato
Reviewed-by: Peter Smith, Onder Kalaci, Sergei Kornilov, Amit Kapila
Discussion: https://postgr.es/m/TYAPR01MB58662174ED62648E0D611194F530A@TYAPR01MB5866.jpnprd01.prod.outlook.com

22 months agoDoc: fix out-of-date example of SPI usage.
Tom Lane [Tue, 18 Jul 2023 15:59:39 +0000 (11:59 -0400)]
Doc: fix out-of-date example of SPI usage.

The "count" argument of SPI_exec() only limits execution when
the query is actually returning rows.  This was not the case
before PG 9.0, so this example was correct when written; but
we missed updating it in commit 2ddc600f8.  Extend the example
to show the behavior both with and without RETURNING.

While here, improve the commentary and markup for the rest
of the example.

David G. Johnston and Tom Lane, per report from Curt Kolovson.
Back- to all supported branches.

Discussion: https://postgr.es/m/CANhYJV6HWtgz_qjx_APfK0PAgLUzY-2vjLuj7i_o=TZF1LAQew@mail.gmail.com

22 months agoFix indentation in twophase.c
Michael Paquier [Tue, 18 Jul 2023 05:04:31 +0000 (14:04 +0900)]
Fix indentation in twophase.c

This has been missed in cb0cca1, noticed before buildfarm member koel
has been able to complain while poking at a different .  Like the
other commit, back all the way down to limit the odds of merge
conflicts.

Back-through: 11

22 months agoFix recovery of 2PC transaction during crash recovery
Michael Paquier [Tue, 18 Jul 2023 04:43:44 +0000 (13:43 +0900)]
Fix recovery of 2PC transaction during crash recovery

A crash in the middle of a checkpoint with some two-phase state data
already flushed to disk by this checkpoint could cause a follow-up crash
recovery to recover twice the same transaction, once from what has been
found in pg_twophase/ at the beginning of recovery and a second time
when replaying its corresponding record.

This would lead to FATAL failures in the startup process during
recovery, where the same transaction would have a state recovered twice
instead of once:
LOG:  recovering prepared transaction 731 from shared memory
LOG:  recovering prepared transaction 731 from shared memory
FATAL:  lock ExclusiveLock on object 731/0/0 is already held

This issue is fixed by skipping the addition of any 2PC state coming
from a record whose equivalent 2PC state file has already been loaded in
TwoPhaseState at the beginning of recovery by restoreTwoPhaseData(),
which is OK as long as the system has not reached a consistent state.

The timing to get a messed up recovery processing is very racy, and
would very unlikely happen.  The thread that has reported the issue has
demonstrated the bug using injection points to force a PANIC in the
middle of a checkpoint.

Issue introduced in 728bd99, so back all the way down.

Reported-by: "suyu.cmj" <[email protected]>
Author: "suyu.cmj" <[email protected]>
Author: Michael Paquier
Discussion: https://postgr.es/m/109e6994-b971-48cb-84f6-829646f18b4c[email protected]
Back-through: 11

22 months agoInclude <limits.h> in fe-auth.c, to get CHAR_BIT reliably.
Tom Lane [Mon, 17 Jul 2023 20:54:54 +0000 (16:54 -0400)]
Include <limits.h> in fe-auth.c, to get CHAR_BIT reliably.

fe-auth.c references CHAR_BIT since commit 3a465cc67, but it
did not #include <limits.h>, which per POSIX is where that
symbol is defined.  This escaped notice so far because
(a) on most platforms, <sys/param.h> pulls in <limits.h>,
(b) even if yours doesn't, OpenSSL pulls it in, so compiling
with --with-openssl masks the omission.

Per bug #18026 from Marcel Hofstetter.  Back- to v16.

Discussion: https://postgr.es/m/18026-d5bb69f79cd16203@postgresql.org

22 months agoRemove db_user_namespace.
Nathan Bossart [Mon, 17 Jul 2023 18:44:59 +0000 (11:44 -0700)]
Remove db_user_namespace.

This feature was intended to be a temporary measure to support
per-database user names.  A better one hasn't materialized in the
~21 years since it was added, and nobody claims to be using it, so
let's just remove it.

Reviewed-by: Michael Paquier, Magnus Hagander
Discussion: https://postgr.es/m/20230630200509.GA2830328%40nathanxps13
Discussion: https://postgr.es/m/20230630215608.GD2941194%40nathanxps13

22 months agoShrink memory contexts struct sizes
David Rowley [Sun, 16 Jul 2023 23:16:56 +0000 (11:16 +1200)]
Shrink memory contexts struct sizes

Here we reduce the block size fields in AllocSetContext, GenerationContext
and SlabContext from Size down to uint32.  Ever since c6e0fe1f2, blocks
for non-dedicated palloc chunks can no longer be larger than 1GB, so
there's no need to store the various block size fields as 64-bit values.
32 bits are enough to store 2^30.

Here we also further reduce the memory context struct sizes by getting rid
of the 'keeper' field which stores a pointer to the context's keeper
block.  All the context types which have this field always allocate the
keeper block in the same allocation as the memory context itself, so the
keeper block always comes right at the end of the context struct.  Add
some macros to calculate that address rather than storing it in the
context.

Overall, in AllocSetContext and GenerationContext, this saves 20 bytes on
64-bit builds which for ALLOCSET_SMALL_SIZES can sometimes mean the
difference between having to allocate a 2nd block and storing all the
required allocations on the keeper block alone.  Such contexts are used
in relcache to store cache entries for indexes, of which there can be
a large number in a single backend.

Author: Melih Mutlu
Reviewed-by: David Rowley
Discussion: https://postgr.es/m/CAGPVpCSOW3uJ1QJmsMR9_oE3X7fG_z4q0AoU4R_w+2RzvroPFg@mail.gmail.com

22 months agoSimplify option handling in pg_ctl.
Nathan Bossart [Fri, 14 Jul 2023 19:35:54 +0000 (12:35 -0700)]
Simplify option handling in pg_ctl.

Now that the in-tree getopt_long() moves non-options to the end of
argv (see commit 411b720343), we can remove pg_ctl's workaround for
getopt_long() implementations that don't reorder argv.

Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/20230713034903.GA991765%40nathanxps13

22 months agoAllow plan nodes with initPlans to be considered parallel-safe.
Tom Lane [Thu, 13 Jul 2023 21:30:14 +0000 (17:30 -0400)]
Allow plan nodes with initPlans to be considered parallel-safe.

If the plan itself is parallel-safe, and the initPlans are too,
there's no reason anymore to prevent the plan from being marked
parallel-safe.  That restriction (dating to commit ab77a5a45) was
really a special case of the fact that we couldn't transmit subplans
to parallel workers at all.  We fixed that in commit 5e6d8d2bb and
follow-ons, but this case never got addressed.

We still forbid attaching initPlans to a Gather node that's
inserted pursuant to debug_parallel_query = regress.  That's because,
when we hide the Gather from EXPLAIN output, we'd hide the initPlans
too, causing cosmetic regression diffs.  It seems inadvisable to
kluge EXPLAIN to the extent required to make the output look the
same, so just don't do it in that case.

Along the way, this also takes care of some sloppiness about updating
path costs to match when we move initplans from one place to another
during createplan.c and setrefs.c.  Since all the planning decisions
are already made by that point, this is just cosmetic; but it seems
good to keep EXPLAIN output consistent with where the initplans are.

The diff in query_planner() might be worth remarking on.  I found that
one because after fixing things to allow parallel-safe initplans, one
partition_prune test case changed plans (as shown in the ) ---
but only when debug_parallel_query was active.  The reason proved to
be that we only bothered to mark Result nodes as potentially
parallel-safe when debug_parallel_query is on.  This neglects the fact
that parallel-safety may be of interest for a sub-query even though
the Result itself doesn't parallelize.

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

22 months agoAccount for optimized MinMax aggregates during SS_finalize_plan.
Tom Lane [Thu, 13 Jul 2023 20:50:13 +0000 (16:50 -0400)]
Account for optimized MinMax aggregates during SS_finalize_plan.

We are capable of optimizing MIN() and MAX() aggregates on indexed
columns into subqueries that exploit the index, rather than the normal
thing of scanning the whole table.  When we do this, we replace the
Aggref node(s) with Params referencing subquery outputs.  Such Params
really ought to be included in the per-plan-node extParam/allParam
sets computed by SS_finalize_plan.  However, we've never done so
up to now because of an ancient implementation choice to perform
that substitution during set_plan_references, which runs after
SS_finalize_plan, so that SS_finalize_plan never sees these Params.

This seems like clearly a bug, yet there have been no field reports
of problems that could trace to it.  This may be because the types
of Plan nodes that could contain Aggrefs do not have any of the
rescan optimizations that are controlled by extParam/allParam.
Nonetheless it seems certain to bite us someday, so let's fix it
in a self-contained  that can be back-ed if we find a
case in which there's a live bug pre-v17.

The cleanest fix would be to perform a separate tree walk to do
these substitutions before SS_finalize_plan runs.  That seems
unattractive, first because a whole-tree mutation pass is expensive,
and second because we lack infrastructure for visiting expression
subtrees in a Plan tree, so that we'd need a new function knowing
as much as SS_finalize_plan knows about that.  I also considered
swapping the order of SS_finalize_plan and set_plan_references,
but that fell foul of various assumptions that seem tricky to fix.
So the approach adopted here is to teach SS_finalize_plan itself
to check for such Aggrefs.  I refactored things a bit in setrefs.c
to avoid having three copies of the code that does that.

Given the lack of any currently-known bug, no test case here.

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

22 months agoImprove error message for MaxAllocSize overrun in accumArrayResult.
Tom Lane [Fri, 14 Jul 2023 14:35:24 +0000 (10:35 -0400)]
Improve error message for MaxAllocSize overrun in accumArrayResult.

Before, if you went past about 64M array elements in array_agg() and
allied functions, you got a generic "invalid memory alloc request
size" error.  This  replaces that with "array size exceeds the
maximum allowed", which seems more user-friendly since it points you
to needing to reduce the size of your array result.  (This is the
same error text you'd get from construct_md_array in the event of
overrunning the maximum physical size for the finished array.)

Per question from Shaozhong Shi.  Since this hasn't come up often,
I don't feel a need to back-.

Discussion: https://postgr.es/m/CA+i5JwYtVS9z2E71PcNKAVPbOn4R2wuj-LqbJsYr_XOz73q7dQ@mail.gmail.com