]> granicus.if.org Git - postgresql/log
postgresql
5 years agoFix misuse of an integer as a bool.
Tom Lane [Mon, 13 May 2019 14:53:19 +0000 (10:53 -0400)]
Fix misuse of an integer as a bool.

pgtls_read_pending is declared to return bool, but what the underlying
SSL_pending function returns is a count of available bytes.

This is actually somewhat harmless if we're using C99 bools, but in
the back branches it's a live bug: if the available-bytes count happened
to be a multiple of 256, it would get converted to a zero char value.
On machines where char is signed, counts of 128 and up could misbehave
as well.  The net effect is that when using SSL, libpq might block
waiting for data even though some has already been received.

Broken by careless refactoring in commit 4e86f1b16, so back-patch
to 9.5 where that came in.

Per bug #15802 from David Binderman.

Discussion: https://postgr.es/m/15802-f0911a97f0346526@postgresql.org

5 years agopostgres_fdw: Fix typo in comment.
Etsuro Fujita [Mon, 13 May 2019 08:30:35 +0000 (17:30 +0900)]
postgres_fdw: Fix typo in comment.

5 years agodoc: PG 12 release notes: normalize attribution names
Bruce Momjian [Mon, 13 May 2019 03:54:02 +0000 (23:54 -0400)]
doc:  PG 12 release notes:  normalize attribution names

Reported-by: David Rowley
Discussion: https://postgr.es/m/CAKJS1f-ktEhmQ2zJQ1L1niuJ9KB8WPA-bE-AhGiFsSO6QASB_w@mail.gmail.com

5 years agodoc: adjust PG 12 release note sections
Bruce Momjian [Mon, 13 May 2019 03:41:53 +0000 (23:41 -0400)]
doc:  adjust PG 12 release note sections

Tighten section designations.

5 years agodocs: fix typo in mention of MSVC
Bruce Momjian [Mon, 13 May 2019 03:24:43 +0000 (23:24 -0400)]
docs:  fix typo in mention of MSVC

5 years agoFix incorrect return value in JSON equality function for scalars
Michael Paquier [Mon, 13 May 2019 00:11:50 +0000 (09:11 +0900)]
Fix incorrect return value in JSON equality function for scalars

equalsJsonbScalarValue() uses a boolean as return type, however for one
code path -1 gets returned, which is confusing.  The origin of the
confusion is visibly that this code got copy-pasted from
compareJsonbScalarValue() since it has been introduced in d1d50bf.

No backpatch, as this is only cosmetic.

Author: Rikard Falkeborn
Discussion: https://postgr.es/m/CADRDgG7mJnek6HNW13f+LF6V=6gag9PM+P7H5dnyWZAv49aBGg@mail.gmail.com

5 years agoFix misoptimization of "{1,1}" quantifiers in regular expressions.
Tom Lane [Sun, 12 May 2019 22:53:12 +0000 (18:53 -0400)]
Fix misoptimization of "{1,1}" quantifiers in regular expressions.

A bounded quantifier with m = n = 1 might be thought a no-op.  But
according to our documentation (which traces back to Henry Spencer's
original man page) it still imposes greediness, or non-greediness in the
case of the non-greedy variant "{1,1}?", on whatever it's attached to.

This turns out not to work though, because parseqatom() optimizes away
the m = n = 1 case without regard for whether it's supposed to change
the greediness of the argument RE.

We can fix this by just not applying the optimization when the greediness
needs to change; the subsequent general cases handle it fine.

The three cases in which we can still apply the optimization are
(a) no quantifier, or quantifier does not impose a preference;
(b) atom has no greediness property, implying it cannot match a
variable amount of text anyway; or
(c) quantifier's greediness is same as atom's.
Note that in most cases where one of these applies, we'd have exited
earlier in the "not a messy case" fast path.  I think it's now only
possible to get to the optimization when the atom involves capturing
parentheses or a non-top-level backref.

Back-patch to all supported branches.  I'd ordinarily be hesitant to
put a subtle behavioral change into back branches, but in this case
it's very hard to see a reason why somebody would write "{1,1}?" unless
they're trying to get the documented change-of-greediness behavior.

Discussion: https://postgr.es/m/5bb27a41-350d-37bf-901e-9d26f5592dd0@charter.net

5 years agoFail pgwin32_message_to_UTF16() for SQL_ASCII messages.
Noah Misch [Sun, 12 May 2019 17:33:05 +0000 (10:33 -0700)]
Fail pgwin32_message_to_UTF16() for SQL_ASCII messages.

The function had been interpreting SQL_ASCII messages as UTF8, throwing
an error when they were invalid UTF8.  The new behavior is consistent
with pg_do_encoding_conversion().  This affects LOG_DESTINATION_STDERR
and LOG_DESTINATION_EVENTLOG, which will send untranslated bytes to
write() and ReportEventA().  On buildfarm member bowerbird, enabling
log_connections caused an error whenever the role name was not valid
UTF8.  Back-patch to 9.4 (all supported versions).

Discussion: https://postgr.es/m/20190512015615.GD1124997@rfd.leadboat.com

5 years agoRearrange pgstat_bestart() to avoid failures within its critical section.
Tom Lane [Sun, 12 May 2019 01:27:13 +0000 (21:27 -0400)]
Rearrange pgstat_bestart() to avoid failures within its critical section.

We long ago decided to design the shared PgBackendStatus data structure to
minimize the cost of writing status updates, which means that writers just
have to increment the st_changecount field twice.  That isn't hooked into
any sort of resource management mechanism, which means that if something
were to throw error between the two increments, the st_changecount field
would be left odd indefinitely.  That would cause readers to lock up.
Now, since it's also a bad idea to leave the field odd for longer than
absolutely necessary (because readers will spin while we have it set),
the expectation was that we'd treat these segments like spinlock critical
sections, with only short, more or less straight-line, code in them.

That was fine as originally designed, but commit 9029f4b37 broke it
by inserting a significant amount of non-straight-line code into
pgstat_bestart(), code that is very capable of throwing errors, not to
mention taking a significant amount of time during which readers will spin.
We have a report from Neeraj Kumar of readers actually locking up, which
I suspect was due to an encoding conversion error in X509_NAME_to_cstring,
though conceivably it was just a garden-variety OOM failure.

Subsequent commits have loaded even more dubious code into pgstat_bestart's
critical section (and commit fc70a4b0d deserves some kind of booby prize
for managing to miss the critical section entirely, although the negative
consequences seem minimal given that the PgBackendStatus entry should be
seen by readers as inactive at that point).

The right way to fix this mess seems to be to compute all these values
into a local copy of the process' PgBackendStatus struct, and then just
copy the data back within the critical section proper.  This plan can't
be implemented completely cleanly because of the struct's heavy reliance
on out-of-line strings, which we must initialize separately within the
critical section.  But still, the critical section is far smaller and
safer than it was before.

In hopes of forestalling future errors of the same ilk, rename the
macros for st_changecount management to make it more apparent that
the writer-side macros create a critical section.  And to prevent
the worst consequences if we nonetheless manage to mess it up anyway,
adjust those macros so that they really are a critical section, ie
they now bump CritSectionCount.  That doesn't add much overhead, and
it guarantees that if we do somehow throw an error while the counter
is odd, it will lead to PANIC and a database restart to reset shared
memory.

Back-patch to 9.5 where the problem was introduced.

In HEAD, also fix an oversight in commit b0b39f72b: it failed to teach
pgstat_read_current_status to copy st_gssstatus data from shared memory to
local memory.  Hence, subsequent use of that data within the transaction
would potentially see changing data that it shouldn't see.

Discussion: https://postgr.es/m/CAPR3Wj5Z17=+eeyrn_ZDG3NQGYgMEOY6JV6Y-WRRhGgwc16U3Q@mail.gmail.com

5 years agodocs: remove second mention of btree max length reduction
Bruce Momjian [Sat, 11 May 2019 22:24:31 +0000 (18:24 -0400)]
docs:  remove second mention of btree max length reduction

I already added that to the incompatibility section as a separate item.

Reported-by: Peter Geoghegan
5 years agodoc: remove pg_config mention from PG 12 release notes
Bruce Momjian [Sat, 11 May 2019 21:59:58 +0000 (17:59 -0400)]
doc:  remove pg_config mention from PG 12 release notes

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

5 years agodocs: PG 12 release notes, mention that REINDEX could now fail
Bruce Momjian [Sat, 11 May 2019 20:42:05 +0000 (16:42 -0400)]
docs:  PG 12 release notes, mention that REINDEX could now fail

This is because of the new tid in the index entry.

Reported-by: Peter Geoghegan
5 years agodocs: add links from the PG 12 release notes to the main docs
Bruce Momjian [Sat, 11 May 2019 20:17:18 +0000 (16:17 -0400)]
docs:  add links from the PG 12 release notes to the main docs

5 years agodocs: adjust PG 12 floating point item
Bruce Momjian [Sat, 11 May 2019 14:29:30 +0000 (10:29 -0400)]
docs:  adjust PG 12 floating point item

Reported-by: Andrew Gierth
Discussion: https://postgr.es/m/87r295hjur.fsf@news-spur.riddles.org.uk

5 years agoHonor TEMP_CONFIG in TAP suites.
Noah Misch [Sat, 11 May 2019 07:22:38 +0000 (00:22 -0700)]
Honor TEMP_CONFIG in TAP suites.

The buildfarm client uses TEMP_CONFIG to implement its extra_config
setting.  Except for stats_temp_directory, extra_config now applies to
TAP suites; extra_config values seen in the past month are compatible
with this.  Back-patch to 9.6, where PostgresNode was introduced, so the
buildfarm can rely on it sooner.

Reviewed by Andrew Dunstan and Tom Lane.

Discussion: https://postgr.es/m/20181229021950.GA3302966@rfd.leadboat.com

5 years agoFix error reporting in reindexdb
Michael Paquier [Sat, 11 May 2019 04:00:54 +0000 (13:00 +0900)]
Fix error reporting in reindexdb

When failing to reindex a table or an index, reindexdb would generate an
extra error message related to a database failure, which is misleading.

Backpatch all the way down, as this has been introduced by 85e9a5a0.

Discussion: https://postgr.es/m/CAOBaU_Yo61RwNO3cW6WVYWwH7EYMPuexhKqufb2nFGOdunbcHw@mail.gmail.com
Author: Julien Rouhaud
Reviewed-by: Daniel Gustafsson, Álvaro Herrera, Tom Lane, Michael
Paquier
Backpatch-through: 9.4

5 years agoFix editing error in floating-point docs.
Andrew Gierth [Sat, 11 May 2019 02:23:55 +0000 (03:23 +0100)]
Fix editing error in floating-point docs.

My fault; the error was introduced in the Ryu patch.

5 years agodoc: add Heikki to PG 12 release note btree item
Bruce Momjian [Sat, 11 May 2019 02:11:13 +0000 (22:11 -0400)]
doc:  add Heikki to PG 12 release note btree item

Reported-by: Peter Geoghegan
Discussion: https://postgr.es/m/CAH2-WzkrX-aA7d3OYtQT+8Mspq+tU5vwuVz=FTzMH3CdrSyprA@mail.gmail.com

5 years agodoc: improve PG 12 item on partitioned tables
Bruce Momjian [Sat, 11 May 2019 01:22:53 +0000 (21:22 -0400)]
doc:  improve PG 12 item on partitioned tables

Reported-by: Amit Langote
Discussion: https://postgr.es/m/5936b052-5d92-a2c9-75d2-0245fb2330b5@lab.ntt.co.jp

5 years agodoc: reorder attribution of PG 12 btree item
Bruce Momjian [Sat, 11 May 2019 01:16:33 +0000 (21:16 -0400)]
doc: reorder attribution of PG 12 btree item

Reported-by: Alexander Korotkov
Discussion: https://postgr.es/m/CAPpHfdvkM-PkyrK6LQitJUDmC_1kOCEtTuseoVhCT=ew0XJmGg@mail.gmail.com

5 years agodocs: properly attribute PG 12 rel item to James Coleman
Bruce Momjian [Sat, 11 May 2019 01:06:38 +0000 (21:06 -0400)]
docs:  properly attribute PG 12 rel item to James Coleman

Reported-by: David Rowley
Discussion: https://postgr.es/m/CAKJS1f-NDmeA_tb0oRFhrgf19xq3A9MeoyMcckY04Ct=_i0c2A@mail.gmail.com

5 years agodocs: PG 12 docs, clarify btree index changes
Bruce Momjian [Sat, 11 May 2019 01:03:31 +0000 (21:03 -0400)]
docs:  PG 12 docs, clarify btree index changes

Reported-by: Peter Geoghegan
Discussion: https://postgr.es/m/CAH2-WzkSYOM1GJVGtAbRW-OqymoCD=QWYG6ro+GaoOW-jPRuDQ@mail.gmail.com

5 years agodoc: PG 12 release note adjustment
Bruce Momjian [Sat, 11 May 2019 00:25:52 +0000 (20:25 -0400)]
doc: PG 12 release note adjustment

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20190510013449.GL3925@telsasoft.com

5 years agoRemove reindex_catalog test from test schedules.
Andres Freund [Mon, 6 May 2019 06:31:58 +0000 (23:31 -0700)]
Remove reindex_catalog test from test schedules.

As none of the approaches for avoiding the deadlock issues seem
promising enough, and all the expected reindex related changes have
been made, apply 60c2951e1bab7e to master as well.

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

5 years agoCope with EINVAL and EIDRM shmat() failures in PGSharedMemoryAttach.
Tom Lane [Fri, 10 May 2019 18:56:41 +0000 (14:56 -0400)]
Cope with EINVAL and EIDRM shmat() failures in PGSharedMemoryAttach.

There's a very old race condition in our code to see whether a pre-existing
shared memory segment is still in use by a conflicting postmaster: it's
possible for the other postmaster to remove the segment in between our
shmctl() and shmat() calls.  It's a narrow window, and there's no risk
unless both postmasters are using the same port number, but that's possible
during parallelized "make check" tests.  (Note that while the TAP tests
take some pains to choose a randomized port number, pg_regress doesn't.)
If it does happen, we treated that as an unexpected case and errored out.

To fix, allow EINVAL to be treated as segment-not-present, and the same
for EIDRM on Linux.  AFAICS, the considerations here are basically
identical to the checks for acceptable shmctl() failures, so I documented
and coded it that way.

While at it, adjust PGSharedMemoryAttach's API to remove its undocumented
dependency on UsedShmemSegAddr in favor of passing the attach address
explicitly.  This makes it easier to be sure we're using a null shmaddr
when probing for segment conflicts (thus avoiding questions about what
EINVAL means).  I don't think there was a bug there, but it required
fragile assumptions about the state of UsedShmemSegAddr during
PGSharedMemoryIsInUse.

Commit c09850992 may have made this failure more probable by applying
the conflicting-segment tests more often.  Hence, back-patch to all
supported branches, as that was.

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

5 years agodoc: add markup for PG 12 release note text
Bruce Momjian [Fri, 10 May 2019 03:26:48 +0000 (23:26 -0400)]
doc:  add markup for PG 12 release note text

I will add links to other parts of the docs later.

5 years agodoc: PG 12 wording improvments
Bruce Momjian [Fri, 10 May 2019 00:58:02 +0000 (20:58 -0400)]
doc: PG 12 wording improvments

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20190510001335.GJ3925@telsasoft.com

5 years agoFix and improve description of locktag types in lock.h
Michael Paquier [Fri, 10 May 2019 00:35:27 +0000 (09:35 +0900)]
Fix and improve description of locktag types in lock.h

The description of the lock type for speculative insertions was
incorrect, being copy-pasted from another one.

As discussed, also move the description for all the fields of lock tag
types from the structure listing lock tag types to the set of macros
setting each LOCKTAG.

Author: John Naylor
Discussion: https://postgr.es/m/CACPNZCtA0-ybaC4fFfaDq_8p_TUOLvGxZH9Dm-=TMHZJarBa7Q@mail.gmail.com

5 years agodoc: more PG 12 wording adjustments
Bruce Momjian [Fri, 10 May 2019 00:32:35 +0000 (20:32 -0400)]
doc:  more PG 12 wording adjustments

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20190510001959.GK3925@telsasoft.com

5 years agodoc: fix capitalization in PG 12 release notes
Bruce Momjian [Fri, 10 May 2019 00:10:17 +0000 (20:10 -0400)]
doc:  fix capitalization in PG 12 release notes

Reported-by: Thomas Munro
Discussion: https://postgr.es/m/CA+hUKGJpep8uSXoDtVF6iROCRKce-39HEhDPUaYFyMn0U5e9ug@mail.gmail.com

5 years agodoc: more PG 12 release note adjustments
Bruce Momjian [Thu, 9 May 2019 23:59:59 +0000 (19:59 -0400)]
doc:  more PG 12 release note adjustments

This adds two more items that should have been included in the
beginning.

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20190508203204.GA25482@telsasoft.com

5 years agodocs: update release notes with fixes
Bruce Momjian [Thu, 9 May 2019 23:27:03 +0000 (19:27 -0400)]
docs:  update release notes with fixes

Reported-by: Justin Pryzby
Discussion: https://postgr.es/m/20190508203204.GA25482@telsasoft.com

5 years agoImprove and fix some error handling for REINDEX INDEX/TABLE CONCURRENTLY
Michael Paquier [Thu, 9 May 2019 23:18:46 +0000 (08:18 +0900)]
Improve and fix some error handling for REINDEX INDEX/TABLE CONCURRENTLY

This improves the user experience when it comes to restrict several
flavors of REINDEX CONCURRENTLY.  First, for INDEX, remove a restriction
on shared relations as we already check after catalog relations.  Then,
for TABLE, add a proper error message when attempting to run the command
on system catalogs.  The code path of CREATE INDEX CONCURRENTLY already
complains about that, but if a REINDEX is issued then then the error
generated is confusing.

While on it, add more tests to check restrictions on catalog indexes and
on toast table/index for catalogs.  Some error messages are improved,
with wording suggestion coming from Tom Lane.

Reported-by: Tom Lane
Author: Michael Paquier
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/23694.1556806002@sss.pgh.pa.us

5 years agoRepair issues with faulty generation of merge-append plans.
Tom Lane [Thu, 9 May 2019 20:52:48 +0000 (16:52 -0400)]
Repair issues with faulty generation of merge-append plans.

create_merge_append_plan failed to honor the CP_EXACT_TLIST flag:
it would generate the expected targetlist but then it felt free to
add resjunk sort targets to it.  This demonstrably leads to assertion
failures in v11 and HEAD, and it's probably just accidental that we
don't see the same in older branches.  I've not looked into whether
there would be any real-world consequences in non-assert builds.
In HEAD, create_append_plan has sprouted the same problem, so fix
that too (although we do not have any test cases that seem able to
reach that bug).  This is an oversight in commit 3fc6e2d7f which
invented the CP_EXACT_TLIST flag, so back-patch to 9.6 where that
came in.

convert_subquery_pathkeys would create pathkeys for subquery output
values if they match any EquivalenceClass known in the outer query
and are available in the subquery's syntactic targetlist.  However,
the second part of that condition is wrong, because such values might
not appear in the subquery relation's reltarget list, which would
mean that they couldn't be accessed above the level of the subquery
scan.  We must check that they appear in the reltarget list, instead.
This can lead to dropping knowledge about the subquery's sort
ordering, but I believe it's okay, because any sort key that the
outer query actually has any interest in would appear in the
reltarget list.

This second issue is of very long standing, but right now there's no
evidence that it causes observable problems before 9.6, so I refrained
from back-patching further than that.  We can revisit that choice if
somebody finds a way to make it cause problems in older branches.
(Developing useful test cases for these issues is really problematic;
fixing convert_subquery_pathkeys removes the only known way to exhibit
the create_merge_append_plan bug, and neither of the test cases added
by this patch causes a problem in all branches, even when considering
the issues separately.)

The second issue explains bug #15795 from Suresh Kumar R ("could not
find pathkey item to sort" with nested DISTINCT queries).  I stumbled
across the first issue while investigating that.

Discussion: https://postgr.es/m/15795-fadb56c8e44ee73c@postgresql.org

5 years agodoc: update PG 12 release notes, v2
Bruce Momjian [Thu, 9 May 2019 20:44:27 +0000 (16:44 -0400)]
doc:  update PG 12 release notes, v2

Adjustments requested by reviewers.

Reported-by: Amit Kapila, Thomas Munro, Andrew Gierth, Amit Langote, Oleg Bartunov, Michael Paquier, Alvaro Herrera, Tatsuo Ishii
Discussion: https://postgr.es/m/20190506233029.ozwged67i7s4qd6c@momjian.us

5 years agoDoc: Update FDW documentation about GetForeignUpperPaths().
Etsuro Fujita [Thu, 9 May 2019 10:50:15 +0000 (19:50 +0900)]
Doc: Update FDW documentation about GetForeignUpperPaths().

In commit d50d172e51, which added support for LIMIT/OFFSET pushdown in
postgres_fdw, a new struct was introduced as the extra parameter of
GetForeignUpperPaths() set for UPPERREL_FINAL, but I forgot to update
the documentation to mention that.

Author: Etsuro Fujita
Discussion: https://postgr.es/m/CAPmGK17uSXQDe31oRb-z1nYyT6vVzkstZkA3_Wbq38U92b9BmQ%40mail.gmail.com

5 years agopostgres_fdw: Fix cost estimation for aggregate pushdown.
Etsuro Fujita [Thu, 9 May 2019 09:39:23 +0000 (18:39 +0900)]
postgres_fdw: Fix cost estimation for aggregate pushdown.

In commit 7012b132d0, which added support for aggregate pushdown in
postgres_fdw, the expense of evaluating the final scan/join target
computed by make_group_input_target() was not accounted for at all in
costing aggregate pushdown paths with local statistics.  The right fix
for this would be to have a separate upper stage to adjust the final
scan/join relation (see comments for apply_scanjoin_target_to_paths());
but for now, fix by adding the tlist eval cost when costing aggregate
pushdown paths with local statistics.

Apply this to HEAD only to avoid destabilizing existing plan choices.

Author: Etsuro Fujita
Reviewed-By: Antonin Houska
Discussion: https://postgr.es/m/5C66A056.60007%40lab.ntt.co.jp

5 years agoFix SxactGlobalXmin tracking.
Thomas Munro [Thu, 9 May 2019 07:11:46 +0000 (19:11 +1200)]
Fix SxactGlobalXmin tracking.

Commit bb16aba50 broke the code that maintains SxactGlobalXmin.  It
could get stuck when a well-timed READ ONLY transaction runs.  If
SxactGlobalXmin stops advancing, transactions on the
FinishedSerializableTransactions queue are never cleaned up, so
resources are effectively leaked.  Revert that hunk of the commit.

Also revert another similar hunk that was probably harmless, but
unnecessary and unjustified, relating to the DOOMED flag in case of
RO_SAFE early release.

Author: Thomas Munro
Reported-by: Tom Lane
Discussion: https://postgr.es/m/16170.1557251214%40sss.pgh.pa.us

5 years agopg_controldata: Add common gettext flags
Peter Eisentraut [Thu, 9 May 2019 07:15:59 +0000 (09:15 +0200)]
pg_controldata: Add common gettext flags

So it picks up strings in pg_log_* calls.  This was forgotten when it
was added to all other relevant subdirectories.

5 years agoFix grammar in error message
Peter Eisentraut [Thu, 9 May 2019 07:14:37 +0000 (09:14 +0200)]
Fix grammar in error message

5 years agoClean up the behavior and API of catalog.c's is-catalog-relation tests.
Tom Lane [Thu, 9 May 2019 03:27:29 +0000 (23:27 -0400)]
Clean up the behavior and API of catalog.c's is-catalog-relation tests.

The right way for IsCatalogRelation/Class to behave is to return true
for OIDs less than FirstBootstrapObjectId (not FirstNormalObjectId),
without any of the ad-hoc fooling around with schema membership.

The previous code was wrong because (1) it claimed that
information_schema tables were not catalog relations but their toast
tables were, which is silly; and (2) if you dropped and recreated
information_schema, which is a supported operation, the behavior
changed.  That's even sillier.  With this definition, "catalog
relations" are exactly the ones traceable to the postgres.bki data,
which seems like what we want.

With this simplification, we don't actually need access to the pg_class
tuple to identify a catalog relation; we only need its OID.  Hence,
replace IsCatalogClass with "IsCatalogRelationOid(oid)".  But keep
IsCatalogRelation as a convenience function.

This allows fixing some arguably-wrong semantics in contrib/sepgsql and
ReindexRelationConcurrently, which were using an IsSystemNamespace test
where what they really should be using is IsCatalogRelationOid.  The
previous coding failed to protect toast tables of system catalogs, and
also was not on board with the general principle that user-created tables
do not become catalogs just by virtue of being renamed into pg_catalog.
We can also get rid of a messy hack in ReindexMultipleTables.

While we're at it, also rename IsSystemNamespace to IsCatalogNamespace,
because the previous name invited confusion with the more expansive
semantics used by IsSystemRelation/Class.

Also improve the comments in catalog.c.

There are a few remaining places in replication-related code that are
special-casing OIDs below FirstNormalObjectId.  I'm inclined to think
those are wrong too, and if there should be any special case it should
just extend to FirstBootstrapObjectId.  But first we need to debate
whether a FOR ALL TABLES publication should include information_schema.

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

5 years agoFix error status of vacuumdb when multiple jobs are used
Michael Paquier [Thu, 9 May 2019 01:29:10 +0000 (10:29 +0900)]
Fix error status of vacuumdb when multiple jobs are used

When running a batch of VACUUM or ANALYZE commands on a given database,
there were cases where it is possible to have vacuumdb not report an
error where it actually should, leading to incorrect status results.

Author: Julien Rouhaud
Reviewed-by: Amit Kapila, Michael Paquier
Discussion: https://postgr.es/m/CAOBaU_ZuTwz7CtqLYJ1Ouuh272bTQPLN8b1bAPk0bCBm4PDMTQ@mail.gmail.com
Backpatch-through: 9.5

5 years agoRemove obsolete nbtree split REDO routine comment.
Peter Geoghegan [Wed, 8 May 2019 19:47:20 +0000 (12:47 -0700)]
Remove obsolete nbtree split REDO routine comment.

Commit dd299df8189, which added suffix truncation to nbtree, simplified
the WAL record format used by page splits.  It became necessary to
explicitly WAL-log the new high key for the left half of a split in all
cases, which relieved the REDO routine from having to reconstruct a new
high key for the left page by copying the first item from the right
page.  Remove a comment that referred to the previous practice.

5 years agoFix error messages
Alvaro Herrera [Wed, 8 May 2019 17:16:54 +0000 (13:16 -0400)]
Fix error messages

Some messages related to foreign servers were reporting the server name
without quotes, or not at all; our style is to have all names be quoted,
and the server name already appears quoted in a few other messages, so
just add quotes and make them all consistent.

Remove an extra "s" in other messages (typos introduced by myself in
f56f8f8da6af).

5 years agoFix documentation for the privileges required for replication functions.
Fujii Masao [Wed, 8 May 2019 16:35:13 +0000 (01:35 +0900)]
Fix documentation for the privileges required for replication functions.

Previously it's documented that use of replication functions is
restricted to superusers. This is true for the functions which
use replication origin, but not for pg_logicl_emit_message() and
functions which use replication slot. For example, not only
superusers but also users with REPLICATION privilege is allowed
to use the functions for replication slot. This commit fixes
the documentation for the privileges required for those replication
functions.

Back-patch to 9.4 (all supported versions).

Author: Matsumura Ryo
Discussion: https://postgr.es/m/03040DFF97E6E54E88D3BFEE5F5480F74ABA6E16@G01JPEXMBYT04

5 years agoFix table lock levels for REINDEX INDEX CONCURRENTLY
Peter Eisentraut [Wed, 8 May 2019 12:15:01 +0000 (14:15 +0200)]
Fix table lock levels for REINDEX INDEX CONCURRENTLY

REINDEX CONCURRENTLY locks tables with ShareUpdateExclusiveLock rather
than the ShareLock used by a plain REINDEX.  However,
RangeVarCallbackForReindexIndex() was not updated for that and still
used the ShareLock only.  This would lead to lock upgrades later,
leading to possible deadlocks.

Reported-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Andres Freund <andres@anarazel.de>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://www.postgresql.org/message-id/flat/20190430151735.wi52sxjvxsjvaxxt%40alap3.anarazel.de

5 years agoProbe only 127.0.0.1 when looking for ports on Unix.
Thomas Munro [Mon, 6 May 2019 03:02:41 +0000 (15:02 +1200)]
Probe only 127.0.0.1 when looking for ports on Unix.

Commit c0985099, later adjusted by commit 4ab02e81, probed 0.0.0.0
in addition to 127.0.0.1, for the benefit of Windows build farm
animals.  It isn't really useful on Unix systems, and turned out to
be a bit inconvenient to users of some corporate firewall software.
Switch back to probing just 127.0.0.1 on non-Windows systems.

Back-patch to 9.6, like the earlier changes.

Discussion: https://postgr.es/m/CA%2BhUKG%2B21EPwfgs4m%2BtqyRtbVqkOUvP8QQ8sWk9%2Bh55Aub1H3A%40mail.gmail.com

5 years agoFix copy-and-paste mistakes in documentation.
Thomas Munro [Wed, 8 May 2019 09:14:14 +0000 (21:14 +1200)]
Fix copy-and-paste mistakes in documentation.

Reported-by: Vik Fearing
5 years agoAdd missing periods to comments.
Etsuro Fujita [Wed, 8 May 2019 07:49:09 +0000 (16:49 +0900)]
Add missing periods to comments.

5 years agoRemove leftover reference to old "flat file" mechanism in a comment.
Heikki Linnakangas [Wed, 8 May 2019 06:32:34 +0000 (09:32 +0300)]
Remove leftover reference to old "flat file" mechanism in a comment.

The flat file mechanism was removed in PostgreSQL 9.0.

5 years agoCorrect obsolete nbtsort.c minimum key comment.
Peter Geoghegan [Wed, 8 May 2019 04:42:12 +0000 (21:42 -0700)]
Correct obsolete nbtsort.c minimum key comment.

It is no longer possible under any circumstances for nbtree code to
reconstruct a strict lower bound key (parent page's pivot tuple key) for
a right sibling page by retrieving the first item in the right sibling
page.

5 years agoAdd jsonpath_encoding_1.out changes missed in 29ceacc3f9
Alexander Korotkov [Tue, 7 May 2019 22:55:31 +0000 (01:55 +0300)]
Add jsonpath_encoding_1.out changes missed in 29ceacc3f9

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

5 years agoRemove word "singleton" out of jsonpath docs
Alexander Korotkov [Mon, 29 Apr 2019 22:12:05 +0000 (01:12 +0300)]
Remove word "singleton" out of jsonpath docs

Word "singleton" is hard for user understanding, especially taking into account
there is only one place it's used in the docs and there is even no definition.
Use more evident wording instead.

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

5 years agoImprove error reporting in jsonpath
Alexander Korotkov [Tue, 23 Apr 2019 14:43:09 +0000 (17:43 +0300)]
Improve error reporting in jsonpath

This commit contains multiple improvements to error reporting in jsonpath
including but not limited to getting rid of following things:

 * definition of error messages in macros,
 * errdetail() when valueable information could fit to errmsg(),
 * word "singleton" which is not properly explained anywhere,
 * line breaks in error messages.

Reported-by: Tom Lane
Discussion: https://postgr.es/m/14890.1555523005%40sss.pgh.pa.us
Author: Alexander Korotkov
Reviewed-by: Tom Lane
5 years agoAdd TRUNCATE parameter to VACUUM.
Fujii Masao [Tue, 7 May 2019 17:10:33 +0000 (02:10 +0900)]
Add TRUNCATE parameter to VACUUM.

This commit adds new parameter to VACUUM command, TRUNCATE,
which specifies that VACUUM should attempt to truncate off
any empty pages at the end of the table and allow the disk space
for the truncated pages to be returned to the operating system.

This parameter, if specified, overrides the vacuum_truncate
reloption. If neither the reloption nor the VACUUM option is
used, the default is true, as before.

Author: Fujii Masao
Reviewed-by: Julien Rouhaud, Masahiko Sawada
Discussion: https://postgr.es/m/CAD21AoD+qtrSDL=GSma4Wd3kLYLeRC0hPna-YAdkDeV4z156vg@mail.gmail.com

5 years agoFix typos and clarify a comment
Magnus Hagander [Tue, 7 May 2019 16:26:09 +0000 (18:26 +0200)]
Fix typos and clarify a comment

Author: Daniel Gustafsson <daniel@yesql.se>

5 years agoAvoid "invalid memory alloc request size" while reading pg_stat_activity.
Tom Lane [Tue, 7 May 2019 15:41:37 +0000 (11:41 -0400)]
Avoid "invalid memory alloc request size" while reading pg_stat_activity.

On a 64-bit machine, if you set track_activity_query_size and
max_connections such that their product exceeds 1GB, shared memory
setup will still succeed (given enough RAM), but attempts to read
pg_stat_activity fail with "invalid memory alloc request size".
Work around that by using MemoryContextAllocHuge to allocate the
local copy of the activity strings.  Using the "huge" API costs us
nothing extra in normal cases, and it seems better than throwing
an error and/or explaining to people why they can't do this.

This situation seems insanely profligate today, but who knows what
people will consider normal in ten or twenty years?  So let's fix it
in HEAD but not worry about a back-patch.

Per report from James Tomson.

Discussion: https://postgr.es/m/1CFDCCD6-B268-48D8-85C8-400D2790B2C3@pushd.com

5 years agodoc: Generate keywords table automatically
Peter Eisentraut [Tue, 7 May 2019 13:29:39 +0000 (15:29 +0200)]
doc: Generate keywords table automatically

The SQL keywords table in the documentation had until now been
generated by some ad hoc scripting outside the source tree once for
each major release.  This changes it to an automated process.

We have the PostgreSQL keywords available in a parseable format in
parser/kwlist.h.  For the relevant SQL standard versions, keep the
keyword lists in new text files.  A new script
generate-keywords-table.pl pulls it all together and produces a
DocBook table.

The final output in the documentation should be identical after this
change.

Discussion: https://www.postgresql.org/message-id/flat/07daeadd-8c82-0d95-5e19-e350502cb749%402ndquadrant.com

5 years agoRevert "Avoid the creation of the free space map for small heap relations".
Amit Kapila [Tue, 7 May 2019 04:00:24 +0000 (09:30 +0530)]
Revert "Avoid the creation of the free space map for small heap relations".

This feature was using a process local map to track the first few blocks
in the relation.  The map was reset each time we get the block with enough
freespace.  It was discussed that it would be better to track this map on
a per-relation basis in relcache and then invalidate the same whenever
vacuum frees up some space in the page or when FSM is created.  The new
design would be better both in terms of API design and performance.

List of commits reverted, in reverse chronological order:

06c8a5090e  Improve code comments in b0eaa4c51b.
13e8643bfc  During pg_upgrade, conditionally skip transfer of FSMs.
6f918159a9  Add more tests for FSM.
9c32e4c350  Clear the local map when not used.
29d108cdec  Update the documentation for FSM behavior..
08ecdfe7e5  Make FSM test portable.
b0eaa4c51b  Avoid creation of the free space map for small heap relations.

Discussion: https://postgr.es/m/20190416180452.3pm6uegx54iitbt5@alap3.anarazel.de

5 years agoRemove some code related to 7.3 and older servers from tools of src/bin/
Michael Paquier [Tue, 7 May 2019 00:39:39 +0000 (09:39 +0900)]
Remove some code related to 7.3 and older servers from tools of src/bin/

This code was broken as of 582edc3, and is most likely not used anymore.
Note that pg_dump supports servers down to 8.0, and psql has code to
support servers down to 7.4.

Author: Julien Rouhaud
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/CAOBaU_Y5y=zo3+2gf+2NJC1pvMYPcbRXoQaPXx=U7+C8Qh4CzQ@mail.gmail.com

5 years agodocs: fist draft version of the PG 12 release notes
Bruce Momjian [Mon, 6 May 2019 23:02:34 +0000 (19:02 -0400)]
docs:  fist draft version of the PG 12 release notes

Still needs text markup, links, word wrap, and indenting.

5 years agoRevert "Make pg_dump emit ATTACH PARTITION instead of PARTITION OF"
Alvaro Herrera [Mon, 6 May 2019 16:23:49 +0000 (12:23 -0400)]
Revert "Make pg_dump emit ATTACH PARTITION instead of PARTITION OF"

... and fallout (from branches 10, 11 and master).  The change was
ill-considered, and it broke a few normal use cases; since we don't have
time to fix it, we'll try again after this week's minor releases.

Reported-by: Rushabh Lathia
Discussion: https://postgr.es/m/CAGPqQf0iQV=PPOv2Btog9J9AwOQp6HmuVd6SbGTR_v3Zp2XT1w@mail.gmail.com

5 years agoAdd tests for error message generation in partition tuple routing
Michael Paquier [Mon, 6 May 2019 12:44:24 +0000 (21:44 +0900)]
Add tests for error message generation in partition tuple routing

This adds extra tests for the error message generated for partition
tuple routing in the executor, using more than three levels of
partitioning including partitioned tables with no partitions.  These
tests have been added to fix CVE-2019-10129 on REL_11_STABLE.  HEAD has
no active bugs in this area, but it lacked coverage.

Author: Michael Paquier
Reviewed-by: Noah Misch
Security: CVE-2019-10129

5 years agoUse checkAsUser for selectivity estimator checks, if it's set.
Dean Rasheed [Mon, 6 May 2019 10:54:32 +0000 (11:54 +0100)]
Use checkAsUser for selectivity estimator checks, if it's set.

In examine_variable() and examine_simple_variable(), when checking the
user's table and column privileges to determine whether to grant
access to the pg_statistic data, use checkAsUser for the privilege
checks, if it's set. This will be the case if we're accessing the
table via a view, to indicate that we should perform privilege checks
as the view owner rather than the current user.

This change makes this planner check consistent with the check in the
executor, so the planner will be able to make use of statistics if the
table is accessible via the view. This fixes a performance regression
introduced by commit e2d4ef8de8, which affects queries against
non-security barrier views in the case where the user doesn't have
privileges on the underlying table, but the view owner does.

Note that it continues to provide the same safeguards controlling
access to pg_statistic for direct table access (in which case
checkAsUser won't be set) and for security barrier views, because of
the nearby checks on rte->security_barrier and rte->securityQuals.

Back-patch to all supported branches because e2d4ef8de8 was.

Dean Rasheed, reviewed by Jonathan Katz and Stephen Frost.

5 years agoFix security checks for selectivity estimation functions with RLS.
Dean Rasheed [Mon, 6 May 2019 10:38:43 +0000 (11:38 +0100)]
Fix security checks for selectivity estimation functions with RLS.

In commit e2d4ef8de8, security checks were added to prevent
user-supplied operators from running over data from pg_statistic
unless the user has table or column privileges on the table, or the
operator is leakproof. For a table with RLS, however, checking for
table or column privileges is insufficient, since that does not
guarantee that the user has permission to view all of the column's
data.

Fix this by also checking for securityQuals on the RTE, and insisting
that the operator be leakproof if there are any. Thus the
leakproofness check will only be skipped if there are no securityQuals
and the user has table or column privileges on the table -- i.e., only
if we know that the user has access to all the data in the column.

Back-patch to 9.5 where RLS was added.

Dean Rasheed, reviewed by Jonathan Katz and Stephen Frost.

Security: CVE-2019-10130

5 years agoBring pg_nextoid()'s error messages into line with message style guide.
Tom Lane [Sun, 5 May 2019 21:06:53 +0000 (17:06 -0400)]
Bring pg_nextoid()'s error messages into line with message style guide.

Noticed while reviewing nearby code.  Given all the disclaimers about
this not being meant as user-facing code, I wonder whether we should
make these non-translatable?  But in any case there's little excuse
for them not to be good English.

5 years agoFix style violations in syscache lookups.
Tom Lane [Sun, 5 May 2019 17:10:07 +0000 (13:10 -0400)]
Fix style violations in syscache lookups.

Project style is to check the success of SearchSysCacheN and friends
by applying HeapTupleIsValid to the result.  A tiny minority of calls
creatively did it differently.  Bring them into line with the rest.

This is just cosmetic, since HeapTupleIsValid is indeed just a null
check at the moment ... but that may not be true forever, and in any
case it puts a mental burden on readers who may wonder why these
call sites are not like the rest.

Back-patch to v11 just to keep the branches in sync.  (The bulk of these
errors seem to have originated in v11 or v12, though a few are old.)

Per searching to see if anyplace else had made the same error
repaired in 62148c352.

5 years agoAdd check for syscache lookup failure in update_relispartition().
Tom Lane [Sun, 5 May 2019 16:44:32 +0000 (12:44 -0400)]
Add check for syscache lookup failure in update_relispartition().

Omitted in commit 05b38c7e6 (though it looks like the original blame
belongs to 9e9befac4).  A failure is admittedly unlikely, but if it
did happen, SIGSEGV is not the approved method of reporting it.

Per Coverity.  Back-patch to v11 where the broken code originated.

5 years agoFix set of issues with memory-allocation system calls in frontend code
Michael Paquier [Sat, 4 May 2019 07:32:19 +0000 (16:32 +0900)]
Fix set of issues with memory-allocation system calls in frontend code

Like the backend, the frontend has wrappers on top of malloc() and such
whose use is recommended.  Particularly, it is possible to do memory
allocation without issuing an error.  Some binaries missed the use of
those wrappers, so let's fix the gap for consistency.

This also fixes two latent bugs:
- In pg_dump/pg_dumpall when parsing an ACL item, on an out-of-memory
error for strdup(), the code considered the failure as a ACL parsing
problem instead of an actual OOM.
- In pg_waldump, an OOM when building the target directory string would
cause a crash.

Author: Daniel Gustafsson
Discussion: https://postgr.es/m/gY0y9xenfoBPc-Tufsr2Zg-MmkrJslm0Tw_CMg4p_j58-k_PXNC0klMdkKQkg61BkXC9_uWo-DcUzfxnHqpkpoR5jjVZrPHqKYikcHIiONhg=@yesql.se

5 years agoMSVC: Build ~35% faster by calling dumpbin just once per directory.
Noah Misch [Sat, 4 May 2019 04:56:47 +0000 (21:56 -0700)]
MSVC: Build ~35% faster by calling dumpbin just once per directory.

Peifeng Qiu

Discussion: https://postgr.es/m/CABmtVJiKXQjast0dQD-8KAtfm8XmyYxo-4Dc7+M+fBr8JRTqkw@mail.gmail.com

5 years agoSuppress compiler warning in non-SSL, non-assert builds.
Noah Misch [Sat, 4 May 2019 04:56:46 +0000 (21:56 -0700)]
Suppress compiler warning in non-SSL, non-assert builds.

Jeff Janes, reviewed by Michael Paquier.

Discussion: https://postgr.es/m/CAMkU=1x8taZfsbPkv_MsWbTtzibW_yQHXoMhF_DTtm=z2hVHDg@mail.gmail.com

5 years agoCorrect more obsolete nbtree page split comments.
Peter Geoghegan [Fri, 3 May 2019 20:34:45 +0000 (13:34 -0700)]
Correct more obsolete nbtree page split comments.

Commit 3f342839 corrected obsolete comments about buffer locks at the
main _bt_insert_parent() call site, but missed similar obsolete comments
above _bt_insert_parent() itself.  Both sets of comments were rendered
obsolete by commit 40dae7ec537, which made the nbtree page split
algorithm more robust.  Fix the comments that were missed the first time
around now.

In passing, refine a related _bt_insert_parent() comment about
re-finding the parent page to insert new downlink.

5 years agoDoc: remove obsolete comment about per-branch documentation.
Tom Lane [Fri, 3 May 2019 16:32:06 +0000 (12:32 -0400)]
Doc: remove obsolete comment about per-branch documentation.

I should have removed this in a0b762626, but forgot.

5 years agoRemove RelationSetIndexList().
Tom Lane [Fri, 3 May 2019 14:26:14 +0000 (10:26 -0400)]
Remove RelationSetIndexList().

In the wake of commit f912d7dec, RelationSetIndexList isn't used any
more.  It was always a horrid wart, so getting rid of it is very nice.
We can also convert rd_indexvalid back to a plain boolean.

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

5 years agoFix reindexing of pg_class indexes some more.
Tom Lane [Thu, 2 May 2019 23:11:28 +0000 (19:11 -0400)]
Fix reindexing of pg_class indexes some more.

Commits 3dbb317d3 et al failed under CLOBBER_CACHE_ALWAYS testing.
Investigation showed that to reindex pg_class_oid_index, we must
suppress accesses to the index (via SetReindexProcessing) before we call
RelationSetNewRelfilenode, or at least before we do CommandCounterIncrement
therein; otherwise, relcache reloads happening within the CCI may try to
fetch pg_class rows using the index's new relfilenode value, which is as
yet an empty file.

Of course, the point of 3dbb317d3 was that that ordering didn't work
either, because then RelationSetNewRelfilenode's own update of the index's
pg_class row cannot access the index, should it need to.

There are various ways we might have got around that, but Andres Freund
came up with a brilliant solution: for a mapped index, we can really just
skip the pg_class update altogether.  The only fields it was actually
changing were relpages etc, but it was just setting them to zeroes which
is useless make-work.  (Correct new values will be installed at the end
of index build.)  All pg_class indexes are mapped and probably always will
be, so this eliminates the problem by removing work rather than adding it,
always a pleasant outcome.  Having taught RelationSetNewRelfilenode to do
it that way, we can revert the code reordering in reindex_index.  (But
I left the moved setup code where it was; there seems no reason why it
has to run without use of the old index.  If you're trying to fix a
busted pg_class index, you'll have had to disable system index use
altogether to get this far.)

Moreover, this means we don't need RelationSetIndexList at all, because
reindex_relation's hacking to make "REINDEX TABLE pg_class" work is
likewise now unnecessary.  We'll leave that code in place in the back
branches, but a follow-on patch will remove it in HEAD.

In passing, do some minor cleanup for commit 5c1560606 (in HEAD only),
notably removing a duplicate newrnode assignment.

Patch by me, using a core idea due to Andres Freund.  Back-patch to all
supported branches, as 3dbb317d3 was.

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

5 years agoheap_prepare_freeze_tuple: Simplify coding
Alvaro Herrera [Thu, 2 May 2019 20:13:48 +0000 (16:13 -0400)]
heap_prepare_freeze_tuple: Simplify coding

Commit d2599ecfcc74 introduced some contorted, confused code around:
readers would think that it's possible for HeapTupleHeaderGetXmin return
a non-frozen value for some frozen tuples, which would be disastrous.
There's no actual bug, but it seems better to make it clearer.

Per gripe from Tom Lane and Andres Freund.
Discussion: https://postgr.es/m/30116.1555430496@sss.pgh.pa.us

5 years agoFix nbtsort.c's page space accounting.
Peter Geoghegan [Thu, 2 May 2019 19:33:35 +0000 (12:33 -0700)]
Fix nbtsort.c's page space accounting.

Commit dd299df8189, which made heap TID a tiebreaker nbtree index
column, introduced new rules on page space management to make suffix
truncation safe.  In general, suffix truncation needs to have a small
amount of extra space available on the new left page when splitting a
leaf page.  This is needed in case it turns out that truncation cannot
even "truncate away the heap TID column", resulting in a
larger-than-firstright leaf high key with an explicit heap TID
representation.

Despite all this, CREATE INDEX/nbtsort.c did not account for the
possible need for extra heap TID space on leaf pages when deciding
whether or not a new item could fit on current page.  This could lead to
"failed to add item to the index page" errors when CREATE
INDEX/nbtsort.c tried to finish off a leaf page that lacked space for a
larger-than-firstright leaf high key (it only had space for firstright
tuple, which was just short of what was needed following "truncation").

Several conditions needed to be met all at once for CREATE INDEX to
fail.  The problem was in the hard limit on what will fit on a page,
which tends to be masked by the soft fillfactor-wise limit.  The easiest
way to recreate the problem seems to be a CREATE INDEX on a low
cardinality text column, with tuples that are of non-uniform width,
using a fillfactor of 100.

To fix, bring nbtsort.c in line with nbtsplitloc.c, which already
pessimistically assumes that all leaf page splits will have high keys
that have a heap TID appended.

Reported-By: Andreas Joseph Krogh
Discussion: https://postgr.es/m/VisenaEmail.c5.3ee7fe277d514162.16a6d785bea@tc7-visena

5 years agoFix some problems with VACUUM (INDEX_CLEANUP FALSE).
Robert Haas [Thu, 2 May 2019 14:07:13 +0000 (10:07 -0400)]
Fix some problems with VACUUM (INDEX_CLEANUP FALSE).

The new nleft_dead_tuples and nleft_dead_itemids fields are confusing
and do not seem like the correct way forward.  One of them is tested
via an assertion that can fail, as it has already done on buildfarm
member topminnow.  Remove the assertion and the fields.

Change the logic for the case where a tuple is not initially pruned
by heap_page_prune but later diagnosed HEAPTUPLE_DEAD by
HeapTupleSatisfiesVacuum.  Previously, tupgone = true was set in
that case, which leads to treating the tuple as one that will be
removed.  In a normal vacuum, that's OK, because we'll remove
index entries for it and then the second heap pass will remove the
tuple itself, but when index cleanup is disabled, those things
don't happen, so we must instead treat it as a recently-dead
tuple that we have voluntarily chosen to keep.

Report and analysis by Tom Lane.  This patch loosely based on one
from Masahiko Sawada, but I changed most of it.

5 years agodoc: clarify behavior of pg_upgrade's clone mode
Bruce Momjian [Wed, 1 May 2019 13:09:28 +0000 (09:09 -0400)]
doc:  clarify behavior of pg_upgrade's clone mode

Be more precise about the benefits of using clone mode.

5 years agoFix union for pgstat message types
Magnus Hagander [Wed, 1 May 2019 10:30:44 +0000 (12:30 +0200)]
Fix union for pgstat message types

The message type for temp files and for checksum failures were missing
from the union. Due to the coding style used there was no compiler error
when this happend. So change the code to actively use the union thereby
producing a compiler error if the same mistake happens again, suggested
by Tom Lane.

Author: Julien Rouhaud
Reported-By: Tomas Vondra
Discussion: https://postgr.es/m/20190430163328.zd4rrlnbvgaqlcdz@development

5 years agoRun catalog reindexing test from 3dbb317d32 serially, to avoid deadlocks.
Andres Freund [Wed, 1 May 2019 00:45:32 +0000 (17:45 -0700)]
Run catalog reindexing test from 3dbb317d32 serially, to avoid deadlocks.

The tests turn out to cause deadlocks in some circumstances. Fairly
reproducibly so with -DRELCACHE_FORCE_RELEASE
-DCATCACHE_FORCE_RELEASE.  Some of the deadlocks may be hard to fix
without disproportionate measures, but others probably should be fixed
- but not in 12.

We discussed removing the new tests until we can fix the issues
underlying the deadlocks, but results from buildfarm animal
markhor (which runs with CLOBBER_CACHE_ALWAYS) indicates that there
might be a more severe, as of yet undiagnosed, issue (including on
stable branches) with reindexing catalogs. The failure is:
ERROR: could not read block 0 in file "base/16384/28025": read only 0 of 8192 bytes
Therefore it seems advisable to keep the tests.

It's not certain that running the tests in isolation removes the risk
of deadlocks. It's possible that additional locks are needed to
protect against a concurrent auto-analyze or such.

Per discussion with Tom Lane.

Discussion: https://postgr.es/m/28926.1556664156@sss.pgh.pa.us
Backpatch: 9.4-, like 3dbb317d3

5 years agoFix unused variable compiler warning in !debug builds.
Andres Freund [Wed, 1 May 2019 00:45:32 +0000 (17:45 -0700)]
Fix unused variable compiler warning in !debug builds.

Introduced in 3dbb317d3.  Fix by using the new local variable in more
places.

Reported-By: Bruce Momjian (off-list)
Backpatch: 9.4-, like 3dbb317d3

5 years agodocs: Fix small copy & paste mistake.
Andres Freund [Tue, 30 Apr 2019 23:18:35 +0000 (16:18 -0700)]
docs: Fix small copy & paste mistake.

Author: Justin Pryzby
Discussion: https://postgr.es/m/20190418005115.r4mat75wvlski3ij@alap3.anarazel.de

5 years agoImprove comment spelling and style in llvmjit_deform.c.
Andres Freund [Tue, 30 Apr 2019 23:13:54 +0000 (16:13 -0700)]
Improve comment spelling and style in llvmjit_deform.c.

Author: Justin Pryzby
Discussion:
    https://postgr.es/m/20190408141828.GE10080@telsasoft.com
    https://postgr.es/m/20181127184133.GM10913@telsasoft.com

5 years agoImprove code inferring length of bitmap for JITed tuple deforming.
Andres Freund [Tue, 30 Apr 2019 22:55:07 +0000 (15:55 -0700)]
Improve code inferring length of bitmap for JITed tuple deforming.

While discussing comment improvements (see next commit) by Justin
Pryzby, Tom complained about a few details of the logic to infer the
length of the NULL bitmap when building the JITed tuple deforming
function. That bitmap allows to avoid checking the tuple header's
natts, a check which often causes a pipeline stall

Improvements:
a) As long as missing columns aren't taken into account, we can
   continue to infer the length of the NULL bitmap from NOT NULL
   columns following it. Previously we stopped at the first missing
   column.  It's unlikely to matter much in practice, but the
   alternative would have been to document why we stop.
b) For robustness reasons it seems better to also check against
   attisdropped - RemoveAttributeById() sets attnotnull to false, but
   an additional check is trivial.
c) Improve related comments

Discussion: https://postgr.es/m/20637.1555957068@sss.pgh.pa.us
Backpatch: -

5 years agoClean up handling of constraint_exclusion and enable_partition_pruning.
Tom Lane [Tue, 30 Apr 2019 19:03:35 +0000 (15:03 -0400)]
Clean up handling of constraint_exclusion and enable_partition_pruning.

The interaction of these parameters was a bit confused/confusing,
and in fact v11 entirely misses the opportunity to apply partition
constraints when a partition is accessed directly (rather than
indirectly from its parent).

In HEAD, establish the principle that enable_partition_pruning controls
partition pruning and nothing else.  When accessing a partition via its
parent, we do partition pruning (if enabled by enable_partition_pruning)
and then there is no need to consider partition constraints in the
constraint_exclusion logic.  When accessing a partition directly, its
partition constraints are applied by the constraint_exclusion logic,
only if constraint_exclusion = on.

In v11, we can't have such a clean division of these GUCs' effects,
partly because we don't want to break compatibility too much in a
released branch, and partly because the clean coding requires
inheritance_planner to have applied partition pruning to a partitioned
target table, which it doesn't in v11.  However, we can tweak things
enough to cover the missed case, which seems like a good idea since
it's potentially a performance regression from v10.  This patch keeps
v11's previous behavior in which enable_partition_pruning overrides
constraint_exclusion for an inherited target table, though.

In HEAD, also teach relation_excluded_by_constraints that it's okay to use
inheritable constraints when trying to prune a traditional inheritance
tree.  This might not be thought worthy of effort given that that feature
is semi-deprecated now, but we have enough infrastructure that it only
takes a couple more lines of code to do it correctly.

Amit Langote and Tom Lane

Discussion: https://postgr.es/m/9813f079-f16b-61c8-9ab7-4363cab28d80@lab.ntt.co.jp
Discussion: https://postgr.es/m/29069.1555970894@sss.pgh.pa.us

5 years agodoc: improve PG 12 to_timestamp()/to_date() wording
Bruce Momjian [Tue, 30 Apr 2019 18:06:57 +0000 (14:06 -0400)]
doc:  improve PG 12 to_timestamp()/to_date() wording

5 years agodoc: move "only" to a more appropriate place in the sentence
Bruce Momjian [Tue, 30 Apr 2019 17:44:31 +0000 (13:44 -0400)]
doc:  move "only" to a more appropriate place in the sentence

5 years agoMessage style fixes
Alvaro Herrera [Tue, 30 Apr 2019 14:00:38 +0000 (10:00 -0400)]
Message style fixes

5 years agoWiden tuple counter variables from long to int64
Alvaro Herrera [Mon, 29 Apr 2019 18:15:19 +0000 (14:15 -0400)]
Widen tuple counter variables from long to int64

Mistake in ab0dfc961b6a; progress reporting would have wrapped around
for indexes created with more than 2^31 tuples.

Reported-by: Peter Geoghegan
Discussion: https://postgr.es/m/CAH2-Wz=WbNxc5ob5NJ9yqo2RMJ0q4HXDS30GVCobeCvC9A1L9A@mail.gmail.com

5 years agoFix potential assertion failure when reindexing a pg_class index.
Andres Freund [Tue, 30 Apr 2019 02:42:04 +0000 (19:42 -0700)]
Fix potential assertion failure when reindexing a pg_class index.

When reindexing individual indexes on pg_class it was possible to
either trigger an assertion failure:
TRAP: FailedAssertion("!(!ReindexIsProcessingIndex(((index)->rd_id)))

That's because reindex_index() called SetReindexProcessing() - which
enables an asserts ensuring no index insertions happen into the index
- before calling RelationSetNewRelfilenode(). That not correct for
indexes on pg_class, because RelationSetNewRelfilenode() updates the
relevant pg_class row, which needs to update the indexes.

The are two reasons this wasn't noticed earlier. Firstly the bug
doesn't trigger when reindexing all of pg_class, as reindex_relation
has code "hiding" all yet-to-be-reindexed indexes. Secondly, the bug
only triggers when the the update to pg_class doesn't turn out to be a
HOT update - otherwise there's no index insertion to trigger the
bug. Most of the time there's enough space, making this bug hard to
trigger.

To fix, move RelationSetNewRelfilenode() to before the
SetReindexProcessing() (and, together with some other code, to outside
of the PG_TRY()).

To make sure the error checking intended by SetReindexProcessing() is
more robust, modify CatalogIndexInsert() to check
ReindexIsProcessingIndex() even when the update is a HOT update.

Also add a few regression tests for REINDEXing of system catalogs.

The last two improvements would have prevented some of the issues
fixed in 5c1560606dc4c from being introduced in the first place.

Reported-By: Michael Paquier
Diagnosed-By: Tom Lane and Andres Freund
Author: Andres Freund
Reviewed-By: Tom Lane
Discussion: https://postgr.es/m/20190418011430.GA19133@paquier.xyz
Backpatch: 9.4-, the bug is present in all branches

5 years agoFix several recently introduced issues around handling new relation forks.
Andres Freund [Tue, 30 Apr 2019 02:28:05 +0000 (19:28 -0700)]
Fix several recently introduced issues around handling new relation forks.

Most of these stem from d25f519107 "tableam: relation creation, VACUUM
FULL/CLUSTER, SET TABLESPACE.".

1) To pass data to the relation_set_new_filenode()
   RelationSetNewRelfilenode() was made to update RelationData.rd_rel
   directly. That's not OK however, as it makes the relcache entries
   temporarily inconsistent. Which among other scenarios is a problem
   if a REINDEX targets an index on pg_class - the
   CatalogTupleUpdate() in RelationSetNewRelfilenode().  Presumably
   that was introduced because other places in the code do so - while
   those aren't "good practice" they don't appear to be actively
   buggy (e.g. because system tables may not be targeted).

   I (Andres) should have caught this while reviewing and signficantly
   evolving the code in that commit, mea culpa.

   Fix that by instead passing in the new RelFileNode as separate
   argument to relation_set_new_filenode() and rely on the relcache to
   update the catalog entry. Also revert that the
   RelationMapUpdateMap() call was changed to immediate, and undo some
   other more unnecessary changes.

2) Document that the relation_set_new_filenode cannot rely on the
   whole relcache entry to be valid. It might be worthwhile to
   refactor the code to never have to rely on that, but given the way
   heap_create() is currently coded, that'd be a large change.

3) ATExecSetTableSpace() shouldn't do FlushRelationBuffers() itself. A
   table AM might not use shared buffers at all. Move to
   index_copy_data() and heapam_relation_copy_data().

4) heapam_relation_set_new_filenode() previously sometimes accessed
   rel->rd_rel->relpersistence rather than the `persistence`
   argument. Code movement mistake.

5) Previously heapam_relation_set_new_filenode() re-opened the smgr
   relation to create the init for, if necesary. Instead have
   RelationCreateStorage() return the SMgrRelation and use it to
   create the init fork.

6) Add a note about the danger of modifying the relcache directly to
   ATExecSetTableSpace() - it's currently not a bug because there's a
   check ERRORing for catalog tables.

Regression tests and assertion improvements that together trigger the
bug described in 1) will be added in a later commit, as there is a
related bug on all branches.

Reported-By: Michael Paquier
Diagnosed-By: Tom Lane and Andres Freund
Author: Andres Freund
Reviewed-By: Tom Lane
Discussion: https://postgr.es/m/20190418011430.GA19133@paquier.xyz

5 years agoRemove obsolete _bt_insert_parent() comment.
Peter Geoghegan [Mon, 29 Apr 2019 21:14:38 +0000 (14:14 -0700)]
Remove obsolete _bt_insert_parent() comment.

Remove a comment that refers to a coding practice that was fully removed
by commit a8b8f4db, which introduced MarkBufferDirty().  It looks like
the comment was even obsolete before then, since it concerns
write-ordering dependencies with synchronous buffer writes.

5 years agoIn walreceiver, don't try to do ereport() in a signal handler.
Tom Lane [Mon, 29 Apr 2019 16:26:07 +0000 (12:26 -0400)]
In walreceiver, don't try to do ereport() in a signal handler.

This is quite unsafe, even for the case of ereport(FATAL) where we won't
return control to the interrupted code, and despite this code's use of
a flag to restrict the areas where we'd try to do it.  It's possible
for example that we interrupt malloc or free while that's holding a lock
that's meant to protect against cross-thread interference.  Then, any
attempt to do malloc or free within ereport() will result in a deadlock,
preventing the walreceiver process from exiting in response to SIGTERM.
We hypothesize that this explains some hard-to-reproduce failures seen
in the buildfarm.

Hence, get rid of the immediate-exit code in WalRcvShutdownHandler,
as well as the logic associated with WalRcvImmediateInterruptOK.
Instead, we need to take care that potentially-blocking operations
in the walreceiver's data transmission logic (libpqwalreceiver.c)
will respond reasonably promptly to the process's latch becoming
set and then call ProcessWalRcvInterrupts.  Much of the needed code
for that was already present in libpqwalreceiver.c.  I refactored
things a bit so that all the uses of PQgetResult use latch-aware
waiting, but didn't need to do much more.

These changes should be enough to ensure that libpqwalreceiver.c
will respond promptly to SIGTERM whenever it's waiting to receive
data.  In principle, it could block for a long time while waiting
to send data too, and this patch does nothing to guard against that.
I think that that hazard is mostly theoretical though: such blocking
should occur only if we fill the kernel's data transmission buffers,
and we don't generally send enough data to make that happen without
waiting for input.  If we find out that the hazard isn't just
theoretical, we could fix it by using PQsetnonblocking, but that
would require more ticklish changes than I care to make now.

This is a bug fix, but it seems like too big a change to push into
the back branches without much more testing than there's time for
right now.  Perhaps we'll back-patch once we have more confidence
in the change.

Patch by me; thanks to Thomas Munro for review.

Discussion: https://postgr.es/m/20190416070119.GK2673@paquier.xyz

5 years agoFix some typos
Michael Paquier [Mon, 29 Apr 2019 14:52:42 +0000 (23:52 +0900)]
Fix some typos

Author: Daniel Gustafsson
Discussion: https://postgr.es/m/42kEeWei6VxLGh12QbR08hiI5Pm-c3XgbK7qj393PSttEhVbnnQoFXHKzXjPRZLUpndWAfHIuZuUqGZBzyXadmEUCSqm9xphWur_I8vESMA=@yesql.se

5 years agoMessage fixes
Alvaro Herrera [Mon, 29 Apr 2019 14:05:07 +0000 (10:05 -0400)]
Message fixes

5 years agoFix potential catalog corruption with temporary identity columns
Peter Eisentraut [Mon, 29 Apr 2019 06:44:51 +0000 (08:44 +0200)]
Fix potential catalog corruption with temporary identity columns

If a temporary table with an identity column and ON COMMIT DROP is
created in a single-statement transaction (not useful, but allowed),
it would leave the catalog corrupted.  We need to add a
CommandCounterIncrement() so that PreCommit_on_commit_actions() sees
the created dependency between table and sequence and can clean it
up.

The analogous and more useful case of doing this in a transaction
block already runs some CommandCounterIncrement() before it gets to
the on-commit cleanup, so it wasn't a problem in practical use.

Several locations for placing the new CommandCounterIncrement() call
were discussed.  This patch places it at the end of
standard_ProcessUtility().  That would also help if other commands
were to create catalog entries that some on-commit action would like
to see.

Bug: #15631
Reported-by: Serge Latyntsev <dnsl48@gmail.com>
Author: Peter Eisentraut <peter.eisentraut@2ndquadrant.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
5 years agoDo pre-release housekeeping on catalog data, and fix jsonpath send/recv.
Tom Lane [Sun, 28 Apr 2019 21:16:50 +0000 (17:16 -0400)]
Do pre-release housekeeping on catalog data, and fix jsonpath send/recv.

Run renumber_oids.pl to move high-numbered OIDs down, as per pre-beta
tasks specified by RELEASE_CHANGES.  (The only change is 8394 -> 3428.)

Also run reformat_dat_file.pl while I'm here.

While looking at the reformat diffs, I chanced to notice that type
jsonpath had typsend and typreceive = '-', which surely is not the
intention given that jsonpath_send and jsonpath_recv exist.
Fix that.  It's safe to assume that these functions have never been
tested :-(.  I didn't try, but somebody should.

5 years agoUse preprocessor conditions compatible with Emacs indent.
Noah Misch [Sun, 28 Apr 2019 19:56:53 +0000 (12:56 -0700)]
Use preprocessor conditions compatible with Emacs indent.

Emacs wrongly indented hundreds of subsequent lines.

5 years agoClean up minor warnings from buildfarm.
Tom Lane [Sun, 28 Apr 2019 16:45:55 +0000 (12:45 -0400)]
Clean up minor warnings from buildfarm.

Be more consistent about use of XXXGetDatum macros in new jsonpath
code.  This is mostly to avoid having code that looks randomly
different from everyplace else that's doing the exact same thing.

In pg_regress.c, avoid an unreferenced-function warning from
compilers that don't understand pg_attribute_unused().  Putting
the function inside the same #ifdef as its only caller is more
straightforward coding anyway.

In be-secure-openssl.c, avoid use of pg_attribute_unused() on a label.
That's pretty creative, but there's no good reason to suppose that
it's portable, and there's absolutely no need to use goto's here in the
first place.  (This wasn't actually causing any buildfarm complaints,
but it's new code in v12 so it has no portability track record.)