postgresql.git
23 months agoEnsure that creation of an empty relfile is fsync'd at checkpoint.
Heikki Linnakangas [Tue, 4 Jul 2023 14:57:03 +0000 (17:57 +0300)]
Ensure that creation of an empty relfile is fsync'd at checkpoint.

If you create a table and don't insert any data into it, the relation file
is never fsync'd. You don't lose data, because an empty table doesn't have
any data to begin with, but if you crash and lose the file, subsequent
operations on the table will fail with "could not open file" error.

To fix, register an fsync request in mdcreate(), like we do for mdwrite().

Per discussion, we probably should also fsync the containing directory
after creating a new file. But that's a separate and much wider issue.

Backpatch to all supported versions.

Reviewed-by: Andres Freund, Thomas Munro
Discussion: https://www.postgresql.org/message-id/d47d8122-415e-425c-d0a2-e0160829702d%40iki.fi

23 months agoAdjust kerberos and ldap tests for Homebrew on ARM
Peter Eisentraut [Tue, 4 Jul 2023 09:14:53 +0000 (11:14 +0200)]
Adjust kerberos and ldap tests for Homebrew on ARM

The Homebrew package manager changed its default installation prefix
for the new architecture, so a couple of tests need tweaks to find
binaries.

This is a partial backpatch of dc513bc654.

23 months agoRe-bin segment when memory pages are freed.
Thomas Munro [Tue, 4 Jul 2023 03:16:34 +0000 (15:16 +1200)]
Re-bin segment when memory pages are freed.

It's OK to be lazy about re-binning memory segments when allocating,
because that can only leave segments in a bin that's too high.  We'll
search higher bins if necessary while allocating next time, and
also eventually re-bin, so no memory can become unreachable that way.

However, when freeing memory, the largest contiguous range of free pages
might go up, so we should re-bin eagerly to make sure we don't leave the
segment in a bin that is too low for get_best_segment() to find.

The re-binning code is moved into a function of its own, so it can be
called whenever free pages are returned to the segment's free page map.

Back-patch to all supported releases.

Author: Dongming Liu <[email protected]>
Reviewed-by: Robert Haas <[email protected]> (earlier version)
Reviewed-by: Thomas Munro <[email protected]>
Discussion: https://postgr.es/m/CAL1p7e8LzB2LSeAXo2pXCW4%2BRya9s0sJ3G_ReKOU%3DAjSUWjHWQ%40mail.gmail.com

23 months agoFix race in SSI interaction with gin fast path.
Thomas Munro [Mon, 3 Jul 2023 04:20:01 +0000 (16:20 +1200)]
Fix race in SSI interaction with gin fast path.

The ginfast.c code previously checked for conflicts in before locking
the relevant buffer, leaving a window where a RW conflict could be
missed.  Re-order.

There was also a place where buffer ID and block number were confused
while trying to predicate-lock a page, noted by visual inspection.

Back-patch to all supported releases.  Fixes one more problem discovered
with the reproducer from bug #17949, in this case when Dmitry tried
other index types.

Reported-by: Artem Anisimov <[email protected]>
Reported-by: Dmitry Dolgov <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Discussion: https://postgr.es/m/17949-a0f17035294a55e2%40postgresql.org

23 months agoFix race in SSI interaction with bitmap heap scan.
Thomas Munro [Mon, 3 Jul 2023 04:18:20 +0000 (16:18 +1200)]
Fix race in SSI interaction with bitmap heap scan.

When performing a bitmap heap scan, we don't want to miss concurrent
writes that occurred after we observed the heap's rs_nblocks, but before
we took predicate locks on index pages.  Therefore, we can't skip
fetching any heap tuples that are referenced by the index, because we
need to test them all with CheckForSerializableConflictOut().  The
old optimization that would ignore any references to blocks >=
rs_nblocks gets in the way of that requirement, because it means that
concurrent writes in that window are ignored.

Removing that optimization shouldn't affect correctness at any isolation
level, because any new tuples shouldn't be visible to an MVCC snapshot.
There also shouldn't be any error-causing references to heap blocks past
the end, because we should have held at least an AccessShareLock on the
table before the index scan.  It can't get smaller while our transaction
is running.  For now, though, we'll keep the optimization at lower
levels to avoid making unnecessary changes in a bug fix.

Back-patch to all supported releases.  In release 11, the code is in a
different place but not fundamentally different.  Fixes one aspect of
bug #17949.

Reported-by: Artem Anisimov <[email protected]>
Reviewed-by: Dmitry Dolgov <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Discussion: https://postgr.es/m/17949-a0f17035294a55e2%40postgresql.org

23 months agoFix race in SSI interaction with empty btrees.
Thomas Munro [Mon, 3 Jul 2023 04:16:27 +0000 (16:16 +1200)]
Fix race in SSI interaction with empty btrees.

When predicate-locking btrees, we have a special case for completely
empty btrees, since there is no page to lock.  This was racy, because,
without buffer lock held, a matching key could be inserted between the
_bt_search() and the PredicateLockRelation() calls.

Fix, by rechecking _bt_search() after taking the relation-level SIREAD
lock, if using SERIALIZABLE isolation and an empty btree is discovered.

Back-patch to all supported releases.  Fixes one aspect of bug #17949.

Reported-by: Artem Anisimov <[email protected]>
Reviewed-by: Dmitry Dolgov <[email protected]>
Reviewed-by: Heikki Linnakangas <[email protected]>
Discussion: https://postgr.es/m/17949-a0f17035294a55e2%40postgresql.org

23 months agoRemove expensive test of postgres_fdw batch inserts
Tomas Vondra [Mon, 3 Jul 2023 16:16:58 +0000 (18:16 +0200)]
Remove expensive test of postgres_fdw batch inserts

The test inserted 70k rows into a foreign table, in order to verify
correct behavior with more than 65535 parameters, and was added in
response to a bug report.

However, this is rather expensive, especially when running the tests
under valgrind, CLOBBER_CACHE_ALWAYS etc. It doesn't seem worth it to
keep running the test, so remove it from all branches (14+).

Backpatch-through: 14
Discussion: https://postgr.es/m/2131017.1623451468@sss.pgh.pa.us

23 months agoUse older package name in pg_basebackup test
Andrew Dunstan [Mon, 3 Jul 2023 14:46:49 +0000 (10:46 -0400)]
Use older package name in pg_basebackup test

Commit 83ed4de20f inadvertently used the new package names. In version
14 or older, use TestLib intead of using PostgreSQL::Test::Utils

23 months agoImprove pg_basebackup long file name test Windows robustness
Andrew Dunstan [Mon, 3 Jul 2023 14:06:26 +0000 (10:06 -0400)]
Improve pg_basebackup long file name test Windows robustness

Creation of a file with a very long name can create problems on Windows
due to its file path limits. Work around that by creating the file via a
symlink with a shorter name.

Error displayed by buildfarm animal fairywren.o

Backpatch to all live branches

23 months agoMake PG_TEST_NOCLEAN work for temporary directories in TAP tests
Michael Paquier [Mon, 3 Jul 2023 01:06:16 +0000 (10:06 +0900)]
Make PG_TEST_NOCLEAN work for temporary directories in TAP tests

When set, this environment variable was only effective for data
directories but not for all the other temporary files created by
PostgreSQL::Test::Utils.  Keeping the temporary files after a successful
run can be useful for debugging purposes.

The documentation is updated to reflect the new behavior, with contents
available in doc/ since v16 and in src/test/perl/README since v15.

Author: Jacob Champion
Reviewed-by: Daniel Gustafsson
Discussion: https://postgr.es/m/CAAWbhmgHtDH1SGZ+Fw05CsXtE0mzTmjbuUxLB9mY9iPKgM6cUw@mail.gmail.com
Discussion: https://postgr.es/m/[email protected]
Backpatch-through: 11

23 months agoFix oversight in handling of modifiedCols since f24523672d
Tomas Vondra [Sun, 2 Jul 2023 18:29:01 +0000 (20:29 +0200)]
Fix oversight in handling of modifiedCols since f24523672d

Commit f24523672d fixed a memory leak by moving the modifiedCols bitmap
into the per-row memory context. In the case of AFTER UPDATE triggers,
the bitmap is however referenced from an event kept until the end of the
query, resulting in a use-after-free bug.

Fixed by copying the bitmap into the AfterTriggerEvents memory context,
which is the one where we keep the trigger events. There's only one
place that needs to do the copy, but the memory context may not exist
yet. Doing that in a separate function seems more readable.

Report by Alexander Pyhalov, fix by me. Backpatch to 13, where the
bitmap was added to the event by commit 71d60e2aa0.

Reported-by: Alexander Pyhalov
Backpatch-through: 13
Discussion: https://postgr.es/m/acddb17c89b0d6cb940eaeda18c08bbe@postgrespro.ru

23 months agoFix memory leak in Incremental Sort rescans
Tomas Vondra [Sun, 2 Jul 2023 16:54:09 +0000 (18:54 +0200)]
Fix memory leak in Incremental Sort rescans

The Incremental Sort had a couple issues, resulting in leaking memory
during rescans, possibly triggering OOM. The code had a couple of
related flaws:

1. During rescans, the sort states were reset but then also set to NULL
   (despite the comment saying otherwise). ExecIncrementalSort then
   sees NULL and initializes a new sort state, leaking the memory used
   by the old one.

2. Initializing the sort state also automatically rebuilt the info about
   presorted keys, leaking the already initialized info. presorted_keys
   was also unnecessarily reset to NULL.

Patch by James Coleman, based on patches by Laurenz Albe and Tom Lane.
Backpatch to 13, where Incremental Sort was introduced.

Author: James Coleman, Laurenz Albe, Tom Lane
Reported-by: Laurenz Albe, Zu-Ming Jiang
Backpatch-through: 13
Discussion: https://postgr.es/m/b2bd02dff61af15e3526293e2771f874cf2a3be7.camel%40cybertec.at
Discussion: https://postgr.es/m/db03c582-086d-e7cd-d4a1-3bc722f81765%40inf.ethz.ch

23 months agodoc: PG _14_ relnotes, remove duplicate commit comment
Bruce Momjian [Fri, 30 Jun 2023 12:37:15 +0000 (08:37 -0400)]
doc:  PG _14_ relnotes, remove duplicate commit comment

Backpatch-through: 14 only

23 months agoFix marking of indisvalid for partitioned indexes at creation
Michael Paquier [Fri, 30 Jun 2023 04:54:56 +0000 (13:54 +0900)]
Fix marking of indisvalid for partitioned indexes at creation

The logic that introduced partitioned indexes missed a few things when
invalidating a partitioned index when these are created, still the code
is written to handle recursions:
1) If created from scratch because a mapping index could not be found,
the new index created could be itself invalid, if for example it was a
partitioned index with one of its leaves invalid.
2) A CCI was missing when indisvalid is set for a parent index, leading
to inconsistent trees when recursing across more than one level for a
partitioned index creation if an invalidation of the parent was
required.

This could lead to the creation of a partition index tree where some of
the partitioned indexes are marked as invalid, but some of the parents
are marked valid, which is not something that should happen (as
validatePartitionedIndex() defines, indisvalid is switched to true for a
partitioned index iff all its partitions are themselves valid).

This patch makes sure that indisvalid is set to false on a partitioned
index if at least one of its partition is invalid.  The flag is set to
true if *all* its partitions are valid.

The regression test added in this commit abuses of a failed concurrent
index creation, marked as invalid, that maps with an index created on
its partitioned table afterwards.

Reported-by: Alexander Lakhin
Reviewed-by: Alexander Lakhin
Discussion: https://postgr.es/m/14987634-43c0-0cb3-e075-94d423607e08@gmail.com
Backpatch-through: 11

23 months agoFix order of operations in ExecEvalFieldStoreDeForm().
Tom Lane [Thu, 29 Jun 2023 14:19:10 +0000 (10:19 -0400)]
Fix order of operations in ExecEvalFieldStoreDeForm().

If the given composite datum is toasted out-of-line,
DatumGetHeapTupleHeader will perform database accesses to detoast it.
That can invalidate the result of get_cached_rowtype, as documented
(perhaps not plainly enough) in that function's API spec; which leads
to strange errors or crashes when we try to use the TupleDesc to read
the tuple.  In short then, trying to update a field of a composite
column could fail intermittently if the overall column value is wide
enough to require toasting.

We can fix the bug at no cost by just changing the order of
operations, since we don't need the TupleDesc until after detoasting.
(Other callers of get_cached_rowtype appear to get this right already,
so there's only one bug.)

Note that the added regression test case reveals this bug reliably
only with debug_discard_caches/CLOBBER_CACHE_ALWAYS.

Per bug #17994 from Alexander Lakhin.  Sadly, this patch does not fix
the missing-values issue revealed in the bug discussion; we'll need
some more work to cover that.

Discussion: https://postgr.es/m/17994-5c7100b51b4790e9@postgresql.org

23 months agoRemove inappropriate raw_expression_tree_walker() code
Peter Eisentraut [Thu, 29 Jun 2023 08:30:55 +0000 (10:30 +0200)]
Remove inappropriate raw_expression_tree_walker() code

It was walking into the ColumnDef->compression field, which is not a
node but a string.  This code is currently not reachable (because the
compression field is only set in situations that don't go through
raw_expression_tree_walker()), but if it had been, this could have
behaved erratically.

2 years agopg_stat_statements: Fix second comment related to entry resets
Michael Paquier [Thu, 29 Jun 2023 00:17:34 +0000 (09:17 +0900)]
pg_stat_statements: Fix second comment related to entry resets

This should have been part of dc73db6, but it got lost in the mix.
Oversight in 6b4d23f.

Author: Japin Li
Discussion: https://postgr.es/m/MEYP282MB1669FC91C764E277821936D3B624A@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM
Backpatch-through: 14

2 years agopg_stat_statements: Fix incorrect comment with entry resets
Michael Paquier [Wed, 28 Jun 2023 23:05:10 +0000 (08:05 +0900)]
pg_stat_statements: Fix incorrect comment with entry resets

Oversight in 6b4d23f.

Author: Japin Li, Richard Guo
Discussion: https://postgr.es/m/MEYP282MB1669FC91C764E277821936D3B624A@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM
Backpatch-through: 14

2 years agoIgnore invalid indexes when enforcing index rules in ALTER TABLE ATTACH PARTITION
Michael Paquier [Wed, 28 Jun 2023 06:57:48 +0000 (15:57 +0900)]
Ignore invalid indexes when enforcing index rules in ALTER TABLE ATTACH PARTITION

A portion of ALTER TABLE .. ATTACH PARTITION is to ensure that the
partition being attached to the partitioned table has a correct set of
indexes, so as there is a consistent index mapping between the
partitioned table and its new-to-be partition.  However, as introduced
in 8b08f7d, the current logic could choose an invalid index as a match,
which is something that can exist when dealing with more than two levels
of partitioning, like attaching a partitioned table (that has
partitions, with an index created by CREATE INDEX ON ONLY) to another
partitioned table.

A partitioned index with indisvalid set to false is equivalent to an
incomplete partition tree, meaning that an invalid partitioned index
does not have indexes defined in all its partitions.  Hence, choosing an
invalid partitioned index can create inconsistent partition index trees,
where the parent attaching to is valid, but its partition may be
invalid.

In the report from Alexander Lakhin, this showed up as an assertion
failure when validating an index.  Without assertions enabled, the
partition index tree would be actually broken, as indisvalid should
be switched to true for a partitioned index once all its partitions are
themselves valid.  With two levels of partitioning, the top partitioned
table used a valid index and was able to link to an invalid index stored
on its partition, itself a partitioned table.

I have studied a few options here (like the possibility to switch
indisvalid to false for the parent), but came down to the conclusion
that we'd better rely on a simple rule: invalid indexes had better never
be chosen, so as the partition attached uses and creates indexes that
the parent expects.  Some regression tests are added to provide some
coverage.  Note that the existing coverage is not impacted.

This is a problem since partitioned indexes exist, so backpatch all the
way down to v11.

Reported-by: Alexander Lakhin
Discussion: https://postgr.es/14987634-43c0-0cb3-e075-94d423607e08@gmail.com
Backpatch-through: 11

2 years agoFix comment on clearing padding.
Heikki Linnakangas [Tue, 27 Jun 2023 07:11:31 +0000 (10:11 +0300)]
Fix comment on clearing padding.

Author: Japin Li
Discussion: https://www.postgresql.org/message-id/MEYP282MB16696317B5DA7D0D92306149B627A@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM

2 years agoCheck for interrupts and stack overflow in TParserGet().
Tom Lane [Sat, 24 Jun 2023 21:18:08 +0000 (17:18 -0400)]
Check for interrupts and stack overflow in TParserGet().

TParserGet() recurses for some token types, meaning it's possible
to drive it to stack overflow.  Since this is a minority behavior,
I chose to add the check_stack_depth() call to the two places that
recurse rather than doing it during every single call.

While at it, add CHECK_FOR_INTERRUPTS(), because this can run
unpleasantly long for long inputs.

Per bug #17995 from Zuming Jiang.  This is old, so back-patch
to all supported branches.

Discussion: https://postgr.es/m/17995-9f20ff3e6389db4c@postgresql.org

2 years agodoc: rename "decades" to be more generic
Bruce Momjian [Sat, 24 Jun 2023 02:50:55 +0000 (22:50 -0400)]
doc:  rename "decades" to be more generic

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/[email protected]

Backpatch-through: 11

2 years agoFix incorrect error message in libpq_pipeline
Michael Paquier [Fri, 23 Jun 2023 08:50:28 +0000 (17:50 +0900)]
Fix incorrect error message in libpq_pipeline

One of the tests for the pipeline mode with portal description expects a
non-NULL PQgetResult, but used an incorrect error message on failure,
telling that PQgetResult being NULL was the expected result.

Author: Jelte Fennema
Discussion: https://postgr.es/m/CAGECzQTkShHecFF+EZrm94Lbsu2ej569T=bz+PjMbw9Aiioxuw@mail.gmail.com
Backpatch-through: 14

2 years agoDoc: Clarify the behavior of triggers/rules in a logical subscriber.
Amit Kapila [Thu, 22 Jun 2023 06:46:51 +0000 (12:16 +0530)]
Doc: Clarify the behavior of triggers/rules in a logical subscriber.

By default, triggers and rules do not fire on a logical replication
subscriber based on the "session_replication_role" GUC being set to
"replica". However, the docs in the logical replication section assumed
that the reader understood how this GUC worked. This modifies the docs to
be more explicit and links back to the GUC itself.

Author: Jonathan Katz, Peter Smith
Reviewed-by: Vignesh C, Euler Taveira
Backpatch-through: 11
Discussion: https://postgr.es/m/5bb2c9a2-499f-e1a2-6e33-5ce96b35cc4a@postgresql.org

2 years agoDoc: mention that extended stats aren't used for joins
David Rowley [Thu, 22 Jun 2023 00:47:53 +0000 (12:47 +1200)]
Doc: mention that extended stats aren't used for joins

Statistics defined by the CREATE STATISTICS command are only used to
assist with the selectivity estimations of base relations, never for
joins.  Here we mention this fact in the notes section of the CREATE
STATISTICS command.

Discussion: https://postgr.es/m/CAApHDvrMuVgDOrmg_EtFDZ=AOovq6EsJNnHH1ddyZ8EqL4yzMw@mail.gmail.com
Backpatch-through: 11

2 years agonbtree VACUUM: cope with topparent inconsistencies.
Peter Geoghegan [Thu, 22 Jun 2023 00:41:54 +0000 (17:41 -0700)]
nbtree VACUUM: cope with topparent inconsistencies.

Avoid "right sibling %u of block %u is not next child" errors when
vacuuming a corrupt nbtree index.  Just LOG the issue and press on.
That way VACUUM will have a decent chance of finishing off all required
processing for the index (and for the table as a whole).

This is similar to recent work from commit 5abff197, as well as work
from commit 5b861baa (later backpatched as commit 43e409ce), which
taught nbtree VACUUM to keep going when its "re-find" check fails.  The
hardening added by this commit takes place directly after the "re-find"
check, right before the critical section for the first stage of page
deletion.

Author: Peter Geoghegan <[email protected]>
Discussion: https://postgr.es/m/CAH2-Wz=dayg0vjs4+er84TS9ami=csdzjpuiCGbEw=idhwqhzQ@mail.gmail.com
Backpatch: 11- (all supported versions).

2 years agodoc: update PG history as over "three decades"
Bruce Momjian [Wed, 21 Jun 2023 23:20:07 +0000 (19:20 -0400)]
doc:  update PG history as over "three decades"

Reported-by: Pierre <[email protected]>
Discussion: https://postgr.es/m/168724660637.399156.7642965215720120947@wrigleys.postgresql.org

Backpatch-through: 11

2 years agoAvoid Assert failure when processing empty statement in aborted xact.
Tom Lane [Wed, 21 Jun 2023 15:07:11 +0000 (11:07 -0400)]
Avoid Assert failure when processing empty statement in aborted xact.

exec_parse_message() wants to create a cached plan in all cases,
including for empty input.  The empty-input path does not have
a test for being in an aborted transaction, making it possible
that plancache.c will fail due to trying to do database lookups
even though there's no real work to do.

One solution would be to throw an aborted-transaction error in
this path too, but it's not entirely clear whether the lack of
such an error was intentional or whether some clients might be
relying on non-error behavior.  Instead, let's hack plancache.c
so that it treats empty statements with the same logic it
already had for transaction control commands, ensuring that it
can soldier through even in an already-aborted transaction.

Per bug #17983 from Alexander Lakhin.  Back-patch to all
supported branches.

Discussion: https://postgr.es/m/17983-da4569fcb878672e@postgresql.org

2 years agoDisable use of archiving in 009_twophase.pl
Michael Paquier [Wed, 21 Jun 2023 07:16:24 +0000 (16:16 +0900)]
Disable use of archiving in 009_twophase.pl

This partially reverts 68cb5af, as using archiving to enforce the
rename of the last partial segment of the old timeline at promotion to
use .partial as suffix is impacting the tests when it does switchovers.
As showed by the logs gathered by the CI in the tests that failed, a new
standby may fail to find the WAL segment it needs to follow a promoted
instance with its timeline jump, as it got renamed to .partial.

This problem would manifest as a run timeout with 009_twophase.pl, as
the new standby repeatedly requests a segment from the promoted primary
that it would not find.

Reported-by: Nathan Bossart
Discussion: https://postgr.es/m/20230621043345.GA787473@nathanxps13
Backpatch-through: 13

2 years agoFix the errhint message and docs for drop subscription failure.
Amit Kapila [Wed, 21 Jun 2023 04:39:28 +0000 (10:09 +0530)]
Fix the errhint message and docs for drop subscription failure.

The existing errhint message and docs were missing the fact that we can't
disassociate from the slot unless the subscription is disabled.

Author: Robert Sjöblom, Peter Smith
Reviewed-by: Peter Eisentraut, Amit Kapila
Backpatch-through: 11
Discussion: https://postgr.es/m/807bdf85-61ea-88e2-5712-6d9fcd4eabff@fortnox.se

2 years agoFix hash join when inner hashkey expressions contain Params.
Tom Lane [Tue, 20 Jun 2023 21:47:36 +0000 (17:47 -0400)]
Fix hash join when inner hashkey expressions contain Params.

If the inner-side expressions contain PARAM_EXEC Params, we must
re-hash whenever the values of those Params change.  The executor
mechanism for that exists already, but we failed to invoke it because
finalize_plan() neglected to search the Hash.hashkeys field for
Params.  This allowed a previous scan's hash table to be re-used
when it should not be, leading to rows missing from the join's output.
(I believe incorrectly-included join rows are impossible however,
since checking the real hashclauses would reject false matches.)

This bug is very ancient, dating probably to d24d75ff1 of 7.4.
Sadly, this simple fix depends on the plan representational changes
made by 2abd7ae9b, so it will only work back to v12.  I thought
about trying to make some kind of hack for v11, but I'm leery
of putting code significantly different from what is used in the
newer branches into a nearly-EOL branch.  Seeing that the bug
escaped detection for a full twenty years, problematic cases
must be rare; so I don't feel too awful about leaving v11 as-is.

Per bug #17985 from Zuming Jiang.  Back-patch to v12.

Discussion: https://postgr.es/m/17985-748b66607acd432e@postgresql.org

2 years agoEnable archiving in recovery TAP test 009_twophase.pl
Michael Paquier [Tue, 20 Jun 2023 01:25:45 +0000 (10:25 +0900)]
Enable archiving in recovery TAP test 009_twophase.pl

This is a follow-up of f663b00, that has been committed to v13 and v14,
tweaking the TAP test for two-phase transactions so as it provides
coverage for the bug that has been fixed.  This change is done in its
own commit for clarity, as v15 and HEAD did not show the problematic
behavior, still missed coverage for it.

While on it, this adds a comment about the dependency of the last
partial segment rename and RecoverPreparedTransactions() at the end of
recovery, as that can be easy to miss.

Author: Michael Paquier
Reviewed-by: Kyotaro Horiguchi
Discussion: https://postgr.es/m/743b9b45a2d4013bd90b6a5cba8d6faeb717ee34[email protected]
Backpatch-through: 13

2 years agoFix failure at promotion with 2PC transactions and archiving enabled
Michael Paquier [Tue, 20 Jun 2023 00:36:35 +0000 (09:36 +0900)]
Fix failure at promotion with 2PC transactions and archiving enabled

When archiving is enabled, a promotion request would fail with the
following error when some 2PC transaction needs to be recovered from
WAL, preventing the promotion to complete:
FATAL:  requested WAL segment pg_wal/000000010000000000000001 has already been removed

The origin of the problem is that the last partial segment of the old
timeline is renamed before recovering the 2PC data via
RecoverPreparedTransactions() at the end of recovery, causing the FATAL
because the segment wanted is now renamed with a .partial suffix.  This
commit reorders a bit the end-of-recovery actions so as the execution of
recovery_end_command, the cleanup of the old segments of the old
timeline (RemoveNonParentXlogFiles) and the last partial segment rename
are done after the 2PC transaction data is recovered with
RecoverPreparedTransactions().  This makes the order of these
end-of-recovery actions more consistent with ~15, at the exception of
the end-of-recovery checkpoint that still needs to happen before all the
actions reordered here in v13 and v14, contrary to what 15~ does.

v15 and newer versions have "fixed" this problem somewhat accidentally
with 811051c, where the end-of-recovery actions got reordered.  In this
case, the recovery of 2PC transactions happens before the renaming of
the last partial segment of the old timeline.

v13 and v14 are the versions that can easily see this problem as per the
refactoring of 38a95731 where XLogReaderState is reset in
XLogBeginRead() before reading the 2PC transaction data.  v11 and v12
could also see this problem, but may finish by reading the 2PC data from
some of the WAL buffers instead.  Perhaps something could be done for
these two branches, but I am not really excited about doing something on
these per the lack of complaints and per the fact that v11 is soon going
to be EOL'd soon (there is always a risk of breaking something).

Note that the TAP test 009_twophase.pl is able to exhibit the issue if
it enables archiving on the primary node, which does not impact the test
coverage as restore_command would remain unused.  This is something that
should be changed on v15 and HEAD as well, so this will be changed in a
separate commit for clarity.

Author: Julian Markwort
Reviewed-by: Kyotaro Horiguchi, Michael Paquier
Discussion: https://postgr.es/m/743b9b45a2d4013bd90b6a5cba8d6faeb717ee34[email protected]
Backpatch-through: 13

2 years agoDon't use partial unique indexes for unique proofs in the planner
David Rowley [Mon, 19 Jun 2023 01:01:58 +0000 (13:01 +1200)]
Don't use partial unique indexes for unique proofs in the planner

Here we adjust relation_has_unique_index_for() so that it no longer makes
use of partial unique indexes as uniqueness proofs.  It is incorrect to
use these as the predicates used by check_index_predicates() to set
predOK makes use of not only baserestrictinfo quals as proofs, but also
qual from join conditions.  For relation_has_unique_index_for()'s case, we
need to know the relation is unique for a given set of columns before any
joins are evaluated, so if predOK was only set to true due to some join
qual, then it's unsafe to use such indexes in
relation_has_unique_index_for().  The final plan may not even make use
of that index, which could result in reading tuples that are not as
unique as the planner previously expected them to be.

Bug: #17975
Reported-by: Tor Erik Linnerud
Backpatch-through: 11, all supported versions
Discussion: https://postgr.es/m/17975-98a90c156f25c952%40postgresql.org

2 years agoFix typo in comment.
Amit Langote [Fri, 16 Jun 2023 01:04:22 +0000 (10:04 +0900)]
Fix typo in comment.

Back-patch down to 11.

Author: Sho Kato (<[email protected]>)
Discussion: https://postgr.es/m/TYCPR01MB68499042A33BC32241193AAF9F5BA%40TYCPR01MB6849.jpnprd01.prod.outlook.com

2 years agointarray: Prevent out-of-bound memory reads with gist__int_ops
Michael Paquier [Thu, 15 Jun 2023 04:45:40 +0000 (13:45 +0900)]
intarray: Prevent out-of-bound memory reads with gist__int_ops

As gist__int_ops stands in intarray, it is possible to store GiST
entries for leaf pages that can cause corruptions when decompressed.
Leaf nodes are stored as decompressed all the time by the compression
method, and the decompression method should map with that, retrieving
the contents of the page without doing any decompression.  However, the
code authorized the insertion of leaf page data with a higher number of
array items than what can be supported, generating a NOTICE message to
inform about this matter (199 for a 8k page, for reference).  When
calling the decompression method, a decompression would be attempted on
this leaf node item but the contents should be retrieved as they are.

The NOTICE message generated when dealing with the compression of a leaf
page and too many elements in the input array for gist__int_ops has been
introduced by 08ee64e, removing the marker stored in the array to track
if this is actually a leaf node.  However, it also missed the fact that
the decompression path should do nothing for a leaf page.  Hence, as the
code stand, a too-large array would be stored as uncompressed but the
decompression path would attempt a decompression rather that retrieving
the contents as they are.

This leads to various problems.  First, even if 08ee64e tried to address
that, it is possible to do out-of-bound chunk writes with a large input
array, with the backend informing about that with WARNINGs.  On
decompression, retrieving the stored leaf data would lead to incorrect
memory reads, leading to crashes or even worse.

Perhaps somebody would be interested in expanding the number of array
items that can be handled in a leaf page for this operator in the
future, which would require revisiting the choice done in 08ee64e, but
based on the lack of reports about this problem since 2005 it does not
look so.  For now, this commit prevents the insertion of data for leaf
pages when using more array items that the code can handle on
decompression, switching the NOTICE message to an ERROR.  If one wishes
to use more array items, gist__intbig_ops is an optional choice.

While on it, use ERRCODE_PROGRAM_LIMIT_EXCEEDED as error code when a
limit is reached, because that's what the module is facing in such
cases.

Author: Ankit Kumar Pandey, Alexander Lakhin
Reviewed-by: Richard Guo, Michael Paquier
Discussion: https://postgr.es/m/796b65c3-57b7-bddf-b0d5-a8afafb8b627@gmail.com
Discussion: https://postgr.es/m/17888-f72930e6b5ce8c14@postgresql.org
Backpatch-through: 11

2 years agoCorrectly update hasSubLinks while mutating a rule action.
Tom Lane [Tue, 13 Jun 2023 19:58:37 +0000 (15:58 -0400)]
Correctly update hasSubLinks while mutating a rule action.

rewriteRuleAction neglected to check for SubLink nodes in the
securityQuals of range table entries.  This could lead to failing
to convert such a SubLink to a SubPlan, resulting in assertion
crashes or weird errors later in planning.

In passing, fix some poor coding in rewriteTargetView:
we should not pass the source parsetree's hasSubLinks
field to ReplaceVarsFromTargetList's outer_hasSubLinks.
ReplaceVarsFromTargetList knows enough to ignore that
when a Query node is passed, but it's still confusing
and bad precedent: if we did try to update that flag
we'd be updating a stale copy of the parsetree.

Per bug #17972 from Alexander Lakhin.  This has been broken since
we added RangeTblEntry.securityQuals (although the presented test
case only fails back to 215b43cdc), so back-patch all the way.

Discussion: https://postgr.es/m/17972-f422c094237847d0@postgresql.org

2 years agoAccept fractional seconds in jsonpath's datetime() method.
Tom Lane [Mon, 12 Jun 2023 14:54:28 +0000 (10:54 -0400)]
Accept fractional seconds in jsonpath's datetime() method.

Commit 927d9abb6 purported to make datetime() accept any string
that could be output for a datetime value by to_jsonb().  But it
overlooked the possibility of fractional seconds being present,
so that cases as simple as to_jsonb(now()) would defeat it.

Fix by adding formats that include ".US" to the list in
executeDateTimeMethod().  (Note that while this is nominally
microseconds, it'll do the right thing for fractions with
fewer than six digits.)

In passing, re-order the list to restore the datatype ordering
specified in its comment.  The violation accidentally did not
break anything; but the next edit might be less lucky, so add
more comments.

Per report from Tim Field.  Back-patch to v13 where datetime()
was added, like the previous patch.

Discussion: https://postgr.es/m/014A028B-5CE6-4FDF-AC24-426CA6FC9CEE@mohiohio.com

2 years agohstore: Tighten key/value parsing check for whitespaces
Michael Paquier [Mon, 12 Jun 2023 00:14:14 +0000 (09:14 +0900)]
hstore: Tighten key/value parsing check for whitespaces

isspace() can be locale-sensitive depending on the platform, causing
hstore to consider as whitespaces characters it should not see as such.
For example, U+0105, being decoded as 0xC4 0x85 in UTF-8, would be
discarded from the input given.

This problem is similar to 9ae2661, though it was missed that hstore
can also manipulate non-ASCII inputs, so replace the existing isspace()
calls with scanner_isspace().

This problem exists for a long time, so backpatch all the way down.

Author: Evan Jones
Discussion: https://postgr.es/m/CA+HWA9awUW0+RV_gO9r1ABZwGoZxPztcJxPy8vMFSTbTfi4jig@mail.gmail.com
Backpatch-through: 11

2 years agoFix missing initializations of MyProc.delayChkptEnd
Michael Paquier [Sun, 11 Jun 2023 01:33:46 +0000 (10:33 +0900)]
Fix missing initializations of MyProc.delayChkptEnd

This commit fixes an oversight introduced in 10520f4, that has added
delayChkptEnd to PGPROC to avoid ABI breakages on stable branches, where
two spots have missed to initialize this variable (delayChkpt was
switched back from int to bool, and it was initialized as 0 so there was
no consequences for it):
- InitProcess(), where the per-process data structures of a backend are
initialized.
- InitAuxiliaryProcess(), same but for auxiliary processes.

An interruption during relation truncation while this flag is set could
cause an assertion failure when a follow-up process does a relation
truncation while reusing the same PGPROC entry.  A second effect could
be incorrect checkpoint end delays.

While on it, add an assertion in ProcArrayClearTransaction() for
delayChkptEnd to be in line with 5788e25.  This is needed only for v14.

This issue affects v11~v14, but not v15~, as we use a single field
called delayChkptFlags to delay checkpoints there.

Author: suyu.cmj ([email protected])
Reviewed-by: Kyotaro Horiguchi, Michael Paquier
Discussion: https://postgr.es/m/9c3d2a49-db5f-43cb-840b-d58f9a684295[email protected]
Backpatch-through: 11

2 years agoRefactor routine to find single log content pattern in TAP tests
Michael Paquier [Fri, 9 Jun 2023 02:56:41 +0000 (11:56 +0900)]
Refactor routine to find single log content pattern in TAP tests

The same routine to check if a specific pattern can be found in the
server logs was copied over four different test scripts.  This refactors
the whole to use a single routine located in PostgreSQL::Test::Cluster,
named log_contains, to grab the contents of the server logs and check
for a specific pattern.

On HEAD, the code previously used assumed that slurp_file() could not
handle an undefined offset, setting it to zero, but slurp_file() does
do an extra fseek() before retrieving the log contents only if an offset
is defined.  In two places, the test was retrieving the full log
contents with slurp_file() after calling substr() to apply an offset,
ignoring that slurp_file() would be able to handle that.

Backpatch all the way down to ease the introduction of new tests that
could rely on the new routine.

Author: Vignesh C
Reviewed-by: Andrew Dunstan, Dagfinn Ilmari Mannsåker, Michael Paquier
Discussion: https://postgr.es/m/CALDaNm0YSiLpjCmajwLfidQrFOrLNKPQir7s__PeVvh9U3uoTQ@mail.gmail.com
Backpatch-through: 11

2 years agoRefactor log check logic for connect_ok/fails in PostgreSQL::Test::Cluster
Michael Paquier [Fri, 9 Jun 2023 00:37:34 +0000 (09:37 +0900)]
Refactor log check logic for connect_ok/fails in PostgreSQL::Test::Cluster

This commit refactors a bit the code in charge of checking for log
patterns when connections fail or succeed, by moving the log pattern
checks into their own routine, for clarity.  This has come up as
something to improve while discussing the refactoring of find_in_log().

Backpatch down to 14 where these routines are used, to ease the
introduction of new tests that could rely on them.

Author: Vignesh C, Michael Paquier
Discussion: https://postgr.es/m/CALDaNm0YSiLpjCmajwLfidQrFOrLNKPQir7s__PeVvh9U3uoTQ@mail.gmail.com
Backpatch-through: 14

2 years agodoc: Fix example command for ALTER FOREIGN TABLE ... OPTIONS.
Fujii Masao [Thu, 8 Jun 2023 11:11:52 +0000 (20:11 +0900)]
doc: Fix example command for ALTER FOREIGN TABLE ... OPTIONS.

In the documentation, previously the example command for
ALTER FOREIGN TABLE ... OPTIONS incorrectly included both
the option name and value with the DROP operation.
The correct syntax for the DROP operation requires only
the name of the option to be specified. This commit fixes
the example by removing the option value from the DROP operation.

Back-patch to all supported versions.

Author: Mehmet Emin KARAKAS <[email protected]>
Reviewed-by: Fujii Masao
Discussion: https://postgr.es/m/CANQrdXAHzbcEYhjGoe5A42OmfvdQhHFJzyKj9gJvHuDKyOF5Ng@mail.gmail.com

2 years agoUse per-tuple context in ExecGetAllUpdatedCols
Tomas Vondra [Wed, 7 Jun 2023 14:48:50 +0000 (16:48 +0200)]
Use per-tuple context in ExecGetAllUpdatedCols

Commit fc22b6623b (generated columns) replaced ExecGetUpdatedCols() with
ExecGetAllUpdatedCols() in a couple places handling UPDATE (triggers and
lock mode). However, ExecGetUpdatedCols() did exec_rt_fetch() while
ExecGetAllUpdatedCols() also allocates memory through bms_union()
without paying attention to the memory context and happened to use the
long-lived ExecutorState, leaking the memory until the end of the query.

The amount of leaked memory is proportional to the number of (updated)
attributes, types of UPDATE triggers, and the number of processed rows
(which for UPDATE ... FROM ... may be much higher than updated rows).

Fixed by switching to the per-tuple context in GetAllUpdatedColumns().
This is fine for all in-core callers, but external callers may need to
copy the result. But we're not aware of any such callers.

Note the issue was introduced by fc22b6623b, but the macros were later
renamed by f50e888990.

Backpatch to 12, where the issue was introduced.

Reported-by: Tomas Vondra
Reviewed-by: Andres Freund, Tom Lane, Jakub Wartak
Backpatch-through: 12
Discussion: https://postgr.es/m/222a3442-7f7d-246c-ed9b-a76209d19239@enterprisedb.com

2 years agoInitialize 'recordXtime' to silence compiler warning.
Heikki Linnakangas [Tue, 6 Jun 2023 17:30:53 +0000 (20:30 +0300)]
Initialize 'recordXtime' to silence compiler warning.

In reality, recordXtime will always be set by the getRecordTimestamp
call, but the compiler doesn't necessarily see that.

Back-patch to all supported versions.

Author: Tristan Partin
Discussion: https://www.postgresql.org/message-id/CT5MN8E11U0M.1NYNCHXYUHY41@gonk

2 years agoDoc: explain about dependency tracking for new-style SQL functions.
Tom Lane [Sun, 4 Jun 2023 17:27:34 +0000 (13:27 -0400)]
Doc: explain about dependency tracking for new-style SQL functions.

5.14 Dependency Tracking was not updated when we added new-style
SQL functions.  Improve that.

Noted by Sami Imseih.  Back-patch to v14 where
new-style SQL functions came in.

Discussion: https://postgr.es/m/2C1933AB-C2F8-499B-9D18-4AC1882256A0@amazon.com

2 years agoFix pg_dump's failure to honor dependencies of SQL functions.
Tom Lane [Sun, 4 Jun 2023 17:05:54 +0000 (13:05 -0400)]
Fix pg_dump's failure to honor dependencies of SQL functions.

A new-style SQL function can contain a parse-time dependency
on a unique index, much as views and matviews can (such cases
arise from GROUP BY and ON CONFLICT clauses, for example).
To dump and restore such a function successfully, pg_dump must
postpone the function until after the unique index is created,
which will happen in the post-data part of the dump.  Therefore
we have to remove the normal constraint that functions are
dumped in pre-data.  Add code similar to the existing logic
that handles this for matviews.  I added test cases for both
as well, since code coverage tests showed that we weren't
testing the matview logic.

Per report from Sami Imseih.  Back-patch to v14 where
new-style SQL functions came in.

Discussion: https://postgr.es/m/2C1933AB-C2F8-499B-9D18-4AC1882256A0@amazon.com

2 years agodoc: add missing "the" in LATERAL sentence.
Bruce Momjian [Thu, 1 Jun 2023 14:22:16 +0000 (10:22 -0400)]
doc:  add missing "the" in LATERAL sentence.

Backpatch-through: 11

2 years agonbtree VACUUM: cope with right sibling link corruption.
Peter Geoghegan [Thu, 25 May 2023 22:32:53 +0000 (15:32 -0700)]
nbtree VACUUM: cope with right sibling link corruption.

Avoid "right sibling's left-link doesn't match" errors when vacuuming a
corrupt nbtree index.  Just LOG the issue and press on.  That way VACUUM
will have a decent chance of finishing off all required processing for
the index (and for the table as a whole).

This error was seen in the field from time to time (it's more than a
theoretical risk), so giving VACUUM the ability to press on like this
has real value.  Nothing short of a REINDEX is expected to fix the
underlying index corruption, so giving up (by throwing an error) risks
making a bad situation far worse.  Anything that blocks forward progress
by VACUUM like this might go unnoticed for a long time.  This could
eventually lead to a wraparound/xidStopLimit outage.

Note that _bt_unlink_halfdead_page() has always been able to bail on
page deletion when the target page's left sibling page was in an
inconsistent state.  It now does the same thing (returns false to back
out of the second phase of deletion) when it notices sibling link
corruption in the target page's right sibling page.

This is similar to the work from commit 5b861baa (later backpatched as
commit 43e409ce), which taught nbtree to press on with vacuuming an
index when page deletion fails to "re-find" a downlink in the target
page's parent page.  The "re-find" check seems to make VACUUM bail on
page deletion more often in practice, but there is no reason to take any
chances here.

Author: Peter Geoghegan <[email protected]>
Reviewed-By: Heikki Linnakangas <[email protected]>
Discussion: https://postgr.es/m/CAH2-Wzko2q2kP1+UvgJyP9g0mF4hopK0NtQZcxwvMv9_ytGhkQ@mail.gmail.com
Backpatch: 11- (all supported versions).

2 years agoFix misbehavior of EvalPlanQual checks with multiple result relations.
Tom Lane [Fri, 19 May 2023 18:26:34 +0000 (14:26 -0400)]
Fix misbehavior of EvalPlanQual checks with multiple result relations.

The idea of EvalPlanQual is that we replace the query's scan of the
result relation with a single injected tuple, and see if we get a
tuple out, thereby implying that the injected tuple still passes the
query quals.  (In join cases, other relations in the query are still
scanned normally.)  This logic was not updated when commit 86dc90056
made it possible for a single DML query plan to have multiple result
relations, when the query target relation has inheritance or partition
children.  We replaced the output for the current result relation
successfully, but other result relations were still scanned normally;
thus, if any other result relation contained a tuple satisfying the
quals, we'd think the EPQ check passed, even if it did not pass for
the injected tuple itself.  This would lead to update or delete
actions getting performed when they should have been skipped due to
a conflicting concurrent update in READ COMMITTED isolation mode.

Fix by blocking all sibling result relations from emitting tuples
during an EvalPlanQual recheck.  In the back branches, the fix is
complicated a bit by the need to not change the size of struct
EPQState (else we'd have ABI-breaking changes in offsets in
struct ModifyTableState).  Like the back-patches of 3f7836ff6
and 4b3e37993, add a separately palloc'd struct to avoid that.
The logic is the same as in HEAD otherwise.

This is only a live bug back to v14 where 86dc90056 came in.
However, I chose to back-patch the test cases further, on the
grounds that this whole area is none too well tested.  I skipped
doing so in v11 though because none of the test applied cleanly,
and it didn't quite seem worth extra work for a branch with only
six months to live.

Per report from Ante Krešić (via Aleksander Alekseev)

Discussion: https://postgr.es/m/CAJ7c6TMBTN3rcz4=AjYhLPD_w3FFT0Wq_C15jxCDn8U4tZnH1g@mail.gmail.com

2 years agoAvoid naming conflict between transactions.sql and namespace.sql.
Tom Lane [Fri, 19 May 2023 14:57:46 +0000 (10:57 -0400)]
Avoid naming conflict between transactions.sql and namespace.sql.

Commits 681d9e462 et al added a test case in namespace.sql that
implicitly relied on there not being a table "public.abc".
However, the concurrently-run transactions.sql test creates precisely
such a table, so with the right timing you'd get a failure.
Creating a table named as generically as "abc" in a common schema
seems like bad practice, so fix this by changing the name of
transactions.sql's table.  (Compare 2cf8c7aa4.)

Marina Polyakova

Discussion: https://postgr.es/m/80d0201636665d82185942e7112257b4@postgrespro.ru

2 years agopageinspect: Fix gist_page_items() with included columns
Michael Paquier [Fri, 19 May 2023 03:38:18 +0000 (12:38 +0900)]
pageinspect: Fix gist_page_items() with included columns

Non-leaf pages of GiST indexes contain key attributes, leaf pages
contain both key and non-key attributes, and gist_page_items() ignored
the handling of non-key attributes.  This caused a few problems when
using gist_page_items() on a GiST index with INCLUDE:
- On a non-leaf page, the function would crash.
- On a leaf page, the function would work, but miss to display all the
values for included attributes.

This commit fixes gist_page_items() to handle such cases in a more
appropriate way, and now displays the values of key and non-key
attributes for each item separately in a style consistent with what
ruleutils.c would generate for the attribute list, depending on the page
type dealt with.  In a way similar to how a record is displayed, values
would be double-quoted for key or non-key attributes if required.

ruleutils.c did not provide a routine able to control if non-key
attributes should be displayed, so an extended() routine for index
definitions is added to work around the leaf and non-leaf page
differences.

While on it, this commit fixes a third problem related to the amount of
data reported for key attributes.  The code originally relied on
BuildIndexValueDescription() (used for error reports on constraints)
that would not print all the data stored in the index but the index
opclass's input type, so this limited the amount of information
available.  This switch makes gist_page_items() much cheaper as there is
no need to run ACL checks for each item printed, which is not an issue
anyway as superuser rights are required to execute the functions of
pageinspect.  Opclasses whose data cannot be displayed can rely on
gist_page_items_bytea().

The documentation of this function was slightly incorrect for the
output results generated on HEAD and v15, so adjust it on these
branches.

Author: Alexander Lakhin, Michael Paquier
Discussion: https://postgr.es/m/17884-cb8c326522977acb@postgresql.org
Backpatch-through: 14

2 years agoFix handling of empty ranges and NULLs in BRIN
Tomas Vondra [Thu, 18 May 2023 22:00:22 +0000 (00:00 +0200)]
Fix handling of empty ranges and NULLs in BRIN

BRIN indexes did not properly distinguish between summaries for empty
(no rows) and all-NULL ranges, treating them as essentially the same
thing. Summaries were initialized with allnulls=true, and opclasses
simply reset allnulls to false when processing the first non-NULL value.
This however produces incorrect results if the range starts with a NULL
value (or a sequence of NULL values), in which case we forget the range
contains NULL values when adding the first non-NULL value.

This happens because the allnulls flag is used for two separate
purposes - to mark empty ranges (not representing any rows yet) and
ranges containing only NULL values.

Opclasses don't know which of these cases it is, and so don't know
whether to set hasnulls=true. Setting the flag in both cases would make
it correct, but it would also make BRIN indexes useless for queries with
IS NULL clauses. All ranges start empty (and thus allnulls=true), so all
ranges would end up with either allnulls=true or hasnulls=true.

The severity of the issue is somewhat reduced by the fact that it only
happens when adding values to an existing summary with allnulls=true.
This can happen e.g. for small tables (because a summary for the first
range exists for all BRIN indexes), or for tables with large fraction of
NULL values in the indexed columns.

Bulk summarization (e.g. during CREATE INDEX or automatic summarization)
that processes all values at once is not affected by this issue. In this
case the flags were updated in a slightly different way, not forgetting
the NULL values.

To identify empty ranges we use a new flag, stored in an unused bit in
the BRIN tuple header so the on-disk format remains the same. A matching
flag is added to BrinMemTuple, into a 3B gap after bt_placeholder.
That means there's no risk of ABI breakage, although we don't actually
pass the BrinMemTuple to any public API.

We could also skip storing index tuples for empty summaries, but then
we'd have to always process such ranges - even if there are no rows in
large parts of the table (e.g. after a bulk DELETE), it would still
require reading the pages etc. So we store them, but ignore them when
building the bitmap.

Backpatch to 11. The issue exists since BRIN indexes were introduced in
9.5, but older releases are already EOL.

Backpatch-through: 11
Reviewed-by: Justin Pryzby, Matthias van de Meent, Alvaro Herrera
Discussion: https://postgr.es/m/402430e4-7d9d-6cf1-09ef-464d80afff3b@enterprisedb.com

2 years agoFix handling of NULLs when merging BRIN summaries
Tomas Vondra [Thu, 18 May 2023 11:00:31 +0000 (13:00 +0200)]
Fix handling of NULLs when merging BRIN summaries

When merging BRIN summaries, union_tuples() did not correctly update the
target hasnulls/allnulls flags. When merging all-NULL summary into a
summary without any NULL values, the result had both flags set to false
(instead of having hasnulls=true).

This happened because the code only considered the hasnulls flags,
ignoring the possibility the source summary has allnulls=true.

Discovered while investigating issues with handling empty BRIN ranges
and handling of NULL values, but it's a separate problem (has nothing to
do with empty ranges).

Fixed by considering both flags on the source summary, and updating the
hasnulls flag on the target summary.

Backpatch to 11. The bug exists since 9.5 (where BRIN indexes were
introduced), but those releases are EOL already.

Discussion: https://postgr.es/m/9d993d0d-e431-2196-9ccc-0554d0e60154%40enterprisedb.com

2 years agoEnsure Soundex difference() function handles empty input sanely.
Tom Lane [Tue, 16 May 2023 14:53:42 +0000 (10:53 -0400)]
Ensure Soundex difference() function handles empty input sanely.

fuzzystrmatch's difference() function assumes that _soundex()
always initializes its output buffer fully.  This was not so for
the case of a string containing no alphabetic characters, resulting
in unstable output and Valgrind complaints.

Fix by using memset() to fill the whole buffer in the early-exit
case.  Also make some cosmetic improvements (I didn't care for the
random switches between "instr[0]" and "*instr" notation).

Report and diagnosis by Alexander Lakhin (bug #17935).
Back-patch to all supported branches.

Discussion: https://postgr.es/m/17935-b99316aa79c18513@postgresql.org

2 years agoDoc: Fix link to fillfactor reloption.
Peter Geoghegan [Wed, 10 May 2023 17:49:46 +0000 (10:49 -0700)]
Doc: Fix link to fillfactor reloption.

Fix a link from the "Heap-Only Tuples" documentation section.
Previously, its "fillfactor" link pointed to the "CREATE TABLE"
command's documentation.  Now the link directly points to the fillfactor
storage parameter documentation (which is about half way into the
"CREATE TABLE" sect1).

Oversight in commit 115464bb.

Backpatch: 12-, the first version with a usable reloption link.

2 years agoStamp 14.8. REL_14_8
Tom Lane [Mon, 8 May 2023 21:15:52 +0000 (17:15 -0400)]
Stamp 14.8.

2 years agoLast-minute updates for release notes.
Tom Lane [Mon, 8 May 2023 16:38:08 +0000 (12:38 -0400)]
Last-minute updates for release notes.

Security: CVE-2023-2454, CVE-2023-2455

2 years agoAdjust sepgsql expected output for 681d9e462 et al.
Tom Lane [Mon, 8 May 2023 15:24:47 +0000 (11:24 -0400)]
Adjust sepgsql expected output for 681d9e462 et al.

Security: CVE-2023-2454

2 years agoHandle RLS dependencies in inlined set-returning functions properly.
Tom Lane [Mon, 8 May 2023 14:12:44 +0000 (10:12 -0400)]
Handle RLS dependencies in inlined set-returning functions properly.

If an SRF in the FROM clause references a table having row-level
security policies, and we inline that SRF into the calling query,
we neglected to mark the plan as potentially dependent on which
role is executing it.  This could lead to later executions in the
same session returning or hiding rows that should have been hidden
or returned instead.

Our thanks to Wolfgang Walther for reporting this problem.

Stephen Frost and Tom Lane

Security: CVE-2023-2455

2 years agoReplace last PushOverrideSearchPath() call with set_config_option().
Noah Misch [Mon, 8 May 2023 13:14:07 +0000 (06:14 -0700)]
Replace last PushOverrideSearchPath() call with set_config_option().

The two methods don't cooperate, so set_config_option("search_path",
...) has been ineffective under non-empty overrideStack.  This defect
enabled an attacker having database-level CREATE privilege to execute
arbitrary code as the bootstrap superuser.  While that particular attack
requires v13+ for the trusted extension attribute, other attacks are
feasible in all supported versions.

Standardize on the combination of NewGUCNestLevel() and
set_config_option("search_path", ...).  It is newer than
PushOverrideSearchPath(), more-prevalent, and has no known
disadvantages.  The "override" mechanism remains for now, for
compatibility with out-of-tree code.  Users should update such code,
which likely suffers from the same sort of vulnerability closed here.
Back-patch to v11 (all supported versions).

Alexander Lakhin.  Reported by Alexander Lakhin.

Security: CVE-2023-2454

2 years agoTranslation updates
Peter Eisentraut [Mon, 8 May 2023 12:33:02 +0000 (14:33 +0200)]
Translation updates

Source-Git-URL: https://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 0ef8754efd61f40389ef749bb6ffecd6abc1555b

2 years agoRelease notes for 15.3, 14.8, 13.11, 12.15, 11.20.
Tom Lane [Sun, 7 May 2023 16:36:12 +0000 (12:36 -0400)]
Release notes for 15.3, 14.8, 13.11, 12.15, 11.20.

2 years agoFix typo with wait event for SLRU buffer of commit timestamps
Michael Paquier [Fri, 5 May 2023 12:25:56 +0000 (21:25 +0900)]
Fix typo with wait event for SLRU buffer of commit timestamps

This wait event was documented as "CommitTsBuffer" since its
introduction, but the code named it "CommitTSBuffer".  This commit fixes
the code to follow the term documented, which is also more consistent
with the naming of the other wait events used for commit timestamps.

Introduced by 5da1493.

Author: Alexander Lakhin
Discussion: https://postgr.es/m/e8c38840-596a-83d6-bd8d-cebc51111572@gmail.com
Backpatch-through: 13

2 years agoFix prove_installcheck when used with PGXS
Peter Eisentraut [Fri, 5 May 2023 04:29:49 +0000 (06:29 +0200)]
Fix prove_installcheck when used with PGXS

Commit 153e215677 added the portlock directory.  This is created in
$ENV{top_builddir} if it is set.  Under PGXS, top_builddir points into
the installation directory, which is not necessarily writable and in
any case inappropriate to use by a test suite.  The cause of the
problem is that the prove_installcheck target in Makefile.global
exports top_builddir, which isn't useful (since no other Perl code
actually reads it) and breaks this use case.  The reason this code is
there is probably that is has been dragged around with various other
changes, in particular a0fc813266, but without a real purpose of its
own.  By just removing the exporting of top_builddir in
prove_installcheck, the portlock directory then ends up under
tmp_check in the build directory, which is more suitable.

Reviewed-by: Andrew Dunstan <[email protected]>
Discussion: https://www.postgresql.org/message-id/78d1cfa6-0065-865d-584b-cde6d8c18aff@enterprisedb.com

2 years agoMove return statements out of PG_TRY blocks.
Nathan Bossart [Wed, 3 May 2023 18:32:43 +0000 (11:32 -0700)]
Move return statements out of PG_TRY blocks.

If we exit a PG_TRY block early via "continue", "break", "goto", or
"return", we'll skip unwinding its exception stack.  This change
moves a couple of such "return" statements in PL/Python out of
PG_TRY blocks.  This was introduced in d0aa965c0a and affects all
supported versions.

We might also be able to add compile-time checks to prevent
recurrence, but that is left as a future exercise.

Reported-by: Mikhail Gribkov, Xing Guo
Author: Xing Guo
Reviewed-by: Michael Paquier, Andres Freund, Tom Lane
Discussion: https://postgr.es/m/CAMEv5_v5Y%2B-D%3DCO1%2Bqoe16sAmgC4sbbQjz%2BUtcHmB6zcgS%2B5Ew%40mail.gmail.com
Discussion: https://postgr.es/m/CACpMh%2BCMsGMRKFzFMm3bYTzQmMU5nfEEoEDU2apJcc4hid36AQ%40mail.gmail.com
Backpatch-through: 11 (all supported versions)

2 years agoIn array_position()/array_positions(), beware of empty input array.
Tom Lane [Thu, 4 May 2023 15:48:23 +0000 (11:48 -0400)]
In array_position()/array_positions(), beware of empty input array.

These functions incautiously fetched the array's first lower bound
even when the array is zero-dimensional, thus fetching the word
after the allocated array space.  While almost always harmless,
with very bad luck this could result in SIGSEGV.  Fix by adding
an early exit for empty input.

Per bug #17920 from Alexander Lakhin.

Discussion: https://postgr.es/m/17920-f7c228c627b6d02e%40postgresql.org

2 years agoTighten array dimensionality checks in Python -> SQL array conversion.
Tom Lane [Thu, 4 May 2023 15:00:33 +0000 (11:00 -0400)]
Tighten array dimensionality checks in Python -> SQL array conversion.

Like plperl before f47004add, plpython wasn't being sufficiently
careful about checking that list-of-list structures represent
rectangular arrays, so that it would accept some cases in which
different parts of the "array" are nested to different depths.
This was exacerbated by Python's weak distinction between
sequences and lists, so that in some cases strings could get
treated as though they are lists (and burst into individual
characters) even though a different ordering of the upper-level
list would give a different result.

Some of this behavior was unreachable (without risking a crash)
before 81eaaf65e.  It seems like a good idea to clean it all up
in the same releases, rather than shipping a non-crashing but
nonetheless visibly buggy behavior in the name of minimal change.
Hence, back-patch.

Per bug #17912 and further testing by Alexander Lakhin.

Discussion: https://postgr.es/m/17912-82ceed78731d9cdc@postgresql.org

2 years agoDoc: clarify behavior of row-limit arguments in the PLs' SPI wrappers.
Tom Lane [Tue, 2 May 2023 21:55:01 +0000 (17:55 -0400)]
Doc: clarify behavior of row-limit arguments in the PLs' SPI wrappers.

plperl, plpython, and pltcl all provide query-execution functions
that are thin wrappers around SPI_execute() or its variants.
The SPI functions document their row-count limit arguments clearly,
as "maximum number of rows to return, or 0 for no limit".  However
the PLs' documentation failed to explain this special behavior of
zero, so that a reader might well assume it means "fetch zero
rows".  Improve that.

Daniel Gustafsson and Tom Lane, per report from Kieran McCusker

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

2 years agodoc: Fix typo in pg_amcheck for term "schema"
Michael Paquier [Tue, 2 May 2023 02:41:00 +0000 (11:41 +0900)]
doc: Fix typo in pg_amcheck for term "schema"

Author: Alexander Lakhin
Discussion: https://postgr.es/m/e8c38840-596a-83d6-bd8d-cebc51111572@gmail.com
Backpatch-through: 14

2 years agoTighten array dimensionality checks in Perl -> SQL array conversion.
Tom Lane [Sat, 29 Apr 2023 17:06:44 +0000 (13:06 -0400)]
Tighten array dimensionality checks in Perl -> SQL array conversion.

plperl_array_to_datum() wasn't sufficiently careful about checking
that nested lists represent a rectangular array structure; it would
accept inputs such as "[1, []]".  This is a bit related to the
PL/Python bug fixed in commit 81eaaf65e, but it doesn't seem to
provide any direct route to a memory stomp.  Instead the likely
failure mode is for makeMdArrayResult to be passed fewer Datums than
the claimed array dimensionality requires, possibly leading to a wild
pointer dereference and SIGSEGV.

Per report from Alexander Lakhin.  It's been broken for a long
time, so back-patch to all supported branches.

Discussion: https://postgr.es/m/5ebae5e4-d401-fadf-8585-ac3eaf53219c@gmail.com

2 years agoHandle zero-length sublist correctly in Python -> SQL array conversion.
Tom Lane [Fri, 28 Apr 2023 16:24:29 +0000 (12:24 -0400)]
Handle zero-length sublist correctly in Python -> SQL array conversion.

If PLySequence_ToArray came across a zero-length sublist, it'd compute
the overall array size as zero, possibly leading to a memory clobber.
(This would likely qualify as a security bug, were it not that plpython
is an untrusted language already.)

I think there are other corner-case issues in this code as well, notably
that the error messages don't match the core code and for some ranges
of array sizes you'd get "invalid memory alloc request size" rather than
the intended message about array size.

Really this code has no business doing its own array size calculation
at all, so remove the faulty code in favor of using ArrayGetNItems().

Per bug #17912 from Alexander Lakhin.  Bug seems to have come in with
commit 94aceed31, so back-patch to all supported branches.

Discussion: https://postgr.es/m/17912-82ceed78731d9cdc@postgresql.org

2 years agoFix crashes with CREATE SCHEMA AUTHORIZATION and schema elements
Michael Paquier [Fri, 28 Apr 2023 10:29:38 +0000 (19:29 +0900)]
Fix crashes with CREATE SCHEMA AUTHORIZATION and schema elements

CREATE SCHEMA AUTHORIZATION with appended schema elements can lead to
crashes when comparing the schema name of the query with the schemas
used in the qualification of some clauses in the elements' queries.

The origin of the problem is that the transformation routine for the
elements listed in a CREATE SCHEMA query uses as new, expected, schema
name the one listed in CreateSchemaStmt itself.  However, depending on
the query, CreateSchemaStmt.schemaname may be NULL, being computed
instead from the role specification of the query given by the
AUTHORIZATION clause, that could be either:
- A user name string, with the new schema name being set to the same
value as the role given.
- Guessed from CURRENT_ROLE, SESSION_ROLE or CURRENT_ROLE, with a new
schema name computed from the security context where CREATE SCHEMA is
running.

Regression tests are added for CREATE SCHEMA with some appended elements
(some of them with schema qualifications), covering also some role
specification patterns.

While on it, this simplifies the context structure used during the
transformation of the elements listed in a CREATE SCHEMA query by
removing the fields for the role specification and the role type.  They
were not used, and for the role specification this could be confusing as
the schema name may by extracted from that at the beginning of
CreateSchemaCommand().

This issue exists for a long time, so backpatch down to all the versions
supported.

Reported-by: Song Hongyu
Author: Michael Paquier
Reviewed-by: Richard Guo
Discussion: https://postgr.es/m/17909-f65c12dfc5f0451d@postgresql.org
Backpatch-through: 11

2 years agoPrevent underflow in KeepLogSeg().
Nathan Bossart [Thu, 27 Apr 2023 20:43:48 +0000 (13:43 -0700)]
Prevent underflow in KeepLogSeg().

The call to XLogGetReplicationSlotMinimumLSN() might return a
greater LSN than the one given to the function.  Subsequent segment
number calculations might then underflow, which could result in
unexpected behavior when removing or recyling WAL files.  This was
introduced with max_slot_wal_keep_size in c655077639.  To fix, skip
the block of code for replication slots if the LSN is greater.

Reported-by: Xu Xingwang
Author: Kyotaro Horiguchi
Reviewed-by: Junwang Zhao
Discussion: https://postgr.es/m/17903-4288d439dee856c6%40postgresql.org
Backpatch-through: 13

2 years agoIn hstore_plpython, avoid crashing when return value isn't a mapping.
Tom Lane [Thu, 27 Apr 2023 15:55:06 +0000 (11:55 -0400)]
In hstore_plpython, avoid crashing when return value isn't a mapping.

Python 3 changed the behavior of PyMapping_Check(), breaking the
test in plpython_to_hstore() that verifies whether a function result
to be transformed is acceptable.  A backwards-compatible fix is to
first verify that the object doesn't pass PySequence_Check().

Perhaps accidentally, our other uses of PyMapping_Check() already
follow uses of PySequence_Check(), so that no other bugs were
created by this change.

Per bug #17908 from Alexander Lakhin.  Back-patch to all supported
branches.

Dmitry Dolgov and Tom Lane

Discussion: https://postgr.es/m/17908-3f19a125d56a11d6@postgresql.org

2 years agoRe-add tracking of wait event SLRUFlushSync
Michael Paquier [Tue, 25 Apr 2023 22:30:47 +0000 (07:30 +0900)]
Re-add tracking of wait event SLRUFlushSync

SLRUFlushSync has been accidently removed during dee663f, that has moved
the flush of the SLRU files to the checkpointer, so add it back.  The
issue has been noticed by Thomas when checking for orphaned wait
events.

Author: Thomas Munro
Reviewed-by: Bharath Rupireddy
Discussion: https://postgr.es/m/CA+hUKGK6tqm59KuF1z+h5Y8fsWcu5v8+84kduSHwRzwjB2aa_A@mail.gmail.com

2 years agoFix vacuum_cost_delay check for balance calculation.
Daniel Gustafsson [Tue, 25 Apr 2023 11:54:10 +0000 (13:54 +0200)]
Fix vacuum_cost_delay check for balance calculation.

Commit 1021bd6a89 excluded autovacuum workers from cost-limit balance
calculations when per-relation options were set.  The code checks for
limit and cost_delay being greater than zero, but since cost_delay can
be set to -1 the test needs to check for greater than or zero.

Backpatch to all supported branches since 1021bd6a89 was backpatched
all the way at the time.

Author: Masahiko Sawada <[email protected]>
Reviewed-by: Melanie Plageman <[email protected]>
Reviewed-by: Daniel Gustafsson <[email protected]>
Discussion: https://postgr.es/m/CAD21AoBS7o6Ljt_vfqPQPf67AhzKu3fR0iqk8B=vVYczMugKMQ@mail.gmail.com
Backpatch-through: v11 (all supported branches)

2 years agoFix buffer refcount leak with FDW bulk inserts
Michael Paquier [Tue, 25 Apr 2023 00:42:36 +0000 (09:42 +0900)]
Fix buffer refcount leak with FDW bulk inserts

The leak would show up when using batch inserts with foreign tables
included in a partition tree, as the slots used in the batch were not
reset once processed.  In order to fix this problem, some
ExecClearTuple() are added to clean up the slots used once a batch is
filled and processed, mapping with the number of slots currently in use
as tracked by the counter ri_NumSlots.

This buffer refcount leak has been introduced in b676ac4 with the
addition of the executor facility to improve bulk inserts for FDWs, so
backpatch down to 14.

Alexander has provided the patch (slightly modified by me).  The test
for postgres_fdw comes from me, based on the test case that the author
has sent in the report.

Author: Alexander Pyhalov
Discussion: https://postgr.es/m/b035780a740efd38dc30790c76927255@postgrespro.ru
Backpatch-through: 14

2 years agoFix memory leakage in plpgsql DO blocks that use cast expressions.
Tom Lane [Mon, 24 Apr 2023 18:19:46 +0000 (14:19 -0400)]
Fix memory leakage in plpgsql DO blocks that use cast expressions.

Commit 04fe805a1 modified plpgsql so that datatype casts make use of
expressions cached by plancache.c, in place of older code where these
expression trees were managed by plpgsql itself.  However, I (tgl)
forgot that we use a separate, shorter-lived cast info hashtable in
DO blocks.  The new mechanism thus resulted in session-lifespan
leakage of the plancache data once a DO block containing one or more
casts terminated.  To fix, split the cast hash table into two parts,
one that tracks only the plancache's CachedExpressions and one that
tracks the expression state trees generated from them.  DO blocks need
their own expression state trees and hence their own version of the
second hash table, but there's no reason they can't share the
CachedExpressions with regular plpgsql functions.

Per report from Ajit Awekar.  Back-patch to v12 where the issue
was introduced.

Ajit Awekar and Tom Lane

Discussion: https://postgr.es/m/CAHv6PyrNaqdvyWUspzd3txYQguFTBSnhx+m6tS06TnM+KWc_LQ@mail.gmail.com

2 years agoRemove duplicate lines of code
Daniel Gustafsson [Mon, 24 Apr 2023 09:16:17 +0000 (11:16 +0200)]
Remove duplicate lines of code

Commit 6df7a9698bb accidentally included two identical prototypes for
default_multirange_selectivi() and commit 086cf1458c6 added a break;
statement where one was already present, thus duplicating it.  While
there is no bug caused by this, fix by removing the duplicated lines
as they provide no value.

Backpatch the fix for duplicate prototypes to v14 and the duplicate
break statement fix to all supported branches to avoid backpatching
hazards due to the removal.

Reported-by: Anton Voloshin <[email protected]>
Discussion: https://postgr.es/m/0e69cb60-0176-f6d0-7e15-6478b7d85724@postgrespro.ru

2 years agoValidate ltree siglen GiST option to be int-aligned
Alexander Korotkov [Sun, 23 Apr 2023 10:58:25 +0000 (13:58 +0300)]
Validate ltree siglen GiST option to be int-aligned

Unaligned siglen could lead to an unaligned access to subsequent key fields.

Backpatch to 13, where opclass options were introduced.

Reported-by: Alexander Lakhin
Bug: 17847
Discussion: https://postgr.es/m/17847-171232970bea406b%40postgresql.org
Reviewed-by: Tom Lane, Pavel Borisov, Alexander Lakhin
Backpatch-through: 13

2 years agoFix custom validators call in build_local_reloptions()
Alexander Korotkov [Sun, 23 Apr 2023 10:55:49 +0000 (13:55 +0300)]
Fix custom validators call in build_local_reloptions()

We need to call them only when validate == true.

Backpatch to 13, where opclass options were introduced.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/2656633.1681831542%40sss.pgh.pa.us
Reviewed-by: Tom Lane, Pavel Borisov
Backpatch-through: 13

2 years agoAvoid character classification in regex escape parsing.
Jeff Davis [Fri, 21 Apr 2023 15:19:41 +0000 (08:19 -0700)]
Avoid character classification in regex escape parsing.

For regex escape sequences, just test directly for the relevant ASCII
characters rather than using locale-sensitive character
classification.

This fixes an assertion failure when a locale considers a non-ASCII
character, such as "൧", to be a digit.

Reported-by: Richard Guo
Discussion: https://postgr.es/m/CAMbWs49Q6UoKGeT8pBkMtJGJd+16CBFZaaWUk9Du+2ERE5g_YA@mail.gmail.com
Backpatch-through: 11

2 years agoUse --strip-unneeded when stripping static libraries with GNU strip.
Tom Lane [Thu, 20 Apr 2023 22:12:32 +0000 (18:12 -0400)]
Use --strip-unneeded when stripping static libraries with GNU strip.

We've long used "--strip-unneeded" for shared libraries but plain
"-x" for static libraries when stripping symbols with GNU strip.
There doesn't seem to be any really good reason for that though,
since --strip-unneeded produces smaller output (as "-x" alone
does not remove debug symbols).  Moreover it seems that
llvm-strip, although it identifies as GNU strip, misbehaves when
given "-x" for this purpose.  It's unclear whether that's
intentional or a bug in llvm-strip, but in any case it seems like
changing to use --strip-unneeded in all cases should be a win.

Note that this doesn't change our behavior when dealing with
non-GNU strip.

Per gripes from Ed Maste and Palle Girgensohn.  Back-patch,
in case anyone wants to use llvm-strip with stable branches.

Discussion: https://postgr.es/m/17898-5308d09543463266@postgresql.org
Discussion: https://postgr.es/m/20230420153338[email protected]

2 years agoUpdate time zone data files to tzdata release 2023c.
Tom Lane [Tue, 18 Apr 2023 18:46:39 +0000 (14:46 -0400)]
Update time zone data files to tzdata release 2023c.

DST law changes in Egypt, Greenland, Morocco, and Palestine.

When observing Moscow time, Europe/Kirov and Europe/Volgograd now
use the abbreviations MSK/MSD instead of numeric abbreviations,
for consistency with other timezones observing Moscow time.

Also, America/Yellowknife is no longer distinct from America/Edmonton;
this affects some pre-1948 timestamps in that area.

2 years agoecpg: Fix handling of strings in ORACLE compat code with SQLDA
Michael Paquier [Tue, 18 Apr 2023 02:20:50 +0000 (11:20 +0900)]
ecpg: Fix handling of strings in ORACLE compat code with SQLDA

When compiled with -C ORACLE, ecpg_get_data() had a one-off issue where
it would incorrectly store the null terminator byte to str[-1] when
varcharsize is 0, which is something that can happen when using SQLDA.
This would eat 1 byte from the previous field stored, corrupting the
results generated.

All the callers of ecpg_get_data() estimate and allocate enough storage
for the data received, and the fix of this commit relies on this
assumption.  Note that this maps to the case where no padding or
truncation is required.

This issue has been introduced by 3b7ab43 with the Oracle compatibility
option, so backpatch down to v11.

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

2 years agoAvoid trying to write an empty WAL record in log_newpage_range().
Tom Lane [Mon, 17 Apr 2023 18:22:06 +0000 (14:22 -0400)]
Avoid trying to write an empty WAL record in log_newpage_range().

If the last few pages in the specified range are empty (all zero),
then log_newpage_range() could try to emit an empty WAL record
containing no FPIs.  This at least upsets an Assert in
ReserveXLogInsertLocation, and might perhaps have bad real-world
consequences in non-assert builds.

This has been broken since log_newpage_range() was introduced,
but the case was hard if not impossible to hit before commit 3d6a98457
decided it was okay to leave VM and FSM pages intentionally zero.
Nonetheless, it seems prudent to back-patch.  log_newpage_range()
was added in v12 but later back-patched, so this affects all
supported branches.

Matthias van de Meent, per report from Justin Pryzby

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

2 years agoFix assignment to array of domain over composite, redux.
Tom Lane [Sat, 15 Apr 2023 16:01:39 +0000 (12:01 -0400)]
Fix assignment to array of domain over composite, redux.

Commit 3e310d837 taught isAssignmentIndirectionExpr() to look through
CoerceToDomain nodes.  That's not sufficient, because since commit
04fe805a1 it's been possible for the planner to simplify
CoerceToDomain to RelabelType when the domain has no constraints
to enforce.  So we need to look through RelabelType too.

Per bug #17897 from Alexander Lakhin.  Although 3e310d837 was
back-patched to v11, it seems sufficient to apply this change
to v12 and later, since 04fe805a1 came in in v12.

Dmitry Dolgov

Discussion: https://postgr.es/m/17897-4216c546c3874044@postgresql.org

2 years agodoc: PQinitOpenSSL and PQinitSSL are obsolete in OpenSSL 1.1.0+
Daniel Gustafsson [Fri, 14 Apr 2023 08:15:50 +0000 (10:15 +0200)]
doc: PQinitOpenSSL and PQinitSSL are obsolete in OpenSSL 1.1.0+

Starting with OpenSSL 1.1.0 there is no need to call PQinitOpenSSL
or PQinitSSL to avoid duplicate initialization of OpenSSL.  Add a
note to the documentation to explain this.

Backpatch to all supported versions as older OpenSSL versions are
equally likely to be used for all branches.

Reported-by: Sebastien Flaesch <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/DBAP191MB12895BFFEC4B5FE0460D0F2FB0459@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM
Backpatch-through: 11, all supported versions

2 years agoFix incorrect partition pruning logic for boolean partitioned tables
David Rowley [Fri, 14 Apr 2023 04:21:42 +0000 (16:21 +1200)]
Fix incorrect partition pruning logic for boolean partitioned tables

The partition pruning logic assumed that "b IS NOT true" was exactly the
same as "b IS FALSE".  This is not the case when considering NULL values.
Fix this so we correctly include any partition which could hold NULL
values for the NOT case.

Additionally, this fixes a bug in the partition pruning code which handles
partitioned tables partitioned like ((NOT boolcol)).  This is a seemingly
unlikely schema design, and it was untested and also broken.

Here we add tests for the ((NOT boolcol)) case and insert some actual data
into those tables and verify we do get the correct rows back when running
queries.  I've also adjusted the existing boolpart tests to include some
data and verify we get the correct results too.

Both the bugs being fixed here could lead to incorrect query results with
fewer rows being returned than expected.  No additional rows could have
been returned accidentally.

In passing, remove needless ternary expression.  It's more simple just to
pass !is_not_clause to makeBoolConst().  It makes sense to do this so the
code is consistent with the bug fix in the "else if" condition just below.

David Kimura did submit a patch to fix the first of the issues here, but
that's not what's being committed here.

Reported-by: David Kimura
Reviewed-by: Richard Guo, David Kimura
Discussion: https://postgr.es/m/CAHnPFjQ5qxs6J_p+g8=ww7GQvfn71_JE+Tygj0S7RdRci1uwPw@mail.gmail.com
Backpatch-through: 11, all supported versions

2 years agoFix parallel-safety marking when moving initplans to another node.
Tom Lane [Wed, 12 Apr 2023 14:46:30 +0000 (10:46 -0400)]
Fix parallel-safety marking when moving initplans to another node.

Our policy since commit ab77a5a45 has been that a plan node having
any initplans is automatically not parallel-safe.  (This could be
relaxed, but not today.)  clean_up_removed_plan_level neglected
this, and could attach initplans to a parallel-safe child plan
node without clearing the plan's parallel-safe flag.  That could
lead to "subplan was not initialized" errors at runtime, in case
an initplan referenced another one and only the referencing one
got transmitted to parallel workers.

The fix in clean_up_removed_plan_level is trivial enough.
materialize_finished_plan also moves initplans from one node
to another, but it's okay because it already copies the source
node's parallel_safe flag.  The other place that does this kind
of thing is standard_planner's hack to inject a top-level Gather
when debug_parallel_query is active.  But that's actually dead
code given that we're correctly enforcing the "initplans aren't
parallel safe" rule, so just replace it with an Assert that
there are no initplans.

Also improve some related comments.

Normally we'd add a regression test case for this sort of bug.
The mistake itself is already reached by existing tests, but there
is accidentally no visible problem.  The only known test case that
creates an actual failure seems too indirect and fragile to justify
keeping it as a regression test (not least because it fails to fail
in v11, though the bug is clearly present there too).

Per report from Justin Pryzby.  Back-patch to all supported branches.

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

2 years agoFix detection of unseekable files for fseek() and ftello() with MSVC
Michael Paquier [Wed, 12 Apr 2023 00:09:58 +0000 (09:09 +0900)]
Fix detection of unseekable files for fseek() and ftello() with MSVC

Calling fseek() or ftello() on a handle to a non-seeking device such as
a pipe or a communications device is not supported.  Unfortunately,
MSVC's flavor of these routines, _fseeki64() and _ftelli64(), do not
return an error when given a pipe as handle.  Some of the logic of
pg_dump and restore relies on these routines to check if a handle is
seekable, causing failures when passing the contents of pg_dump to
pg_restore through a pipe, for example.

This commit introduces wrappers for fseeko() and ftello() on MSVC so as
any callers are able to properly detect the cases of non-seekable
handles.  This relies mainly on GetFileType(), sharing a bit of code
with the MSVC port for fstat().  The code in charge of getting a file
type is refactored into a new file called win32common.c, shared by
win32stat.c and the new win32fseek.c.  It includes the MSVC ports for
fseeko() and ftello().

Like 765f5df, this is backpatched down to 14, where the fstat()
implementation for MSVC is able to understand about files larger than
4GB in size.  Using a TAP test for that is proving to be tricky as
IPC::Run handles the pipes by itself, still I have been able to check
the fix manually.

Reported-by: Daniel Watzinger
Author: Juan José Santamaría Flecha, Michael Paquier
Discussion: https://postgr.es/m/CAC+AXB26a4EmxM2suXxPpJaGrqAdxracd7hskLg-zxtPB50h7A@mail.gmail.com
Backpatch-through: 14

2 years agoDoc: add missed entries in BRIN extensibility tables.
Tom Lane [Mon, 10 Apr 2023 19:49:48 +0000 (15:49 -0400)]
Doc: add missed entries in BRIN extensibility tables.

The tables in "71.3. Extensibility" listing the support functions
for bloom and minmax-multi opclasses should include the associated
options function.  While this isn't quite as required as the rest,
you need it for full functionality of the opclass.

Back-patch to v14 where these functions were added.

2 years agoDoc: adjust examples of EXTRACT() output to match current reality.
Tom Lane [Mon, 10 Apr 2023 17:09:18 +0000 (13:09 -0400)]
Doc: adjust examples of EXTRACT() output to match current reality.

EXTRACT(EPOCH), EXTRACT(SECOND), and some related cases print more
trailing zeroes than they used to.  This behavior change happened
with commit a2da77cdb (Change return type of EXTRACT to numeric),
and it was intentional according to the commit log:

    - Return values when extracting fields with possibly fractional
      values, such as second and epoch, now have the full scale that the
      value has internally (so, for example, '1.000000' instead of just
      '1').

It's been like that for two releases now, so while I suggested
changing this back, it's probably better to adjust the documentation
examples.

Per bug #17866 from Евгений Жужнев.  Back-patch to v14 where the
change came in.

Discussion: https://postgr.es/m/17866-18eb70095b1594e2@postgresql.org

2 years agoFor Kerberos testing, disable DNS lookups
Stephen Frost [Fri, 7 Apr 2023 23:36:12 +0000 (19:36 -0400)]
For Kerberos testing, disable DNS lookups

Similar to 8dff2f224, this disables DNS lookups by the Kerberos library
to look up the KDC and the realm while the Kerberos tests are running.
In some environments, these lookups can take a long time and end up
timing out and causing tests to fail.  Further, since this isn't really
our domain, we shouldn't be sending out these DNS requests during our
tests.

2 years agoFor Kerberos testing, disable reverse DNS lookup
Stephen Frost [Fri, 7 Apr 2023 23:36:12 +0000 (19:36 -0400)]
For Kerberos testing, disable reverse DNS lookup

In our Kerberos test suite, there isn't much need to worry about the
normal canonicalization that Kerberos provides by looking up the reverse
DNS for the IP address connected to, and in some cases it can actively
cause problems (eg: a captive portal wifi where the normally not
resolvable localhost address used ends up being resolved anyway, and
not to the domain we are using for testing, causing the entire
regression test to fail with errors about not being able to get a TGT
for the remote realm for cross-realm trust).

Therefore, disable it by adding rdns = false into the krb5.conf that's
generated for the test.

Reviewed-By: Heikki Linnakangas
Discussion: https://postgr.es/m/Y/[email protected]

2 years agoStabilize just-added regression test cases.
Tom Lane [Thu, 6 Apr 2023 22:13:49 +0000 (18:13 -0400)]
Stabilize just-added regression test cases.

The tests added by commits 029dea882 et al turn out to produce
different output under -DRANDOMIZE_ALLOCATED_MEMORY.  This is
not a bug exactly: that flag causes coerce_type() to invoke
the input function twice when coercing an unknown-type literal
to a specific type.  So you get tsqueryin's bleat about an empty
tsquery twice.  Revise the test query to avoid that.

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

2 years agoFix ts_headline() edge cases for empty query and empty search text.
Tom Lane [Thu, 6 Apr 2023 19:52:37 +0000 (15:52 -0400)]
Fix ts_headline() edge cases for empty query and empty search text.

tsquery's GETQUERY() macro is only safe to apply to a tsquery
that is known non-empty; otherwise it gives a pointer to garbage.
Before commit 5a617d75d, ts_headline() avoided this pitfall, but
only in a very indirect, nonobvious way.  (hlCover could not reach
its TS_execute call, because if the query contains no lexemes
then hlFirstIndex would surely return -1.)  After that commit,
it fell into the trap, resulting in weird errors such as
"unrecognized operator" and/or valgrind complaints.  In HEAD,
fix this by not calling TS_execute_locations() at all for an
empty query.  In the back branches, add a defensive check to
hlCover() --- that's not fixing any live bug, but I judge the
code a bit too fragile as-is.

Also, both mark_hl_fragments() and mark_hl_words() were careless
about the possibility of empty search text: in the cases where
no match has been found, they'd end up telling mark_fragment() to
mark from word indexes 0 to 0 inclusive, even when there is no
word 0.  This is harmless since we over-allocated the prs->words
array, but it does annoy valgrind.  Fix so that the end index is -1
and thus mark_fragment() will do nothing in such cases.

Bottom line is that this fixes a live bug in HEAD, but in the
back branches it's only getting rid of a valgrind nitpick.
Back-patch anyway.

Per report from Alexander Lakhin.

Discussion: https://postgr.es/m/c27f642d-020b-01ff-ae61-086af287c4fd@gmail.com

2 years agoFix another issue with ENABLE/DISABLE TRIGGER on partitioned tables.
Tom Lane [Wed, 5 Apr 2023 16:56:30 +0000 (12:56 -0400)]
Fix another issue with ENABLE/DISABLE TRIGGER on partitioned tables.

In v13 and v14, the ENABLE/DISABLE TRIGGER USER variant malfunctioned
on cloned triggers, failing to find the clones because it thought they
were system triggers.  Other variants of ENABLE/DISABLE TRIGGER would
improperly apply a superuserness check.  Fix by adjusting the is-it-
a-system-trigger check to match reality in those branches.  (As far
as I can find, this is the only place that got it wrong.)

There's no such bug in v15/HEAD, because we revised the catalog
representation of system triggers to be what this code was expecting.
However, add the test case to these branches anyway, because this area
is visibly pretty fragile.  Also remove an obsoleted comment.

The recent v15/HEAD commit 6949b921d fixed a nearby bug.  I now see
that my commit message for that was inaccurate: the behavior of
recursing to clone triggers is older than v15, but it didn't apply
to the case in v13/v14 because in those branches parent partitioned
tables have no pg_trigger entries for foreign-key triggers.  But add
the test case from that commit to v13/v14, just to show what is
happening there.

Per bug #17886 from DzmitryH.

Discussion: https://postgr.es/m/17886-5406d5d828aa4aa3@postgresql.org

2 years agodoc: Update error messages in RLS examples
John Naylor [Wed, 5 Apr 2023 07:16:19 +0000 (14:16 +0700)]
doc: Update error messages in RLS examples

Since 8b9e9644d, the messages for failed permissions checks report
"table" where appropriate, rather than "relation".

Backpatch to all supported branches