postgresql.git
17 months agoCheck if ii_AmCache is NULL in aminsertcleanup
Tomas Vondra [Mon, 27 Nov 2023 15:52:59 +0000 (16:52 +0100)]
Check if ii_AmCache is NULL in aminsertcleanup

Fix a bug introduced by c1ec02be1d79. It may happen that the executor
opens indexes on the result relation, but no rows end up being inserted.
Then the index_insert_cleanup still gets executed, but passes down NULL
to the AM callback. The AM callback may not expect this, as is the case
of brininsertcleanup, leading to a crash.

Fixed by only calling the cleanup callback if (ii_AmCache != NULL). This
way the AM can simply assume to only see a valid cache.

Reported-by: Richard Guo
Discussion: https://postgr.es/m/CAMbWs4-w9qC-o9hQox9UHvdVZAYTp8OrPQOKtwbvzWaRejTT=Q@mail.gmail.com

17 months agoReduce rate of walwriter wakeups due to async commits.
Heikki Linnakangas [Mon, 27 Nov 2023 15:42:39 +0000 (17:42 +0200)]
Reduce rate of walwriter wakeups due to async commits.

XLogSetAsyncXactLSN(), called at asynchronous commit, would wake up
walwriter every time the LSN advances, but walwriter doesn't actually
do anything unless it has at least 'wal_writer_flush_after' full
blocks of WAL to write. Repeatedly waking up walwriter to do nothing
is a waste of CPU cycles in both walwriter and the backends doing the
wakeups. To fix, apply the same logic in XLogSetAsyncXactLSN() to
decide whether to wake up walwriter, as walwriter uses to determine if
it has any work to do.

In the passing, rename misleadingly named 'flushbytes' local variable
to 'flushblocks'.

Author: Andres Freund, Heikki Linnakangas
Discussion: https://www.postgresql.org/message-id/20231024230929.vsc342baqs7kmbte@awork3.anarazel.de

17 months agoAvoid unconditionally filling in missing values with NULL in pgoutput.
Amit Kapila [Mon, 27 Nov 2023 03:19:55 +0000 (08:49 +0530)]
Avoid unconditionally filling in missing values with NULL in pgoutput.

52e4f0cd4 introduced a bug in pgoutput in which missing values in tuples
were incorrectly filled in with NULL. The problem was the use of
CreateTupleDescCopy where CreateTupleDescCopyConstr was required, as the
former drops the constraints in the tuple description (specifically, the
default value constraint) on the floor.

The bug could result in incorrectness when a table replicated via
`REPLICA IDENTITY FULL` underwent a schema change that added a column
with a default value. The problem is that in such cases updates fill NULL
values in old tuples for missing columns for default values. Then on the
subscriber, we failed to find a matching tuple and missed updating the
required row.

Author: Nikhil Benesch
Reviewed-by: Hou Zhijie, Amit Kapila
Backpatch-through: 15
Discussion: http://postgr.es/m/CAPWqQZTEpZQamYsGMn6ZDRvVywwpVPiKH6OY4KSgA+NmeqFNzA@mail.gmail.com

17 months agoTrack statement entry timestamp in contrib/pg_stat_statements
Alexander Korotkov [Mon, 27 Nov 2023 00:51:18 +0000 (02:51 +0200)]
Track statement entry timestamp in contrib/pg_stat_statements

This patch adds 'stats_since' and 'minmax_stats_since' columns to the
pg_stat_statements view and pg_stat_statements() function.  The new min/max
reset mode for the pg_stat_stetments_reset() function is controlled by the
parameter minmax_only.

'stat_since' column is populated with the current timestamp when a new
statement is added to the pg_stat_statements hashtable.  It provides clean
information about statistics collection time intervals for each statement.
Besides it can be used by sampling solutions to detect situations when a
statement was evicted and stored again between samples.

Such a sampling solution could derive any pg_stat_statements statistic values
for an interval between two samples with the exception of all min/max
statistics. To address this issue this patch adds the ability to reset
min/max statistics independently of the statement reset using the new
minmax_only parameter of the pg_stat_statements_reset(userid oid, dbid oid,
queryid bigint, minmax_only boolean) function. The timestamp of such reset
is stored in the minmax_stats_since field for each statement.
pg_stat_statements_reset() function now returns the timestamp of a reset as the
result.

Discussion: https://postgr.es/m/flat/72e80e7b160a6eb189df9ef6f068cce3765d37f8.camel%40moonset.ru
Author: Andrei Zubkov
Reviewed-by: Julien Rouhaud, Hayato Kuroda, Yuki Seino, Chengxi Sun
Reviewed-by: Anton Melnikov, Darren Rush, Michael Paquier, Sergei Kornilov
Reviewed-by: Alena Rybakina, Andrei Lepikhov
17 months agoAdd NOT NULL checking of pg_stat_statements_reset() in tests
Alexander Korotkov [Mon, 27 Nov 2023 00:50:59 +0000 (02:50 +0200)]
Add NOT NULL checking of pg_stat_statements_reset() in tests

This is preliminary patch.  It adds NOT NULL checking for the result of
pg_stat_statements_reset() function. It is needed for upcoming patch
"Track statement entry timestamp" that will change the result type of
this function to the timestamp of a reset performed.

Discussion: https://postgr.es/m/flat/72e80e7b160a6eb189df9ef6f068cce3765d37f8.camel%40moonset.ru
Author: Andrei Zubkov
Reviewed-by: Julien Rouhaud, Hayato Kuroda, Yuki Seino, Chengxi Sun
Reviewed-by: Anton Melnikov, Darren Rush, Michael Paquier, Sergei Kornilov
Reviewed-by: Alena Rybakina, Andrei Lepikhov
17 months agoFix race condition with BIO methods initialization in libpq with threads
Michael Paquier [Mon, 27 Nov 2023 00:40:44 +0000 (09:40 +0900)]
Fix race condition with BIO methods initialization in libpq with threads

The libpq code in charge of creating per-connection SSL objects was
prone to a race condition when loading the custom BIO methods needed by
my_SSL_set_fd().  As BIO methods are stored as a static variable, the
initialization of a connection could fail because it could be possible
to have one thread refer to my_bio_methods while it is being manipulated
by a second concurrent thread.

This error has been introduced by 8bb14cdd33de, that has removed
ssl_config_mutex around the call of my_SSL_set_fd(), that itself sets
the custom BIO methods used in libpq.  Like previously, the BIO method
initialization is now protected by the existing ssl_config_mutex, itself
initialized earlier for WIN32.

While on it, document that my_bio_methods is protected by
ssl_config_mutex, as this can be easy to miss.

Reported-by: Willi Mann
Author: Willi Mann, Michael Paquier
Discussion: https://postgr.es/m/e77abc4c-4d03-4058-a9d7-ef0035657e04@celonis.com
Backpatch-through: 12

17 months agoDisplay length and bounds histograms in pg_stats
Alexander Korotkov [Sun, 26 Nov 2023 23:30:39 +0000 (01:30 +0200)]
Display length and bounds histograms in pg_stats

Values corresponding to STATISTIC_KIND_RANGE_LENGTH_HISTOGRAM and
STATISTIC_KIND_BOUNDS_HISTOGRAM were not exposed to pg_stats when these
slot kinds were introduced in 918eee0c49.

This commit adds the missing fields to pg_stats.

Catversion is bumped.

Discussion: https://postgr.es/m/flat/b67d8b57-9357-7e82-a2e7-f6ce6eaeec67@postgrespro.ru
Author: Egor Rogov, Soumyadeep Chakraborty
Reviewed-by: Tomas Vondra, Justin Pryzby, Jian He
17 months agoUpdate comments for pg_statistic catalog table
Alexander Korotkov [Sun, 26 Nov 2023 23:29:56 +0000 (01:29 +0200)]
Update comments for pg_statistic catalog table

Make a reminder that pg_stats view needs to be modified whenever a new slot
kind is added.  To prevent situations like 918eee0c49 when pg_stats was
forgotten to be updated.

Also, revise the comment that only non-null, non-empty rows are considered
for the range length histogram.

Discussion: https://postgr.es/m/flat/b67d8b57-9357-7e82-a2e7-f6ce6eaeec67@postgrespro.ru
Author: Egor Rogov, Soumyadeep Chakraborty
Reviewed-by: Tomas Vondra, Justin Pryzby, Jian He
17 months agoDoc: list AT TIME ZONE and COLLATE in operator precedence table.
Tom Lane [Sun, 26 Nov 2023 21:40:22 +0000 (16:40 -0500)]
Doc: list AT TIME ZONE and COLLATE in operator precedence table.

These constructs have precedence, but we forgot to list them.
In HEAD, mention AT LOCAL as well as AT TIME ZONE.

Per gripe from Shay Rojansky.

Discussion: https://postgr.es/m/CADT4RqBPdbsZW7HS1jJP319TMRHs1hzUiP=iRJYR6UqgHCrgNQ@mail.gmail.com

17 months agoFix brin.c indentation issues introduced by c1ec02be1d
Tomas Vondra [Sun, 26 Nov 2023 20:35:32 +0000 (21:35 +0100)]
Fix brin.c indentation issues introduced by c1ec02be1d

Per buildfarm member koel.

17 months agoUse fipshash in brin_multi test
Peter Eisentraut [Sat, 25 Nov 2023 21:18:53 +0000 (22:18 +0100)]
Use fipshash in brin_multi test

This fixes some md5() calls that snuck in in 0457109344 after we had
removed them all in 208bf364a9.

Reviewed-by: Tomas Vondra <tomas.vondra@enterprisedb.com>
Discussion: https://www.postgresql.org/message-id/a35eaf0f-b19c-7797-e296-7b7e2adc473e@eisentraut.org

17 months agoReuse BrinDesc and BrinRevmap in brininsert
Tomas Vondra [Sat, 25 Nov 2023 19:27:04 +0000 (20:27 +0100)]
Reuse BrinDesc and BrinRevmap in brininsert

The brininsert code used to initialize (and destroy) BrinDesc and
BrinRevmap for each tuple, which is not free. This patch initializes
these structures only once, and reuses them for all inserts in the same
command. The data is passed through indexInfo->ii_AmCache.

This also introduces an optional AM callback "aminsertcleanup" that
allows performing custom cleanup in case simply pfree-ing ii_AmCache is
not sufficient (which is the case when the cache contains TupleDesc,
Buffers, and so on).

Author: Soumyadeep Chakraborty
Reviewed-by: Alvaro Herrera, Matthias van de Meent, Tomas Vondra
Discussion: https://postgr.es/m/CAE-ML%2B9r2%3DaO1wwji1sBN9gvPz2xRAtFUGfnffpd0ZqyuzjamA%40mail.gmail.com

17 months agoC comment: add header to pg_test_fsync.c
Bruce Momjian [Sat, 25 Nov 2023 16:04:46 +0000 (11:04 -0500)]
C comment:  add header to pg_test_fsync.c

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/CAB7nPqT1c9WrUw4+eSGF_-ru7ERBOC50a4r3tS1s-yT4OaYsLg@mail.gmail.com

Author: Michael Paquier

Backpatch-through: master

17 months agoC comment: clarify that WAL files can be _recycled_ or removed
Bruce Momjian [Sat, 25 Nov 2023 15:48:18 +0000 (10:48 -0500)]
C comment:  clarify that WAL files can be _recycled_ or removed

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/CAB7nPqSDdF0heotQU3gsepgqx+9c+6KjLd3R6aNYH7KKfDd2ig@mail.gmail.com

Author: Michael Paquier

Backpatch-through: master

17 months agoUse SECS_PER_HOUR macro in tzparser.c, instead of constants
Bruce Momjian [Sat, 25 Nov 2023 03:36:23 +0000 (22:36 -0500)]
Use SECS_PER_HOUR macro in tzparser.c, instead of constants

Reported-by: CharSyam
Discussion: https://postgr.es/m/CAMrLSE5j_aWfoBDMrSvk14oBKSy+-2cjzNNH_FciirA7Kwo9TA@mail.gmail.com

Author: CharSyam

Backpatch-through: master

17 months agodoc: gin_page_opaque_info() must be a _compressed_ GIN page
Bruce Momjian [Sat, 25 Nov 2023 03:02:07 +0000 (22:02 -0500)]
doc:  gin_page_opaque_info() must be a _compressed_ GIN page

Reported-by: Jeff Janes
Discussion: https://postgr.es/m/CAMkU=1xvzQxTAiYNM2PWJ6snMTPh3u3Ammbwss7mvAShS2Ohww@mail.gmail.com

Author: Jeff Janes

Backpatch-through: master

17 months agodoc: improve ALTER TABLE "offical constraint" wording
Bruce Momjian [Sat, 25 Nov 2023 01:07:14 +0000 (20:07 -0500)]
doc:  improve ALTER TABLE "offical constraint" wording

Reported-by: Josh Kupershmidt
Discussion: https://postgr.es/m/CAK3UJRF=KY_nx_TRQq+t6jOrtS2rry79ktkzPiMDhFx_K=dZAg@mail.gmail.com

Author: Josh Kupershmidt

Backpatch-through: master

17 months agoDoc: un-break PDF build.
Tom Lane [Sat, 25 Nov 2023 01:02:53 +0000 (20:02 -0500)]
Doc: un-break PDF build.

Oversight in 5c4c7efad: gotta adjust the cell height for removal of
an entry.  Per buildfarm.

17 months agogitignore generated file targets-meson.sgml.
Tom Lane [Sat, 25 Nov 2023 00:51:03 +0000 (19:51 -0500)]
gitignore generated file targets-meson.sgml.

Oversight in 07cb29737.

17 months agomodify segno. for pg_walfile_name() and pg_walfile_name_offset()
Bruce Momjian [Sat, 25 Nov 2023 00:44:09 +0000 (19:44 -0500)]
modify segno. for pg_walfile_name() and pg_walfile_name_offset()

Previously these functions returned the previous segment number if the
LSN was on a segment boundary.  We now always return the current segment
number for an LSN.

Docs updated to reflect this change.  Regression tests added, author
Andres Freund.

Also mentioned in thread https://postgr.es/m/flat/20220204225057.GA1535307%40nathanxps13#d964275c9540d8395e138efc0a75f7e8

BACKWARD INCOMPATIBILITY

Reported-by: Kyotaro Horiguchi
Discussion: https://postgr.es/m/20190726.172120.101752680.horikyota.ntt@gmail.com

Co-authored-by: Kyotaro Horiguchi
Backpatch-through: master

17 months agodoc: remove documentation for deprecated @@@ operator
Bruce Momjian [Fri, 24 Nov 2023 23:01:56 +0000 (18:01 -0500)]
doc:  remove documentation for deprecated @@@ operator

Reported-by: Kyotaro HORIGUCHI
Discussion: https://postgr.es/m/CAF4Au4wmUsZRVhR+ySpvabRfB_1D1fnrPY9TRAKO2DEbi4Cpgg@mail.gmail.com

Co-authored-by: Oleg Bartunov
Backpatch-through: master

17 months agodoc: mention vacuum's removal of commit timestamp information
Bruce Momjian [Fri, 24 Nov 2023 22:56:28 +0000 (17:56 -0500)]
doc:  mention vacuum's removal of commit timestamp information

Reported-by: Kyotaro HORIGUCHI
Discussion: https://postgr.es/m/20180622.172132.230342845.horiguchi.kyotaro@lab.ntt.co.jp

Co-authored-by: Kyotaro HORIGUCHI
Backpatch-through: 16

17 months agoFix whitespace.
Thomas Munro [Fri, 24 Nov 2023 21:39:32 +0000 (10:39 +1300)]
Fix whitespace.

Use tabs instead of spaces for new paragraph, like existing paragraphs.

17 months agoImprove comments about pqsignal().
Thomas Munro [Fri, 24 Nov 2023 20:41:33 +0000 (09:41 +1300)]
Improve comments about pqsignal().

Explain where pqsignal() came from, what problem it originally solved
without assuming the reader is familiar with historical Unixen, why we
still need it, what it does for us now, and the key differences in
frontend code on Windows.

Reviewed-by: Heikki Linnakangas <hlinnaka@iki.fi>
Discussion: https://postgr.es/m/CA%2BhUKG%2BRst1h3uo%2BXRgdRVnWHBa4mmj5gFbmCzZr73s-Fh_5JA%40mail.gmail.com

17 months agodoc: add docs for age(xid) and mxid_age(xid)
Bruce Momjian [Fri, 24 Nov 2023 19:36:00 +0000 (14:36 -0500)]
doc:  add docs for age(xid) and mxid_age(xid)

Reported-by: David Rowley
Discussion: https://postgr.es/m/CAKJS1f_OQpz7rpe-KJmskVxbU06buiXbfonxG3JLB+nGCJ5E=g@mail.gmail.com

Backpatch-through: 16

17 months agoFix timing-dependent failure in GSSAPI data transmission.
Tom Lane [Thu, 23 Nov 2023 18:30:18 +0000 (13:30 -0500)]
Fix timing-dependent failure in GSSAPI data transmission.

When using GSSAPI encryption in non-blocking mode, libpq sometimes
failed with "GSSAPI caller failed to retransmit all data needing
to be retried".  The cause is that pqPutMsgEnd rounds its transmit
request down to an even multiple of 8K, and sometimes that can lead
to not requesting a write of data that was requested to be written
(but reported as not written) earlier.  That can upset pg_GSS_write's
logic for dealing with not-yet-written data, since it's possible
the data in question had already been incorporated into an encrypted
packet that we weren't able to send during the previous call.

We could fix this with a one-or-two-line hack to disable pqPutMsgEnd's
round-down behavior, but that seems like making the caller work around
a behavior that pg_GSS_write shouldn't expose in this way.  Instead,
adjust pg_GSS_write to never report a partial write: it either
reports a complete write, or reflects the failure of the lower-level
pqsecure_raw_write call.  The requirement still exists for the caller
to present at least as much data as on the previous call, but with
the caller-visible write start point not moving there is no temptation
for it to present less.  We lose some ability to reclaim buffer space
early, but I doubt that that will make much difference in practice.

This also gets rid of a rather dubious assumption that "any
interesting failure condition (from pqsecure_raw_write) will recur
on the next try".  We've not seen failure reports traceable to that,
but I've never trusted it particularly and am glad to remove it.

Make the same adjustments to the equivalent backend routine
be_gssapi_write().  It is probable that there's no bug on the backend
side, since we don't have a notion of nonblock mode there; but we
should keep the logic the same to ease future maintenance.

Per bug #18210 from Lars Kanis.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/18210-4c6d0b14627f2eb8@postgresql.org

17 months agoUse ResourceOwner to track WaitEventSets.
Heikki Linnakangas [Thu, 23 Nov 2023 11:31:36 +0000 (13:31 +0200)]
Use ResourceOwner to track WaitEventSets.

A WaitEventSet holds file descriptors or event handles (on Windows).
If FreeWaitEventSet is not called, those fds or handles are leaked.
Use ResourceOwners to track WaitEventSets, to clean those up
automatically on error.

This was a live bug in async Append nodes, if a FDW's
ForeignAsyncRequest function failed. (In back branches, I will apply a
more localized fix for that based on PG_TRY-PG_FINALLY.)

The added test doesn't check for leaking resources, so it passed even
before this commit. But at least it covers the code path.

In the passing, fix misleading comment on what the 'nevents' argument
to WaitEventSetWait means.

Report by Alexander Lakhin, analysis and suggestion for the fix by
Tom Lane. Fixes bug #17828.

Reviewed-by: Alexander Lakhin, Thomas Munro
Discussion: https://www.postgresql.org/message-id/472235.1678387869@sss.pgh.pa.us

17 months agoC comment: fix typos with unnecessary apostrophes
Bruce Momjian [Thu, 23 Nov 2023 04:41:15 +0000 (23:41 -0500)]
C comment:  fix typos with unnecessary apostrophes

Reported-by: Vinayak Pokale
Discussion: https://postgr.es/m/CAEySZvh7gPTOqMhuKOBXEt=qF_1BCvFQB4MAJ4yaTPJHxgX_zw@mail.gmail.com

Author: Vinayak Pokale

Backpatch-through: master

17 months agodoc: remove double-negative in REFRESH MATERIALIZED ... CONCURR
Bruce Momjian [Wed, 22 Nov 2023 21:40:10 +0000 (16:40 -0500)]
doc:  remove double-negative in REFRESH MATERIALIZED ... CONCURR

Reported-by: ap@robillo.net
Discussion: https://postgr.es/m/20170208152743.1411.6073@wrigleys.postgresql.org

Backpatch-through: master

17 months agoFix the initial sync tables with no columns.
Amit Kapila [Wed, 22 Nov 2023 06:14:14 +0000 (11:44 +0530)]
Fix the initial sync tables with no columns.

The copy command formed for initial sync was using parenthesis for tables
with no columns leading to syntax error. This patch avoids adding
parenthesis for such tables.

Reported-by: Justin G
Author: Vignesh C
Reviewed-by: Peter Smith, Amit Kapila
Backpatch-through: 15
Discussion: http://postgr.es/m/18203-df37fe354b626670@postgresql.org

17 months agoStop the search once the slot for replication origin is found.
Amit Kapila [Wed, 22 Nov 2023 03:09:24 +0000 (08:39 +0530)]
Stop the search once the slot for replication origin is found.

In replorigin_session_setup(), we were needlessly looping for
max_replication_slots even after finding an existing slot for the origin.
This shouldn't hurt us much except for probably large values of
max_replication_slots.

Author: Antonin Houska
Discussion: http://postgr.es/m/2694.1700471273@antos

17 months agodoc: FreeBSD uses camcontrol identify, not atacontrol, for cache
Bruce Momjian [Wed, 22 Nov 2023 01:09:20 +0000 (20:09 -0500)]
doc: FreeBSD uses camcontrol identify, not atacontrol, for cache

This is for IDE drive cache control, same as SCSI (already documented
properly).

Reported-by: John Ekins
Discussion: https://postgr.es/m/20170808224017.8424.69170@wrigleys.postgresql.org

Author: John Ekins

Backpatch-through: 12

17 months agoFix query checking consistency of table amhandlers in opr_sanity.sql
Michael Paquier [Wed, 22 Nov 2023 00:32:06 +0000 (09:32 +0900)]
Fix query checking consistency of table amhandlers in opr_sanity.sql

As written, the query checked for an access method of type 's', which is
not an AM type supported in the core code.

Error introduced by 8586bf7ed888.  As this query is not checking what it
should, backpatch all the way down.

Reviewed-by: Aleksander Alekseev
Discussion: https://postgr.es/m/ZVxJkAJrKbfHETiy@paquier.xyz
Backpatch-through: 12

17 months agodoc: vacuum_cost_limit controls when vacuum_cost_delay happens
Bruce Momjian [Tue, 21 Nov 2023 20:32:04 +0000 (15:32 -0500)]
doc:  vacuum_cost_limit controls when vacuum_cost_delay happens

Mention this relationship.

Reported-by: Martín Marqués
Discussion: https://postgr.es/m/CABeG9LtsAVP4waKngUYo-HAiiowcb8xEjQvDDfhX_nFi5SJ4jw@mail.gmail.com

Author: Martín Marqués

Backpatch-through: master

17 months agoRemove unneeded assignments in for loop header
Alvaro Herrera [Tue, 21 Nov 2023 15:10:27 +0000 (16:10 +0100)]
Remove unneeded assignments in for loop header

The last use of this variable in the loop body was removed by commit
93df658a0189.

17 months agoAvoid overflow in fe_utils' printTable()
Alvaro Herrera [Tue, 21 Nov 2023 13:55:29 +0000 (14:55 +0100)]
Avoid overflow in fe_utils' printTable()

The original code would miscalculate the total number of cells when the
table to print has more than ~4 billion cells, leading to an unnecessary
error.  Repair by changing some computations to be 64-bits wide.  Add
some necessary overflow checks.

Author: Hongxu Ma <interma@outlook.com>
Discussion: https://postgr.es/m/TYBP286MB0351B057B101C90D7C1239E6B4E2A@TYBP286MB0351.JPNP286.PROD.OUTLOOK.COM

17 months agoSimplify some logic in CreateReplicationSlot()
Michael Paquier [Tue, 21 Nov 2023 04:55:01 +0000 (13:55 +0900)]
Simplify some logic in CreateReplicationSlot()

This refactoring reduces the code in charge of creating replication
slots from two "if" block to a single one, making it slightly cleaner.

This change is possible since 1d04a59be31b, that has removed the
intermediate code that existed between the two "if" blocks in charge of
initializing the output message buffer.

Author: Peter Smith
Discussion: https://postgr.es/m/CAHut+PtnJzqKT41Zt8pChRzba=QgCqjtfYvcf84NMj3VFJoKfw@mail.gmail.com

17 months agoLog messages for replication slot acquisition and release.
Amit Kapila [Tue, 21 Nov 2023 02:29:53 +0000 (07:59 +0530)]
Log messages for replication slot acquisition and release.

This commit log messages (at LOG level when log_replication_commands is
set, otherwise at DEBUG1 level) when walsenders acquire and release
replication slots. These messages help to know the lifetime of a
replication slot - one can know how long a streaming standby, logical
subscriber, or replication slot consumer is down. These messages will be
useful on production servers to debug and analyze inactive replication
slots.

Note that these messages are emitted only for walsenders but not for
backends. This is because walsenders are the ones that typically hold
replication slots for longer durations, unlike backends which hold them
for executing replication related functions.

Author: Bharath Rupireddy
Reviewed-by: Peter Smith, Amit Kapila, Alvaro Herrera
Discussion: http://postgr.es/m/CALj2ACX17G7F-jeLt+7KhJ6YxVeRwR8Zk0rDh4VnT546o0UpTQ@mail.gmail.com

17 months agomeson: Document build targets, add 'help' target
Andres Freund [Tue, 21 Nov 2023 01:46:40 +0000 (17:46 -0800)]
meson: Document build targets, add 'help' target

Currently important build targets are somewhat hard to discover. This commit
documents important meson build targets in the sgml documentation. But it's
awkward to have to lookup build targets in the docs when hacking, so this also
adds a 'help' target, printing out the same information. To avoid having to
duplicate information in two places, generate both docbook and interactive
docs from a single source.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/20231108232121.ww542mt6lfo6f26f@awork3.anarazel.de

17 months agomeson: Add 'world' target
Andres Freund [Tue, 21 Nov 2023 01:46:40 +0000 (17:46 -0800)]
meson: Add 'world' target

We have this for make as well.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/20231103163848.26egkh5qdgw3vmil@awork3.anarazel.de

17 months agodocs: meson: Change what 'docs' target builds
Andres Freund [Tue, 21 Nov 2023 01:46:40 +0000 (17:46 -0800)]
docs: meson: Change what 'docs' target builds

This undoes the change in what the 'docs' target builds 969509c3f2e. Tom was
concerned with having a target to just build the html docs, which a prior
commit now provided explicitly.

A subsequent commit will overhaul the documentation for the documentation
targets.

While at it, move all target in doc/src/sgml/Makefile up to just after the
default "html" target, and add a comment explaining "all" is *not* the default
target.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/20230209203855.njrepiupc3rmehfw@awork3.anarazel.de
Discussion: https://postgr.es/m/20231103163848.26egkh5qdgw3vmil@awork3.anarazel.de

17 months agomeson: docs: Add {html,man} targets, rename install-doc-*
Andres Freund [Tue, 21 Nov 2023 01:46:40 +0000 (17:46 -0800)]
meson: docs: Add {html,man} targets, rename install-doc-*

We have toplevel html, man targets in the autoconf build as well. It'd be odd
to have an 'html' target but have the install target be 'install-doc-html',
thus rename the install targets to match.

Reviewed-by: Christoph Berg <myon@debian.org>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/20231103163848.26egkh5qdgw3vmil@awork3.anarazel.de

17 months agoOptimize check_search_path() by using SearchPathCache.
Jeff Davis [Mon, 20 Nov 2023 23:53:42 +0000 (15:53 -0800)]
Optimize check_search_path() by using SearchPathCache.

A hash lookup is faster than re-validating the string, particularly
because we use SplitIdentifierString() for validation.

Important when search_path changes frequently.

Discussion: https://postgr.es/m/04c8592dbd694e4114a3ed87139a7a04e4363030.camel%40j-davis.com

17 months agoBe more paranoid about OOM in search_path cache.
Jeff Davis [Mon, 20 Nov 2023 23:21:30 +0000 (15:21 -0800)]
Be more paranoid about OOM in search_path cache.

Recent commit f26c2368dc introduced a search_path cache, but left some
potential out-of-memory hazards. Simplify the code and make it safer
against OOM.

This change reintroduces one list_copy(), losing a small amount of the
performance gained in f26c2368dc. A future change may optimize away
the list_copy() again if it can be done in a safer way.

Discussion: https://postgr.es/m/e6fded24cb8a2c53d4ef069d9f69cc7baaafe9ef.camel@j-davis.com

17 months agoPrevent overflow for block number in buffile.c
Michael Paquier [Mon, 20 Nov 2023 00:14:53 +0000 (09:14 +0900)]
Prevent overflow for block number in buffile.c

As coded, the start block calculated by BufFileAppend() would overflow
once more than 16k files are used with a default block size.  This issue
existed before b1e5c9fa9ac4, but there's no reason not to be clean about
it.

Per report from Coverity, with a fix suggested by Tom Lane.

17 months agoLock table in DROP STATISTICS
Tomas Vondra [Sun, 19 Nov 2023 20:03:29 +0000 (21:03 +0100)]
Lock table in DROP STATISTICS

The DROP STATISTICS code failed to properly lock the table, leading to

  ERROR:  tuple concurrently deleted

when executed concurrently with ANALYZE.

Fixed by modifying RemoveStatisticsById() to acquire the same lock as
ANALYZE. This function is called only by DROP STATISTICS, as ANALYZE
calls RemoveStatisticsDataById() directly.

Reported by Justin Pryzby, fix by me. Backpatch through 12. The code was
like this since it was introduced in 10, but older releases are EOL.

Reported-by: Justin Pryzby
Reviewed-by: Tom Lane
Backpatch-through: 12

Discussion: https://postgr.es/m/ZUuk-8CfbYeq6g_u@pryzbyj2023

17 months agoGuard against overflow in interval_mul() and interval_div().
Dean Rasheed [Sat, 18 Nov 2023 14:41:20 +0000 (14:41 +0000)]
Guard against overflow in interval_mul() and interval_div().

Commits 146604ec43 and a898b409f6 added overflow checks to
interval_mul(), but not to interval_div(), which contains almost
identical code, and so is susceptible to the same kinds of
overflows. In addition, those checks did not catch all possible
overflow conditions.

Add additional checks to the "cascade down" code in interval_mul(),
and copy all the overflow checks over to the corresponding code in
interval_div(), so that they both generate "interval out of range"
errors, rather than returning bogus results.

Given that these errors are relatively easy to hit, back-patch to all
supported branches.

Per bug #18200 from Alexander Lakhin, and subsequent investigation.

Discussion: https://postgr.es/m/18200-5ea288c7b2d504b1%40postgresql.org

17 months agodoc: improve description of privileges for MERGE and update glossary.
Dean Rasheed [Sat, 18 Nov 2023 12:41:23 +0000 (12:41 +0000)]
doc: improve description of privileges for MERGE and update glossary.

On the MERGE page, the description of the privileges required could be
taken to imply that the SELECT privilege is required on all columns of
the data source, whereas actually it is only required on the columns
referred to by conditions or expressions in the MERGE command. Re-word
it to make that a little clearer, and mention expressions as well as
conditions.

Also, add a glossary entry for MERGE, and nearby on the glossary page,
mention MERGE in the list of commands that cannot update a
materialized view.

Noted by Jian He. Patch by me, reviewed by Jian He.

Discussion: https://postgr.es/m/CACJufxHuSoRXKwr0MtSFLXuT2nFVWcVfEWhxg7qdP9h%2Bs3a%2BUw%40mail.gmail.com

17 months agomeson: Fix missing dependency from install-quiet to sepgsql.sql
Andres Freund [Sat, 18 Nov 2023 00:29:48 +0000 (16:29 -0800)]
meson: Fix missing dependency from install-quiet to sepgsql.sql

This could lead to an error like

ERROR: File 'contrib/sepgsql/sepgsql.sql' could not be found

Backpatch: 16-, where meson was added

17 months agosimplehash: preserve consistency in case of OOM.
Jeff Davis [Fri, 17 Nov 2023 21:58:16 +0000 (13:58 -0800)]
simplehash: preserve consistency in case of OOM.

Compute size first, then allocate, then update the structure.

Previously, an out-of-memory when growing could leave the hashtable in
an inconsistent state.

Discussion: https://postgr.es/m/20231117201334.eyb542qr5yk4gilq@awork3.anarazel.de
Reviewed-by: Andres Freund
Reviewed-by: Gurjeet Singh
17 months agodocs: Fix standalone INSTALL, broken in 06c70849fb2
Andres Freund [Fri, 17 Nov 2023 21:35:17 +0000 (13:35 -0800)]
docs: Fix standalone INSTALL, broken in 06c70849fb2

We should probably check that INSTALL can be generated in CI.

Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/795075.1700254192@sss.pgh.pa.us

17 months agodoc: update query section to show LIMIT/OFFSET like SELECT
Bruce Momjian [Fri, 17 Nov 2023 21:46:43 +0000 (16:46 -0500)]
doc:  update query section to show LIMIT/OFFSET like SELECT

The parameter names were slightly better in SELECT, so make them match.

Reported-by: Euler Taveira
Discussion: https://postgr.es/m/CAHE3wgh-EYuAbLG1VS3QTHii1TgWS31h-fYEgrdda7oTOuskOQ@mail.gmail.com

Backpatch-through: master

17 months agoRelease lock on heap buffer before vacuuming FSM
Andres Freund [Fri, 17 Nov 2023 19:02:52 +0000 (11:02 -0800)]
Release lock on heap buffer before vacuuming FSM

When there are no indexes on a table, we vacuum each heap block after
pruning it and then update the freespace map. Periodically, we also
vacuum the freespace map. This was done while unnecessarily holding a
lock on the heap page. Release the lock before calling
FreeSpaceMapVacuumRange() and, while we're at it, ensure the range
includes the heap block we just vacuumed.

There are no known deadlocks or other similar issues, therefore don't
backpatch. It's certainly not good to do all this work under a lock, but it's
not frequently reached, making it not worth the risk of backpatching.

Author: Melanie Plageman <melanieplageman@gmail.com>
Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/CAAKRu_YiL%3D44GvGnt1dpYouDSSoV7wzxVoXs8m3p311rp-TVQQ%40mail.gmail.com

17 months agoExtract column statistics from CTE references, if possible.
Tom Lane [Fri, 17 Nov 2023 19:36:23 +0000 (14:36 -0500)]
Extract column statistics from CTE references, if possible.

examine_simple_variable() left this as an unimplemented case years
ago, with the result that plans for queries involving un-flattened
CTEs might be much stupider than necessary.  It's not hard to extend
the existing logic for RTE_SUBQUERY cases to also be able to drill
down into CTEs, so let's do that.

There was some discussion of whether this patch breaks the idea
of a MATERIALIZED CTE being an optimization fence.  We concluded
it's okay, because we already allow the outer planner level to
see the estimated width and rowcount of the CTE result, and
letting it see column statistics too seems fairly equivalent.
Basically, what we expect of the optimization fence is that the
outer query should not affect the plan chosen for the CTE query.
Once that plan is chosen, it's okay for the outer planner level
to make use of whatever information we have about it.

Jian Guo and Tom Lane, per complaint from Hans Buschmann

Discussion: https://postgr.es/m/4504e67078d648cdac3651b2960da6e7@nidsa.net

17 months agodocs: Document --with-selinux/-Dselinux options centrally
Andres Freund [Fri, 17 Nov 2023 18:23:02 +0000 (10:23 -0800)]
docs: Document --with-selinux/-Dselinux options centrally

Previously --with-selinux was documented only in the in the sepgsql
documentation and there was no corresponding documentation for meson. There
are further improvements that could be made, but this change seems worthwhile
even on its own.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reported-by: Christoph Berg <myon@debian.org>
Discussion: https://postgr.es/m/20231103163848.26egkh5qdgw3vmil@awork3.anarazel.de

17 months agomeson: Change default of 'selinux' feature option to auto
Andres Freund [Fri, 17 Nov 2023 18:23:02 +0000 (10:23 -0800)]
meson: Change default of 'selinux' feature option to auto

There is really no reason for selinux to behave differently than other
options.

Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Discussion: https://postgr.es/m/20231103211601.bgqx3cfq6pz2lmjw@awork3.anarazel.de

17 months agoAllow tests to pass in OpenSSL FIPS mode (rest)
Peter Eisentraut [Fri, 17 Nov 2023 13:40:13 +0000 (14:40 +0100)]
Allow tests to pass in OpenSSL FIPS mode (rest)

This adds alternative expected files for various tests.

In src/test/regress/sql/password.sql, we make a small change to the
test so that the CREATE ROLE still succeeds even if the ALTER ROLE
that attempts to set a password might fail.  That way, the roles are
available for the rest of the test file in either case.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://www.postgresql.org/message-id/flat/dbbd927f-ef1f-c9a1-4ec6-c759778ac852%40enterprisedb.com

17 months agoDon't specify number of dimensions in cases where we don't know it.
Tom Lane [Fri, 17 Nov 2023 16:29:42 +0000 (11:29 -0500)]
Don't specify number of dimensions in cases where we don't know it.

A few places in array_in() and plperl would report a misleading value
(always MAXDIM+1) for the number of dimensions in the input, because
we'd error out as soon as that was clearly too large rather than
scanning the entire input.  There doesn't seem to be much value in
offering the true number, at least not enough to justify the extra
complication involved in trying to get it.  So just remove that
parenthetical remark.  We already have other places that do it
like that, anyway.

Per suggestions from Alexander Lakhin and Heikki Linnakangas.

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

17 months agoAllow tests to pass in OpenSSL FIPS mode (TAP tests)
Peter Eisentraut [Fri, 17 Nov 2023 13:40:13 +0000 (14:40 +0100)]
Allow tests to pass in OpenSSL FIPS mode (TAP tests)

Some tests using md5 authentication have to be skipped.  In other
cases, we can rewrite the tests to use a different authentication
method.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://www.postgresql.org/message-id/flat/dbbd927f-ef1f-c9a1-4ec6-c759778ac852%40enterprisedb.com

17 months agopgcrypto: Allow tests to pass in OpenSSL FIPS mode
Peter Eisentraut [Fri, 17 Nov 2023 13:40:13 +0000 (14:40 +0100)]
pgcrypto: Allow tests to pass in OpenSSL FIPS mode

This adds several alternative expected files for when MD5 and 3DES are
not available.  This is similar to the alternative expected files for
when the legacy provider is disabled.  In fact, running the pgcrypto
tests in FIPS mode makes use of some of these existing alternative
expected files as well (e.g., for blowfish).

These new expected files currently cover the FIPS mode provided by
OpenSSL 3.x as well as the modified OpenSSL 3.x from Red Hat (e.g.,
Fedora 38), but not the modified OpenSSL 1.x from Red Hat (e.g.,
Fedora 35).  (The latter will have some error message wording
differences.)

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://www.postgresql.org/message-id/flat/dbbd927f-ef1f-c9a1-4ec6-c759778ac852%40enterprisedb.com

17 months agoChange logtape/tuplestore code to use int64 for block numbers
Michael Paquier [Fri, 17 Nov 2023 02:20:53 +0000 (11:20 +0900)]
Change logtape/tuplestore code to use int64 for block numbers

The code previously relied on "long" as type to track block numbers,
which would be 4 bytes in all Windows builds or any 32-bit builds.  This
limited the code to be able to handle up to 16TB of data with the
default block size of 8kB, like during a CLUSTER.  This code now relies
on a more portable int64, which should be more than enough for at least
the next 20 years to come.

This issue has been reported back in 2017, but nothing was done about it
back then, so here we go now.

Reported-by: Peter Geoghegan
Reviewed-by: Heikki Linnakangas
Discussion: https://postgr.es/m/CAH2-WznCscXnWmnj=STC0aSa7QG+BRedDnZsP=Jo_R9GUZvUrg@mail.gmail.com

17 months agoRemove NOT_USED BufFileTellBlock() from buffile.c
Michael Paquier [Fri, 17 Nov 2023 01:46:50 +0000 (10:46 +0900)]
Remove NOT_USED BufFileTellBlock() from buffile.c

This routine has been marked as NOT_USED since 20ad43b576d9 from 2000,
and a patch is planned to switch the logtape/tuplestore APIs to rely on
int64 rather than long for the block nunbers, which is more portable.

Keeping it is more confusing than anything at this stage, so let's get
rid of it entirely.

Thanks for Heikki Linnakangas for the poke on this one.

Discussion: https://postgr.es/m/5047be8c-7ee6-4dd5-af76-6c916c3103b4@iki.fi

17 months agopgcrypto: Split off pgp-encrypt-md5 test
Peter Eisentraut [Thu, 16 Nov 2023 14:57:21 +0000 (15:57 +0100)]
pgcrypto: Split off pgp-encrypt-md5 test

In FIPS mode, these tests will fail.  By having them in a separate
file, it would make it easier to have an alternative output file or
selectively disable these tests.  This isn't done here; this is just
some preparation.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://www.postgresql.org/message-id/2766054.1700080156@sss.pgh.pa.us

17 months agoEnsure we preprocess expressions before checking their volatility.
Tom Lane [Thu, 16 Nov 2023 15:05:14 +0000 (10:05 -0500)]
Ensure we preprocess expressions before checking their volatility.

contain_mutable_functions and contain_volatile_functions give
reliable answers only after expression preprocessing (specifically
eval_const_expressions).  Some places understand this, but some did
not get the memo --- which is not entirely their fault, because the
problem is documented only in places far away from those functions.
Introduce wrapper functions that allow doing the right thing easily,
and add commentary in hopes of preventing future mistakes from
copy-and-paste of code that's only conditionally safe.

Two actual bugs of this ilk are fixed here.  We failed to preprocess
column GENERATED expressions before checking mutability, so that the
code could fail to detect the use of a volatile function
default-argument expression, or it could reject a polymorphic function
that is actually immutable on the datatype of interest.  Likewise,
column DEFAULT expressions weren't preprocessed before determining if
it's safe to apply the attmissingval mechanism.  A false negative
would just result in an unnecessary table rewrite, but a false
positive could allow the attmissingval mechanism to be used in a case
where it should not be, resulting in unexpected initial values in a
new column.

In passing, re-order the steps in ComputePartitionAttrs so that its
checks for invalid column references are done before applying
expression_planner, rather than after.  The previous coding would
not complain if a partition expression contains a disallowed column
reference that gets optimized away by constant folding, which seems
to me to be a behavior we do not want.

Per bug #18097 from Jim Keener.  Back-patch to all supported versions.

Discussion: https://postgr.es/m/18097-ebb179674f22932f@postgresql.org

17 months agoExplicitly skip TAP tests under Meson if disabled
Peter Eisentraut [Thu, 16 Nov 2023 07:06:12 +0000 (08:06 +0100)]
Explicitly skip TAP tests under Meson if disabled

If the tap_tests option is disabled under Meson, the TAP tests are
currently not registered at all.  But this makes it harder to see what
is going on, why suddently there are fewer tests than before.

Instead, run testwrap with an option that marks the test as skipped.
That way, the total list and count of tests is constant whether the
option is enabled or not.

Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://www.postgresql.org/message-id/ad5ec96d-69ec-317b-a137-367ea5019b61@eisentraut.org

17 months agoAdd target "slru" to pg_stat_reset_shared()
Michael Paquier [Thu, 16 Nov 2023 06:41:34 +0000 (15:41 +0900)]
Add target "slru" to pg_stat_reset_shared()

Currently, pg_stat_reset_shared() cannot reset the counters in the view
pg_stat_slru even if it is a type of shared stats.  This patch adds
support for a new value in pg_stat_reset_shared(), called "slru", able
to do that.  Note that pg_stat_reset_shared(NULL) also resets SLRU
counters.

There may be a point in removing pg_stat_reset_slru() that was
introduced in 28cac71bd368 (v13~) as the new option overlaps with this
function, but we would lose the ability to reset individual SLRU
counters.  This is left for future reconsideration.

Author: Atsushi Torikoshi
Discussion: https://postgr.es/m/e3c25d72e81378e7b64f3c52e0306fc9@oss.nttdata.com

17 months agopsql: Add some completion support for CREATE TABLE .. AS
Michael Paquier [Thu, 16 Nov 2023 00:44:29 +0000 (09:44 +0900)]
psql: Add some completion support for CREATE TABLE .. AS

"AS" is added as a suggested keyword for CREATE TABLE for a few query
patterns, including the case where a list of columns is given in
parenthesis.

More queries can be now completed with the keywords supported for
queries in a CTAS, after:
CREATE TABLE [TEMP|TEMPORARY|UNLOGGED] <name> [ (...) ] AS

Author: Gilles Darold
Reviewed-by: Jim Jones
Discussion: https://postgr.es/m/e462b251-99a7-4abc-aedc-214688742c80@darold.net

17 months agoFix fallback implementation for pg_atomic_test_set_flag().
Nathan Bossart [Wed, 15 Nov 2023 21:04:18 +0000 (15:04 -0600)]
Fix fallback implementation for pg_atomic_test_set_flag().

The fallback implementation of pg_atomic_test_set_flag() that uses
atomic-exchange gives pg_atomic_exchange_u32_impl() an extra
argument.  This issue has been present since the introduction of
the atomics API in commit b64d92f1a5.

Reviewed-by: Andres Freund
Discussion: https://postgr.es/m/20231114035439.GA1809032%40nathanxps13
Backpatch-through: 12

17 months agoRetire MemoryContextResetAndDeleteChildren() macro.
Nathan Bossart [Wed, 15 Nov 2023 19:42:30 +0000 (13:42 -0600)]
Retire MemoryContextResetAndDeleteChildren() macro.

As of commit eaa5808e8e, MemoryContextResetAndDeleteChildren() is
just a backwards compatibility macro for MemoryContextReset().  Now
that some time has passed, this macro seems more likely to create
confusion.

This commit removes the macro and replaces all remaining uses with
calls to MemoryContextReset().  Any third-party code that use this
macro will need to be adjusted to call MemoryContextReset()
instead.  Since the two have behaved the same way since v9.5, such
adjustments won't produce any behavior changes for all
currently-supported versions of PostgreSQL.

Reviewed-by: Amul Sul, Tom Lane, Alvaro Herrera, Dagfinn Ilmari Mannsåker
Discussion: https://postgr.es/m/20231113185950.GA1668018%40nathanxps13

17 months agosrc/test/modules/test_dsa needs a .gitignore file.
Tom Lane [Wed, 15 Nov 2023 18:59:54 +0000 (13:59 -0500)]
src/test/modules/test_dsa needs a .gitignore file.

Without this, "git status" is unhappy after a check-world run.
Oversight in 325f54033.

17 months agodoc: align column order with pg_stat_statements view
Daniel Gustafsson [Wed, 15 Nov 2023 13:07:00 +0000 (14:07 +0100)]
doc: align column order with pg_stat_statements view

Commit 5a3423ad8e mistakenly didn't plac the new columns for JIT
deform counters at the end to match their placement in the view.
Fix by placing the new columns last to be consistent.

Author: Julien Rouhaud <rjuju123@gmail.com>
Discussion: https://postgr.es/m/fuhxmigipmodhq3bah5iddd2ksfinrva75wqjyg2g2e647p4v7@yev2gynrnr5f

17 months agoClear CurrentResourceOwner earlier in CommitTransaction.
Heikki Linnakangas [Wed, 15 Nov 2023 09:34:35 +0000 (10:34 +0100)]
Clear CurrentResourceOwner earlier in CommitTransaction.

Alexander reported a crash with repeated create + drop database, after
the ResourceOwner rewrite (commit b8bff07daa). That was fixed by the
previous commit, but it nevertheless seems like a good idea clear
CurrentResourceOwner earlier, because you're not supposed to use it
for anything after we start releasing it.

Reviewed-by: Alexander Lakhin
Discussion: https://www.postgresql.org/message-id/11b70743-c5f3-3910-8e5b-dd6c115ff829%40gmail.com

17 months agoAdd test_dsa module.
Heikki Linnakangas [Wed, 15 Nov 2023 09:34:31 +0000 (10:34 +0100)]
Add test_dsa module.

This covers basic calls within a single backend process, and also
calling dsa_allocate() or dsa_get_address() while in a different
resource owners. The latter case was fixed by the previous commit.

Discussion: https://www.postgresql.org/message-id/11b70743-c5f3-3910-8e5b-dd6c115ff829%40gmail.com

17 months agoFix dsa.c with different resource owners.
Heikki Linnakangas [Wed, 15 Nov 2023 09:34:28 +0000 (10:34 +0100)]
Fix dsa.c with different resource owners.

The comments in dsa.c suggested that areas were owned by resource
owners, but it was not in fact tracked explicitly. The DSM attachments
held by the dsa were owned by resource owners, but not the area
itself.  That led to confusion if you used one resource owner to
attach or create the area, but then switched to a different resource
owner before allocating or even just accessing the allocations in the
area with dsa_get_address(). The additional DSM segments associated
with the area would get owned by a different resource owner than the
initial segment.  To fix, add an explicit 'resowner' field to
dsa_area.  It replaces the 'mapping_pinned' flag; resowner == NULL now
indicates that the mapping is pinned.

This is arguably a bug fix, but I'm not backpatching because it
doesn't seem to be a live bug in the back branches. In 'master', it is
a bug because commit b8bff07daa made ResourceOwners more strict so
that you are no longer allowed to remember new resources in a
ResourceOwner after you have started to release it. Merely accessing a
dsa pointer might need to attach a new DSM segment, and before this
commit it was temporarily remembered in the current owner for a very
brief period even if the DSA was pinned. And that could happen in
AtEOXact_PgStat(), which is called after the owner is already released.

Reported-by: Alexander Lakhin
Reviewed-by: Alexander Lakhin, Thomas Munro, Andres Freund
Discussion: https://www.postgresql.org/message-id/11b70743-c5f3-3910-8e5b-dd6c115ff829%40gmail.com

17 months agoAdd cache for recomputeNamespacePath().
Jeff Davis [Wed, 15 Nov 2023 01:51:03 +0000 (17:51 -0800)]
Add cache for recomputeNamespacePath().

When search_path is changed to something that was previously set, and
no invalidation happened in between, use the cached list of namespace
OIDs rather than recomputing them. This avoids syscache lookups and
ACL checks.

Important when the search_path changes frequently, such as when set in
proconfig.

An earlier version of this patch was reviewd by Nathan Bossart. This
version simplifies a few things and is safer in case of OOM.

Discussion: https://www.postgresql.org/message-id/abf4ce8804e0e05dff8c1725ae6a8ed28b7d66e0.camel%40j-davis.com
Reviewed-by: Nathan Bossart
17 months agodoc: Improve description of targets for pg_stat_reset_shared()
Michael Paquier [Wed, 15 Nov 2023 00:41:10 +0000 (09:41 +0900)]
doc: Improve description of targets for pg_stat_reset_shared()

This commit changes the documentation so as the supported targets are
documented with itemized list, making it easier to understand the view a
given target affects.

Author: Atsushi Torikoshi
Discussion: https://postgr.es/m/e3c25d72e81378e7b64f3c52e0306fc9@oss.nttdata.com

18 months agoChange how a base backup decides which files have checksums.
Robert Haas [Tue, 14 Nov 2023 15:51:05 +0000 (10:51 -0500)]
Change how a base backup decides which files have checksums.

Previously, it thought that any plain file located under global, base,
or a tablespace directory had checksums unless it was in a short list
of excluded files. Now, it thinks that files in those directories have
checksums if parse_filename_for_nontemp_relation says that they are
relation files. (Temporary relation files don't matter because they're
excluded from the backup anyway.)

This changes the behavior if you have stray files not managed by
PostgreSQL in the relevant directories. Previously, you'd get some
kind of checksum-related complaint if such files existed, assuming
that the cluster had checksums enabled and that the base backup
wasn't run with NOVERIFY_CHECKSUMS. Now, you won't get those
complaints any more. That seems like an improvement to me, because
those files were presumably not created by PostgreSQL and so there
is no reason to think that they would be checksummed like a
PostgreSQL relation file. (If we want to complain about such files,
we should complain about them existing at all, not just about their
checksums.)

The point of this change is to make the code more consistent.
sendDir() was already calling parse_filename_for_nontemp_relation()
as part of an effort to determine which files to include in the
backup. So, it already had the information about whether a certain
file was a relation file. sendFile() then used a separate method,
embodied in is_checksummed_file(), to make what is essentially
the same determination. It's better not to make the same decision
using two different methods, especially in closely-related code.

Patch by me. Reviewed by Dilip Kumar and Álvaro Herrera. Thanks
also to Jakub Wartak and Peter Eisentraut for comments, suggestions,
and testing on the larger patch set of which this is a part.

Discussion: http://postgr.es/m/CAFiTN-snhaKkWhi2Gz5i3cZeKefun6sYL==wBoqqnTXxX4_mFA@mail.gmail.com
Discussion: http://postgr.es/m/202311141312.u4qx5gtpvfq3@alvherre.pgsql

18 months agoSupport +/- infinity in the interval data type.
Dean Rasheed [Tue, 14 Nov 2023 10:58:49 +0000 (10:58 +0000)]
Support +/- infinity in the interval data type.

This adds support for infinity to the interval data type, using the
same input/output representation as the other date/time data types
that support infinity. This allows various arithmetic operations on
infinite dates, timestamps and intervals.

The new values are represented by setting all fields of the interval
to INT32/64_MIN for -infinity, and INT32/64_MAX for +infinity. This
ensures that they compare as less/greater than all other interval
values, without the need for any special-case comparison code.

Note that, since those 2 values were formerly accepted as legal finite
intervals, pg_upgrade and dump/restore from an old database will turn
them from finite to infinite intervals. That seems OK, since those
exact values should be extremely rare in practice, and they are
outside the documented range supported by the interval type, which
gives us a certain amount of leeway.

Bump catalog version.

Joseph Koshakow, Jian He, and Ashutosh Bapat, reviewed by me.

Discussion: https://postgr.es/m/CAAvxfHea4%2BsPybKK7agDYOMo9N-Z3J6ZXf3BOM79pFsFNcRjwA%40mail.gmail.com

18 months agodoc: Update note about Bison and Flex build requirements
Peter Eisentraut [Tue, 14 Nov 2023 10:00:49 +0000 (11:00 +0100)]
doc: Update note about Bison and Flex build requirements

Updating the Windows-specific chapter was forgotten by 721856ff24.

18 months agoFix capitalization of "Tcl"
Peter Eisentraut [Tue, 14 Nov 2023 09:44:44 +0000 (10:44 +0100)]
Fix capitalization of "Tcl"

18 months agoFix whitespace
Peter Eisentraut [Tue, 14 Nov 2023 09:41:17 +0000 (10:41 +0100)]
Fix whitespace

18 months agoReplace Gen_dummy_probes.sed with Gen_dummy_probes.pl
Peter Eisentraut [Tue, 14 Nov 2023 08:47:07 +0000 (09:47 +0100)]
Replace Gen_dummy_probes.sed with Gen_dummy_probes.pl

To generate a dummy probes.h file when dtrace is not available, we had
two different scripts: A sed version, which is the original version,
and a Perl version, which was generated by s2p.  This split was
necessary because Perl was not a mandatory build dependency on Unix,
but sed was not guaranteed to be available on Windows.

(The Meson build system used the sed version even on Windows, which
was probably incorrect and probably would have had to be fixed before
elevating that build system from experimental status.)

As of 721856ff24, Perl is a required build dependency, so this split
is no longer necessary.  We can just use the Perl script in all build
environments and remove a whole bunch of infrastructure to keep the
two variants in sync.

The new Gen_dummy_probes.pl is not the version generated by s2p but a
new implementation written by hand by adapting the sed version to Perl
syntax.

Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://www.postgresql.org/message-id/3fd0f1bc-4483-4ba9-8aa0-64765b052039@eisentraut.org

18 months agoAllow new role 'regress_dump_login_role' to log in under SSPI.
Tom Lane [Tue, 14 Nov 2023 05:31:39 +0000 (00:31 -0500)]
Allow new role 'regress_dump_login_role' to log in under SSPI.

Semi-blind attempt to fix a70f2a57f to work on Windows,
along the same lines as 5253519b2.  Per buildfarm.

18 months agoAdd support for pg_stat_reset_slru without argument
Michael Paquier [Tue, 14 Nov 2023 00:50:52 +0000 (09:50 +0900)]
Add support for pg_stat_reset_slru without argument

pg_stat_reset_slru currently requires an input argument, either:
- NULL to reset the SLRU counters of everything.
- A specific value to reset a single SLRU cache.

This commit adds support for a new pattern: pg_stat_reset_slru without
any argument works the same way as pg_stat_reset_slru(NULL), relying on
a DEFAULT in the function definition to handle this case.  This makes
the function more consistent with 23c8c0c8f472.

Bump catalog version.

Author: Bharath Rupireddy
Reviewed-by: Atsushi Torikoshi
Discussion: https://postgr.es/m/CALj2ACW1VizYg01EeH_cA-7qA+4NzWVAoZ5Lw9_XYO1RRHAZbA@mail.gmail.com

18 months agoDon't try to dump RLS policies or security labels for extension objects.
Tom Lane [Mon, 13 Nov 2023 22:04:10 +0000 (17:04 -0500)]
Don't try to dump RLS policies or security labels for extension objects.

checkExtensionMembership() set the DUMP_COMPONENT_SECLABEL and
DUMP_COMPONENT_POLICY flags for extension member objects, even though
we lack any infrastructure for tracking extensions' initial settings
of these properties.  This is not OK.  The result was that a dump
would always include commands to set these properties for extension
objects that have them, with at least three negative consequences:

1. The restoring user might not have privilege to set these properties
on these objects.

2. The properties might be incorrect/irrelevant for the version of the
extension that's installed in the destination database.

3. The dump itself might fail, in the case of RLS properties attached
to extension tables that the dumping user lacks privilege to LOCK.
(That's because we must get at least AccessShareLock to ensure that
we don't fail while trying to decompile the RLS expressions.)

When and if somebody cares to invent initial-state infrastructure for
extensions' RLS policies and security labels, we could think about
finding another way around problem #3.  But in the absence of such
infrastructure, this whole thing is just wrong and we shouldn't do it.

(Note: this applies only to ordinary dumps; binary-upgrade dumps
still dump and restore extension member objects separately, with
all properties.)

Tom Lane and Jacob Champion.  Back-patch to all supported branches.

Discussion: https://postgr.es/m/00d46a48-3324-d9a0-49bf-e7f0f11d1038@timescale.com

18 months agodoc: clarify handling of ts_headline() operators & extra words
Bruce Momjian [Mon, 13 Nov 2023 21:35:55 +0000 (16:35 -0500)]
doc:  clarify handling of ts_headline() operators & extra words

Reported-by: Ngigi Waithaka & Alex Malek
Bug: 15172

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

Backpatch-through: 16

18 months agopsql: improve description consistency of \dTS data types
Bruce Momjian [Mon, 13 Nov 2023 21:26:59 +0000 (16:26 -0500)]
psql:  improve description consistency of \dTS data types

This was done particularly for geometric data types.

Reported-by: Christoph Berg
Discussion: https://postgr.es/m/YGI8Leuk0WvmNWLr@msg.df7cb.de

Co-authored-by: Kyotaro Horiguchi
Backpatch-through: master

18 months agodoc: clarify handling of range upper/lower/upper_inf/lower_inf()
Bruce Momjian [Mon, 13 Nov 2023 21:08:01 +0000 (16:08 -0500)]
doc: clarify handling of range upper/lower/upper_inf/lower_inf()

Clarify handling of infinite range bounds.

Reported-by: jani.rahkola@iki.fi
Discussion: https://postgr.es/m/160508672127.25505.8356390205508789564@wrigleys.postgresql.org

Co-authored-by: Laurenz Albe
Backpatch-through: 16

18 months agoImprove default and empty privilege outputs in psql.
Tom Lane [Mon, 13 Nov 2023 20:41:27 +0000 (15:41 -0500)]
Improve default and empty privilege outputs in psql.

Default privileges are represented as NULL::aclitem[] in catalog ACL
columns, while revoking all privileges leaves an empty aclitem[].
These two cases used to produce identical output in psql meta-commands
like \dp.  Using something like "\pset null '(default)'" as a
workaround for spotting the difference did not work, because null
values were always displayed as empty strings by describe.c's
meta-commands.

This patch improves that with two changes:

1. Print "(none)" for empty privileges so that the user is able to
   distinguish them from default privileges, even without special
   workarounds.

2. Remove the special handling of null values in describe.c,
   so that "\pset null" is honored like everywhere else.
   (This affects all output from these commands, not only ACLs.)

The privileges shown by \dconfig+ and \ddp as well as the column
privileges shown by \dp are not affected by change #1, because the
respective aclitem[] is reset to NULL or deleted from the catalog
instead of leaving an empty array.

Erik Wienhold and Laurenz Albe

Discussion: https://postgr.es/m/1966228777.127452.1694979110595@office.mailbox.org

18 months agodoc: move ROW IS NULL examples to a different chapter
Bruce Momjian [Mon, 13 Nov 2023 20:20:54 +0000 (15:20 -0500)]
doc:  move ROW IS NULL examples to a different chapter

Also add examples.

Reported-by: Wolfgang Walther
Discussion: https://postgr.es/m/21ff8e9c-627a-f949-fb00-a41b9ddcc9d3@technowledgy.de

Backpatch-through: master

18 months agodoc: clarify that pg_global can _only_ be used for system tabs.
Bruce Momjian [Mon, 13 Nov 2023 19:53:38 +0000 (14:53 -0500)]
doc:  clarify that pg_global can _only_ be used for system tabs.

Reported-by: zhoushulin1992@gmail.com
Discussion: https://postgr.es/m/160499688847.25495.8682880307938679648@wrigleys.postgresql.org

Backpatch-through: master

18 months agoAdjust file_fdw regression tests for acc95f29ef FREEZE commit
Bruce Momjian [Mon, 13 Nov 2023 19:44:39 +0000 (14:44 -0500)]
Adjust file_fdw regression tests for acc95f29ef FREEZE commit

Reported-by: Tom Lane
Discussion: https://postgr.es/m/2161529.1699899452@sss.pgh.pa.us

Backpatch-through: master

18 months agodoc: restructure ALTER DEFAULT PRIVILEGES
Bruce Momjian [Mon, 13 Nov 2023 19:27:38 +0000 (14:27 -0500)]
doc:  restructure ALTER DEFAULT PRIVILEGES

Clarify that default privileges are not inherited and reorder
paragraphs.  This is a follow up to a recent ALTER DEFAULT PRIVILEGES
doc patch.

Reported-by: Sanjay Minni
Diagnosed-by: AMpxBo=M35hcH1g4Vg=KRJ0-77FOJcvdrdiVF5KSOAdOG-LvKQ@mail.gmail.com
Co-authored-by: Laurenz Albe
Backpatch-through: 16

18 months agoImprove readability and error detection of array_in().
Tom Lane [Mon, 13 Nov 2023 18:01:47 +0000 (13:01 -0500)]
Improve readability and error detection of array_in().

Rewrite array_in() and its subroutines so that we make only one
pass over the input text, rather than two.  This requires
potentially re-pallocing the working arrays values[] and nulls[]
larger than our initial guess, but that cost will hopefully be made
up by avoiding duplicate parsing.  In any case this coding seems
much clearer and more straightforward than what we had before.

This also fixes array_in() to reject non-rectangular input (that is,
different brace depths in different parts of the input) more reliably
than before, and to give a better error message when it does so.
This is analogous to the plpython and plperl fixes in 0553528e7 and
f47004add.  Like those PLs, we now accept input such as '{{},{}}'
as a valid representation of an empty array, which we did not before.

Additionally, reject explicit array subscripts that are outside the
integer range (previously you just got whatever atoi() converted
them to), and make some other minor improvements in error reporting.

Although this is arguably a bug fix, it's also a behavioral change
that might trip somebody up, so no back-patch.

Tom Lane, Heikki Linnakangas, and Jian He.  Thanks to Alexander Lakhin
for the initial report and for review/testing.

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

18 months agodoc: correct description of libpq's PQsetnonblocking() mode
Bruce Momjian [Mon, 13 Nov 2023 18:01:08 +0000 (13:01 -0500)]
doc:  correct description of libpq's PQsetnonblocking() mode

Reported-by: Yugo NAGATA
Discussion: https://postgr.es/m/20210713115949.702986955f8ccf23fa81073c@sraoss.co.jp

Backpatch-through: master

18 months agoAdd error about the use of FREEZE in COPY TO
Bruce Momjian [Mon, 13 Nov 2023 17:53:03 +0000 (12:53 -0500)]
Add error about the use of FREEZE in COPY TO

Also clarify some other error wording.

Reported-by: Kyotaro Horiguchi
Discussion: https://postgr.es/m/20220802.133046.1941977979333284049.horikyota.ntt@gmail.com

Backpatch-through: master

18 months agodoc: remove RUNAS instructions for pg_upgrade on Windows
Bruce Momjian [Mon, 13 Nov 2023 17:40:38 +0000 (12:40 -0500)]
doc:  remove RUNAS instructions for pg_upgrade on Windows

None of our other tools have such a recommendation.

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

Backpatch-through: master

18 months agoDon't release index root page pin in ginFindParents().
Tom Lane [Mon, 13 Nov 2023 16:44:35 +0000 (11:44 -0500)]
Don't release index root page pin in ginFindParents().

It's clearly stated in the comments that ginFindParents() must keep
the pin on the index's root page that's associated with the topmost
GinBtreeStack item.  However, the code path for the case that the
desired downlink has been pushed down to the next index level
ignored this proviso, and would release the pin anyway if we were
still examining the root level.  That led to an assertion failure
or "buffer NNNN is not owned by resource owner" error later, when
we try to release the pin again at the end of the insertion.

This is quite hard to reproduce, since it can only happen if an
index root page split occurs concurrently with our own insertion.
Thanks to Jeff Janes for finding a test case that triggers it
often enough to allow investigation.

This has been there since the beginning of GIN, so back-patch
to all supported branches.

Discussion: https://postgr.es/m/CAMkU=1yCAKtv86dMrD__Ja-7KzjE=uMeKX8y__cx5W-OEWy2ow@mail.gmail.com

18 months agodoc: Add missing semicolon in example
Daniel Gustafsson [Mon, 13 Nov 2023 13:13:03 +0000 (14:13 +0100)]
doc: Add missing semicolon in example

One of the examples on the SELECT page was missing a semicolon from
a listing which has the look and feel of being a psql session. This
adds the missing semicolon and also removes the newline between the
query and results to match the other examples nearby.

Backpatch to all supported branches to avoid backpatching issues on
this page.

Reported-by: tim.needham2@gmail.com
Discussion: https://postgr.es/m/169965004097.225187.12941375915673151540@wrigleys.postgresql.org
Backpatch-through: v12

18 months agoRemove incorrect file reference in comment.
Etsuro Fujita [Mon, 13 Nov 2023 10:05:00 +0000 (19:05 +0900)]
Remove incorrect file reference in comment.

Commit b7eda3e0e moved XidInMVCCSnapshot() from tqual.c into snapmgr.c,
but follow-up commit c91560def incorrectly updated this reference.  We
could fix it, but as pointed out by Daniel Gustafsson, 1) the reader can
easily find the file that contains the definition of that function, e.g.
by grepping, and 2) this kind of reference is prone to going stale; so
let's just remove it.

Back-patch to all supported branches.

Reviewed by Daniel Gustafsson.

Discussion: https://postgr.es/m/CAPmGK145VdKkPBLWS2urwhgsfidbSexwY-9zCL6xSUJH%2BBTUUg%40mail.gmail.com