postgresql.git
18 months agomeson: docs: Install all manpages, not just ones in man1
Andres Freund [Fri, 3 Nov 2023 18:46:52 +0000 (11:46 -0700)]
meson: docs: Install all manpages, not just ones in man1

In f13eb16485f I made a mistake leading to only man1 being installed. I will
report a bug suggesting that meson warn about mistakes of this sort.

Reported-by: Christoph Berg <myon@debian.org>
Discussion: https://postgr.es/m/ZUU5pRQO6ZUeBsi6@msg.df7cb.de
Backpatch: 16-, where the meson build was introduced

18 months agodoc: move HBA reload instructions above the syntax details
Bruce Momjian [Fri, 3 Nov 2023 18:03:22 +0000 (14:03 -0400)]
doc:  move HBA reload instructions above the syntax details

Reported-by: John <johrss@amazon.com>
Discussion: https://postgr.es/m/165947088723.651.7641196693246068619@wrigleys.postgresql.org

Backpatch-through: master

18 months agodoc: \copy can get data values \. and end-of-input confused
Bruce Momjian [Fri, 3 Nov 2023 17:57:59 +0000 (13:57 -0400)]
doc: \copy can get data values \. and end-of-input confused

Reported-by: Svante Richter
Discussion: https://postgr.es/m/fcd57e4-8f23-4c3e-a5db-2571d09208e2@beta.fastmail.com

Backpatch-through: 11

18 months agodoc: CREATE DATABASE doesn't copy db-level perms. from template
Bruce Momjian [Fri, 3 Nov 2023 17:39:50 +0000 (13:39 -0400)]
doc: CREATE DATABASE doesn't copy db-level perms. from template

Reported-by: david@kapitaltrading.com
Discussion: https://postgr.es/m/166007719137.995877.13951579839074751714@wrigleys.postgresql.org

Backpatch-through: 11

18 months agodoc: mention ORDER BY for some aggregates, add ORDER BY examples
Bruce Momjian [Fri, 3 Nov 2023 17:05:27 +0000 (13:05 -0400)]
doc: mention ORDER BY for some aggregates, add ORDER BY examples

Discussion: https://postgr.es/m/CAKFQuwb+4SWnfrfQKB-UM1P1x97Xk+ybSar4xM32XGLd=fq9bA@mail.gmail.com

Co-authored-by: David G. Johnston
Backpatch-through: master

18 months agoDoc: update CREATE RULE ref page's hoary discussion of views.
Tom Lane [Fri, 3 Nov 2023 15:48:23 +0000 (11:48 -0400)]
Doc: update CREATE RULE ref page's hoary discussion of views.

This text left one with the impression that an ON SELECT rule could
be attached to a plain table, which has not been true since commit
264c06820 (meaning the text was already misleading when written,
evidently by me in 96bd67f61).  However, it didn't get really bad
until b23cd185f removed the convert-a-table-to-a-view logic, which
had made it possible for scripts that thought they were attaching
ON SELECTs to tables to still work.

Rewrite into a form that makes it clear that an ON SELECT rule
is better regarded as an implementation detail of a view.
Pre-v16, point out that adding ON SELECT to a table actually
converts it to a view.

Per bug #18178 from Joshua Uyehara.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18178-05534d7064044d2d@postgresql.org

18 months agodoc: ALTER DEFAULT PRIVILEGES does not affect inherited roles
Bruce Momjian [Fri, 3 Nov 2023 13:51:53 +0000 (09:51 -0400)]
doc:  ALTER DEFAULT PRIVILEGES does not affect inherited roles

Reported-by: Jordi Gutiérrez Hermoso
Discussion: https://postgr.es/m/72652d72e1816bfc3c05d40f9e0e0373d07823c8.camel@octave.org

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

18 months agoAdd missing unicode_category.c to MSVC build scripts
David Rowley [Fri, 3 Nov 2023 07:12:36 +0000 (20:12 +1300)]
Add missing unicode_category.c to MSVC build scripts

Fixes MSVC build failure introduced by a02b37fc0

18 months agoStabilize postgres_fdw tests on 32-bit machines
David Rowley [Thu, 2 Nov 2023 23:35:37 +0000 (12:35 +1300)]
Stabilize postgres_fdw tests on 32-bit machines

cac169d68 adjusted DEFAULT_FDW_TUPLE_COST and that seems to have caused
a test to become unstable on 32-bit machines.

4b14e1871 tried to fix this as originally the plan was flipping between
a Nested Loop and Hash Join.  That commit forced the Nested Loop, but
there's still flexibility to push or not push the sort to the remote
server and 32-bit seems to prefer to push and on 64-bit, the costs
prefer not to.

Here let's just turn off enable_sort to significantly encourage the sort
to take place on the remote server.

Reported-by: Michael Paquier, Richard Guo
Discussion: https://postgr.es/m/ZUM2IhA8X2lrG50K@paquier.xyz

18 months agoMake GetConfigOption/GetConfigOptionResetString return "" for NULL.
Tom Lane [Thu, 2 Nov 2023 15:53:36 +0000 (11:53 -0400)]
Make GetConfigOption/GetConfigOptionResetString return "" for NULL.

As per the preceding commit, GUC APIs generally expose NULL-valued
string variables as empty strings.  Extend that policy to
GetConfigOption() and GetConfigOptionResetString(), eliminating
a crash hazard for unwary callers, as well as a fundamental
ambiguity in GetConfigOption()'s API.

No back-patch, since this is an API change and conceivably somebody
somewhere is depending on this corner case.

Xing Guo, Aleksander Alekseev, Tom Lane

Discussion: https://postgr.es/m/CACpMh+AyDx5YUpPaAgzVwC1d8zfOL4JoD-uyFDnNSa1z0EsDQQ@mail.gmail.com

18 months agoBe more wary about NULL values for GUC string variables.
Tom Lane [Thu, 2 Nov 2023 15:47:33 +0000 (11:47 -0400)]
Be more wary about NULL values for GUC string variables.

get_explain_guc_options() crashed if a string GUC marked GUC_EXPLAIN
has a NULL boot_val.  Nosing around found a couple of other places
that seemed insufficiently cautious about NULL string values, although
those are likely unreachable in practice.  Add some commentary
defining the expectations for NULL values of string variables,
in hopes of forestalling future additions of more such bugs.

Xing Guo, Aleksander Alekseev, Tom Lane

Discussion: https://postgr.es/m/CACpMh+AyDx5YUpPaAgzVwC1d8zfOL4JoD-uyFDnNSa1z0EsDQQ@mail.gmail.com

18 months agoAttempt to stabilize postgres_fdw tests
David Rowley [Thu, 2 Nov 2023 10:16:34 +0000 (23:16 +1300)]
Attempt to stabilize postgres_fdw tests

cac169d68 adjusted DEFAULT_FDW_TUPLE_COST and that seems to have caused
a test to become unstable on 32-bit machines.  Try to make it stable
again.

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/ZUM2IhA8X2lrG50K@paquier.xyz

18 months agoAdditional unicode primitive functions.
Jeff Davis [Thu, 2 Nov 2023 05:47:06 +0000 (22:47 -0700)]
Additional unicode primitive functions.

Introduce unicode_version(), icu_unicode_version(), and
unicode_assigned().

The latter requires introducing a new lookup table for the Unicode
General Category, which is generated along with the other Unicode
lookup tables.

Discussion: https://postgr.es/m/CA+TgmoYzYR-yhU6k1XFCADeyj=Oyz2PkVsa3iKv+keM8wp-F_A@mail.gmail.com
Reviewed-by: Peter Eisentraut
18 months agoPrevent startup of logical replication launcher during pg_upgrade
Michael Paquier [Thu, 2 Nov 2023 05:34:51 +0000 (14:34 +0900)]
Prevent startup of logical replication launcher during pg_upgrade

The logical replication launcher may start apply workers during an
upgrade.  This could be the cause of corruptions on a new cluster if
these are able to apply changes before the physical files are copied
over to the new cluster.

The chance of being able to do so is small as pg_upgrade uses its own
port and unix domain directory (the latter is customizable with
--socketdir), but just preventing the launcher to start is safer at the
end, because we are then sure that no changes will be applied.  Like
29d0a77fa660 for max_slot_wal_keep_size, this is only set when a cluster
uses v17 or newer.

Author: Vignesh C
Discussion: https://postgr.es/m/CALDaNm2g9ZKf=y8X6z6MsLCuh8WwU-=Q6pLj35NFi2M5BZNS_A@mail.gmail.com

18 months agoFix 003_check_guc.pl when loading modules with custom GUCs
Michael Paquier [Thu, 2 Nov 2023 03:38:05 +0000 (12:38 +0900)]
Fix 003_check_guc.pl when loading modules with custom GUCs

The test missed that custom GUCs need to be ignored from the list of
parameters that can exist in postgresql.conf.sample.  This caused the
test to fail on a server where such a module is loaded, when using
EXTRA_INSTALL and TEMP_CONFIG, for instance.

Author: Anton A. Melnikov
Discussion: https://postgr.es/m/fc5509ce-5144-4dac-8d13-21793da44fc5@postgrespro.ru
Backpatch-through: 15

18 months agoIncrease DEFAULT_FDW_TUPLE_COST from 0.01 to 0.2
David Rowley [Thu, 2 Nov 2023 01:30:15 +0000 (14:30 +1300)]
Increase DEFAULT_FDW_TUPLE_COST from 0.01 to 0.2

0.01 was unrealistically low as it's the same as the default
cpu_tuple_cost and 10x cheaper than the default parallel_tuple_cost.
It's hard to imagine a situation where fetching a tuple from a foreign
server would be cheaper than fetching one from a parallel worker.

After some experimentation on a loopback server, somewhere between 0.15
and 0.3 seems more realistic.  Here we split the difference and set it
to 0.2.

This will cause operations that reduce the number of tuples (e.g.
aggregation) to be more likely to take place on the foreign server.

Adjusting this causes some plan changes in the postgres_fdw regression
tests.  This is because penalizing each Path with the additional tuple
costs causes some dilution of the costs of the other operations being
charged for and results in various paths appearing to be closer to the
same costs such that add_path's STD_FUZZ_FACTOR is more likely to see two
paths as costing (fuzzily) the same.  This isn't ideal, but it shouldn't
be reason enough to use artificially low costs.

Discussion: https://postgr.es/m/CAApHDvopVjjfh5c1Ed2HRvDdfom2dEpMwwiu5-f1AnmYprJngA@mail.gmail.com

18 months agodoc: Replace reference to ERRCODE_RAISE_EXCEPTION by "raise_exception"
Michael Paquier [Wed, 1 Nov 2023 22:33:02 +0000 (07:33 +0900)]
doc: Replace reference to ERRCODE_RAISE_EXCEPTION by "raise_exception"

This part of the documentation refers to exceptions as handled by
PL/pgSQL, and using the internal error code is confusing.

Per thinko in 66bde49d96a9.

Reported-by: Euler Taveira, Bruce Momjian
Discussion: https://postgr.es/m/ZUEUnLevXyW7DlCs@momjian.us
Backpatch-through: 11

18 months agodoc: add reference to wire protocol details
Bruce Momjian [Wed, 1 Nov 2023 17:57:04 +0000 (13:57 -0400)]
doc:  add reference to wire protocol details

Discussion: https://postgr.es/m/143A51B2-80B1-4ECD-AF67-F7061377FF63@hotmail.com

Author: Li Japin

Backpatch-through: master

18 months agoFix function name in comment
Daniel Gustafsson [Wed, 1 Nov 2023 10:46:30 +0000 (11:46 +0100)]
Fix function name in comment

The name of the function resulting from the macro expansion was
incorrectly stated.

Backpatch to 16 where it was introduced.

Author: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Discussion: https://postgr.es/m/20231101.172308.1740861597185391383.horikyota.ntt@gmail.com
Backpatch-through: v16

18 months agodoc: Expand section related to LWLocks and shared memory
Michael Paquier [Wed, 1 Nov 2023 05:54:13 +0000 (14:54 +0900)]
doc: Expand section related to LWLocks and shared memory

The documentation includes a section describing how to define custom
LWLocks in extensions using the shmem hooks.  However, it has never
mentioned the second, more flexible method based on the following
routines:
- LWLockNewTrancheId() to allocate a tranche ID.
- LWLockRegisterTranche() to associate a name to a tranche ID.
- LWLockInitialize() to initialize a LWLock with a tranche ID.

autoprewarm.c is the only example of extension in the tree that
allocates a LWLock this way.

This commit adds some documentation about all that.  While on it, a
comment is added about the need of AddinShmemInitLock.  This is required
especially for EXEC_BACKEND builds (aka Windows, normally), as per a
remark from Alexander, because backends can execute shmem initialization
paths concurrently.

Author: Aleksander Alekseev, Michael Paquier
Discussion: https://postgr.es/m/CAJ7c6TPKhFgL+54cdTD9yGpG4+sNcyJ+N1GvQqAxgWENAOa3VA@mail.gmail.com

18 months agodoc: add missing word to sentence about Paris
Bruce Momjian [Tue, 31 Oct 2023 17:18:42 +0000 (13:18 -0400)]
doc:  add missing word to sentence about Paris

Reported-by: Tang <tanghy.fnst@fujitsu.com>
Discussion: https://postgr.es/m/OS0PR01MB6113393560A1DF115ADFB153FB2D9@OS0PR01MB6113.jpnprd01.prod.outlook.com

Backpatch-through: master

18 months agoC comment: mention why no setting lasterrno in dir_existsfile()
Bruce Momjian [Tue, 31 Oct 2023 15:59:14 +0000 (11:59 -0400)]
C comment: mention why no setting lasterrno in dir_existsfile()

Reported-by: Wei Sun
Discussion: https://postgr.es/m/tencent_1276C08F98579CC19D8A4488C848A8411806@qq.com

Backpatch-through: master

18 months agoC comment: improve statistics computation comment example
Bruce Momjian [Tue, 31 Oct 2023 15:42:02 +0000 (11:42 -0400)]
C comment:  improve statistics computation comment example

Discussion: https://postgr.es/m/CAKFQuwbD672Sc0EXv0ifx3pzfQ5UAEpiAeaBGKz_Ox-4d2NGCA@mail.gmail.com

Author: David G. Johnston

Backpatch-through: master

18 months agoC comment: adjust statistics mention
Bruce Momjian [Tue, 31 Oct 2023 15:02:04 +0000 (11:02 -0400)]
C comment:  adjust statistics mention

No need to talk about the statistics collector.

Discussion: https://postgr.es/m/8a82417cdb6e8038fe276d4960e3207a@oss.nttdata.com

Author: Álvaro Herrera

Backpatch-through: master

18 months agodoc: improve ALTER SYSTEM description of value list quoting
Bruce Momjian [Tue, 31 Oct 2023 14:21:32 +0000 (10:21 -0400)]
doc: improve ALTER SYSTEM description of value list quoting

Reported-by: splarv@ya.ru
Discussion: https://postgr.es/m/167105927893.1897.13227723035830709578@wrigleys.postgresql.org

Backpatch-through: 11

18 months agodoc: improve bpchar and character type length details
Bruce Momjian [Tue, 31 Oct 2023 14:13:11 +0000 (10:13 -0400)]
doc:  improve bpchar and character type length details

Reported-by: Jeff Davis
Discussion: https://postgr.es/m/32a9b8357e8e29b04f395f92c53b64e015a4caf1.camel@j-davis.com

Author: Jeff Davis, adjustments by me

Backpatch-through: 16

18 months agodoc: add function argument and query parameter limits
Bruce Momjian [Tue, 31 Oct 2023 13:23:09 +0000 (09:23 -0400)]
doc:  add function argument and query parameter limits

Also reorder entries and add commas.

Reported-by: David G. Johnston
Discussion: https://postgr.es/m/CAKFQuwYeNPxeocV3_0+Zx=_Xwvg+sNyEMdzyG5s2E2e0hZLQhg@mail.gmail.com

Author: David G. Johnston (partial)

Backpatch-through: 12

18 months agodoc: 1-byte varlena headers can be used for user PLAIN storage
Bruce Momjian [Tue, 31 Oct 2023 13:10:35 +0000 (09:10 -0400)]
doc:  1-byte varlena headers can be used for user PLAIN storage

This also updates some C comments.

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

Author: Laurenz Albe (doc patch)

Backpatch-through: 11

18 months agoimprove alignment of postgresql.conf comments
Bruce Momjian [Tue, 31 Oct 2023 12:51:12 +0000 (08:51 -0400)]
improve alignment of postgresql.conf comments

Discussion: https://postgr.es/m/CAHut+Ps5MdQ1b4jp9rd63zfE2X25mV58y1W+hm2v53svtGDxBQ@mail.gmail.com

Author: Peter Smith

Backpatch-through: master

18 months agoAdjust the order of the prechecks in pgrowlocks()
David Rowley [Tue, 31 Oct 2023 03:42:08 +0000 (16:42 +1300)]
Adjust the order of the prechecks in pgrowlocks()

4b8266415 added a precheck to pgrowlocks() to ensure the given object's
pg_class.relam is HEAP_TABLE_AM_OID, however, that check was put before
another check which was checking if the given object was a partitioned
table.  Since the pg_class.relam is always InvalidOid for partitioned
tables, if pgrowlocks() was called passing a partitioned table, then the
"only heap AM is supported" error would be raised instead of the intended
error about the given object being a partitioned table.

Here we simply move the pg_class.relam check to after the check that
verifies that we are in fact working with a normal (non-partitioned)
table.

Reported-by: jian he
Discussion: https://postgr.es/m/CACJufxFaSp_WguFCf0X98951zFVX+dXFnF1mxAb-G3g1HiHOow@mail.gmail.com
Backpatch-through: 12, where 4b8266415 was introduced.

18 months agoDiagnose !indisvalid in more SQL functions.
Noah Misch [Mon, 30 Oct 2023 21:46:05 +0000 (14:46 -0700)]
Diagnose !indisvalid in more SQL functions.

pgstatindex failed with ERRCODE_DATA_CORRUPTED, of the "can't-happen"
class XX.  The other functions succeeded on an empty index; they might
have malfunctioned if the failed index build left torn I/O or other
complex state.  Report an ERROR in statistics functions pgstatindex,
pgstatginindex, pgstathashindex, and pgstattuple.  Report DEBUG1 and
skip all index I/O in maintenance functions brin_desummarize_range,
brin_summarize_new_values, brin_summarize_range, and
gin_clean_pending_list.  Back-patch to v11 (all supported versions).

Discussion: https://postgr.es/m/20231001195309.a3@google.com

18 months agoamcheck: Distinguish interrupted page deletion from corruption.
Noah Misch [Mon, 30 Oct 2023 21:46:05 +0000 (14:46 -0700)]
amcheck: Distinguish interrupted page deletion from corruption.

This prevents false-positive reports about "the first child of leftmost
target page is not leftmost of its level", "block %u is not leftmost"
and "left link/right link pair".  They appeared if amcheck ran before
VACUUM cleaned things, after a cluster exited recovery between the
first-stage and second-stage WAL records of a deletion.  Back-patch to
v11 (all supported versions).

Reviewed by Peter Geoghegan.

Discussion: https://postgr.es/m/20231005025232.c7.nmisch@google.com

18 months agopgindent run to fix commits de64268561 and 5ae2087202a
Bruce Momjian [Mon, 30 Oct 2023 18:52:35 +0000 (14:52 -0400)]
pgindent run to fix commits de64268561 and 5ae2087202a

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/ZT9YH7-TTx27V3yW@paquier.xyz

Backpatch-through: master

18 months agoFill in more of ObjectProperty
Peter Eisentraut [Mon, 30 Oct 2023 10:08:53 +0000 (06:08 -0400)]
Fill in more of ObjectProperty

Fill in .objtype field where an appropriate value exists.

These cases are currently not used (see also comments at
get_object_type()), but we might as well fill in what's possible in
case additional uses arise.

Discussion: https://www.postgresql.org/message-id/flat/75ae5875-3abc-dafc-8aec-73247ed41cde@eisentraut.org

18 months agoAdd STREAM_START/STREAM_STOP for transactional messages during decoding.
Amit Kapila [Mon, 30 Oct 2023 09:06:21 +0000 (14:36 +0530)]
Add STREAM_START/STREAM_STOP for transactional messages during decoding.

In test_decoding module, when skip_empty_xacts option was specified, add
stream_start/stop for streaming transactional messages. This makes the
handling of transactional messages stream consistent irrespective of
whether skip_empty_xacts option was specified.

Commit 26dd0284b9 made a similar change for non-streaming messages but
forgot to update the streaming cases.

Author: Peter Smith
Reviewed-by: Amit Kapila
Discussion: http://postgr.es/m/OS0PR01MB5716AEBD2988F8F5E9D5985794DFA@OS0PR01MB5716.jpnprd01.prod.outlook.com

18 months agoFix indentation in contrib/amcheck/verify_nbtree.c
Alexander Korotkov [Mon, 30 Oct 2023 08:34:15 +0000 (10:34 +0200)]
Fix indentation in contrib/amcheck/verify_nbtree.c

Reported-by: Michael Paquier
Discussion: https://postgr.es/m/ZT9YoDPEQBUMrIHg%40paquier.xyz

18 months agoExpand regression tests for pg_stat_reset_shared()
Michael Paquier [Mon, 30 Oct 2023 08:19:24 +0000 (17:19 +0900)]
Expand regression tests for pg_stat_reset_shared()

This commit adds coverage for the stats reset of recovery_prefetch, and
for the case where an invalid value is given in input of the function.

Author: Bharath Rupireddy
Discussion: https://postgr.es/m/CALj2ACW9Uk7x61oSix9qK0xR4Jhy3cgg6pobQ-Q3GNsUbFrn8A@mail.gmail.com

18 months agoDelay recovery mode LOG after reading backup_label and/or checkpoint record
Michael Paquier [Mon, 30 Oct 2023 06:28:20 +0000 (15:28 +0900)]
Delay recovery mode LOG after reading backup_label and/or checkpoint record

When beginning recovery, a LOG is displayed by the startup process to
show which recovery mode will be used depending on the .signal file(s)
set in the data folder, like "standby mode", recovery up to a given
target type and value, or archive recovery.

A different patch is under discussion to simplify the startup code by
requiring the presence of recovery.signal and/or standby.signal when a
backup_label file is read.  Delaying a bit this LOG ensures that the
correct recovery mode would be reported, and putting it at this position
does not make it lose its value.

While on it, this commit adds a few comments documenting a bit more the
initial recovery steps and their dependencies, and fixes an incorrect
comment format.  This introduces no behavior changes.

Extracted from a larger patch by me.

Reviewed-by: David Steele, Bowen Shi
Discussion: https://postgr.es/m/ZArVOMifjzE7f8W7@paquier.xyz

18 months agoDoc: Make link names consistent in logical replication commands.
Amit Kapila [Mon, 30 Oct 2023 05:16:31 +0000 (10:46 +0530)]
Doc: Make link names consistent in logical replication commands.

Commit 536f410111 added links in the ALTER SUBSCRIPTION command page. The
link names used were slightly different from what other logical
replication commands like CREATE SUBSCRIPTION/PUBLICATION have but were
consistent with other docs. This patch changes the link names for all the
parameters to have 'params' word in the CREATE SUBSCRIPTION/PUBLICATION
pages.

Author: Peter Smith
Reviewed-by: Amit Kapila
Discussion: http://postgr.es/m/CAHut%2BPu2S4RdzYKR7H5_E7QYWyq5hB0hL4EFrYbP91Qso62jeg%40mail.gmail.com

18 months agoMention standby.signal in FATALs for checkpoint record missing at recovery
Michael Paquier [Mon, 30 Oct 2023 04:56:02 +0000 (13:56 +0900)]
Mention standby.signal in FATALs for checkpoint record missing at recovery

When beginning recovery from a base backup by reading a backup_label
file, it may be possible that no checkpoint record is available
depending on the method used when the case backup was taken, which would
prevent recovery from beginning.  In this case, the FATAL messages
issued, initially added by c900c15269f0f, mentioned recovery.signal as
an option to do recovery but not standby.signal.  Let's add it as an
available option, for clarity.

Per suggestion from Bowen Shi, extracted from a larger patch by me.

Author: Michael Paquier
Discussion: https://postgr.es/m/CAM_vCudkSjr7NsNKSdjwtfAm9dbzepY6beZ5DP177POKy8=2aw@mail.gmail.com

18 months agoIntroduce pg_stat_checkpointer
Michael Paquier [Mon, 30 Oct 2023 00:47:16 +0000 (09:47 +0900)]
Introduce pg_stat_checkpointer

Historically, the statistics of the checkpointer have been always part
of pg_stat_bgwriter.  This commit removes a few columns from
pg_stat_bgwriter, and introduces pg_stat_checkpointer with equivalent,
renamed columns (plus a new one for the reset timestamp):
- checkpoints_timed -> num_timed
- checkpoints_req -> num_requested
- checkpoint_write_time -> write_time
- checkpoint_sync_time -> sync_time
- buffers_checkpoint -> buffers_written

The fields of PgStat_CheckpointerStats and its SQL functions are renamed
to match with the new field names, for consistency.  Note that
background writer and checkpointer have been split into two different
processes in commits 806a2aee3791 and bf405ba8e460.  The pgstat
structures were already split, making this change straight-forward.

Bump catalog version.

Author: Bharath Rupireddy
Reviewed-by: Bertrand Drouvot, Andres Freund, Michael Paquier
Discussion: https://postgr.es/m/CALj2ACVxX2ii=66RypXRweZe2EsBRiPMj0aHfRfHUeXJcC7kHg@mail.gmail.com

18 months agoRefactor some code related to transaction-level statistics for relations
Michael Paquier [Sun, 29 Oct 2023 23:23:39 +0000 (08:23 +0900)]
Refactor some code related to transaction-level statistics for relations

This commit refactors find_tabstat_entry() so as transaction counters
for inserted, updated and deleted tuples are included in the result
returned.   If a shared entry is found for a relation, its result is now
a copy of the PgStat_TableStatus entry retrieved from shared memory.
This idea has been proposed by Andres Freund.

While on it, the following SQL functions, used in system views, are
refactored with macros, in the same spirit as 83a1a1b56645, reducing the
amount of code:
- pg_stat_get_xact_tuples_deleted()
- pg_stat_get_xact_tuples_inserted()
- pg_stat_get_xact_tuples_updated()

There is now only one caller of find_tabstat_entry() in the tree.

Author: Bertrand Drouvot
Discussion: https://postgr.es/m/b9e1f543-ee93-8168-d530-d961708ad9d3@gmail.com

18 months agoFix instable 006_login_trigger.pl test
Alexander Korotkov [Sun, 29 Oct 2023 22:23:53 +0000 (01:23 +0300)]
Fix instable 006_login_trigger.pl test

Handling of login trigger FATAL error could cause a timing-dependant panic of
IPC::Run.  This commit excludes checks which involves handling of such errors.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/2268825.1698618066%40sss.pgh.pa.us

18 months agoTeach pg_dump about the new pg_subscription.subrunasowner option.
Tom Lane [Sun, 29 Oct 2023 16:56:24 +0000 (12:56 -0400)]
Teach pg_dump about the new pg_subscription.subrunasowner option.

Among numerous other oversights, commit 482675987 neglected to fix
pg_dump to dump this new subscription option.  Since the new default
is "false" while the previous behavior corresponds to "true", this
would cause legacy subscriptions to silently change behavior during
dump/reload or pg_upgrade.  That seems like a bad idea.  Even if it
was intended, failing to preserve the option once set in a new
installation is certainly not OK.

While here, reorder associated stanzas in pg_dump to match the
field order in pg_subscription, in hopes of reducing the impression
that all this code was written with the aid of a dartboard.

Back-patch to v16 where this new field was added.

Philip Warner (cosmetic tweaks by me)

Discussion: https://postgr.es/m/20231027042539.01A3A220F0A@thebes.rime.com.au

18 months agoGuard against overflow in make_interval().
Dean Rasheed [Sun, 29 Oct 2023 15:46:04 +0000 (15:46 +0000)]
Guard against overflow in make_interval().

The original code did very little to guard against integer or floating
point overflow when computing the interval's fields.  Detect any such
overflows and error out, rather than silently returning bogus results.

Joseph Koshakow, reviewed by Ashutosh Bapat and me.

Discussion: https://postgr.es/m/CAAvxfHcm1TPwH_zaGWuFoL8pZBestbRZTU6Z%3D-RvAdSXTPbKfg%40mail.gmail.com

18 months agobtree_gin: Fix calculation of leftmost interval value.
Dean Rasheed [Sun, 29 Oct 2023 11:14:37 +0000 (11:14 +0000)]
btree_gin: Fix calculation of leftmost interval value.

Formerly, the value computed by leftmostvalue_interval() was a long
way short of the minimum possible interval value.  As a result, an
index scan on a GIN index on an interval column with < or <= operators
would miss large negative interval values.

Fix by setting all fields of the leftmost interval to their minimum
values, ensuring that the result is less than any other possible
interval.  Since this only affects index searches, no index rebuild is
necessary.

Back-patch to all supported branches.

Dean Rasheed, reviewed by Heikki Linnakangas.

Discussion: https://postgr.es/m/CAEZATCV80%2BgOfF8ehNUUfaKBZgZMDfCfL-g1HhWGb6kC3rpDfw%40mail.gmail.com

18 months agoFix intra-query memory leak when a SRF returns zero rows.
Tom Lane [Sat, 28 Oct 2023 18:04:42 +0000 (14:04 -0400)]
Fix intra-query memory leak when a SRF returns zero rows.

When looping around after finding that the set-returning function
returned zero rows for the current input tuple, ExecProjectSet
neglected to reset either of the two memory contexts it's
responsible for cleaning out.  Typically this wouldn't cause much
problem, because once the SRF does return at least one row, the
contexts would get reset on the next call.  However, if the SRF
returns no rows for many input tuples in succession, quite a lot
of memory could be transiently consumed.

To fix, make sure we reset both contexts while looping around.

Per bug #18172 from Sergei Kornilov.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/18172-9b8c5fc1d676ded3@postgresql.org

18 months agodoc: add links to Postgres features intro
Bruce Momjian [Sat, 28 Oct 2023 18:02:46 +0000 (14:02 -0400)]
doc:  add links to Postgres features intro

Reported-by: Elena Indrupskaya
Discussion: https://postgr.es/m/1a666b2e-d373-1c94-1005-1700e023670d@postgrespro.ru

Backpatch-through: master

18 months agodoc: comment wording improvement
Bruce Momjian [Sat, 28 Oct 2023 16:58:32 +0000 (12:58 -0400)]
doc:  comment wording improvement

Discussion: https://postgr.es/m/CAEG8a3L7UoZXH1VmzpV-VDkex2kt68nWKuW1WiohoT=RrzYKWA@mail.gmail.com

Author: Junwang Zhao

Backpatch-through: master

18 months agoRemove PHOT from our default timezone abbreviations list.
Tom Lane [Sat, 28 Oct 2023 15:54:40 +0000 (11:54 -0400)]
Remove PHOT from our default timezone abbreviations list.

Debian recently decided to split out a bunch of "obsolete" timezone
names into a new tzdata-legacy package, which isn't installed by
default.  One of these zone names is Pacific/Enderbury, and that
breaks our regression tests (on --with-system-tzdata builds)
because our default timezone abbreviations list defines PHOT as
Pacific/Enderbury.

Pacific/Enderbury got renamed to Pacific/Kanton in tzdata 2021b,
so that in distros that still have this entry it's just a symlink
to Pacific/Kanton anyway.  So one answer would be to redefine PHOT
as Pacific/Kanton.  However, then things would fail if the
installed tzdata predates 2021b, which is recent enough that that
seems like a real problem.

Instead, let's just remove PHOT from the default list.  That seems
likely to affect nobody in the real world, because (a) it was an
abbreviation that the tzdb crew made up in the first place, with
no evidence of real-world usage, and (b) the total human population
of the Phoenix Islands is less than two dozen persons, per Wikipedia.
If anyone does use this zone abbreviation they can easily put it back
via a custom abbreviations file.

We'll keep PHOT in the Pacific.txt reference file, but change it
to Pacific/Kanton there, as that definition seems more likely to
be useful to future readers of that file.

Per report from Victor Wagner.  Back-patch to all supported
branches.

Discussion: https://postgr.es/m/20231027152049.4b5c8044@wagner.wagner.home

18 months agoAllow relkind 'I' in type_sanity test.
Tom Lane [Sat, 28 Oct 2023 01:50:44 +0000 (21:50 -0400)]
Allow relkind 'I' in type_sanity test.

This is cosmetic at present, since no partitioned indexes have
been created yet at the stage of the regression tests when
type_sanity runs.  But it's confusing that this list of allowed
values doesn't match reality, so fix it.

Noted by Jian He.

Discussion: https://postgr.es/m/CACJufxHhr58q-YoBeqnY5P-u8Xe2X5sMtsr3LYE1nQDwdqjB4w@mail.gmail.com

18 months agodoc: improve text around consistency of statistics values
Bruce Momjian [Sat, 28 Oct 2023 01:24:55 +0000 (21:24 -0400)]
doc:  improve text around consistency of statistics values

Discussion: https://postgr.es/m/CAKFQuwZ4CXtTyR19vFbd9WwmW-4BvgAenmF2CfUpx0LWwRPGYg@mail.gmail.com

Author: David G. Johnston

Backpatch-through: master

18 months agodoc: improve config syncfs wording
Bruce Momjian [Sat, 28 Oct 2023 01:11:48 +0000 (21:11 -0400)]
doc:  improve config syncfs wording

Reported-by: Eric Mutta
Discussion: https://postgr.es/m/166126549332.651.12934187158820082671@wrigleys.postgresql.org

Backpatch-through: master

18 months agoClarify the result order of unnest(multirange).
Jeff Davis [Fri, 27 Oct 2023 22:21:42 +0000 (15:21 -0700)]
Clarify the result order of unnest(multirange).

It is best not to mention the storage order, because that is
an implementation detail and has confused at least one user,
who assumed that the storage order is the order in which the
constituent ranges were written in SQL.

Since the sorting order is explained at the beginning of the
page, it should be sufficient to say that the ranges are
returned in ascending order.

Author: Laurenz Albe
Reviewed-by: Daniel Fredouille
Discussion: https://postgr.es/m/169627213477.3727338.17653654241633692682%40wrigleys.postgresql.org

18 months agodoc Improve C GUC-related comments
Bruce Momjian [Fri, 27 Oct 2023 23:05:25 +0000 (19:05 -0400)]
doc  Improve C GUC-related comments

Discussion: https://postgr.es/m/CAEG8a3LZHTR5S+OPZCbZvECwsqdbx=pBRFZZyDjKaAtgoALOQQ@mail.gmail.com

Author: Junwang Zhao

Backpatch-through: master

18 months agodoc: wording improvements
Bruce Momjian [Fri, 27 Oct 2023 21:23:09 +0000 (17:23 -0400)]
doc:  wording improvements

Discussion: https://postgr.es/m/a5180360-ec04-ac58-25ce-3d795d3d1f6c@postgrespro.ru

Author: Ekaterina Kiryanova

Backpatch-through: master

18 months agoTeach contrib/amcheck to check the unique constraint violation
Alexander Korotkov [Fri, 27 Oct 2023 21:21:23 +0000 (00:21 +0300)]
Teach contrib/amcheck to check the unique constraint violation

Add the 'checkunique' argument to bt_index_check() and bt_index_parent_check().
When the flag is specified the procedures will check the unique constraint
violation for unique indexes.  Only one heap entry for all equal keys in
the index should be visible (including posting list entries).  Report an error
otherwise.

pg_amcheck called with the --checkunique option will do the same check for all
the indexes it checks.

Author: Anastasia Lubennikova <lubennikovaav@gmail.com>
Author: Pavel Borisov <pashkin.elfe@gmail.com>
Author: Maxim Orlov <orlovmg@gmail.com>
Reviewed-by: Mark Dilger <mark.dilger@enterprisedb.com>
Reviewed-by: Zhihong Yu <zyu@yugabyte.com>
Reviewed-by: Peter Geoghegan <pg@bowt.ie>
Reviewed-by: Aleksander Alekseev <aleksander@timescale.com>
Discussion: https://postgr.es/m/CALT9ZEHRn5xAM5boga0qnrCmPV52bScEK2QnQ1HmUZDD301JEg%40mail.gmail.com

18 months agoSplit event_trigger_login test from event_trigger test
Alexander Korotkov [Fri, 27 Oct 2023 20:50:07 +0000 (23:50 +0300)]
Split event_trigger_login test from event_trigger test

That allows to still run event_trigger test in parallel with oidjoins test,
and save ~50ms of tests runtime.

Discussion: https://postgr.es/m/202310271047.mnwkql6nhbwi%40alvherre.pgsql
Author: Alvaro Herrera, Alexander Korotkov

18 months agoFix minmax-multi distance for extreme interval values
Tomas Vondra [Fri, 27 Oct 2023 15:57:44 +0000 (17:57 +0200)]
Fix minmax-multi distance for extreme interval values

When calculating distance for interval values, the code mostly mimicked
interval_mi, i.e. it built a new interval value for the difference.
That however does not work for sufficiently distant interval values,
when the difference overflows the interval range.

Instead, we can calculate the distance directly, without constructing
the intermediate (and unnecessary) interval value.

Backpatch to 14, where minmax-multi indexes were introduced.

Reported-by: Dean Rasheed
Reviewed-by: Ashutosh Bapat, Dean Rasheed
Backpatch-through: 14
Discussion: https://postgr.es/m/eef0ea8c-4aaa-8d0d-027f-58b1f35dd170@enterprisedb.com

18 months agoFix minmax-multi on infinite date/timestamp values
Tomas Vondra [Fri, 27 Oct 2023 15:57:28 +0000 (17:57 +0200)]
Fix minmax-multi on infinite date/timestamp values

Make sure that infinite values in date/timestamp columns are treated as
if in infinite distance. Infinite values should not be merged with other
values, leaving them as outliers. The code however returned distance 0
in this case, so that infinite values were merged first. While this does
not break the index (i.e. it still produces correct query results), it
may make it much less efficient.

We don't need explicit handling of infinite date/timestamp values when
calculating distances, because those values are represented as extreme
but regular values (e.g. INT64_MIN/MAX for the timestamp type).

We don't need an exact distance, just a value that is much larger than
distanced between regular values. With the added cast to double values,
we can simply subtract the values.

The regression test queries a value in the "gap" and checks the range
was properly eliminated by the BRIN index.

This only affects minmax-multi indexes on timestamp/date columns with
infinite values, which is not very common in practice. The affected
indexes may need to be rebuilt.

Backpatch to 14, where minmax-multi indexes were introduced.

Reported-by: Ashutosh Bapat
Reviewed-by: Ashutosh Bapat, Dean Rasheed
Backpatch-through: 14
Discussion: https://postgr.es/m/eef0ea8c-4aaa-8d0d-027f-58b1f35dd170@enterprisedb.com

18 months agoFix calculation in brin_minmax_multi_distance_date
Tomas Vondra [Fri, 27 Oct 2023 15:57:11 +0000 (17:57 +0200)]
Fix calculation in brin_minmax_multi_distance_date

When calculating the distance between date values, make sure to subtract
them in the right order, i.e. (larger - smaller).

The distance is used to determine which values to merge, and is expected
to be a positive value. The code unfortunately did the subtraction in
the opposite order, i.e. (smaller - larger), thus producing negative
values and merging values the most distant values first.

The resulting index is correct (i.e. produces correct results), but may
be significantly less efficient. This affects all minmax-multi indexes
on date columns.

Backpatch to 14, where minmax-multi indexes were introduced.

Reported-by: Ashutosh Bapat
Reviewed-by: Ashutosh Bapat, Dean Rasheed
Backpatch-through: 14
Discussion: https://postgr.es/m/eef0ea8c-4aaa-8d0d-027f-58b1f35dd170@enterprisedb.com

18 months agoFix overflow when calculating timestamp distance in BRIN
Tomas Vondra [Fri, 27 Oct 2023 15:56:27 +0000 (17:56 +0200)]
Fix overflow when calculating timestamp distance in BRIN

When calculating distances for timestamp values for BRIN minmax-multi
indexes, we need to be careful about overflows for extreme values. If
the value overflows into a negative value, the index may be inefficient.

The new regression test checks this for the timestamp type by adding a
table with enough values to force range compaction/merging. The values
are close to min/max, which means a risk of overflow.

Fixed by converting the int64 values to double first, before calculating
the distance. This prevents the overflow. We may lose some precision, of
course, but that's good enough. In the worst case we build a slightly
less efficient index, but for large distances this won't matter.

This only affects minmax-multi indexes on timestamp columns, with ranges
containing values sufficiently distant to cause an overflow. That seems
like a fairly rare case in practice.

Backpatch to 14, where minmax-multi indexes were introduced.

Reported-by: Ashutosh Bapat
Reviewed-by: Ashutosh Bapat, Dean Rasheed
Backpatch-through: 14
Discussion: https://postgr.es/m/eef0ea8c-4aaa-8d0d-027f-58b1f35dd170@enterprisedb.com

18 months agodoc: clarify logical decoding's deadlock of system tables
Bruce Momjian [Fri, 27 Oct 2023 15:35:47 +0000 (11:35 -0400)]
doc: clarify logical decoding's deadlock of system tables

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

Backpatch-through: master

18 months ago|--- gitweb subject length limit ----------------|-email limit-|
Bruce Momjian [Fri, 27 Oct 2023 15:05:47 +0000 (11:05 -0400)]
|--- gitweb subject length limit ----------------|-email limit-|
doc:  fix first-person wording

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

Backpatch-through: master

18 months agoAdjust parallel_schedule with event triggers on authenticated login
Alexander Korotkov [Fri, 27 Oct 2023 08:30:39 +0000 (11:30 +0300)]
Adjust parallel_schedule with event triggers on authenticated login

Event triggers on authenticated login could catch the connection of the
concurrent test.  In order to prevent this side effect we need to run
the event_trigger test alone.

Discussion: https://postgr.es/m/flat/CAMEv5_sS5G7K1PCV2oBx5+1NF1ZneJ6C5Z_xV_SWsZMukdFZiA@mail.gmail.com
Author: Mikhail A. Gribkov
Reviewed-by: Aleksander Alekseev
18 months agoCommit b195e6d482 forgot to update meson.build.
Amit Kapila [Fri, 27 Oct 2023 07:49:49 +0000 (13:19 +0530)]
Commit b195e6d482 forgot to update meson.build.

Author: Hayato Kuroda
Discussion: http://postgr.es/m/TYCPR01MB58701BA358D80073ED1BD528F5DCA@TYCPR01MB5870.jpnprd01.prod.outlook.com

18 months agoUse shorter file names in the upgrade logical slots test.
Amit Kapila [Fri, 27 Oct 2023 05:39:45 +0000 (11:09 +0530)]
Use shorter file names in the upgrade logical slots test.

The longer file names exceeded the Windows path limit on buildfarm animal
fairywren.

Diagnosed-by: Hou Zhijie
Author: Hayato Kuroda
Reviewed-by: Bharath Rupireddy
Discussion: http://postgr.es/m/OS0PR01MB57160DF709ACD02248DB830C94DDA@OS0PR01MB5716.jpnprd01.prod.outlook.com

18 months agoMake UniqueRelInfo a node
Alexander Korotkov [Fri, 27 Oct 2023 02:29:48 +0000 (05:29 +0300)]
Make UniqueRelInfo a node

d3d55ce571 changed RelOptInfo.unique_for_rels from the list of Relid sets to
the list of UniqueRelInfo's.  But it didn't make UniqueRelInfo a node.
This commit makes UniqueRelInfo a node.  Also this commit revises some
comments related to RelOptInfo.unique_for_rels.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/flat/1189851.1698340331%40sss.pgh.pa.us

18 months agoRemove buffers_backend and buffers_backend_fsync from pg_stat_checkpointer
Michael Paquier [Fri, 27 Oct 2023 02:16:39 +0000 (11:16 +0900)]
Remove buffers_backend and buffers_backend_fsync from pg_stat_checkpointer

Two attributes related to checkpointer statistics are removed in this
commit:
- buffers_backend, that counts the number of buffers written directly by
a backend.
- buffers_backend_fsync, that counts the number of times a backend had
to do fsync() by its own.

These are actually not checkpointer properties but backend properties.
Also, pg_stat_io provides a more accurate and equivalent report of these
numbers, by tracking all the I/O stats related to backends, including
writes and fsyncs, so storing them in pg_stat_checkpointer was
redundant.

Thanks also to Robert Haas and Amit Kapila for their input.

Bump catalog version.

Author: Bharath Rupireddy
Reviewed-by: Bertrand Drouvot, Andres Freund
Discussion: https://postgr.es/m/20230210004604.mcszbscsqs3bc5nx@awork3.anarazel.de

18 months agoOptimize various aggregate deserialization functions, take 2
David Rowley [Thu, 26 Oct 2023 21:41:55 +0000 (10:41 +1300)]
Optimize various aggregate deserialization functions, take 2

f0efa5aec added initReadOnlyStringInfo to allow a StringInfo to be
initialized from an existing buffer and also relaxed the requirement
that a StringInfo's buffer must be NUL terminated at data[len].  Now
that we have that, there's no need for these aggregate deserial
functions to use appendBinaryStringInfo() as that rather wastefully
palloc'd a new buffer and memcpy'd in the bytea's buffer.  Instead, we can
just use the bytea's buffer and point the StringInfo directly to that
using the new initializer function.

In Amdahl's law, this speeds up the serial portion of parallel
aggregates and makes sum(numeric), avg(numeric), var_pop(numeric),
var_samp(numeric), variance(numeric), stddev_pop(numeric),
stddev_samp(numeric), stddev(numeric), array_agg(anyarray),
string_agg(text) and string_agg(bytea) scale better in parallel queries.

Author: David Rowley
Discussion: https://postgr.es/m/CAApHDvr%3De-YOigriSHHm324a40HPqcUhSp6pWWgjz5WwegR%3DcQ%40mail.gmail.com

18 months agoAdd "Add trailing commas to enum definitions" to .git-blame-ignore-revs
Peter Eisentraut [Thu, 26 Oct 2023 11:03:43 +0000 (13:03 +0200)]
Add "Add trailing commas to enum definitions" to .git-blame-ignore-revs

Discussion: https://www.postgresql.org/message-id/flat/386f8c45-c8ac-4681-8add-e3b0852c1620%40eisentraut.org

18 months agoAvoid compiler warning in non-assert builds
Amit Langote [Thu, 26 Oct 2023 08:12:24 +0000 (17:12 +0900)]
Avoid compiler warning in non-assert builds

After 01575ad788e3, expand_single_inheritance_child()'s parentOID
variable is read only in an Assert, provoking a compiler warning in
non-assert builds.  Fix that by marking the variable with
PG_USED_FOR_ASSERTS_ONLY.

Per report and suggestion from David Rowley

Discussion: https://postgr.es/m/CAApHDvpjA_8Wxu4DCTRVAvPxC9atwMe6N%2ByvrcGsgb7mrfdpJA%40mail.gmail.com

18 months agoAdd trailing commas to enum definitions
Peter Eisentraut [Thu, 26 Oct 2023 07:16:25 +0000 (09:16 +0200)]
Add trailing commas to enum definitions

Since C99, there can be a trailing comma after the last value in an
enum definition.  A lot of new code has been introducing this style on
the fly.  Some new patches are now taking an inconsistent approach to
this.  Some add the last comma on the fly if they add a new last
value, some are trying to preserve the existing style in each place,
some are even dropping the last comma if there was one.  We could
nudge this all in a consistent direction if we just add the trailing
commas everywhere once.

I omitted a few places where there was a fixed "last" value that will
always stay last.  I also skipped the header files of libpq and ecpg,
in case people want to use those with older compilers.  There were
also a small number of cases where the enum type wasn't used anywhere
(but the enum values were), which ended up confusing pgindent a bit,
so I left those alone.

Discussion: https://www.postgresql.org/message-id/flat/386f8c45-c8ac-4681-8add-e3b0852c1620%40eisentraut.org

18 months agoIntroduce the concept of read-only StringInfos
David Rowley [Thu, 26 Oct 2023 03:31:48 +0000 (16:31 +1300)]
Introduce the concept of read-only StringInfos

There were various places in our codebase which conjured up a StringInfo
by manually assigning the StringInfo fields and setting the data field
to point to some existing buffer.  There wasn't much consistency here as
to what fields like maxlen got set to and in one location we didn't
correctly ensure that the buffer was correctly NUL terminated at len
bytes, as per what was documented as required in stringinfo.h

Here we introduce 2 new functions to initialize StringInfos.  One allows
callers to initialize a StringInfo passing along a buffer that is
already allocated by palloc.  Here the StringInfo code uses this buffer
directly rather than doing any memcpying into a new allocation.  Having
this as a function allows us to verify the buffer is correctly NUL
terminated.  StringInfos initialized this way can be appended to and
reset just like any other normal StringInfo.

The other new initialization function also accepts an existing buffer,
but the given buffer does not need to be a pointer to a palloc'd chunk.
This buffer could be a pointer pointing partway into some palloc'd chunk
or may not even be palloc'd at all.  StringInfos initialized this way
are deemed as "read-only".  This means that it's not possible to
append to them or reset them.

For the latter of the two new initialization functions mentioned above,
we relax the requirement that the data buffer must be NUL terminated.
Relaxing this requirement is convenient in a few places as it can save
us from having to allocate an entire new buffer just to add the NUL
terminator or save us from having to temporarily add a NUL only to have to
put the original char back again later.

Incompatibility note:

Here we also forego adding the NUL in a few places where it does not
seem to be required.  These locations are passing the given StringInfo
into a type's receive function.  It does not seem like any of our
built-in receive functions require this, but perhaps there's some UDT
out there in the wild which does require this.  It is likely worthy of
a mention in the release notes that a UDT's receive function mustn't rely
on the input StringInfo being NUL terminated.

Author: David Rowley
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/CAApHDvorfO3iBZ%3DxpiZvp3uHtJVLyFaPBSvcAhAq2HPLnaNSwQ%40mail.gmail.com

18 months agoPrevent duplicate RTEPermissionInfo for plain-inheritance parents
Amit Langote [Thu, 26 Oct 2023 02:53:56 +0000 (11:53 +0900)]
Prevent duplicate RTEPermissionInfo for plain-inheritance parents

Currently, expand_single_inheritance_child() doesn't reset
perminfoindex in a plain-inheritance parent's child RTE, because
prior to 387f9ed0a0, the executor would use the first child RTE to
locate the parent's RTEPermissionInfo.  That in turn causes
add_rte_to_flat_rtable() to create an extra RTEPermissionInfo
belonging to the parent's child RTE with the same content as the one
belonging to the parent's original ("root") RTE.

In 387f9ed0a0, we changed things so that the executor can now use the
parent's "root" RTE for locating its RTEPermissionInfo instead of the
child RTE, so the latter's perminfoindex need not be set anymore, so
make it so.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/839708.1698174464@sss.pgh.pa.us
Backpatch-through: 16

18 months agoMigrate logical slots to the new node during an upgrade.
Amit Kapila [Thu, 26 Oct 2023 01:24:16 +0000 (06:54 +0530)]
Migrate logical slots to the new node during an upgrade.

While reading information from the old cluster, a list of logical
slots is fetched. At the later part of upgrading, pg_upgrade revisits the
list and restores slots by executing pg_create_logical_replication_slot()
on the new cluster. Migration of logical replication slots is only
supported when the old cluster is version 17.0 or later.

If the old node has invalid slots or slots with unconsumed WAL records,
the pg_upgrade fails. These checks are needed to prevent data loss.

The significant advantage of this commit is that it makes it easy to
continue logical replication even after upgrading the publisher node.
Previously, pg_upgrade allowed copying publications to a new node. With
this patch, adjusting the connection string to the new publisher will
cause the apply worker on the subscriber to connect to the new publisher
automatically. This enables seamless continuation of logical replication,
even after an upgrade.

Author: Hayato Kuroda, Hou Zhijie
Reviewed-by: Peter Smith, Bharath Rupireddy, Dilip Kumar, Vignesh C, Shlok Kyal
Discussion: http://postgr.es/m/TYAPR01MB58664C81887B3AF2EB6B16E3F5939@TYAPR01MB5866.jpnprd01.prod.outlook.com
Discussion: http://postgr.es/m/CAA4eK1+t7xYcfa0rEQw839=b2MzsfvYDPz3xbD+ZqOdP3zpKYg@mail.gmail.com

18 months agoDoc: remove misleading info about ecpg's CONNECT/DISCONNECT DEFAULT.
Tom Lane [Wed, 25 Oct 2023 21:34:47 +0000 (17:34 -0400)]
Doc: remove misleading info about ecpg's CONNECT/DISCONNECT DEFAULT.

As far as I can see, ecpg has no notion of a "default" open
connection.  You can do "CONNECT TO DEFAULT" but that just specifies
letting libpq use all its default connection parameters --- the
resulting connection is not special subsequently.  In particular,
SET CONNECTION = DEFAULT and DISCONNECT DEFAULT simply act on a
connection named DEFAULT, if you've made one; they do not have
special lookup rules.  But the documentation of these commands
makes it look like they do.

Simplest fix, I think, is just to remove the paras suggesting that
DEFAULT is special here.

Also, SET CONNECTION *does* have one special lookup rule, which
is that it recognizes CURRENT as an alias for the currently selected
connection.  SET CONNECTION = CURRENT is a no-op, so it's pretty
useless, but nonetheless it does something different from selecting
a connection by name; so we'd better document it.

Per report from Sylvain Frandaz.  Back-patch to all supported
versions.

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

18 months agoRemove dead code in pg_ctl.c.
Nathan Bossart [Wed, 25 Oct 2023 21:26:59 +0000 (16:26 -0500)]
Remove dead code in pg_ctl.c.

Missed in 39969e2a1e.

Author: David Steele
Discussion: https://postgr.es/m/0c742f0c-d663-419d-b5a7-4fe867f5566c%40pgmasters.net

18 months agoDoc fix: Interfacing Extensions to Indexes
Jeff Davis [Wed, 25 Oct 2023 20:20:15 +0000 (13:20 -0700)]
Doc fix: Interfacing Extensions to Indexes

Refer to CREATE ACCESS METHOD rather than suggesting direct changes to
pg_am. Also corrects index-specific language that predated table
access methods.

Discussion: https://postgr.es/m/20231025172551.685b7799455f9a6addcf5afa@sraoss.co.jp
Reported-by: Yugo NAGATA <nagata@sraoss.co.jp>
18 months agoFix some regression tests for d3d55ce57136
Alexander Korotkov [Wed, 25 Oct 2023 11:53:14 +0000 (14:53 +0300)]
Fix some regression tests for d3d55ce57136

Add missing (cost off) to explain.

18 months agoRemove useless self-joins
Alexander Korotkov [Wed, 25 Oct 2023 09:46:22 +0000 (12:46 +0300)]
Remove useless self-joins

The Self Join Elimination (SJE) feature removes an inner join of a plain table
to itself in the query tree if is proved that the join can be replaced with
a scan without impacting the query result.  Self join and inner relation are
replaced with the outer in query, equivalence classes, and planner info
structures. Also, inner restrictlist moves to the outer one with removing
duplicated clauses. Thus, this optimization reduces the length of the range
table list (this especially makes sense for partitioned relations), reduces
the number of restriction clauses === selectivity estimations, and potentially
can improve total planner prediction for the query.

The SJE proof is based on innerrel_is_unique machinery.

We can remove a self-join when for each outer row:
 1. At most one inner row matches the join clause.
 2. Each matched inner row must be (physically) the same row as the outer one.

In this patch we use the next approach to identify a self-join:
 1. Collect all merge-joinable join quals which look like a.x = b.x
 2. Add to the list above the baseretrictinfo of the inner table.
 3. Check innerrel_is_unique() for the qual list.  If it returns false, skip
    this pair of joining tables.
 4. Check uniqueness, proved by the baserestrictinfo clauses. To prove
    the possibility of self-join elimination inner and outer clauses must have
    an exact match.

The relation replacement procedure is not trivial and it is partly combined
with the one, used to remove useless left joins.  Tests, covering this feature,
were added to join.sql.  Some regression tests changed due to self-join removal
logic.

Discussion: https://postgr.es/m/flat/64486b0b-0404-e39e-322d-0801154901f3%40postgrespro.ru
Author: Andrey Lepikhov, Alexander Kuzmenkov
Reviewed-by: Tom Lane, Robert Haas, Andres Freund, Simon Riggs, Jonathan S. Katz
Reviewed-by: David Rowley, Thomas Munro, Konstantin Knizhnik, Heikki Linnakangas
Reviewed-by: Hywel Carver, Laurenz Albe, Ronan Dunklau, vignesh C, Zhihong Yu
Reviewed-by: Greg Stark, Jaime Casanova, Michał Kłeczek, Alena Rybakina
Reviewed-by: Alexander Korotkov
18 months agoUse snprintf instead of sprintf in pg_regress.
Daniel Gustafsson [Wed, 25 Oct 2023 08:53:11 +0000 (10:53 +0200)]
Use snprintf instead of sprintf in pg_regress.

To avoid static analyzers sounding the alarm, move to using snprintf
instead of sprintf. This was an oversight in 66d6086cbcbfc8dee789a6.

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

18 months agoAdd missing include dir and references to libpq for MSVC build
David Rowley [Wed, 25 Oct 2023 02:37:37 +0000 (15:37 +1300)]
Add missing include dir and references to libpq for MSVC build

66d6086cb adjusted pg_regress to require this but forgot to adjust the
Visual Studio build script.

18 months agodoc: Fix some typos and grammar
Michael Paquier [Wed, 25 Oct 2023 00:40:55 +0000 (09:40 +0900)]
doc: Fix some typos and grammar

Author: Ekaterina Kiryanova, Elena Indrupskaya, Oleg Sibiryakov, Maxim
Yablokov
Discussion: https://postgr.es/m/7aad518b-3e6d-47f3-9184-b1d69cb412e7@postgrespro.ru
Backpatch-through: 11

18 months agoLog OpenSSL version in ./configure output
Michael Paquier [Wed, 25 Oct 2023 00:26:22 +0000 (09:26 +0900)]
Log OpenSSL version in ./configure output

This information is useful to know when scanning buildfarm results, and
it is already displayed in Meson.  The output of `openssl version` is
logged, with the command retrieved from PATH.

This depends on c8e4030d1bdd, so backpatch down to 16.

Reviewed-by: Peter Eisentraut, Daniel Gustafsson, Tom Lane
Discussion: https://postgr.es/m/ZTW9yOlZaSVoFhTz@paquier.xyz
Backpatch-through: 16

18 months agoReword memory terminology for PQresultMemorySize
Daniel Gustafsson [Tue, 24 Oct 2023 20:18:19 +0000 (22:18 +0200)]
Reword memory terminology for PQresultMemorySize

Rather than using the generic word "space" we might as well use "memory"
since that's precisely what we're dealing with here.

This was extracted from a larger patch around terminology changes where
the remaining hunks were rejected.

Author: Gurjeet Singh <gurjeet@singh.im>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CABwTF4UHO_NtcsOL6_XZfnpKg_0XBFKa7B-7_x5zs3MRZm3-Tg@mail.gmail.com

18 months agoSpeed up pg_regress server readiness testing.
Daniel Gustafsson [Tue, 24 Oct 2023 19:37:35 +0000 (21:37 +0200)]
Speed up pg_regress server readiness testing.

Instead of connecting to the server with psql to check if it is ready
for running tests, this changes pg_regress to use PQPing which avoids
performing system() calls which are expensive on some platforms, like
Windows. The frequency of tests is also increased in order to connect
to the server faster.

This patch is part of a larger effort to make testing consume fewer
resources in order to be able to fit more tests into the available
CI system constraints.

Reviewed-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/20230823192239.jxew5s3sjru63lio@awork3.anarazel.de

18 months agoFix problems when a plain-inheritance parent table is excluded.
Tom Lane [Tue, 24 Oct 2023 18:48:28 +0000 (14:48 -0400)]
Fix problems when a plain-inheritance parent table is excluded.

When an UPDATE/DELETE/MERGE's target table is an old-style
inheritance tree, it's possible for the parent to get excluded
from the plan while some children are not.  (I believe this is
only possible if we can prove that a CHECK ... NO INHERIT
constraint on the parent contradicts the query WHERE clause,
so it's a very unusual case.)  In such a case, ExecInitModifyTable
mistakenly concluded that the first surviving child is the target
table, leading to at least two bugs:

1. The wrong table's statement-level triggers would get fired.

2. In v16 and up, it was possible to fail with "invalid perminfoindex
0 in RTE with relid nnnn" due to the child RTE not having permissions
data included in the query plan.  This was hard to reproduce reliably
because it did not occur unless the update triggered some non-HOT
index updates.

In v14 and up, this is easy to fix by defining ModifyTable.rootRelation
to be the parent RTE in plain inheritance as well as partitioned cases.

While the wrong-triggers bug also appears in older branches, the
relevant code in both the planner and executor is quite a bit
different, so it would take a good deal of effort to develop and
test a suitable patch.  Given the lack of field complaints about the
trigger issue, I'll desist for now.  (Patching v11 for this seems
unwise anyway, given that it will have no more releases after next
month.)

Per bug #18147 from Hans Buschmann.

Amit Langote and Tom Lane

Discussion: https://postgr.es/m/18147-6fc796538913ee88@postgresql.org

18 months agoDoc: indexUnchanged is strictly a hint.
Peter Geoghegan [Tue, 24 Oct 2023 16:27:27 +0000 (09:27 -0700)]
Doc: indexUnchanged is strictly a hint.

Clearly spell out the limitations of aminsert()'s indexUnchanged hinting
mechanism in the index AM documentation.

Oversight in commit 9dc718bd, which added the "logically unchanged
index" hint (which is used to trigger bottom-up index deletion).

Author: Peter Geoghegan <pg@bowt.ie>
Reported-By: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-By: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/CAH2-WzmU_BQ=-H9L+bxTSMQBqHMjp1DSwGypvL0gKs+dTOfkKg@mail.gmail.com
Backpatch: 14-, where indexUnchanged hinting was introduced.

18 months agoAssert that buffers are marked dirty before XLogRegisterBuffer().
Jeff Davis [Tue, 24 Oct 2023 00:17:46 +0000 (17:17 -0700)]
Assert that buffers are marked dirty before XLogRegisterBuffer().

Enforce the rule from transam/README in XLogRegisterBuffer(), and
update callers to follow the rule.

Hash indexes sometimes register clean pages as a part of the locking
protocol, so provide a REGBUF_NO_CHANGE flag to support that use.

Discussion: https://postgr.es/m/c84114f8-c7f1-5b57-f85a-3adc31e1a904@iki.fi
Reviewed-by: Heikki Linnakangas
18 months agodoc: Improve example query related to pg_wait_events
Michael Paquier [Mon, 23 Oct 2023 23:40:43 +0000 (08:40 +0900)]
doc: Improve example query related to pg_wait_events

Author: Pavel Luzanov
Discussion: https://postgr.es/m/4f79be75-7e30-4817-b0da-4a691ea5427f@postgrespro.ru

18 months agoFix typos in wait_event.c
Michael Paquier [Mon, 23 Oct 2023 23:05:29 +0000 (08:05 +0900)]
Fix typos in wait_event.c

Noticed while working on a different patch.  Introduced in af720b4c50a1.

18 months agoChange struct tablespaceinfo's oid member from 'char *' to 'Oid'
Robert Haas [Mon, 23 Oct 2023 19:17:26 +0000 (15:17 -0400)]
Change struct tablespaceinfo's oid member from 'char *' to 'Oid'

This shouldn't change behavior except in the unusual case where
there are file in the tablespace directory that have entirely
numeric names but are nevertheless not possible names for a
tablespace directory, either because their names have leading zeroes
that shouldn't be there, or the value is actually zero, or because
the value is too large to represent as an OID.

In those cases, the directory would previously have made it into
the list of tablespaceinfo objects and no longer will. Thus, base
backups will now ignore such directories, instead of treating them
as legitimate tablespace directories. Similarly, if entries for
such tablespaces occur in a tablespace_map file, they will now
be rejected as erroneous, instead of being honored.

This is infrastructure for future work that wants to be able to
know the tablespace of each relation that is part of a backup
*as an OID*. By strengthening the up-front validation, we don't
have to worry about weird cases later, and can more easily avoid
repeated string->integer conversions.

Patch by me, reviewed by David Steele.

Discussion: http://postgr.es/m/CA+TgmoZNVeBzoqDL8xvr-nkaepq815jtDR4nJzPew7=3iEuM1g@mail.gmail.com

18 months agoRefactor parse_filename_for_nontemp_relation to parse more.
Robert Haas [Mon, 23 Oct 2023 19:08:53 +0000 (15:08 -0400)]
Refactor parse_filename_for_nontemp_relation to parse more.

Instead of returning the number of characters in the RelFileNumber,
return the RelFileNumber itself. Continue to return the fork number,
as before, and additionally return the segment number.

parse_filename_for_nontemp_relation now rejects a RelFileNumber or
segment number that begins with a leading zero. Before, we accepted
such cases as relation filenames, but if we continued to do so after
this change, the function might return the same values for two
different files (e.g. 1234.5 and 001234.5 or 1234.005) which could be
annoying for callers. Since we don't actually ever generate filenames
with leading zeroes in the names, any such files that we find must
have been created by something other than PostgreSQL, and it is
therefore reasonable to treat them as non-relation files.

Along the way, change unlogged_relation_entry to store a RelFileNumber
rather than an OID. This update should have been made in
851f4cc75cdd8c831f1baa9a7abf8c8248b65890, but it was overlooked.
It's trivial to make the update as part of this commit, perhaps more
trivial than it would have been without it, so do that.

Patch by me, reviewed by David Steele.

Discussion: http://postgr.es/m/CA+TgmoZNVeBzoqDL8xvr-nkaepq815jtDR4nJzPew7=3iEuM1g@mail.gmail.com

18 months agoRemove unnecessary break in pg_logical_replication_slot_advance()
Michael Paquier [Mon, 23 Oct 2023 01:20:30 +0000 (10:20 +0900)]
Remove unnecessary break in pg_logical_replication_slot_advance()

pg_logical_replication_slot_advance() included a break condition to stop
when a targeted LSN is reached, when processing a series of WAL records
with XLogReadRecord().  Since 38a957316d7e, it matched with the check of
its main while loop.  This condition saved from an extra CFI check,
actually pointless, so let's remove this condition and simplify the
code.

In passing, fix an incorrect comment.

Author: Bharath Rupireddy
Reviewed-by: Tom Lane, Gurjeet Singh
Discussion: https://postgr.es/m/CALj2ACWfGDLQ2cy7ZKwxnJqbDkO6Yvqqrqxne5ZN4HYm=PRTGg@mail.gmail.com

18 months agodoc: Fix some grammar and inconsistent tags
Michael Paquier [Mon, 23 Oct 2023 00:58:55 +0000 (09:58 +0900)]
doc: Fix some grammar and inconsistent tags

Author: Ekaterina Kiryanova, Elena Indrupskaya, Oleg Sibiryakov, Maxim
Yablokov
Discussion: https://postgr.es/m/4c2a430b-32e2-44e2-aeca-03b7db6824e4@postgrespro.ru

18 months agoLog LLVM library version in configure output.
Thomas Munro [Sun, 22 Oct 2023 01:17:00 +0000 (14:17 +1300)]
Log LLVM library version in configure output.

When scanning build farm results, it's useful to be able to see which
version is in use.  For the Meson build system, this information was
already displayed.

Back-patch to all supported branches.

Discussion: https://postgr.es/m/4022690.1697852728%40sss.pgh.pa.us

18 months agoFix min_dynamic_shared_memory on Windows.
Thomas Munro [Sat, 21 Oct 2023 21:04:55 +0000 (10:04 +1300)]
Fix min_dynamic_shared_memory on Windows.

When min_dynamic_shared_memory is set above 0, we try to find space in a
pre-allocated region of the main shared memory area instead of calling
dsm_impl_XXX() routines to allocate more.  The dsm_pin_segment() and
dsm_unpin_segment() routines had a bug: they called dsm_impl_XXX()
routines even for main region segments.  Nobody noticed before now
because those routines do nothing on Unix, but on Windows they'd fail
while attempting to duplicate an invalid Windows HANDLE.  Add the
missing gating.

Back-patch to 14, where commit 84b1c63a added this feature.  Fixes
pgsql-bugs bug #18165.

Reported-by: Maxime Boyer <maxime.boyer@cra-arc.gc.ca>
Tested-by: Alexander Lakhin <exclusion@gmail.com>
Discussion: https://postgr.es/m/18165-bf4f525cea6e51de%40postgresql.org

18 months agoAllow ALTER SYSTEM to set unrecognized custom GUCs.
Tom Lane [Sat, 21 Oct 2023 17:35:19 +0000 (13:35 -0400)]
Allow ALTER SYSTEM to set unrecognized custom GUCs.

Previously, ALTER SYSTEM failed if the target GUC wasn't present in
the session's GUC hashtable.  That is a reasonable behavior for core
(single-part) GUC names, and for custom GUCs for which we have loaded
an extension that's reserved the prefix.  But it's unnecessarily
restrictive otherwise, and it also causes inconsistent behavior:
you can "ALTER SYSTEM SET foo.bar" only if you did "SET foo.bar"
earlier in the session.  That's fairly silly.

Hence, refactor things so that we can execute ALTER SYSTEM even
if the variable doesn't have a GUC hashtable entry, as long as the
name meets the custom-variable naming requirements and does not
have a reserved prefix.  (It's safe to do this even if the
variable belongs to an extension we currently don't have loaded.
A bad value will at worst cause a WARNING when the extension
does get loaded.)

Also, adjust GRANT ON PARAMETER to have the same opinions about
whether to allow an unrecognized GUC name, and to throw the
same errors if not (it previously used a one-size-fits-all
message for several distinguishable conditions).  By default,
only a superuser will be allowed to do ALTER SYSTEM SET on an
unrecognized name, but it's possible to GRANT the ability to
do it.

Patch by me, pursuant to a documentation complaint from
Gavin Panella.  Arguably this is a bug fix, but given the
lack of other complaints I'll refrain from back-patching.

Discussion: https://postgr.es/m/2617358.1697501956@sss.pgh.pa.us
Discussion: https://postgr.es/m/169746329791.169914.16613647309012285391@wrigleys.postgresql.org

18 months agoMake some error strings more generic
Alvaro Herrera [Fri, 20 Oct 2023 20:52:15 +0000 (22:52 +0200)]
Make some error strings more generic

It's undesirable to have SQL commands or configuration options in a
translatable error string, so take some of these out.