]> granicus.if.org Git - postgresql/log
postgresql
6 years agoUpdate comment
Peter Eisentraut [Fri, 19 Jan 2018 00:36:34 +0000 (19:36 -0500)]
Update comment

The "callback" that this comment was referring to was removed by commit
c0a15e07cd718cb6e455e68328f522ac076a0e4b, so update to match the current
code.

6 years agoFix typo and improve punctuation
Peter Eisentraut [Thu, 18 Jan 2018 18:00:49 +0000 (13:00 -0500)]
Fix typo and improve punctuation

6 years agoAdd tests for session_replication_role
Peter Eisentraut [Thu, 18 Jan 2018 16:24:07 +0000 (11:24 -0500)]
Add tests for session_replication_role

This was hardly tested at all.  The trigger case was lightly tested by
the logical replication tests, but rules and event triggers were not
tested at all.

6 years agoExtend configure's __int128 test to check for a known gcc bug.
Tom Lane [Thu, 18 Jan 2018 16:09:44 +0000 (11:09 -0500)]
Extend configure's __int128 test to check for a known gcc bug.

On Sparc64, use of __attribute__(aligned(8)) with __int128 causes faulty
code generation in gcc versions at least through 5.5.0.  We can work around
that by disabling use of __int128, so teach configure to test for the bug.

This solution doesn't fix things for the case of cross-compiling with a
buggy compiler; to support that nicely, we'd need to add a manual disable
switch.  Unless more such cases turn up, it doesn't seem worth the work.
Affected users could always edit pg_config.h manually.

In passing, fix some typos in the existing configure test for __int128.
They're harmless because we only compile that code not run it, but
they're still confusing for anyone looking at it closely.

This is needed in support of commit 751804998, so back-patch to 9.5
as that was.

Marina Polyakova, Victor Wagner, Tom Lane

Discussion: https://postgr.es/m/0d3a9fa264cebe1cb9966f37b7c06e86@postgrespro.ru

6 years agodoc: Expand documentation of session_replication_role
Peter Eisentraut [Thu, 18 Jan 2018 14:34:51 +0000 (09:34 -0500)]
doc: Expand documentation of session_replication_role

6 years agoReorder C includes
Bruce Momjian [Wed, 17 Jan 2018 23:09:57 +0000 (18:09 -0500)]
Reorder C includes

Reorder header files in joinrels.c and pathnode.c in alphabetical order,
removing unnecessary ones.

Author: Etsuro Fujita

6 years agopostgres_fdw: Avoid 'outer pathkeys do not match mergeclauses' error.
Robert Haas [Wed, 17 Jan 2018 21:18:39 +0000 (16:18 -0500)]
postgres_fdw: Avoid 'outer pathkeys do not match mergeclauses' error.

When pushing down a join to a foreign server, postgres_fdw constructs
an alternative plan to be used for any EvalPlanQual rechecks that
prove to be necessary.  This plan is stored as the outer subplan of
the Foreign Scan implementing the pushed-down join.  Previously, this
alternative plan could have a different nominal sort ordering than its
parent, which seemed OK since there will only be one tuple per base
table anyway in the case of an EvalPlanQual recheck.  Actually,
though, it caused a problem if that path was used as a building block
for the EvalPlanQual recheck plan of a higher-level foreign join,
because we could end up with a merge join one of whose inputs was not
labelled with the correct sort order.  Repair by injecting an extra
Sort node into the EvalPlanQual recheck plan whenever it would
otherwise fail to be sorted at least as well as its parent Foreign
Scan.

Report by Jeff Janes.  Patch by me, reviewed by Tom Lane, who also
provided the test case and comment text.

Discussion: http://postgr.es/m/CAMkU=1y2G8VOVBHv3iXU2TMAj7-RyBFFW1uhkr5sm9LQ2=X35g@mail.gmail.com

6 years agoRemove useless lookup of root partitioned rel in ExecInitModifyTable().
Tom Lane [Wed, 17 Jan 2018 19:44:15 +0000 (14:44 -0500)]
Remove useless lookup of root partitioned rel in ExecInitModifyTable().

node->partitioned_rels is only set in UPDATE/DELETE cases, but
ExecInitModifyTable only uses its "rel" variable in INSERT cases,
so the extra logic to find the root rel is just a waste of complexity
and cycles.

Etsuro Fujita, reviewed by Amit Langote

Discussion: https://postgr.es/m/93cf9816-2f7d-0f67-8ed2-4a4e497a6ab8@lab.ntt.co.jp

6 years agoAbility to advance replication slots
Simon Riggs [Wed, 17 Jan 2018 11:38:34 +0000 (11:38 +0000)]
Ability to advance replication slots

Ability to advance both physical and logical replication slots using a
new user function pg_replication_slot_advance().

For logical advance that means records are consumed as fast as possible
and changes are not given to output plugin for sending. Makes 2nd phase
(after we reached SNAPBUILD_FULL_SNAPSHOT) of replication slot creation
faster, especially when there are big transactions as the reorder buffer
does not have to deal with data changes and does not have to spill to
disk.

Author: Petr Jelinek
Reviewed-by: Simon Riggs
6 years agoFix compiler warnings due to commit cc4feded
Andrew Dunstan [Wed, 17 Jan 2018 08:33:02 +0000 (03:33 -0500)]
Fix compiler warnings due to commit cc4feded

6 years agoCentralize json and jsonb handling of datetime types
Andrew Dunstan [Wed, 17 Jan 2018 00:07:13 +0000 (19:07 -0500)]
Centralize json and jsonb handling of datetime types

The creates a single function JsonEncodeDateTime which will format these
data types in an efficient and consistent manner. This will be all the
more important when we come to jsonpath so we don't have to implement yet
more code doing the same thing in two more places.

This also extends the code to handle time and timetz types which were
not previously handled specially. This requires exposing the time2tm and
timetz2tm functions.

Patch from Nikita Glukhov

6 years agoRemove useless use of bit-masking macros
Peter Eisentraut [Tue, 16 Jan 2018 22:12:16 +0000 (17:12 -0500)]
Remove useless use of bit-masking macros

In this case, the macros SET_8_BYTES(), GET_8_BYTES(), SET_4_BYTES(),
GET_4_BYTES() are no-ops, so we can just remove them.

The plan is to perhaps remove them from the source code altogether, so
we'll start here.

Discussion: https://www.postgresql.org/message-id/5d51721a-69ef-2053-9172-599b539f0628@2ndquadrant.com

6 years agoCope with indicator arrays that do not have the correct length.
Michael Meskes [Sat, 13 Jan 2018 13:56:49 +0000 (14:56 +0100)]
Cope with indicator arrays that do not have the correct length.

Patch by: "Rader, David" <davidr@openscg.com>

6 years agodocs: replace dblink() mention with foreign data mention
Bruce Momjian [Fri, 12 Jan 2018 21:53:25 +0000 (16:53 -0500)]
docs:  replace dblink() mention with foreign data mention

Reported-by: steven.winfield@cantabcapital.com
Discussion: https://postgr.es/m/20171031105039.17183.850@wrigleys.postgresql.org

6 years agoFix postgres_fdw to cope with duplicate GROUP BY entries.
Tom Lane [Fri, 12 Jan 2018 21:52:49 +0000 (16:52 -0500)]
Fix postgres_fdw to cope with duplicate GROUP BY entries.

Commit 7012b132d, which added the ability to push down aggregates and
grouping to the remote server, wasn't careful to ensure that the remote
server would have the same idea we do about which columns are the grouping
columns, in cases where there are textually identical GROUP BY expressions.
Such cases typically led to "targetlist item has multiple sortgroupref
labels" errors.

To fix this reliably, switch over to using "GROUP BY column-number" syntax
rather than "GROUP BY expression" in transmitted queries, and adjust
foreign_grouping_ok() to be more careful about duplicating the sortgroupref
labeling of the local pathtarget.

Per bug #14890 from Sean Johnston.  Back-patch to v10 where the buggy code
was introduced.

Jeevan Chalke, reviewed by Ashutosh Bapat

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

6 years agoAvoid unnecessary failure in SELECT concurrent with ALTER NO INHERIT.
Tom Lane [Fri, 12 Jan 2018 20:46:37 +0000 (15:46 -0500)]
Avoid unnecessary failure in SELECT concurrent with ALTER NO INHERIT.

If a query against an inheritance tree runs concurrently with an ALTER
TABLE that's disinheriting one of the tree members, it's possible to get
a "could not find inherited attribute" error because after obtaining lock
on the removed member, make_inh_translation_list sees that its columns
have attinhcount=0 and decides they aren't the columns it's looking for.

An ideal fix, perhaps, would avoid including such a just-removed member
table in the query at all; but there seems no way to accomplish that
without adding expensive catalog rechecks or creating a likelihood of
deadlocks.  Instead, let's just drop the check on attinhcount.  In this
way, a query that's included a just-disinherited child will still
succeed, which is not a completely unreasonable behavior.

This problem has existed for a long time, so back-patch to all supported
branches.  Also add an isolation test verifying related behaviors.

Patch by me; the new isolation test is based on Kyotaro Horiguchi's work.

Discussion: https://postgr.es/m/20170626.174612.23936762.horiguchi.kyotaro@lab.ntt.co.jp

6 years agoFix incorrect handling of subquery pullup in the presence of grouping sets.
Tom Lane [Fri, 12 Jan 2018 17:24:50 +0000 (12:24 -0500)]
Fix incorrect handling of subquery pullup in the presence of grouping sets.

If we flatten a subquery whose target list contains constants or
expressions, when those output columns are used in GROUPING SET columns,
the planner was capable of doing the wrong thing by merging a pulled-up
expression into the surrounding expression during const-simplification.
Then the late processing that attempts to match subexpressions to grouping
sets would fail to match those subexpressions to grouping sets, with the
effect that they'd not go to null when expected.

To fix, wrap such subquery outputs in PlaceHolderVars, ensuring that
they preserve their separate identity throughout the planner's expression
processing.  This is a bit of a band-aid, because the wrapper defeats
const-simplification even in places where it would be safe to allow.
But a nicer fix would likely be too invasive to back-patch, and the
consequences of the missed optimizations probably aren't large in most
cases.

Back-patch to 9.5 where grouping sets were introduced.

Heikki Linnakangas, with small mods and better test cases by me;
additional review by Andrew Gierth

Discussion: https://postgr.es/m/7dbdcf5c-b5a6-ef89-4958-da212fe10176@iki.fi

6 years agoFix parsing of compatibility mode argument.
Michael Meskes [Fri, 12 Jan 2018 14:59:43 +0000 (15:59 +0100)]
Fix parsing of compatibility mode argument.

Patch by Ashutosh Sharma <ashu.coek88@gmail.com>

6 years agoRemove hard-coded schema knowledge about pg_attribute from genbki.pl
Alvaro Herrera [Fri, 12 Jan 2018 14:21:42 +0000 (11:21 -0300)]
Remove hard-coded schema knowledge about pg_attribute from genbki.pl

Add the ability to label a column's default value in the catalog header,
and implement this for pg_attribute.  A new function in Catalog.pm is
used to fill in a tuple with defaults.  The build process will complain
loudly if a catalog entry is incomplete,

Commit 8137f2c3232 labeled variable length columns for the C preprocessor.
Expose that label to genbki.pl so we can exclude those columns from schema
macros in a general fashion. Also, format schema macro entries according
to their types.

This means slightly less code maintenance, but more importantly it's a
proving ground for mechanisms intended to be used in later commits.

While at it, I (Álvaro) couldn't resist making some changes in
genbki.pl: rename some functions to actually indicate their purpose
instead of actively misleading onlookers; and don't iterate on the whole
of pg_type to find the entry for each catalog row, using a hash instead
of an array.

Author: John Naylor, some changes by Álvaro Herrera
Discussion: https://postgr.es/m/CAJVSVGVJHwD8sfDfZW9TbCHWKf=C1YDRM-rF=2JenRU_y+VcFg@mail.gmail.com

6 years agoC comment: fix "the the" mentions in C comments
Bruce Momjian [Fri, 12 Jan 2018 02:50:21 +0000 (21:50 -0500)]
C comment:  fix "the the" mentions in C comments

Reported-by: Christoph Dreis
Discussion: https://postgr.es/m/007e01d3519e$2734ca10$759e5e30$@freenet.de

Author: Christoph Dreis

6 years agoRefactor subscription tests to use PostgresNode's wait_for_catchup
Peter Eisentraut [Mon, 8 Jan 2018 22:32:09 +0000 (17:32 -0500)]
Refactor subscription tests to use PostgresNode's wait_for_catchup

This was nearly the same code.  Extend wait_for_catchup to allow waiting
for pg_current_wal_lsn() and use that in the subscription tests.  Also
change one use in the pg_rewind tests to use this.

Also remove some broken code in wait_for_catchup and
wait_for_slot_catchup.  The error message in case the waiting failed
wanted to show the current LSN, but the way it was written never
worked.  So since nobody ever cared, just remove it.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agoAdd QueryEnvironment to ExplainOneQuery_hook's parameter list.
Tom Lane [Thu, 11 Jan 2018 17:16:18 +0000 (12:16 -0500)]
Add QueryEnvironment to ExplainOneQuery_hook's parameter list.

This should have been done in commit 18ce3a4ab, which added that parameter
to ExplainOneQuery, but it was overlooked.  This makes it impossible for
a user of the hook to pass the queryEnv down to ExplainOnePlan.

It's too late to change this API in v10, I suppose, but fortunately
passing NULL to ExplainOnePlan will work in nearly all interesting
cases in v10.  That might not be true forever, so we'd better fix it.

Tatsuro Yamada, reviewed by Thomas Munro

Discussion: https://postgr.es/m/890e8dd9-c1c7-a422-6892-874f5eaee048@lab.ntt.co.jp

6 years agoCosmetic fix in postgres_fdw.c.
Tom Lane [Thu, 11 Jan 2018 16:53:59 +0000 (11:53 -0500)]
Cosmetic fix in postgres_fdw.c.

Make the forward declaration of estimate_path_cost_size match its
actual definition.

Tatsuro Yamada

Discussion: https://postgr.es/m/96f2f554-1eeb-fe6f-e0db-650771886781@lab.ntt.co.jp

6 years agodoc: add JSON acronym
Bruce Momjian [Thu, 11 Jan 2018 16:21:24 +0000 (11:21 -0500)]
doc:  add JSON acronym

Reported-by: torsten.grust@gmail.com
Discussion: https://postgr.es/m/20171024201849.1488.71071@wrigleys.postgresql.org

6 years agoFix Latin spelling
Peter Eisentraut [Thu, 11 Jan 2018 13:31:11 +0000 (08:31 -0500)]
Fix Latin spelling

"c.f." should be "cf.".

6 years agollow negative coordinate for ~> (cube, int) operator
Teodor Sigaev [Thu, 11 Jan 2018 11:49:36 +0000 (14:49 +0300)]
llow negative coordinate for ~> (cube, int) operator

~> (cube, int) operator was especially designed for knn-gist search.
However, knn-gist supports only ascending ordering of results. Nevertheless
it would be useful to support descending ordering by ~> (cube, int) operator.
We provide workaround for that: negative coordinate give us inversed value
of corresponding cube bound. Therefore, knn search using negative coordinate
gives us an effect of descending ordering by cube bound.

Author: Alexander Korotkov
Reviewed by: Tomas Vondra, Andrey Borodin
Discussion: https://www.postgresql.org/message-id/flat/a9657f6a-b497-36ff-e56-482a2c7e3292@2ndquadrant.com

6 years agoFix behavior of ~> (cube, int) operator
Teodor Sigaev [Thu, 11 Jan 2018 11:41:14 +0000 (14:41 +0300)]
Fix behavior of ~> (cube, int) operator

~> (cube, int) operator was especially designed for knn-gist search.
However, it appears that knn-gist search can't work correctly with current
behavior of this operator when dataset contains cubes of variable
dimensionality. In this case, the same value of second operator argument
can point to different dimension depending on dimensionality of particular cube.
Such behavior is incompatible with gist indexing of cubes, and knn-gist doesn't
work correctly for it.

This patch changes behavior of ~> (cube, int) operator by introducing dimension
numbering where value of second argument unambiguously identifies number of
dimension. With new behavior, this operator can be correctly supported by
knn-gist. Relevant changes to cube operator class are also included.

Backpatch to v9.6 where operator was introduced.

Since behavior of ~> (cube, int) operator is changed, depending entities
must be refreshed after upgrade. Such as, expression indexes using this
operator must be reindexed, materialized views must be rebuilt, stored
procedures and client code must be revised to correctly use new behavior.
That should be mentioned in release notes.

Noticed by: Tomas Vondra
Author: Alexander Korotkov
Reviewed by: Tomas Vondra, Andrey Borodin
Discussion: https://www.postgresql.org/message-id/flat/a9657f6a-b497-36ff-e56-482a2c7e3292@2ndquadrant.com

6 years agoFix sample INSTR() functions in the plpgsql documentation.
Tom Lane [Wed, 10 Jan 2018 22:13:29 +0000 (17:13 -0500)]
Fix sample INSTR() functions in the plpgsql documentation.

These functions are stated to be Oracle-compatible, but they weren't.
Yugo Nagata noticed that while our code returns zero for a zero or
negative fourth parameter (occur_index), Oracle throws an error.
Further testing by me showed that there was also a discrepancy in the
interpretation of a negative third parameter (beg_index): Oracle thinks
that a negative beg_index indicates the last place where the target
substring can *begin*, whereas our code thinks it is the last place
where the target can *end*.

Adjust the sample code to behave like Oracle in both these respects.
Also change it to be a CDATA[] section, simplifying copying-and-pasting
out of the documentation source file.  And fix minor problems in the
introductory comment, which wasn't very complete or accurate.

Back-patch to all supported branches.  Although this patch only touches
documentation, we should probably call it out as a bug fix in the next
minor release notes, since users who have adopted the functions will
likely want to update their versions.

Yugo Nagata and Tom Lane

Discussion: https://postgr.es/m/20171229191705.c0b43a8c.nagata@sraoss.co.jp

6 years agoUse portal pinning in PL/Perl and PL/Python
Peter Eisentraut [Tue, 12 Dec 2017 15:26:47 +0000 (10:26 -0500)]
Use portal pinning in PL/Perl and PL/Python

PL/pgSQL "pins" internally generated portals so that user code cannot
close them by guessing their names.  Add this functionality to PL/Perl
and PL/Python as well, preventing users from manually closing cursors
created by spi_query and plpy.cursor, respectively.  (PL/Tcl does not
currently offer any cursor functionality.)

6 years agoAdd tests for PL/pgSQL returning unnamed portals as refcursor
Peter Eisentraut [Wed, 10 Jan 2018 21:39:13 +0000 (16:39 -0500)]
Add tests for PL/pgSQL returning unnamed portals as refcursor

Existing tests only covered returning explicitly named portals as
refcursor.  The unnamed cursor case was recently broken without a test
failing.

6 years agoRevert "Move portal pinning from PL/pgSQL to SPI"
Peter Eisentraut [Wed, 10 Jan 2018 21:01:17 +0000 (16:01 -0500)]
Revert "Move portal pinning from PL/pgSQL to SPI"

This reverts commit b3617cdfbba1b5381e9d1c6bc0839500e8eb7273.

This broke returning unnamed cursors from PL/pgSQL functions.
Apparently, there are no test cases for this.

6 years agoRemove dubious micro-optimization in ckpt_buforder_comparator().
Tom Lane [Wed, 10 Jan 2018 20:50:54 +0000 (15:50 -0500)]
Remove dubious micro-optimization in ckpt_buforder_comparator().

It seems incorrect to assume that the list of CkptSortItems can never
contain duplicate page numbers: concurrent activity could result in some
page getting dropped from a low-numbered buffer and later loaded into a
high-numbered buffer while BufferSync is scanning the buffer pool.
If that happened, the comparator would give self-inconsistent results,
potentially confusing qsort().  Saving one comparison step is not worth
possibly getting the sort wrong.

So far as I can tell, nothing would actually go wrong given our current
implementation of qsort().  It might get a bit slower than expected
if there were a large number of duplicates of one value, but that's
surely a probability-epsilon case.  Still, the comment is wrong,
and if we ever switched to another sort implementation it might be
less forgiving.

In passing, avoid casting away const-ness of the argument pointers;
I've not seen any compiler complaints from that, but it seems likely
that some compilers would not like it.

Back-patch to 9.6 where this code came in, just in case I've underestimated
the possible consequences.

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

6 years agoAdd missing "return" statement to accumulate_append_subpath.
Robert Haas [Wed, 10 Jan 2018 16:18:40 +0000 (11:18 -0500)]
Add missing "return" statement to accumulate_append_subpath.

Without this, Parallel Append can end up with extra children.

Report by Rajkumar Raghuwanshi.  Fix by Amit Khandekar.  Brown
paper bag bug by me.

Discussion: http://postgr.es/m/CAKcux6mBF-NiddyEe9LwymoUC5+wh8bQJ=uk2gGkOE+L8cv=LA@mail.gmail.com

6 years agoMove portal pinning from PL/pgSQL to SPI
Peter Eisentraut [Fri, 15 Dec 2017 20:24:10 +0000 (15:24 -0500)]
Move portal pinning from PL/pgSQL to SPI

PL/pgSQL "pins" internally generated (unnamed) portals so that user code
cannot close them by guessing their names.  This logic is also useful in
other languages and really for any code.  So move that logic into SPI.
An unnamed portal obtained through SPI_cursor_open() and related
functions is now automatically pinned, and SPI_cursor_close()
automatically unpins a portal that is pinned.

In the core distribution, this affects PL/Perl and PL/Python, preventing
users from manually closing cursors created by spi_query and
plpy.cursor, respectively.  (PL/Tcl does not currently offer any cursor
functionality.)

Reviewed-by: Andrew Dunstan <andrew.dunstan@2ndquadrant.com>
6 years agoGive more accurate error message for dropping pinned portal
Peter Eisentraut [Wed, 10 Jan 2018 14:22:07 +0000 (09:22 -0500)]
Give more accurate error message for dropping pinned portal

The previous code gave the same error message for attempting to drop
pinned and active portals, but those are separate states, so give
separate error messages.

6 years agoFix allowing of leading zero on exponents in pgbench test results
Teodor Sigaev [Wed, 10 Jan 2018 08:33:37 +0000 (11:33 +0300)]
Fix allowing of leading zero on exponents in pgbench test results

Commit bc7fa0c15c590ddf4872e426abd76c2634f22aca accidentally lost fixes of
0aa1d489ea756b96b6d5573692ae9cd5d143c2a5 commit.

Thanks to Thomas Munro

6 years agoRemove outdated/removed Win32 URLs in C comments
Bruce Momjian [Tue, 9 Jan 2018 23:33:11 +0000 (18:33 -0500)]
Remove outdated/removed Win32 URLs in C comments

Reported-by: Ashutosh Sharma
6 years agoExpression evaluation based aggregate transition invocation.
Andres Freund [Tue, 9 Jan 2018 21:25:38 +0000 (13:25 -0800)]
Expression evaluation based aggregate transition invocation.

Previously aggregate transition and combination functions were invoked
by special case code in nodeAgg.c, evaluating input and filters
separately using the expression evaluation machinery. That turns out
to not be great for performance for several reasons:

- repeated expression evaluations have some cost
- the transition functions invocations are poorly predicted, as
  commonly there are multiple aggregates in a query, resulting in the
  same call-stack invoking different functions.
- filter and input computation had to be done separately
- the special case code made it hard to implement JITing of the whole
  transition function invocation

Address this by building one large expression that computes input,
evaluates filters, and invokes transition functions.

This leads to moderate speedups in queries bottlenecked by aggregate
computations, and enables large speedups for similar cases once JITing
is done.

There's potential for further improvement:
- It'd be nice if we could simplify the somewhat expensive
  aggstate->all_pergroups lookups.
- right now there's still an advance_transition_function invocation in
  nodeAgg.c, leading to some code duplication.

Author: Andres Freund
Discussion: https://postgr.es/m/20170901064131.tazjxwus3k2w3ybh@alap3.anarazel.de

6 years agoChange some bogus PageGetLSN calls to BufferGetLSNAtomic
Alvaro Herrera [Tue, 9 Jan 2018 18:54:39 +0000 (15:54 -0300)]
Change some bogus PageGetLSN calls to BufferGetLSNAtomic

As src/backend/access/transam/README says, PageGetLSN may only be called
by processes holding either exclusive lock on buffer, or a shared lock
on buffer plus buffer header lock.  Therefore any place that only holds
a shared buffer lock must use BufferGetLSNAtomic instead of PageGetLSN,
which internally obtains buffer header lock prior to reading the LSN.

A few callsites failed to comply with this rule.  This was detected by
running all tests under a new (not committed) assertion that verifies
PageGetLSN locking contract.  All but one of the callsites that failed
the assertion are fixed by this patch.  Remaining callsites were
inspected manually and determined not to need any change.

The exception (unfixed callsite) is in TestForOldSnapshot, which only
has a Page argument, making it impossible to access the corresponding
Buffer from it.  Fixing that seems a much larger patch that will have to
be done separately; and that's just as well, since it was only
introduced in 9.6 and other bugs are much older.

Some of these bugs are ancient; backpatch all the way back to 9.3.

Authors: Jacob Champion, Asim Praveen, Ashwin Agrawal
Reviewed-by: Michaël Paquier
Discussion: https://postgr.es/m/CABAq_6GXgQDVu3u12mK9O5Xt5abBZWQ0V40LZCE+oUf95XyNFg@mail.gmail.com

6 years agoImplement TZH and TZM timestamp format patterns
Andrew Dunstan [Tue, 9 Jan 2018 19:25:05 +0000 (14:25 -0500)]
Implement TZH and TZM timestamp format patterns

These are compatible with Oracle and required for the datetime template
language for jsonpath in an upcoming patch.

Nikita Glukhov and Andrew Dunstan, reviewed by Pavel Stehule.

6 years agoRemove PortalGetQueryDesc()
Peter Eisentraut [Sat, 16 Dec 2017 22:43:41 +0000 (17:43 -0500)]
Remove PortalGetQueryDesc()

After having gotten rid of PortalGetHeapMemory(), there seems little
reason to keep one Portal access macro around that offers no actual
abstraction and isn't consistently used anyway.

Reviewed-by: Andrew Dunstan <andrew.dunstan@2ndquadrant.com>
Reviewed-by: Alvaro Herrera <alvherre@alvh.no-ip.org>
6 years agoUpdate portal-related memory context names and API
Peter Eisentraut [Sat, 16 Dec 2017 22:26:26 +0000 (17:26 -0500)]
Update portal-related memory context names and API

Rename PortalMemory to TopPortalContext, to avoid confusion with
PortalContext and align naming with similar top-level memory contexts.

Rename PortalData's "heap" field to portalContext.  The "heap" naming
seems quite antiquated and confusing.  Also get rid of the
PortalGetHeapMemory() macro and access the field directly, which we do
for other portal fields, so this abstraction doesn't buy anything.

Reviewed-by: Andrew Dunstan <andrew.dunstan@2ndquadrant.com>
Reviewed-by: Alvaro Herrera <alvherre@alvh.no-ip.org>
6 years agoRewrite list_qsort() to avoid trashing its input list.
Tom Lane [Tue, 9 Jan 2018 18:25:53 +0000 (13:25 -0500)]
Rewrite list_qsort() to avoid trashing its input list.

The initial implementation of list_qsort(), from commit ab7271677,
re-used the ListCells of the input list while not touching the List
header.  This meant that anybody who still had a pointer to the
original header would now be in possession of a corrupted list,
a problem that seems sure to bite us eventually.

One possible solution is to re-use the original List header as well,
giving the function the semantics of update-in-place.  However, that
doesn't seem like a very good idea either given the way that the
function is used in the planner: create_path functions aren't normally
supposed to modify their input lists.  It doesn't look like there would
be a problem today, but it's not hard to foresee a time when modifying
a list of Paths in-place could have side-effects on some other append
path.

On the whole, and in view of the likelihood that this function might
be used in other contexts in the future, it seems best to get rid of
the micro-optimization of re-using the input list cells.  Just build
a new list.

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

6 years agoImprove the heuristic for ordering child paths of a parallel append.
Tom Lane [Tue, 9 Jan 2018 18:07:52 +0000 (13:07 -0500)]
Improve the heuristic for ordering child paths of a parallel append.

Commit ab7271677 introduced code that attempts to order the child
scans of a Parallel Append node in a way that will minimize execution
time, based on total cost and startup cost.  However, it failed to
think hard about what to do when estimated costs are exactly equal;
a case that's particularly likely to occur when comparing on startup
cost.  In such a case the ordering of the child paths would be left
to the whims of qsort, an algorithm that isn't even stable.

We can improve matters by applying the rule used elsewhere in the
planner: if total costs are equal, sort on startup cost, and
vice versa.  When both cost estimates are exactly equal, rather
than letting qsort do something unpredictable, sort based on the
child paths' relids, which should typically result in sorting in
inheritance order.  (The latter provision requires inventing a
qsort-style comparator for bitmapsets, but maybe we'll have use
for that for other reasons in future.)

This results in a few plan changes in the select_parallel test,
but those all look more reasonable than before, when the actual
underlying cost numbers are taken into account.

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

6 years agoWhile waiting for a condition variable, detect postmaster death.
Tom Lane [Tue, 9 Jan 2018 17:34:46 +0000 (12:34 -0500)]
While waiting for a condition variable, detect postmaster death.

The general assumption for postmaster child processes is that they
should just exit(1), reasonably promptly, if the postmaster disappears.
condition_variable.c neglected this consideration and could be left
waiting forever, if the counterpart process it is waiting for has
done the right thing and exited.

We had some discussion of adjusting the WaitEventSet API to make it
harder to make this type of mistake in future; but for the moment,
and for v10, let's make this narrow fix.

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

6 years agoFix ssl tests for when tls-server-end-point is not supported
Peter Eisentraut [Tue, 9 Jan 2018 17:28:49 +0000 (12:28 -0500)]
Fix ssl tests for when tls-server-end-point is not supported

Add a function to TestLib that allows us to check pg_config.h and then
decide the expected test outcome based on that.

Author: Michael Paquier <michael.paquier@gmail.com>

6 years agoFix race condition during replication origin drop.
Tom Lane [Tue, 9 Jan 2018 17:09:30 +0000 (12:09 -0500)]
Fix race condition during replication origin drop.

replorigin_drop() misunderstood the API for condition variables: it
had ConditionVariablePrepareToSleep and ConditionVariableCancelSleep
inside its test-and-sleep loop, rather than outside the loop as
intended.  The net effect is a narrow race-condition window wherein,
if the process using a replication slot releases it immediately after
replorigin_drop() releases the ReplicationOriginLock, replorigin_drop()
would get into the condition variable's wait list too late and then
wait indefinitely for a signal that won't come.

Because there's a different CV for each replication slot, we can't
just move the ConditionVariablePrepareToSleep call to above the
test-and-sleep loop.  What we can do, in the wake of commit 13db3b936,
is drop the ConditionVariablePrepareToSleep call entirely.  This fix
depends on that commit because (at least in principle) the slot matching
the target replication origin might move around, so that once in a blue
moon successive loop iterations might involve different CVs.  We can now
cope with such a scenario, at the cost of an extra trip through the
retry loop.

(There are ways we could fix this bug without depending on that commit,
but they're all a lot more complicated than this way.)

While at it, upgrade the rather skimpy comments in this function.

Back-patch to v10 where this code came in.

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

6 years agoAllow ConditionVariable[PrepareTo]Sleep to auto-switch between CVs.
Tom Lane [Tue, 9 Jan 2018 16:39:10 +0000 (11:39 -0500)]
Allow ConditionVariable[PrepareTo]Sleep to auto-switch between CVs.

The original coding here insisted that callers manually cancel any prepared
sleep for one condition variable before starting a sleep on another one.
While that's not a huge burden today, it seems like a gotcha that will bite
us in future if the use of condition variables increases; anything we can
do to make the use of this API simpler and more robust is attractive.
Hence, allow these functions to automatically switch their attention to
a different CV when required.  This is safe for the same reason it was OK
for commit aced5a92b to let a broadcast operation cancel any prepared CV
sleep: whenever we return to the other test-and-sleep loop, we will
automatically re-prepare that CV, paying at most an extra test of that
loop's exit condition.

Back-patch to v10 where condition variables were introduced.  Ordinarily
we would probably not back-patch a change like this, but since it does not
invalidate any coding pattern that was legal before, it seems safe enough.
Furthermore, there's an open bug in replorigin_drop() for which the
simplest fix requires this.  Even if we chose to fix that in some more
complicated way, the hazard would remain that we might back-patch some
other bug fix that requires this behavior.

Patch by me, reviewed by Thomas Munro.

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

6 years agoDon't allow VACUUM VERBOSE ANALYZE VERBOSE.
Robert Haas [Tue, 9 Jan 2018 15:12:58 +0000 (10:12 -0500)]
Don't allow VACUUM VERBOSE ANALYZE VERBOSE.

There are plans to extend the syntax for ANALYZE, so we need to break
the link between VacuumStmt and AnalyzeStmt.  But apart from that, the
syntax above is undocumented and, if discovered by users, might give
the impression that the VERBOSE option for VACUUM differs from the
verbose option from ANALYZE, which it does not.

Nathan Bossart, reviewed by Michael Paquier and Masahiko Sawada

Discussion: http://postgr.es/m/D3FC73E2-9B1A-4DB4-8180-55F57D116B4E@amazon.com

6 years agoImprove scripting language in pgbench
Teodor Sigaev [Tue, 9 Jan 2018 15:02:04 +0000 (18:02 +0300)]
Improve scripting language in pgbench

Added:
 - variable now might contain integer, double, boolean and null values
 - functions ln, exp
 - logical AND/OR/NOT
 - bitwise AND/OR/NOT/XOR
 - bit right/left shift
 - comparison operators
 - IS [NOT] (NULL|TRUE|FALSE)
 - conditional choice (in form of when/case/then)

New operations and functions allow to implement more complicated test scenario.

Author: Fabien Coelho with minor editorization by me
Reviewed-By: Pavel Stehule, Jeevan Ladhe, me
Discussion: https://www.postgresql.org/message-id/flat/alpine.DEB.2.10.1604030742390.31618@sto

6 years agoFix comment.
Robert Haas [Tue, 9 Jan 2018 14:39:31 +0000 (09:39 -0500)]
Fix comment.

RELATION_IS_OTHER_TEMP is tested in the caller, not here.

Discussion: http://postgr.es/m/5A5438E4.3090709@lab.ntt.co.jp

6 years agopg_upgrade: prevent check on live cluster from generating error
Bruce Momjian [Tue, 9 Jan 2018 03:43:51 +0000 (22:43 -0500)]
pg_upgrade:  prevent check on live cluster from generating error

Previously an inaccurate but harmless error was generated when running
--check on a live server before reporting the servers as compatible.
The fix is to split error reporting and exit control in the exec_prog()
API.

Reported-by: Daniel Westermann
Backpatch-through: 10

6 years agoCosmetic improvements in condition_variable.[hc].
Tom Lane [Mon, 8 Jan 2018 23:28:03 +0000 (18:28 -0500)]
Cosmetic improvements in condition_variable.[hc].

Clarify a bunch of comments.

Discussion: https://postgr.es/m/CAEepm=0NWKehYw7NDoUSf8juuKOPRnCyY3vuaSvhrEWsOTAa3w@mail.gmail.com

6 years agoImprove error detection capability in proclists.
Tom Lane [Mon, 8 Jan 2018 23:07:04 +0000 (18:07 -0500)]
Improve error detection capability in proclists.

Previously, although the initial state of a proclist_node is expected
to be next == prev == 0, proclist_delete_offset would reset nodes to
next == prev == INVALID_PGPROCNO when removing them from a list.
This is the same state that a node in a singleton list has, so that
it's impossible to distinguish not-in-a-list from in-a-list.  Change
proclist_delete_offset to reset removed nodes to next == prev == 0,
making it possible to distinguish those cases, and then add Asserts
to the list add and delete functions that the supplied node isn't
or is in a list at entry.  Also tighten assertions about the node
being in the particular list (not some other one) where it is possible
to check that in O(1) time.

In ConditionVariablePrepareToSleep, since we don't expect the process's
cvWaitLink to already be in a list, remove the more-or-less-useless
proclist_contains check; we'd rather have proclist_push_tail's new
assertion fire if that happens.

Improve various comments related to proclists, too.

Patch by me, reviewed by Thomas Munro.  This isn't back-patchable, since
there could theoretically be inlined copies of proclist_delete_offset in
third-party modules.  But it's only improving debuggability anyway.

Discussion: https://postgr.es/m/CAEepm=0NWKehYw7NDoUSf8juuKOPRnCyY3vuaSvhrEWsOTAa3w@mail.gmail.com

6 years agoBack off chattiness in RemovePgTempFiles().
Tom Lane [Mon, 8 Jan 2018 01:40:40 +0000 (20:40 -0500)]
Back off chattiness in RemovePgTempFiles().

In commit 561885db0, as part of normalizing RemovePgTempFiles's error
handling, I removed its behavior of silently ignoring ENOENT failures
during directory opens.  Thomas Munro points out that this is a bad idea at
the top level, because we don't create pgsql_tmp directories until needed.
Thus this coding could produce LOG messages in perfectly normal situations,
which isn't what I intended.  Restore the suppression of ENOENT logging,
but only at top level --- it would still be unexpected for a nested temp
directory to disappear between seeing it in the parent directory and
opening it.

Discussion: https://postgr.es/m/CAEepm=2y06SehAkTnd5sU_eVqdv5P-=Srt1y5vYNQk6yVDVaPw@mail.gmail.com

6 years agoAdd TIMELINE to backup_label file
Simon Riggs [Sat, 6 Jan 2018 12:24:19 +0000 (12:24 +0000)]
Add TIMELINE to backup_label file

Allows new test to confirm timelines match

Author: Michael Paquier
Reviewed-by: David Steele
6 years agoDefault monitoring roles - errata
Simon Riggs [Sat, 6 Jan 2018 11:48:21 +0000 (11:48 +0000)]
Default monitoring roles - errata

25fff40798fc4ac11a241bfd9ab0c45c085e2212 introduced
default monitoring roles. Apply these corrections:

* Allow access to pg_stat_get_wal_senders()
  by role pg_read_all_stats

* Correct comment in pg_stat_get_wal_receiver()
  to show it is no longer superuser-only.

Author: Feike Steenbergen
Reviewed-by: Michael Paquier
Apply to HEAD, then later backpatch to 10

6 years agoRemove return values of ConditionVariableSignal/Broadcast.
Tom Lane [Sat, 6 Jan 2018 01:33:26 +0000 (20:33 -0500)]
Remove return values of ConditionVariableSignal/Broadcast.

In the wake of commit aced5a92b, the semantics of these results are
a bit squishy: we can tell whether we signaled some other process(es),
but we do not know which ones were real waiters versus mere sentinels
for ConditionVariableBroadcast operations.  It does not help much that
ConditionVariableBroadcast will attempt to pass on the signal to the
next real waiter, because (a) there might not be one, and (b) that will
only happen awhile later, anyway.  So these results could overstate how
much effect the calls really had.

However, no existing caller of either function pays any attention to its
result value, so it seems reasonable to just define that as a required
property of a correct algorithm.  To encourage correctness and save some
tiny number of cycles, change both functions to return void.

Patch by me, per an observation by Thomas Munro.  No back-patch, since
if any third parties happen to be using these functions, they might not
appreciate an API break in a minor release.

Discussion: https://postgr.es/m/CAEepm=0NWKehYw7NDoUSf8juuKOPRnCyY3vuaSvhrEWsOTAa3w@mail.gmail.com

6 years agoReorder steps in ConditionVariablePrepareToSleep for more safety.
Tom Lane [Sat, 6 Jan 2018 00:42:49 +0000 (19:42 -0500)]
Reorder steps in ConditionVariablePrepareToSleep for more safety.

In the admittedly-very-unlikely case that AddWaitEventToSet fails,
ConditionVariablePrepareToSleep would error out after already having
set cv_sleep_target, which is probably bad, and after having already
set cv_wait_event_set, which is very bad.  Transaction abort might or
might not clean up cv_sleep_target properly; but there is nothing
that would be aware that the WaitEventSet wasn't fully constructed,
so that all future condition variable sleeps would be broken.
We can easily guard against these hazards with slight restructuring.

Back-patch to v10 where condition_variable.c was introduced.

Discussion: https://postgr.es/m/CAEepm=0NWKehYw7NDoUSf8juuKOPRnCyY3vuaSvhrEWsOTAa3w@mail.gmail.com

6 years agoRewrite ConditionVariableBroadcast() to avoid live-lock.
Tom Lane [Sat, 6 Jan 2018 00:21:30 +0000 (19:21 -0500)]
Rewrite ConditionVariableBroadcast() to avoid live-lock.

The original implementation of ConditionVariableBroadcast was, per its
self-description, "the dumbest way possible".  Thomas Munro found out
it was a bit too dumb.  An awakened process may immediately re-queue
itself, if the specific condition it's waiting for is not yet satisfied.
If this happens before ConditionVariableBroadcast is able to see the wait
queue as empty, then ConditionVariableBroadcast will re-awaken the same
process, repeating the cycle.  Given unlucky timing this back-and-forth
can repeat indefinitely; loops lasting thousands of seconds have been
seen in testing.

To fix, add our own process to the end of the wait queue to serve as a
sentinel, and exit the broadcast loop once our process is not there
anymore.  There are various special considerations described in the
comments, the principal disadvantage being that wakers can no longer
be sure whether they awakened a real waiter or just a sentinel.  But in
practice nobody pays attention to the result of ConditionVariableSignal
or ConditionVariableBroadcast anyway, so that problem seems hypothetical.

Back-patch to v10 where condition_variable.c was introduced.

Tom Lane and Thomas Munro

Discussion: https://postgr.es/m/CAEepm=0NWKehYw7NDoUSf8juuKOPRnCyY3vuaSvhrEWsOTAa3w@mail.gmail.com

6 years agoFactor error generation out of ExecPartitionCheck.
Robert Haas [Fri, 5 Jan 2018 20:18:03 +0000 (15:18 -0500)]
Factor error generation out of ExecPartitionCheck.

At present, we always raise an ERROR if the partition constraint
is violated, but a pending patch for UPDATE tuple routing will
consider instead moving the tuple to the correct partition.
Refactor to make that simpler.

Amit Khandekar, reviewed by Amit Langote, David Rowley, and me.

Discussion: http://postgr.es/m/CAJ3gD9cue54GbEzfV-61nyGpijvjZgCcghvLsB0_nL8Nm8HzCA@mail.gmail.com

6 years agopg_upgrade: remove C comment
Bruce Momjian [Fri, 5 Jan 2018 19:49:36 +0000 (14:49 -0500)]
pg_upgrade:  remove C comment

Revert another part of 959ee6d267fb24e667fc64e9837a376e236e84a5 .

Backpatch-through: 10

6 years agopg_upgrade: revert part of patch for ease of translation
Bruce Momjian [Fri, 5 Jan 2018 19:46:27 +0000 (14:46 -0500)]
pg_upgrade:  revert part of patch for ease of translation

Revert part of 959ee6d267fb24e667fc64e9837a376e236e84a5 .

Backpatch-through: 10

6 years agopg_upgrade: simplify code layout in a few places
Bruce Momjian [Fri, 5 Jan 2018 19:11:15 +0000 (14:11 -0500)]
pg_upgrade:  simplify code layout in a few places

Backpatch-through: 9.4 (9.3 didn't need improving)

6 years agoFix failure to delete spill files of aborted transactions
Alvaro Herrera [Fri, 5 Jan 2018 15:17:10 +0000 (12:17 -0300)]
Fix failure to delete spill files of aborted transactions

Logical decoding's reorderbuffer.c may spill transaction files to disk
when transactions are large.  These are supposed to be removed when they
become "too old" by xid; but file removal requires the boundary LSNs of
the transaction to be known.  The final_lsn is only set when we see the
commit or abort record for the transaction, but nothing sets the value
for transactions that crash, so the removal code misbehaves -- in
assertion-enabled builds, it crashes by a failed assertion.

To fix, modify the final_lsn of transactions that don't have a value
set, to the LSN of the very latest change in the transaction.  This
causes the spilled files to be removed appropriately.

Author: Atsushi Torikoshi
Reviewed-by: Kyotaro HORIGUCHI, Craig Ringer, Masahiko Sawada
Discussion: https://postgr.es/m/54e4e488-186b-a056-6628-50628e4e4ebc@lab.ntt.co.jp

6 years agoAnother attempt at fixing build with various OpenSSL versions
Peter Eisentraut [Fri, 5 Jan 2018 00:09:27 +0000 (19:09 -0500)]
Another attempt at fixing build with various OpenSSL versions

It seems we can't easily work around the lack of
X509_get_signature_nid(), so revert the previous attempts and just
disable the tls-server-end-point feature if we don't have it.

6 years agoAdd missing includes
Peter Eisentraut [Thu, 4 Jan 2018 22:55:14 +0000 (17:55 -0500)]
Add missing includes

<openssl/x509.h> is necessary to look into the X509 struct, used by
ac3ff8b1d8f98da38c53a701e6397931080a39cf.

6 years agoMinor preparatory refactoring for UPDATE row movement.
Robert Haas [Thu, 4 Jan 2018 21:25:49 +0000 (16:25 -0500)]
Minor preparatory refactoring for UPDATE row movement.

Generalize is_partition_attr to has_partition_attrs and make it
accessible from outside tablecmds.c.  Change map_partition_varattnos
to clarify that it can be used for mapping between any two relations
in a partitioning hierarchy, not just parent -> child.

Amit Khandekar, reviewed by Amit Langote, David Rowley, and me.
Some comment changes by me.

Discussion: http://postgr.es/m/CAJ3gD9fWfxgKC+PfJZF3hkgAcNOy-LpfPxVYitDEXKHjeieWQQ@mail.gmail.com

6 years agoFix build with older OpenSSL versions
Peter Eisentraut [Thu, 4 Jan 2018 21:22:06 +0000 (16:22 -0500)]
Fix build with older OpenSSL versions

Apparently, X509_get_signature_nid() is only in fairly new OpenSSL
versions, so use the lower-level interface it is built on instead.

6 years agoFix new test case to not be endian-dependent.
Tom Lane [Thu, 4 Jan 2018 20:59:29 +0000 (15:59 -0500)]
Fix new test case to not be endian-dependent.

Per buildfarm.

Discussion: https://postgr.es/m/ec295792-a69f-350f-6287-25a20e8f31d5@gmail.com

6 years agoSimplify and encapsulate tuple routing support code.
Robert Haas [Thu, 4 Jan 2018 20:48:15 +0000 (15:48 -0500)]
Simplify and encapsulate tuple routing support code.

Instead of having ExecSetupPartitionTupleRouting return multiple out
parameters, have it return a pointer to a structure containing all of
those different things.  Also, provide and use a cleanup function,
ExecCleanupTupleRouting, instead of cleaning up all of the resources
allocated by ExecSetupPartitionTupleRouting individually.

Amit Khandekar, reviewed by Amit Langote, David Rowley, and me

Discussion: http://postgr.es/m/CAJ3gD9fWfxgKC+PfJZF3hkgAcNOy-LpfPxVYitDEXKHjeieWQQ@mail.gmail.com

6 years agoImplement channel binding tls-server-end-point for SCRAM
Peter Eisentraut [Thu, 4 Jan 2018 20:18:39 +0000 (15:18 -0500)]
Implement channel binding tls-server-end-point for SCRAM

This adds a second standard channel binding type for SCRAM.  It is
mainly intended for third-party clients that cannot implement
tls-unique, for example JDBC.

Author: Michael Paquier <michael.paquier@gmail.com>

6 years agoFix incorrect computations of length of null bitmap in pageinspect.
Tom Lane [Thu, 4 Jan 2018 19:59:00 +0000 (14:59 -0500)]
Fix incorrect computations of length of null bitmap in pageinspect.

Instead of using our standard macro for this calculation, this code
did it itself ... and got it wrong, leading to incorrect display of
the null bitmap in some cases.  Noted and fixed by Maksim Milyutin.

In passing, remove a uselessly duplicative error check.

Errors were introduced in commit d6061f83a; back-patch to 9.6
where that came in.

Maksim Milyutin, reviewed by Andrey Borodin

Discussion: https://postgr.es/m/ec295792-a69f-350f-6287-25a20e8f31d5@gmail.com

6 years agoRefactor channel binding code to fetch cbind_data only when necessary
Peter Eisentraut [Thu, 4 Jan 2018 18:53:09 +0000 (13:53 -0500)]
Refactor channel binding code to fetch cbind_data only when necessary

As things stand now, channel binding data is fetched from OpenSSL and
saved into the SCRAM exchange context for any SSL connection attempted
for a SCRAM authentication, resulting in data fetched but not used if no
channel binding is used or if a different channel binding type is used
than what the data is here for.

Refactor the code in such a way that binding data is fetched from the
SSL stack only when a specific channel binding is used for both the
frontend and the backend.  In order to achieve that, save the libpq
connection context directly in the SCRAM exchange state, and add a
dependency to SSL in the low-level SCRAM routines.

This makes the interface in charge of initializing the SCRAM context
cleaner as all its data comes from either PGconn* (for frontend) or
Port* (for the backend).

Author: Michael Paquier <michael.paquier@gmail.com>

6 years agoDefine LDAPS_PORT if it's missing and disable implicit LDAPS on Windows
Peter Eisentraut [Thu, 4 Jan 2018 15:34:41 +0000 (10:34 -0500)]
Define LDAPS_PORT if it's missing and disable implicit LDAPS on Windows

Some versions of Windows don't define LDAPS_PORT.

Also, Windows' ldap_sslinit() is documented to use LDAPS even if you
said secure=0 when the port number happens to be 636 or 3269.  Let's
avoid using the port number to imply that you want LDAPS, so that
connection strings have the same meaning on Windows and Unix.

Author: Thomas Munro
Discussion: https://postgr.es/m/CAEepm%3D23B7GV4AUz3MYH1TKpTv030VHxD2Sn%2BLYWDv8d-qWxww%40mail.gmail.com

6 years agoCode review for Parallel Append.
Robert Haas [Thu, 4 Jan 2018 12:56:09 +0000 (07:56 -0500)]
Code review for Parallel Append.

- Remove unnecessary #include mistakenly added in execnodes.h.
- Fix mistake in comment in choose_next_subplan_for_leader.
- Adjust row estimates in cost_append for a possibly-different
  parallel divisor.
- Clamp row estimates in cost_append after operations that may
  not produce integers.

Amit Kapila, with cosmetic adjustments by me.

Discussion: http://postgr.es/m/CAA4eK1+qcbeai3coPpRW=GFCzFeLUsuY4T-AKHqMjxpEGZBPQg@mail.gmail.com

6 years agoTweak parallel hash join test case in hopes of improving stability.
Tom Lane [Thu, 4 Jan 2018 06:06:58 +0000 (01:06 -0500)]
Tweak parallel hash join test case in hopes of improving stability.

This seems to make things better on gaur, let's see what the rest
of the buildfarm thinks.

Thomas Munro

Discussion: https://postgr.es/m/CAEepm=1uuT8iJxMEsR=jL+3zEi87DB2v0+0H9o_rUXXCZPZT3A@mail.gmail.com

6 years agoClean up tupdesc.c for recent changes.
Tom Lane [Wed, 3 Jan 2018 22:53:06 +0000 (17:53 -0500)]
Clean up tupdesc.c for recent changes.

TupleDescCopy needs to have the same effects as CreateTupleDescCopy in
that, since it doesn't copy constraints, it should clear the per-attribute
fields associated with them.  Oversight in commit cc5f81366.

Since TupleDescCopy has already established the presumption that it
can just flat-copy the entire attribute array in one go, propagate
that approach into CreateTupleDescCopy and CreateTupleDescCopyConstr.
(I'm suspicious that this would lead to valgrind complaints if we
had any trailing padding in the struct, but we do not, and anyway
fixing that seems like a job for a separate commit.)

Add some better comments.

Thomas Munro, reviewed by Vik Fearing, some additional hacking by me

Discussion: https://postgr.es/m/CAEepm=0NvOGZ8B6GbQyQe2C_c2m3LKJ9w=8OMBaYRLgZ_Gw6Nw@mail.gmail.com

6 years agoFix typo
Alvaro Herrera [Wed, 3 Jan 2018 22:12:06 +0000 (19:12 -0300)]
Fix typo

Author: Dagfinn Ilmari Mannsåker
Discussion: https://postgr.es/m/d8jefpk4jtd.fsf@dalvik.ping.uio.no

6 years agoRevert "Fix isolation test to be less timing-dependent"
Alvaro Herrera [Wed, 3 Jan 2018 14:16:34 +0000 (11:16 -0300)]
Revert "Fix isolation test to be less timing-dependent"

This reverts commit 2268e6afd596.  It turned out that inconsistency in
the report is still possible, so go back to the simpler formulation of
the test and instead add an alternate expected output.

Discussion: https://postgr.es/m/20180103193728.ysqpcp2xjnqpiep7@alvherre.pgsql

6 years agoRename pg_rewind's copy_file_range() to avoid conflict with new linux syscall.
Andres Freund [Wed, 3 Jan 2018 20:00:11 +0000 (12:00 -0800)]
Rename pg_rewind's copy_file_range() to avoid conflict with new linux syscall.

Upcoming versions of glibc will contain copy_file_range(2), a wrapper
around a new linux syscall for in-kernel copying of data ranges. This
conflicts with pg_rewinds function of the same name.

Therefore rename pg_rewinds version. As our version isn't a generic
copying facility we decided to choose a rewind specific function name.

Per buildfarm animal caiman and subsequent discussion with Tom Lane.

Author: Andres Freund
Discussion:
    https://postgr.es/m/20180103033425.w7jkljth3e26sduc@alap3.anarazel.de
    https://postgr.es/m/31122.1514951044@sss.pgh.pa.us
Backpatch: 9.5-, where pg_rewind was introduced

6 years agoFix use of config-specific libraries for Windows OpenSSL
Andrew Dunstan [Wed, 3 Jan 2018 20:26:39 +0000 (15:26 -0500)]
Fix use of config-specific libraries for Windows OpenSSL

Commit 614350a3 allowed for an different builds of OpenSSL libraries on
Windows, but ignored the fact that the alternative builds don't have
config-specific libraries. This patch fixes the Solution file to ask for
the correct libraries.

per offline discussions with Leonardo Cecchi and Marco Nenciarini,

Backpatch to all live branches.

6 years agoMake XactLockTableWait work for transactions that are not yet self-locked
Alvaro Herrera [Wed, 3 Jan 2018 20:26:20 +0000 (17:26 -0300)]
Make XactLockTableWait work for transactions that are not yet self-locked

XactLockTableWait assumed that its xid argument has already added itself
to the lock table.  That assumption led to another assumption that if
locking the xid has succeeded but the xid is reported as still in
progress, then the input xid must have been a subtransaction.

These assumptions hold true for the original uses of this code in
locking related to on-disk tuples, but they break down in logical
replication slot snapshot building -- in particular, when a standby
snapshot logged contains an xid that's already in ProcArray but not yet
in the lock table.  This leads to assertion failures that can be
reproduced all the way back to 9.4, when logical decoding was
introduced.

To fix, change SubTransGetParent to SubTransGetTopmostTransaction which
has a slightly different API: it returns the argument Xid if there is no
parent, and it goes all the way to the top instead of moving up the
levels one by one.  Also, to avoid busy-waiting, add a 1ms sleep to give
the other process time to register itself in the lock table.

For consistency, change ConditionalXactLockTableWait the same way.

Author: Petr Jelínek
Discussion: https://postgr.es/m/1B3E32D8-FCF4-40B4-AEF9-5C0E3AC57969@postgrespro.ru
Reported-by: Konstantin Knizhnik
Diagnosed-by: Stas Kelvich, Petr Jelínek
Reviewed-by: Andres Freund, Robert Haas
6 years agoFix some minor errors in new PHJ code.
Tom Lane [Wed, 3 Jan 2018 17:53:49 +0000 (12:53 -0500)]
Fix some minor errors in new PHJ code.

Correct ExecParallelHashTuplePrealloc's estimate of whether the
space_allowed limit is exceeded.  Be more consistent about tuples that
are exactly HASH_CHUNK_THRESHOLD in size (they're "small", not "large").
Neither of these things explain the current buildfarm unhappiness, but
they're still bugs.

Thomas Munro, per gripe by me

Discussion: https://postgr.es/m/CAEepm=34PDuR69kfYVhmZPgMdy8pSA-MYbpesEN1SR+2oj3Y+w@mail.gmail.com

6 years agoTeach eval_const_expressions() to handle some more cases.
Tom Lane [Wed, 3 Jan 2018 17:35:09 +0000 (12:35 -0500)]
Teach eval_const_expressions() to handle some more cases.

Add some infrastructure (mostly macros) to make it easier to write
typical cases for constant-expression simplification.  Add simplification
processing for ArrayRef, RowExpr, and ScalarArrayOpExpr node types,
which formerly went unsimplified even if all their inputs were constants.
Also teach it to simplify FieldSelect from a composite constant.
Make use of the new infrastructure to reduce the amount of code needed
for the existing ArrayExpr and ArrayCoerceExpr cases.

One existing test case changes output as a result of the fact that
RowExpr can now be folded to a constant.  All the new code is exercised
by existing test cases according to gcov, so I feel no need to add
additional tests.

Tom Lane, reviewed by Dmitry Dolgov

Discussion: https://postgr.es/m/3be3b82c-e29c-b674-2163-bf47d98817b1@iki.fi

6 years agoAllow ldaps when using ldap authentication
Peter Eisentraut [Wed, 3 Jan 2018 15:00:08 +0000 (10:00 -0500)]
Allow ldaps when using ldap authentication

While ldaptls=1 provides an RFC 4513 conforming way to do LDAP
authentication with TLS encryption, there was an earlier de facto
standard way to do LDAP over SSL called LDAPS.  Even though it's not
enshrined in a standard, it's still widely used and sometimes required
by organizations' network policies.  There seems to be no reason not to
support it when available in the client library.  Therefore, add support
when using OpenLDAP 2.4+ or Windows.  It can be configured with
ldapscheme=ldaps or ldapurl=ldaps://...

Add tests for both ways of requesting LDAPS and a test for the
pre-existing ldaptls=1.  Modify the 001_auth.pl test for "diagnostic
messages", which was previously relying on the server rejecting
ldaptls=1.

Author: Thomas Munro
Reviewed-By: Peter Eisentraut
Discussion: https://postgr.es/m/CAEepm=1s+pA-LZUjQ-9GQz0Z4rX_eK=DFXAF1nBQ+ROPimuOYQ@mail.gmail.com

6 years agoFix isolation test to be less timing-dependent
Alvaro Herrera [Wed, 3 Jan 2018 14:16:42 +0000 (11:16 -0300)]
Fix isolation test to be less timing-dependent

I did this by adding another locking process, which makes the other two
wait.  This way the output should be stable enough.

Per buildfarm and Andres Freund
Discussion: https://postgr.es/m/20180103034445.t3utrtrnrevfsghm@alap3.anarazel.de

6 years agoUpdate copyright for 2018
Bruce Momjian [Wed, 3 Jan 2018 04:30:12 +0000 (23:30 -0500)]
Update copyright for 2018

Backpatch-through: certain files through 9.3

6 years agoSimplify representation of aggregate transition values a bit.
Andres Freund [Wed, 3 Jan 2018 02:02:37 +0000 (18:02 -0800)]
Simplify representation of aggregate transition values a bit.

Previously aggregate transition values for hash and other forms of
aggregation (i.e. sort and no group by) were represented
differently. Hash based aggregation used a grouping set indexed array
pointing to an array of transition values, whereas other forms of
aggregation used one flattened array with the index being computed out
of grouping set and transition offsets.

That made upcoming changes hard, so represent both as grouping set
indexed array of per-group data.

As a nice side-effect this also makes aggregation slightly faster,
because computing offsets with `transno + (setno * numTrans)` turns
out not to be that cheap (too big for x86 lea for example).

Author: Andres Freund
Discussion: https://postgr.es/m/20171128003121.nmxbm2ounxzb6n2t@alap3.anarazel.de

6 years agoEnsure proper alignment of tuples in HashMemoryChunkData buffers.
Tom Lane [Wed, 3 Jan 2018 02:23:02 +0000 (21:23 -0500)]
Ensure proper alignment of tuples in HashMemoryChunkData buffers.

The previous coding relied (without any documentation) on the data[]
member of HashMemoryChunkData being at a MAXALIGN'ed offset.  If it
was not, the tuples would not be maxaligned either, leading to failures
on alignment-picky machines.  While there seems to be no live bug on any
platform we support, this is clearly pretty fragile: any addition to or
rearrangement of the fields in HashMemoryChunkData could break it.
Let's remove the hazard by getting rid of the data[] member and instead
using pointer arithmetic with an explicitly maxalign'ed offset.

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

6 years agoFix deadlock hazard in CREATE INDEX CONCURRENTLY
Alvaro Herrera [Tue, 2 Jan 2018 22:16:16 +0000 (19:16 -0300)]
Fix deadlock hazard in CREATE INDEX CONCURRENTLY

Multiple sessions doing CREATE INDEX CONCURRENTLY simultaneously are
supposed to be able to work in parallel, as evidenced by fixes in commit
c3d09b3bd23f specifically to support this case.  In reality, one of the
sessions would be aborted by a misterious "deadlock detected" error.

Jeff Janes diagnosed that this is because of leftover snapshots used for
system catalog scans -- this was broken by 8aa3e47510b9 keeping track of
(registering) the catalog snapshot.  To fix the deadlocks, it's enough
to de-register that snapshot prior to waiting.

Backpatch to 9.4, which introduced MVCC catalog scans.

Include an isolationtester spec that 8 out of 10 times reproduces the
deadlock with the unpatched code for me (Álvaro).

Author: Jeff Janes
Diagnosed-by: Jeff Janes
Reported-by: Jeremy Finzel
Discussion: https://postgr.es/m/CAMa1XUhHjCv8Qkx0WOr1Mpm_R4qxN26EibwCrj0Oor2YBUFUTg%40mail.gmail.com

6 years agoDon't cast between GinNullCategory and bool
Peter Eisentraut [Tue, 26 Dec 2017 18:47:18 +0000 (13:47 -0500)]
Don't cast between GinNullCategory and bool

The original idea was that we could use an isNull-style bool array
directly as a GinNullCategory array.  However, the existing code already
acknowledges that that doesn't really work, because of the possibility
that bool as currently defined can have arbitrary bit patterns for true
values.  So it has to loop through the nullFlags array to set each bool
value to an acceptable value.  But if we are looping through the whole
array anyway, we might as well build a proper GinNullCategory array
instead and abandon the type casting.  That makes the code much safer in
case bool is ever changed to something else.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agoFix EXPLAIN ANALYZE output for Parallel Hash.
Andres Freund [Mon, 1 Jan 2018 22:38:23 +0000 (14:38 -0800)]
Fix EXPLAIN ANALYZE output for Parallel Hash.

In a race case, EXPLAIN ANALYZE could fail to display correct nbatch
and size information.  Refactor so that participants report only on
batches they worked on rather than trying to report on all of them,
and teach explain.c to consider the HashInstrumentation object from
all participants instead of picking the first one it can find.  This
should fix an occasional build farm failure in the "join" regression
test.

Author: Thomas Munro
Reviewed-By: Andres Freund
Discussion: https://postgr.es/m/30219.1514428346%40sss.pgh.pa.us

6 years agoIn tests, await an LSN no later than the recovery target.
Noah Misch [Mon, 1 Jan 2018 05:58:29 +0000 (21:58 -0800)]
In tests, await an LSN no later than the recovery target.

Otherwise, the test fails with "Timed out while waiting for standby to
catch up".  This happened rarely, perhaps only when autovacuum wrote WAL
between our choosing the recovery target and choosing the LSN to await.
Commit b26f7fa6ae2b4e5d64525b3d5bc66a0ddccd9e24 fixed one case of this.
Fix two more.  Back-patch to 9.6, which introduced the affected test.

Discussion: https://postgr.es/m/20180101055227.GA2952815@rfd.leadboat.com

6 years agoMerge coding of return/exit/continue cases in plpgsql's loop statements.
Tom Lane [Sun, 31 Dec 2017 22:20:17 +0000 (17:20 -0500)]
Merge coding of return/exit/continue cases in plpgsql's loop statements.

plpgsql's five different loop control statements contained three distinct
implementations of the same (or what ought to be the same, at least)
logic for handling return/exit/continue result codes from their child
statements.  At best, that's trouble waiting to happen, and there seems
no very good reason for the coding to be so different.  Refactor so that
all the common logic is expressed in a single macro.

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

6 years agoImprove regression tests' code coverage for plpgsql control structures.
Tom Lane [Sun, 31 Dec 2017 22:04:11 +0000 (17:04 -0500)]
Improve regression tests' code coverage for plpgsql control structures.

I noticed that our code coverage report showed considerable deficiency
in test coverage for PL/pgSQL control statements.  Notably, both
exec_stmt_block and most of the loop control statements had very poor
coverage of handling of return/exit/continue result codes from their
child statements; and exec_stmt_fori was seriously lacking in feature
coverage, having no test that exercised its BY or REVERSE features,
nor verification that its overflow defenses work.

Now that we have some infrastructure for plpgsql-specific test scripts,
the natural thing to do is make a new script rather than further extend
plpgsql.sql.  So I created a new script plpgsql_control.sql with the
charter to test plpgsql control structures, and moved a few existing
tests there because they fell entirely under that charter.  I then
added new test cases that exercise the bits of code complained of above.

Of the five kinds of loop statements, only exec_stmt_while's result code
handling is fully exercised by these tests.  That would be a deficiency
as things stand, but a follow-on commit will merge the loop statements'
result code handling into one implementation.  So testing each usage of
that implementation separately seems redundant.

In passing, also add a couple test cases to plpgsql.sql to more fully
exercise plpgsql's code related to expanded arrays --- I had thought
that area was sufficiently covered already, but the coverage report
showed a couple of un-executed code paths.

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

6 years agoFix typo
Alvaro Herrera [Fri, 29 Dec 2017 21:32:32 +0000 (18:32 -0300)]
Fix typo

6 years agoPerform slot validity checks in a separate pass over expression.
Andres Freund [Fri, 29 Dec 2017 20:38:15 +0000 (12:38 -0800)]
Perform slot validity checks in a separate pass over expression.

This reduces code duplication a bit, but the primary benefit that it
makes JITing expression evaluation easier. When doing so we can't, as
previously done in the interpreted case, really change opcode without
recompiling. Nor dow we just carry around unnecessary branches to
avoid re-checking over and over.

As a minor side-effect this makes ExecEvalStepOp() O(log(N)) rather
than O(N).

Author: Andres Freund
Discussion: https://postgr.es/m/20170901064131.tazjxwus3k2w3ybh@alap3.anarazel.de

6 years agoRely on executor utils to build targetlist for DML RETURNING.
Andres Freund [Fri, 29 Dec 2017 20:26:29 +0000 (12:26 -0800)]
Rely on executor utils to build targetlist for DML RETURNING.

This is useful because it gets rid of the sole direct user of
ExecAssignResultType(). A future commit will likely make use of that
and combine creating the targetlist with the initialization of the
result slot. But it seems like good code hygiene anyway.

Author: Andres Freund
Discussion: https://postgr.es/m/20170901064131.tazjxwus3k2w3ybh@alap3.anarazel.de

6 years agoProperly set base backup backends to active in pg_stat_activity
Magnus Hagander [Fri, 29 Dec 2017 15:19:51 +0000 (16:19 +0100)]
Properly set base backup backends to active in pg_stat_activity

When walsenders were included in pg_stat_activity, only the ones
actually streaming WAL were listed as active when they were active. In
particular, the connections sending base backups were listed as being
idle. Which means that a regular pg_basebackup would show up with one
active and one idle connection, when both were active.

This patch updates to set all walsenders to active when they are
(including those doing very fast things like IDENTIFY_SYSTEM), and then
back to idle. Details about exactly what they are doing is available in
pg_stat_replication.

Patch by me, review by Michael Paquier and David Steele.