Commit graph

28793 commits

Author SHA1 Message Date
Peter Eisentraut
57f93af36f Resolve unknown-type literals in property expressions
When a string literal is provided as a property expression, the data
type of the property was set to "unknown", which may lead to various
failures when the property is used in GRAPH_TABLE or when its data
type is compared against other properties with the same name.  To fix
this, call resolveTargetListUnknowns() on the targetlist of new
properties being added to resolve unknown type literals.

Reported-by: Noah Misch <noah@leadboat.com>
Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/20260630173053.51.noahmisch%40microsoft.com
2026-07-08 10:34:31 +02:00
Peter Eisentraut
16a4b3ef8e Fix replace_property_refs() ignoring the root of expression tree
replace_property_refs() called expression_tree_mutator() with the root
of the expression tree as the input node.  But
expression_tree_mutator() does not call the mutator function on the
root node, so the root node remains unchanged.  If the root node is a
property reference or a lateral reference -- the two node kinds that
replace_property_refs_mutator() rewrites -- it is returned unchanged.
Modules after the rewriter do not know about property reference nodes,
resulting in "ERROR: unrecognized node type: 63".  Since varlevelsup
of lateral references is not incremented, they are not resolved
correctly in the planner, leading to many different symptoms.  Fix
this by calling replace_property_refs_mutator() directly from
replace_property_refs(), similar to how other mutator functions do.

The only case when a property reference or a lateral reference can be
the root of a GRAPH_TABLE expression tree is when it is a bare
property reference or a bare lateral reference in the WHERE clause.
The COLUMNS clause is passed to replace_property_refs() as a
targetlist.  Every other expression has at least one expression node
covering the property reference or a lateral reference in the
expression tree.  That explains why this bug was not seen so far.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reported-by: Noah Misch <noah@leadboat.com>
Discussion: https://www.postgresql.org/message-id/flat/20260630173053.51.noahmisch%40microsoft.com
2026-07-08 09:57:02 +02:00
Michael Paquier
d92e98340f Fix more Datum conversion inconsistencies
This is a continuation of the work done in ac59a90bef.  The
*GetDatum() macros for output should match with what the SQL functions
use as DatumGet*() in input.

Aleksander has spotted some of the areas patched here, for pageinspect.
I have spotted the rest while digging into the state of the tree.

There is no behavior change after this commit, since all the affected
values are small enough that the signed bit is never used.

Author: Aleksander Alekseev <aleksander@tigerdata.com>
Author: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/afLsqRjVqKK8hhKk@paquier.xyz
2026-07-08 13:22:50 +09:00
Richard Guo
4721430f19 Tighten nullingrels checks for outer joins
When fixing up the targetlist and qpqual of an outer join, we must
account for the effects of the outer join.  Vars and PHVs appearing
there are logically above the join, so they should have nullingrels
equal to the input Vars/PHVs' nullingrels plus the bit added by the
outer join.

Determining the effects of the outer join can be tricky when the join
has been commuted with another one per outer join identity 3.  In this
case, the Vars/PHVs in the join's targetlist and qpqual should have
the same nullingrels that they would if the two joins had been done in
syntactic order.  Unfortunately, in setrefs.c, we don't have enough
information to identify what that should be, so we have to use
superset nullingrels matches instead of exact ones.

However, we can tighten the check somewhat.  Currently, we check
whether the jointype is JOIN_INNER and use NRM_SUPERSET if it is not.
We can improve this by checking whether the Join node has non-empty
ojrelids and using NRM_SUPERSET only in that case.  This allows us to
perform exact matches in more situations.

To support this, we record the outer-join relids in Join plan nodes.
This information can also improve EXPLAIN (RANGE_TABLE) output by
showing which outer-join relids are completed by each Join plan node.
We may discover additional uses for this information in the future.

Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAMbWs482_DFHzQ079ZPp6c8UvmFdz3Jj+4K8tVRu9g2Bw34NPA@mail.gmail.com
2026-07-08 12:02:21 +09:00
Richard Guo
3b0991059f Remove nrm_match parameter from fix_upper_expr
With the changes in the previous commit, we can now use exact
nullingrels matches in all cases when fixing up expressions of
upper-level plan nodes that are not joins.  Therefore, we can remove
the nrm_match parameter from fix_upper_expr(), along with the
corresponding field in fix_upper_expr_context.

Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAMbWs482_DFHzQ079ZPp6c8UvmFdz3Jj+4K8tVRu9g2Bw34NPA@mail.gmail.com
2026-07-08 12:01:44 +09:00
Richard Guo
9dce6b5a42 Use exact nullingrels matches for NestLoopParams
We have been using NRM_SUBSET to process NestLoopParams in setrefs.c,
because Vars or PHVs in NestLoopParam expressions may previously have
had nullingrels that were just subsets of those in the Vars or PHVs
actually available from the outer side.

Since 66e9df9f6, identify_current_nestloop_params ensures that any
Vars or PHVs seen in a NestLoopParam expression have nullingrels that
include exactly the outer-join relids that appear in the outer side's
output and can null the respective Var or PHV.  As noted in that
commit's message, we can now safely use NRM_EQUAL to process
NestLoopParams in setrefs.c.

This patch makes that change and removes the definition of NRM_SUBSET,
along with all remaining checks for it, since it is no longer used.

Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAMbWs482_DFHzQ079ZPp6c8UvmFdz3Jj+4K8tVRu9g2Bw34NPA@mail.gmail.com
2026-07-08 12:00:36 +09:00
Jeff Davis
e6e08dc554 pg_locale_libc.c: add missing casts to unsigned char.
Discussion: https://postgr.es/m/20260630012919.78@rfd.leadboat.com
Backpatch-through: 19
2026-07-07 18:20:15 -07:00
Jeff Davis
dbbeafe61a pg_locale_libc.c: add guards to ctype methods.
Necessary for 16-bit wchar_t platforms (Windows).

Other guards are just defensive. Also correct style issue with
branches.

Reported-by: Noah Misch <noah@leadboat.com>
Discussion: https://postgr.es/m/20260630012919.78@rfd.leadboat.com
Backpatch-through: 19
2026-07-07 18:20:06 -07:00
Jeff Davis
3ab2abc949 Fix obsolete comment.
Reported-by: Noah Misch <noah@leadboat.com>
Discussion: https://postgr.es/m/20260630012919.78@rfd.leadboat.com
Backpatch-through: 19
2026-07-07 18:19:59 -07:00
Jeff Davis
d34ce773d2 Fix unintentional behavior change from 5a38104b36.
Reported-by: Noah Misch <noah@leadboat.com>
Discussion: https://postgr.es/m/20260630012919.78@rfd.leadboat.com
Backpatch-through: 19
2026-07-07 18:04:33 -07:00
Richard Guo
906b1e4a19 Propagate stadistinct through GROUP BY/DISTINCT in subqueries and CTEs
Previously, examine_simple_variable() would return early when a
subquery or CTE used GROUP BY or DISTINCT.  It could detect uniqueness
for single-column cases, but for multi-column GROUP BY or DISTINCT,
selectivity estimation fell back on 1/DEFAULT_NUM_DISTINCT (1/200).
This produced wildly inaccurate estimates for filters and joins on
such columns, often leading the planner to choose nested loop joins
where hash joins would be far better.  This was a significant factor
in poor TPC-DS benchmark performance.

For DISTINCT or GROUP BY key columns that are simple Vars, we now
recurse into the subquery to obtain the base table's stadistinct,
which remains valid after grouping (the set of distinct values is
preserved).  However, MCV frequencies, histograms, and correlation
data are not valid because GROUP BY and DISTINCT change the frequency
distribution of key columns.  So we strip all stats slots from the
copied stats tuple, causing callers like var_eq_const() to use the
1/ndistinct estimate instead.  If stadistinct is stored as a negative
value (a fraction of the base table's row count), we convert it to an
absolute count so it is not misinterpreted relative to the subquery's
output row count.

stanullfrac is adjusted too, since grouping collapses NULLs.  For a
single grouping key, at most one NULL group survives, so the null
fraction is 1/(ndistinct+1).  For multiple grouping keys the null
fraction depends on the joint distribution of the keys, which we don't
have, so we approximate it as zero; NULLs collapse far more
aggressively than non-NULLs, so the real fraction is well below the
base table's, and erring low keeps estimates on the hash-join-favoring
side.

Non-key columns (e.g., aggregate outputs) continue to get no stats,
same as before.

Author: Richard Guo <guofenglinux@gmail.com>
Reviewed-by: wenhui qiu <qiuwenhuifx@gmail.com>
Discussion: https://postgr.es/m/CAMbWs49rWYrecgreDhKsfx3VSDW=qo35s+iAmgGu=wpARrM8_g@mail.gmail.com
2026-07-08 09:38:31 +09:00
Richard Guo
96ab9a990e Fix EXPLAIN failure when deparsing SQL/JSON aggregates
If an expression containing an aggregate is evaluated above the plan
node that computes the aggregate, as happens with window functions or
with expressions postponed to above the final sort, setrefs.c replaces
the Aggref or WindowFunc with a Var referencing the lower node's
output.  For SQL/JSON aggregates such as JSON_ARRAYAGG and
JSON_OBJECTAGG, deparsing the containing JsonConstructorExpr then
failed with "invalid JsonConstructorExpr underlying node type", since
get_json_agg_constructor() did not expect a Var there.

Fix by resolving the Var back to the underlying Aggref or WindowFunc
and deparsing the constructor as if the aggregate were computed at the
current node.  The JsonConstructorExpr retains the RETURNING clause
and the ABSENT/NULL ON NULL and WITH UNIQUE options, and the arguments
come from the resolved aggregate, so the original JSON aggregate
syntax is reproduced in full.  This mirrors how get_agg_expr() already
looks through such a Var when deparsing a combining aggregate.

Reported-by: Thom Brown <thom@linux.com>
Author: Richard Guo <guofenglinux@gmail.com>
Discussion: https://postgr.es/m/CAA-aLv5QYTaMOk=Qhv6cgwceeHETZV8YJvWZ_rH+yVZCuchATA@mail.gmail.com
Backpatch-through: 16
2026-07-08 08:46:43 +09:00
Jeff Davis
07211f64ac unicode_case.c: change API to signal UTF8 decoding error.
Errors at this point are not expected, but if encountered, signal to
the caller so it can raise the appropriate error.

Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Discussion: https://postgr.es/m/c355354e6c3f4a7aafb047361b73db247260fca0.camel@j-davis.com
2026-07-07 15:34:05 -07:00
Heikki Linnakangas
7258c891d4 Remove unused tuple fetch in speculative completion
heapam_tuple_complete_speculative() fetched a tuple from the slot only
to free it immediately afterwards, without ever using it.

The function only needs slot->tts_tid to complete or abort the
speculative insertion, so remove the unnecessary fetch and pfree().

Author: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Japin Li <japinli@hotmail.com>
Reviewed-by: Xuneng Zhou <xunengzhou@gmail.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Discussion: https://www.postgresql.org/message-id/FCB61654-575D-4F08-AA7E-ED462EDE48A7@gmail.com
2026-07-08 01:16:24 +03:00
Heikki Linnakangas
99319edb8f Deduplicate metapage sanity checks in _bt_gettrueroot()
Replace the metapage sanity checks in _bt_gettrueroot() with a call to
_bt_getmeta(), which does exactly the same checks.

Author: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Neil Chen <carpenter.nail.cz@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAEoWx2nisjqs4iC9o4Hu7-Ab767=cMZZzmhBGb8SaQtMMmVqPQ@mail.gmail.com
2026-07-08 00:25:24 +03:00
Jeff Davis
21ffc271d4 unicode_case.c: defend against truncated UTF8.
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/c355354e6c3f4a7aafb047361b73db247260fca0.camel@j-davis.com
Backpatch-through: 17
2026-07-07 13:34:55 -07:00
Heikki Linnakangas
6f7199a124 Cleanup comments/docs around the new shmem request callbacks
Make it explicit in the docs that the shmem initialization callbacks
are called while holding ShmemIndexLock.

Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAExHW5sHs+eSiTDOd14buayc6JbBX=Hm5ssFMBK0Ki9sTGEOuA@mail.gmail.com
Backpatch-through: 19
2026-07-07 22:32:36 +03:00
Heikki Linnakangas
9c9ddf109b Fix gistkillitems for GiST root page
GiST index killitems feature misbehaves for single-page GiST index,
i.e. one that has only a root page. This is caused by the GiST scan's
curBlkno variable not being initialized for the first-to-scan page,
which is the root page.  Fix this by moving the initializing of
curBlkno into gistScanPage(), where we also set the related curPageLSN
variable.

Commit 377b7ab145 actually added a regression test for this already,
but it merely noted that it's not working and memorized the result
where the items were not killed. Now they are, as the test shows.

This has been broken all along, but since it's just a very minor
performance issue on tiny tables, I didn't bother backpatching it.

Author: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru>
Reviewed-by: Soumya S Murali <soumyamurali.work@gmail.com>
Discussion: https://postgr.es/m/CALdSSPgZWX_D8%2BFx4YQqRN5eW5iSx_rJdqQhCfdWTvqKXVfJ4w%40mail.gmail.com
Discussion: https://postgr.es/m/lxzj26ga6ippdeunz6kuncectr5gfuugmm2ry22qu6hcx6oid6@lzx3sjsqhmt6
2026-07-07 21:21:16 +03:00
Heikki Linnakangas
650bb73c13 Rename register_unlink_segment() to register_unlink_tombstone()
Only "tombstone" files (first segment of main fork) are unlinked after
checkpoints, so rename the function and remove the extra arguments to
make that more clear.

Additionally, add an assertion in mdunlinkfiletag() that the FileTag
only contains expected values.

Author: Matthias van de Meent <boekewurm+postgres@gmail.com>
Reviewed-by: Thomas Munro <thomas.munro@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAEze2WjfP95SL_Hsu7GzYXLnQyEsT49zOnNvbY_mBLCFiQra1g@mail.gmail.com
2026-07-07 20:05:56 +03:00
Noah Misch
592de8bd21 Fix pg_dump ACL minimization for PROPERTY GRAPH.
Adding a GRANT caused pg_dump to emit a useless REVOKE + GRANT of owner
privileges, as seen in a dump of the regression database:

  REVOKE ALL ON PROPERTY GRAPH graph_rls_schema.cabinet FROM nm;
  GRANT ALL ON PROPERTY GRAPH graph_rls_schema.cabinet TO nm;
  GRANT ALL ON PROPERTY GRAPH graph_rls_schema.cabinet TO PUBLIC;

For normal dumps, this has no functional consequences.  For --no-owner
restores, the extra statements may fail or locate unrelated users of the
destination cluster.

The problem was pg_dump assuming NULL relacl implies acldefault('r'),
the default for TABLE.  Fix by teaching acldefault() to retrieve the
PROPERTY GRAPH default ACL.  So pg_dump can still dump from 19beta1, use
acldefault('g') for v20+ only.  For v19, use a hard-coded snapshot of
the v19 default.

information_schema.pg_property_graph_privileges also misused
acldefault('r'), but its "c.prtype IN ('SELECT')" predicate compensated
for it.  Switch to the new acldefault('g') for clarity.  Bump catversion
since a new view won't work with old binaries.  Back-patch to v19, which
introduced PROPERTY GRAPH.

Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Discussion: https://postgr.es/m/20260630023308.c7.noahmisch@microsoft.com
Backpatch-through: 19
2026-07-07 09:51:04 -07:00
Nathan Bossart
b34fd845e0 Remove unnecessary volatile qualifiers.
This commit cleans up volatile qualifiers that fit the below
criteria:

* Accesses to shared memory protected by a spinlock or LWLock.
Before commit 0709b7ee72, callers had to use volatile when
accessing spinlock-protected shared memory.  Since spinlock
acquire/release became compiler barriers, and because LWLocks
provide the same guarantee, that is no longer necessary.  These
either predate that change or were cargo-culted from code that did.

* Pointers used only to find the address of a member.  The volatile
qualifier only affects accesses made by dereferencing the pointer,
so it is unnecessary there.

* Accesses to struct members that are marked volatile in the struct
definition.  There's no need to mark these pointers volatile,
either.

* Leftovers from removed PG_TRY blocks.  These were marked volatile
to protect a value that is modified inside a PG_TRY block, but the
PG_TRY has since been removed.

Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi>
Discussion: https://postgr.es/m/akQ5eJR1tCCXme8e%40nathan
2026-07-07 10:57:48 -05:00
Daniel Gustafsson
b9df8d5b8e Replace hardcoded mentions of pg_hosts.conf with GUC
Three error messages were using the default file name pg_hosts.conf
and not the variable backing the GUC, which would make logging be
confusing for users who have renamed the file using the GUC.  Fix
by consistently using the HostsFileName variable.

Backpatch down to v19 where serverside SNI was introduced.

Author: Zsolt Parragi <zsolt.parragi@percona.com>
Reviewed-by: Surya Poondla <suryapoondla4@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/CAN4CZFMARYjQfgyRaCKOXDO=Q91kuKn=pSC02DAOOr23ojhEGQ@mail.gmail.com
Backpatch-through: 19
2026-07-07 17:34:58 +02:00
David Rowley
d007800f02 Fix COUNT's logic for window run condition support
9d9c02ccd added code to allow the executor to stop early when processing
WindowAgg nodes where a monotonic window function starts producing
values that result in a pushed-down qual no longer matching, and will
never match again due to the window function's monotonic properties.

That commit requires a SupportRequestWFuncMonotonic to exist on the
window function and for it to detect when the function is monotonic.  For
COUNT(ANY) and COUNT(*), the support function failed to consider some
cases where the WindowClause used EXCLUDE to exclude certain rows from
being aggregated.  Some WindowClause definitions mean we aggregate rows
that come after the current row, and when processing those rows later,
if we EXCLUDE certain rows, the monotonic property can be broken.
Wrongly treating the COUNT(*) or COUNT(ANY) aggregate as monotonic could
lead to rows being filtered that should not be filtered from the result
set.

Another issue was that the support function for the COUNT aggregate
mistakenly thought that a WindowClause without an ORDER BY meant that
the results would be both monotonically increasing and decreasing, but
that's only true when in RANGE mode, where all rows are peers.

It is possible to support various cases that do have an EXCLUDE clause,
but getting the logic correct for the exact set of cases that are valid
is quite complex and would likely better be left for a future project.

Here, we mostly disable run condition pushdown when there is an EXCLUDE
clause unless the clause is for EXCLUDE CURRENT ROW, uses COUNT(*)
(rather than COUNT(ANY)), and the window aggregate has no FILTER clause.

Bug: #19533
Reported-by: Qifan Liu <imchifan@163.com>
Author: Chengpeng Yan <chengpeng_yan@outlook.com>
Author: David Rowley <dgrowleyml@gmail.com>
Reviewed-by: Richard Guo <guofenglinux@gmail.com>
Reviewed-by: John Naylor <johncnaylorls@gmail.com>
Discussion: https://postgr.es/m/19533-413a1014e5d0e766@postgresql.org
Backpatch-through: 15
2026-07-07 23:57:45 +12:00
Peter Eisentraut
04fc2564fb Don't cast pgoff_t to possibly 32-bit types for output
pgoff_t is most likely a 64-bit integer, so casting it to a 32-bit
type for output could lose data.  In the cases addressed here, the
files cannot actually get that large, so this is only cosmetic and to
set better examples for the future.  (Similar issues that could have
actual practical impact were addressed separately in commit
e8f851d6172.)

In one case, the 32-bit size is baked into the protocol, so here we
add an elog and document this discrepancy.

Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/20ce62fa-47fc-457b-b504-12f3c1651726%40eisentraut.org
2026-07-07 11:45:09 +02:00
Peter Eisentraut
2ce7458365 Update GROUP BY ALL comments about window functions
When GROUP BY ALL was added in commit ef38a4d975, the SQL standard
working draft was silent on what to do with window functions.  This
has now been fixed in the SQL standard working draft.  Update the
documentation and code comments about that.

Also make the documentation more specific that we are only talking
about aggregate functions referring to the same query level, which is
another thing that has been made more precise in the SQL standard
working draft since.

The PostgreSQL implementation was already doing the right thing for
both aspects, so no functionality changes.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/flat/CAHM0NXjz0kDwtzoe-fnHAqPB1qA8_VJN0XAmCgUZ%2BiPnvP5LbA%40mail.gmail.com
2026-07-07 08:47:07 +02:00
Amit Langote
4c75cc7863 Enforce RETURNING typmod on SQL/JSON DEFAULT behavior expressions
transformJsonBehavior() coerced an ON EMPTY / ON ERROR DEFAULT
expression only when its type differed from the RETURNING type's OID.
When the base type matched but the RETURNING type carried a type
modifier (e.g. numeric(4,1) or varchar(3)), the coercion that enforces
the typmod was skipped, so the DEFAULT value could violate the
declared type:

    SELECT JSON_VALUE(jsonb '{}', '$.a'
                      RETURNING numeric(4,1) DEFAULT 99999.999 ON EMPTY);

returned 99999.999, which 99999.999::numeric(4,1) would reject; the
value could even be stored into a numeric(4,1) column, as later
coercions trust its already-correct type label.

Fix by also coercing when the RETURNING type has a typmod, except for
a NULL constant.  coerce_to_target_type() is a no-op when the typmod
already matches.  The matching-OID short-circuit dates to 74c96699be.

Reported-by: Ewan Young <kdbase.hack@gmail.com>
Author: Ewan Young <kdbase.hack@gmail.com>
Discussion: https://postgr.es/m/CAON2xHPO9f4cAmyGn1mQ=VqoS7wN5rz4yOiqudxX78zninZpCw@mail.gmail.com
Backpatch-through: 17
2026-07-07 08:27:32 +09:00
Robert Haas
4c84545067 Use PG_MODULE_MAGIC_EXT in newly introduced modules
We forgot to use the PG_MODULE_MAGIC_EXT in some newly added modules:
pg_plan_advice, pg_stash_advice and the pgrepack output plugin and
instead used the older PG_MODULE_MAGIC macro.

Author: Andreas Karlsson <andreas@proxel.se>
Discussion: http://postgr.es/m/ad7b910c-d145-4120-994d-2e55c456aa75@proxel.se
Backpatch-through: 19
2026-07-06 15:45:58 -04:00
Tom Lane
42b7ff3aae Fix mishandling of leading '\' in nondeterministic LIKE.
The loop in MatchText() processed a leading '\' without regard to
nondeterministic locales, which is problematic if what the '\'
precedes is an ordinary character that should be subject to
nondeterministic matching.  We'd insist on a literal match for it,
which is not right and is not like what happens with a '\' that
follows some ordinary characters.  Worse, we'd then advance the text
and pattern pointers by one byte, so that if the escaped character
is multibyte the next loop iteration would take the nondeterministic
code path starting at a point within the character.  That could very
possibly cause pg_strncoll() to misbehave.

The fix is quite simple: move the stanza that handles '\' down past
the one that handles nondeterminism.  The stanzas for '%' and '_'
are fine where they are, but the '\' stanza is only correct for
deterministic matching.  The logic for nondeterministic cases is
already prepared to do the right things with a '\'.

While here, I replaced tests of "locale && !locale->deterministic"
with a boolean local variable, reasoning that those are in the hot
loop paths so saving a branch and indirect fetch is worth the
trouble.  I also improved a number of related comments.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/391592.1783187986@sss.pgh.pa.us
Backpatch-through: 18
2026-07-06 14:47:58 -04:00
Tom Lane
d6ffcae32a Fix LIKE matching with nondeterministic collations and backslashes.
Commit 85b7efa1c added support for LIKE with nondeterministic
collations, but it included a bug in the de-escaping logic for
literal pattern substrings.  That unconditionally skipped all
backslashes, but when it encounters '\\' it should emit the second
backslash as a de-escaped character.  That led to acting as though
the escaped backslash was not there.

Bug: #19474
Reported-by: Bowen Shi <zxwsbg12138@gmail.com>
Author: Nitin Motiani <nitinmotiani@google.com>
Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com>
Reviewed-by: Ewan Young <kdbase.hack@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19474-5b86a95f3d9a7ecb@postgresql.org
Discussion: https://postgr.es/m/CAH5HC94yU+K8Gcdy12M5BS8gwD_SXLSHzc9k5tNk7JDnpBiFMA@mail.gmail.com
Backpatch-through: 18
2026-07-06 14:35:21 -04:00
Tom Lane
2d7808e6fc Fix LIKE/regex optimization for indexscan with exact-match pattern.
Commit 85b7efa1c introduced support for LIKE with non-deterministic
collations.  By moving some conditionals around, it accidentally broke
the optimization for converting a LIKE or regex exact-match pattern
to an equality indexqual when the index collation doesn't match the
expression collation.  That should be allowed if the expression
collation is deterministic.  This patch re-introduces the optimization
for that common case.

One important beneficiary of this optimization is the "\d tablename"
command in psql.  Without this fix that will do a seqscan on pg_class
instead of an index point lookup.

Reported-by: Andres Freund <andres@anarazel.de>
Author: Jelte Fennema-Nio <postgres@jeltef.nl>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/DHBQIZX8SZVI.ZX614ZMFL645@jeltef.nl
Backpatch-through: 18
2026-07-06 13:06:24 -04:00
Robert Haas
e8914ec22f Prevent satisfies_hash_partition from crashing with VARIADIC NULL.
Commit f3b0897a12 fixed some
related problems, but overlooked this one. That commit first
appeared in PostgreSQL 11, so back-patch to all supported branches.

Backpatch-through: 14
Discussion: http://postgr.es/m/CA+TgmobsvQw3F+KRYT83=N3teh8D2t-oPR=U06QDZJE3viCJRg@mail.gmail.com
Reviewed-by: Tender Wang <tndrwang@gmail.com>
Reviewed-by: Ewan Young <kdbase.hack@gmail.com>
2026-07-06 12:51:29 -04:00
Peter Eisentraut
e994f956e4 Forbid generated columns in FOR PORTION OF
With virtual generated columns there is no column to assign to, and we
shouldn't assign directly to stored generated columns either.  (Once
we have PERIODs, we will allow a stored generated column here, but we
will assign to its start/end inputs.)

We can't do this in parse analysis, because views haven't yet been
rewritten, so they mask generated columns.

Author: Paul A. Jungwirth <pj@illuminatedcomputing.com>
Discussion: https://www.postgresql.org/message-id/agOOykf2HV26yVfU%40nathan
2026-07-06 09:32:09 +02:00
Richard Guo
44fb59fc60 Fix qual pushdown past grouping with mismatched equivalence
The planner has two optimizations that move a qual clause across a
grouping boundary: subquery_planner transfers HAVING clauses to WHERE
so they can be evaluated before aggregation, and qual_is_pushdown_safe
pushes outer restriction clauses into a subquery past its DISTINCT,
DISTINCT ON, window PARTITION BY, or set-operation grouping layer.
Both produce wrong results when the moved clause's equivalence
relation disagrees with the grouping's, since the clause then filters
rows the grouping would have merged.

The disagreement has two forms.  A type may belong to multiple btree
opfamilies whose equality operators disagree (e.g. record_ops vs
record_image_ops); or the grouping may use a nondeterministic
collation, where comparing the column under a different collation, or
wrapping it in a function or operator, can distinguish values the
collation considers equal.  Because we cannot prove an arbitrary
expression preserves that equality, a grouping column with a
nondeterministic collation is safe to push only as a direct operand of
a comparison under its own collation.

Fix both call sites through a shared walker parameterized by a
callback that maps each Var to the grouping equality operator for its
column (or InvalidOid for non-grouping Vars).  For HAVING, the
callback recovers the SortGroupClause's eqop via the GROUP Var's
varattno, which requires running before flatten_group_exprs while
havingQual still contains GROUP Vars.  For subquery pushdown, the
callback recovers the eqop from subquery->distinctClause, a window's
partitionClause, or any grouping node in the SetOperationStmt tree.
The walker fires only when there is an equivalence boundary to cross,
gated by either the existing UNSAFE_NOTIN_DISTINCTON_CLAUSE and
UNSAFE_NOTIN_PARTITIONBY_CLAUSE flags or by a recursive check for any
grouping node in the set-op tree.

Back-patch to v18 only.  The HAVING half relies on the RTE_GROUP
mechanism introduced in v18 (commit 247dea89f), which is what lets us
identify grouping expressions via GROUP Vars on pre-flatten
havingQual.  Pre-v18 branches lack that machinery, so a back-patch
there would need a different approach.  Given the absence of field
reports of these bugs on back branches, the risk of carrying a
different fix on stable branches is not justified.

Author: Richard Guo <guofenglinux@gmail.com>
Reviewed-by: Thom Brown <thom@linux.com>
Reviewed-by: Florin Irion <irionr@gmail.com>
Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com>
Reviewed-by: Tender Wang <tndrwang@gmail.com>
Reviewed-by: Chengpeng Yan <chengpeng_yan@outlook.com>
Discussion: https://postgr.es/m/CAMbWs4-QLZpn3UVOpeG2fOxxhdnkDNMZ_3Zcm3dqJwRAphz68g@mail.gmail.com
Backpatch-through: 18
2026-07-06 16:13:14 +09:00
Michael Paquier
9d1188f298 Emit a warning when io_min_workers exceeds io_max_workers
When io_min_workers is set strictly higher than io_max_workers, the
minimum has no effect since the pool will never grow past
io_max_workers.  Previously this was silently accepted, which could
be confusing for users expecting at least io_min_workers workers to
always be running.

In order to avoid noise in the server logs, the following restrictions
are in place:
- The only process printing the WARNING is the IO worker with ID 0, on
startup and reload, which is we know the only process always running
when using IO workers.
- At reload, the message shows only if one of the bounds has changed.

Note that this commit reuses a log message updated by 7905416eef.

Author: Baji Shaik <baji.pgdev@gmail.com>
Reviewed-by: Tristan Partin <tristan@partin.io>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Discussion: https://postgr.es/m/CA+fm-RO_O7-XThg2qjj=ir35x9nOFbZYu07gttqAbM5T88QB4Q@mail.gmail.com
2026-07-06 11:37:36 +09:00
Michael Paquier
a924407ce0 Improve checks and error messages of pgstat_register_kind()
pgstat_register_kind() did not validate that required callbacks are
set, which could lead to NULL pointer dereferences when trying to
register a stats kind.  This adds a couple of checks:
- Fox fixed-sized kinds, init_shmem_cb, reset_all_cb, and snapshot_cb
are required.
- For variable-sized kinds, flush_pending_cb is called when there is
pending data, pending_size being required.

These issues should be easy to notice for someone developing an
extension that relies on the custom pgstats APIs.  No backpatch is done
as it is mainly a life improvement.

Author: Sami Imseih <samimseih@gmail.com>
Discussion: https://postgr.es/m/CAA5RZ0uNoe=xT7QsU1K0mMRg-QAwPtupPWZ2J3weM2PjVL2tiA@mail.gmail.com
2026-07-06 10:49:28 +09:00
Peter Eisentraut
0e4f0827f6 Fix properties orphaned by dropping a label
AlterPropGraph() cleans up pg_propgraph_property entries that are
orphaned by dropping an element or by dropping properties associated
with an element.  But it did not clean up pg_propgraph_property
entries that are orphaned by dropping labels associated with an
element.  Fix this missing case.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Author: zengman <zengman@halodbtech.com>
Discussion: https://www.postgresql.org/message-id/flat/tencent_76F6ACA2364EAA1E5DBD7A47%40qq.com
2026-07-05 13:51:32 +02:00
Tom Lane
a8c2547eaa Disallow renaming a rule to "_RETURN".
ON SELECT rules must be named "_RETURN", while other kinds of rules
must not be; this ancient restriction is depended on by various client
code.  We successfully enforced this convention in most places, but
ALTER RULE allowed renaming a non-SELECT rule to "_RETURN".  Notably,
that would break dump/restore, since the eventual CREATE RULE command
would reject the name.

While at it, remove DefineQueryRewrite's hack to substitute "_RETURN"
for the convention that was used before 7.3.  We dropped other
server-side code that supported restoring pre-7.3 dumps some time ago
(notably in e58a59975 and nearby commits), but this bit was missed.

Bug: #19543
Reported-by: Adam Pickering <adamkpickering@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19543-461228e77f3b32fc@postgresql.org
Backpatch-through: 14
2026-07-04 11:34:26 -04:00
Peter Eisentraut
e0ff7fd9aa Make property graph object descriptions better translatable
getObjectDescription() currently constructs property graph-related
object descriptions incrementally with appendStringInfo().  This
effectively fixes the word order in English, which makes the messages
difficult to translate naturally into languages such as Japanese.

Author: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/20260528.121622.1662808269492494574.horikyota.ntt%40gmail.com
2026-07-03 23:46:19 +02:00
Álvaro Herrera
5ee9d7c299
REPACK CONCURRENTLY: Initialize the range table more honestly
We were skipping a bunch of things that are mostly unnecessary for
REPACK.  However, one thing that seems would be better to pass closer to
truth, is the updatedCols bitmapset in the range table entry for the
repacked table.  Cons up an RTE and install it into the EState.

This only has an effect on btree indexes, because certain operations are
optimized in the case of unchanged columns; and even then, correctnesss
is not being compromised.

The values we pass after this commit are not fully trustworthy either,
because we simply say "all columns were updated" for all insert/updates,
regardless of whether their values were actually modified or not.
However, this way we err to the side of caution rather than to the
opposite direction as we were originally doing.  This could be refined
in the future, but there's a trade-off: determining whether the column
was in fact updated could be expensive.

Author: Antonin Houska <ah@cybertec.at>
Reviewed-by: Ewan Young <kdbase.hack@gmail.com>
Backpatch-through: 19
Discussion: https://postgr.es/m/18222.1782126731@localhost
2026-07-03 20:04:48 +02:00
Peter Eisentraut
efd7d8d7d4 Resolve unknown-type literals in GRAPH_TABLE COLUMNS
The unknown-type literals in the COLUMNS clause of a GRAPH_TABLE are
now resolved to the appropriate types.  Without that, this could cause
various failures.

Author: Satya Narlapuram <satyanarlapuram@gmail.com>
Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Junwang Zhao <zhjwpku@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/CAHg%2BQDcyKNWyzDoKMxiZNjv7C-wAxs8y0ZoNkOV137Y%2Bnk3UXg%40mail.gmail.com
2026-07-03 17:10:42 +02:00
Alexander Korotkov
c40819ebf9 Prevent access to other sessions' empty temp tables
Commit ce146621 ensures that ERROR is raised if a session tries to read
pages of another session's temp table.  But there is a corner case where
the other session's temp table is empty -- in this case the INSERT
command bypasses our checks and executes without any errors.

Such behavior is inconsistent and erroneous: it leaves an invalid buffer
in the temp buffers pool.  Since the buffer was created for another
session's temp table, we get an error "no such file or directory" when
trying to flush it.

This commit fixes it by adding a RELATION_IS_OTHER_TEMP check in the
relation-extension path.

Backpatch to 16, because it is the first release after 31966b151e, which
introduced a separate local relation extension function
ExtendBufferedRelLocal(), which lacks of RELATION_IS_OTHER_TEMP() check.
As this fix introduces more checks to 013_temp_obj_multisession.pl, backpatch
the whole test script to 16.

Discussion: https://postgr.es/m/CAJDiXgiX2XZBHDNo%2BzBbvku%2BtchrUurvPRaN1_40mEQ1_sG90g%40mail.gmail.com
Author: Daniil Davydov <3danissimo@gmail.com>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Reviewed-by: Imran Zaheer <imran.zhir@gmail.com>
Reviewed-by: ZizhuanLiu X-MAN <44973863@qq.com>
Backpatch-through: 16
2026-07-03 18:02:14 +03:00
Peter Eisentraut
96418a6da9 Fix handling of dropping a property not associated with the given label
When dropping a property by name from a label, the code checked only
whether the property existed in the graph's property catalog.  It did
not verify that the property was actually associated with the given
label, resulting in passing InvalidOid to performDeletion().  Fix it
by explicilty checking the label property association.

While at it also rearrange the code so as to avoid multiple ereport
calls for the same error in the same block.

Author: Chao Li <lic@highgo.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/1DA5D52A-4AFA-426E-83F7-42ED974D682B%40gmail.com
2026-07-03 16:29:42 +02:00
Álvaro Herrera
3be823486f
Fix REPACK CONCURRENTLY for stored generated columns
In order to replay concurrent changes, REPACK CONCURRENTLY needs the
pg_attrdef tuples for the transient table to be there, in case a tuple
is modified concurrently with REPACK and requires to store the value
from the generated column (which, with the current arrangements, means
all tuples concurrently updated or inserted).  Fix by creating a copy of
them from the original table.  Add a test that tickles the bug.

Author: Antonin Houska <ah@cybertec.at>
Reported-by: Ewan Young <kdbase.hack@gmail.com>
Diagnosed-by: Ewan Young <kdbase.hack@gmail.com>
Reviewed-by: Ewan Young <kdbase.hack@gmail.com>
Backpatch-through: 19
Discussion: https://postgr.es/m/CAON2xHMrELwx9vKg6niSf8fMBA=-MGXmG=MPQU6+vMVhGjF8kQ@mail.gmail.com
2026-07-03 12:22:37 +02:00
Peter Eisentraut
7afa11feca Prevent dropping the last label from a property graph element
Per SQL/PGQ standard, every graph element must have at least one
label.  When dropping a label from a graph element, ensure that there
exists at least one other label on the element.  If the label being
dropped is the only label on the element, raise an error.

We hold a ShareRowExclusiveLock when modifying a property graph.
Hence the label will not be dropped even when multiple labels are
being dropped concurrently.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Author: Satyanarayana Narlapuram <satyanarlapuram@gmail.com>
Reported-by: Satyanarayana Narlapuram <satyanarlapuram@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAHg+QDeP=mTHTV48R23zKMy1SBmCKZ_L7-z5zKnYyw+K0x-gCg@mail.gmail.com
2026-07-03 12:10:31 +02:00
Michael Paquier
71fa15af59 Fix typo in pg_stat_us_to_ms()
The function converts microseconds to milliseconds, but the parameter
name used "ms".

Thinko in ac8d53dae5.

Author: Tatsuya Kawata <kawatatatsuya0913@gmail.com>
Discussion: https://postgr.es/m/CAHza6qfek15rehnA0GXMCpF2z=Gy6C+3vmcWCMVkU4JiRD8k7g@mail.gmail.com
2026-07-03 12:22:14 +09:00
Fujii Masao
084734ff5a Remove replication slot advice from MultiXact wraparound hints
Previously, MultiXactId wraparound hints suggested dropping stale
replication slots. While that advice is appropriate for transaction ID
wraparound, where replication slots can hold back XID horizons,
it was misleading for MultiXactId wraparound. Following it could lead
users to drop replication slots unnecessarily without helping resolve
the MultiXactId wraparound condition.

MultiXact cleanup is not directly delayed by replication slots.
Instead, it depends on whether old MultiXactIds can still be seen
as live by running transactions.

This commit removes the replication slot advice from MultiXactId
wraparound hints, and documents that stale replication slots are
normally not relevant to resolving MultiXactId wraparound problems.

Backpatch to all supported branches.

BUG #18876
Reported-by: Haruka Takatsuka <harukat@sraoss.co.jp>
Author: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/18876-0d0b53bad5a1f4c1@postgresql.org
Backpatch-through: 14
2026-07-03 11:16:34 +09:00
Fujii Masao
c8bd8387c2 Add log_statement_max_length GUC to limit logged statement text
Very large statements can make server logs grow unexpectedly. This is
particularly painful when applications accidentally or intentionally
send huge literal values and statement logging is enabled: the full
statement text may be written to the log even when DBA sees only
its leading part is useful for normal operations.

This commit adds log_statement_max_length GUC that limits the number
of bytes of statement text emitted by statement logging. The setting
applies to statements logged by log_statement, log_min_duration_statement,
log_min_duration_sample, and log_transaction_sample_rate. A positive
value truncates the logged statement body to at most that many bytes,
zero  logs an empty statement body, and the default value -1 preserves
the existing behavior of logging statements in full.

Truncation is byte-based, matching the GUC unit, but it clips only
at multibyte character boundaries so that the log output remains valid.
This setting does not affect statements logged because of
log_min_error_statement; handling error-statement logging can be
considered separately.

Author: Jim Jones <jim.jones@uni-muenster.de>
Author: Kirill Gavrilov <diphantxm@gmail.com>
Reviewed-by: Kirill Reshke <reshkekirill@gmail.com>
Reviewed-by: Álvaro Herrera <alvherre@kurilemu.de>
Reviewed-by: Maxym Kharchenko <maxymkharchenko@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Discussion: https://postgr.es/m/CA+E0NR4S+NC6+QHyY_vUuQZMzLhKqczMx-jJVqtjAxF6+=JwAA@mail.gmail.com
2026-07-03 08:47:18 +09:00
John Naylor
51cd5d6f05 Use ssup_datum_*_cmp in more places
The int2, oid, and oid8 "fastcmp" comparators are functionally
equivalent to the ssup_datum_int32_cmp (for int2) and
ssup_datum_unsigned_cmp (for oid, oid8) functions added by commit
697492434, so simplify by using the latter instead. This has the
added benefit of making these types eligible for radix sort.

Author: Baji Shaik <baji.pgdev@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/CA+fm-RMyLC94NfrxCh273+dKs44U0ZJjRczznvzvgw=KtpPNVw@mail.gmail.com
2026-07-02 15:55:11 +07:00
John Naylor
3eca140531 Fix loss of precision in pg_stat_us_to_ms()
Multiplying by the constant 0.001 can produce trailing-digit noise in
displayed values (for example 0.009000000000000001 instead of 0.009,
with default extra_float_digits) because 0.001 cannot be represented
exactly in binary floating point. Use division by 1000.0 instead,
matching code elsewhere in the tree.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Discussion: https://postgr.es/m/akIYkMK4bHe9qX/N@bdtpg
2026-07-02 13:26:56 +07:00
Amit Kapila
6b41bd1a45 Expand comment on the slot recheck in drop_local_obsolete_slots().
The existing comment explained that a user-created slot could reuse the
same shared memory as 'local_slot' during the window between selecting a
slot to drop and locking its database, and that we therefore recheck
before dropping.  It did not, however, spell out the fuller consequence:
because local_slot points to a reusable slot-array entry, its fields may
already describe a replacement slot, so the earlier drop decision and the
slot_database used for locking could relate to an unrelated slot/database.

Expand the comment to describe this, and note that the recheck prevents
us from dropping a user-created replacement slot while the residual risk
(such as briefly locking an unrelated database) is confined to the cycle
and is acceptable given the race is rare and non-fatal.

No functional change.

Author: Fujii Masao <masao.fujii@gmail.com>
Author: Xuneng Zhou <xunengzhou@gmail.com>
Author: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAHGQGwGGyEDL3dh7uJ6qPsGvnq4QK_R8+U=12CaprnzwrwaLGA@mail.gmail.com
Discussion: https://postgr.es/m/CAHGQGwHqQ1PPVFfYKVxLfRyC-byRdwSN0NeaHj9SLYV97oO5cw@mail.gmail.com
2026-07-02 09:34:17 +05:30