]> granicus.if.org Git - postgresql/log
postgresql
6 years agoPrevent generation of bogus subquery scan paths.
Robert Haas [Wed, 25 Apr 2018 19:14:14 +0000 (15:14 -0400)]
Prevent generation of bogus subquery scan paths.

Commit 0927d2f46ddd4cf7d6bf2cc84b3be923e0aedc52 didn't check that
consider_parallel was set for the target relation or account for
the possibility that required_outer might be non-empty.

To prevent future bugs of this ilk, add some assertions to
add_partial_path and do a bit of future-proofing of the code
recently added to recurse_set_operations.

Report by Andreas Seltenreich.  Patch by Jeevan Chalke.  Review
by Amit Kapila and by me.

Discussion: http://postgr.es/m/CAM2+6=U+9otsyF2fYB8x_2TBeHTR90itarqW=qAEjN-kHaC7kw@mail.gmail.com

6 years agoAdd amcheck missing downlink tests.
Teodor Sigaev [Wed, 25 Apr 2018 19:05:53 +0000 (22:05 +0300)]
Add amcheck missing downlink tests.

Also use palloc0() for main amcheck state, and adjust a few comments.

Somehow I pushed old version of patch in commit
4eaf7eaccb291f5d32d9f05284bfca9c5744de9a, so commit the difference.

Peter Geoghegan

6 years agoReindent Perl files with perltidy version 20170521.
Tom Lane [Wed, 25 Apr 2018 18:00:19 +0000 (14:00 -0400)]
Reindent Perl files with perltidy version 20170521.

Discussion: https://postgr.es/m/CABUevEzK3cNiHZQ18f5tK0guoT+cN_jWeVzhYYxY=r+1Q3SmoA@mail.gmail.com

6 years agoChange pgindent/README to specify that we use perltidy version 20170521.
Tom Lane [Wed, 25 Apr 2018 17:58:39 +0000 (13:58 -0400)]
Change pgindent/README to specify that we use perltidy version 20170521.

Per discussion, this is now the project's standard version.
Update the obsolete URL, and explain how to install a specific version.

Discussion: https://postgr.es/m/CABUevEzK3cNiHZQ18f5tK0guoT+cN_jWeVzhYYxY=r+1Q3SmoA@mail.gmail.com

6 years agoAdd missing and dangling downlink checks to amcheck
Teodor Sigaev [Wed, 25 Apr 2018 15:02:55 +0000 (18:02 +0300)]
Add missing and dangling downlink checks to amcheck

When bt_index_parent_check() is called with the heapallindexed option,
allocate a second Bloom filter to fingerprint block numbers that appear
in the downlinks of internal pages.  Use Bloom filter probes when
walking the B-Tree to detect missing downlinks.  This can detect subtle
problems with page deletion/VACUUM, such as corruption caused by the bug
just fixed in commit 6db4b499.

The downlink Bloom filter is bound in size by work_mem.  Its optimal
size is typically far smaller than that of the regular heapallindexed
Bloom filter, especially when the index has high fan-out.

Author: Peter Geoghegan
Reviewer: Teodor Sigaev
Discussion: https://postgr.es/m/CAH2-WznUzY4fWTjm1tBB3JpVz8cCfz7k_qVp5BhuPyhivmWJFg@mail.gmail.com

6 years agoFix typo
Magnus Hagander [Wed, 25 Apr 2018 07:29:50 +0000 (09:29 +0200)]
Fix typo

Author: Michael Paquier

6 years agoUpdate ExecInitPartitionInfo comment
Alvaro Herrera [Wed, 25 Apr 2018 02:00:48 +0000 (23:00 -0300)]
Update ExecInitPartitionInfo comment

Remove the words "if not already done."  This obsolete wording
corresponds to an early development version of what became edd44738bc8.

Author: Etsuro Fujita
Reviewed-by: Amit Langote
Discussion: https://postgr.es/m/5ADF117B.5030606@lab.ntt.co.jp

6 years agoInitialize ExprStates once in run-time partition pruning
Alvaro Herrera [Tue, 24 Apr 2018 17:03:10 +0000 (14:03 -0300)]
Initialize ExprStates once in run-time partition pruning

Instead of doing ExecInitExpr every time a Param needs to be evaluated
in run-time partition pruning, do it once during run-time pruning
set-up and cache the exprstate in PartitionPruneContext, saving a lot of
work.

Author: David Rowley
Reviewed-by: Amit Langote, Álvaro Herrera
Discussion: https://postgr.es/m/CAKJS1f8-x+q-90QAPDu_okhQBV4DPEtPz8CJ=m0940GyT4DA4w@mail.gmail.com

6 years agoAdd GUC enable_partition_pruning
Alvaro Herrera [Mon, 23 Apr 2018 20:57:43 +0000 (17:57 -0300)]
Add GUC enable_partition_pruning

This controls both plan-time and execution-time new-style partition
pruning.  While finer-grain control is possible (maybe using an enum GUC
instead of boolean), there doesn't seem to be much need for that.

This new parameter controls partition pruning for all queries:
trivially, SELECT queries that affect partitioned tables are naturally
under its control since they are using the new technology.  However,
while UPDATE/DELETE queries do not use the new code, we make the new GUC
control their behavior also (stealing control from
constraint_exclusion), because it is more natural, and it leads to a
more natural transition to the future in which those queries will also
use the new pruning code.

Constraint exclusion still controls pruning for regular inheritance
situations (those not involving partitioned tables).

Author: David Rowley
Review: Amit Langote, Ashutosh Bapat, Justin Pryzby, David G. Johnston
Discussion: https://postgr.es/m/CAKJS1f_0HwsxJG9m+nzU+CizxSdGtfe6iF_ykPYBiYft302DCw@mail.gmail.com

6 years agoFix handling of partition bounds for boolean partitioning columns.
Tom Lane [Mon, 23 Apr 2018 19:29:11 +0000 (15:29 -0400)]
Fix handling of partition bounds for boolean partitioning columns.

Previously, you could partition by a boolean column as long as you
spelled the bound values as string literals, for instance FOR VALUES
IN ('t').  The trouble with this is that ruleutils.c printed that as
FOR VALUES IN (TRUE), which is reasonable syntax but wasn't accepted by
the grammar.  That results in dump-and-reload failures for such cases.

Apply a minimal fix that just causes TRUE and FALSE to be converted to
strings 'true' and 'false'.  This is pretty grotty, but it's too late for
a more principled fix in v11 (to say nothing of v10).  We should revisit
the whole issue of how partition bound values are parsed for v12.

Amit Langote

Discussion: https://postgr.es/m/e05c5162-1103-7e37-d1ab-6de3e0afaf70@lab.ntt.co.jp

6 years agoFix typo in logical truncate replication
Peter Eisentraut [Mon, 23 Apr 2018 17:38:22 +0000 (13:38 -0400)]
Fix typo in logical truncate replication

This could result in some misbehavior in a cascading replication setup.

6 years agoMake Emacs settings match perltidy configuration
Peter Eisentraut [Mon, 23 Apr 2018 15:44:31 +0000 (11:44 -0400)]
Make Emacs settings match perltidy configuration

Set Emacs's perl-continued-statement-offset to match perltidy's
--continuation-indentation, which is 2 (not overridden in PostgreSQL's
profile) rather than the 4 that Emacs uses by default.

6 years agoAdd missing pstrdup
Alvaro Herrera [Mon, 23 Apr 2018 14:50:21 +0000 (11:50 -0300)]
Add missing pstrdup

Lifetime of the input string is not right, so create a separate copy.

Author: Amit Langote
Discussion: https://postgr.es/m/a2773420-50d1-0a42-3396-fe42b0921134@lab.ntt.co.jp

6 years agoRemove useless default clause in switch
Alvaro Herrera [Mon, 23 Apr 2018 14:46:30 +0000 (11:46 -0300)]
Remove useless default clause in switch

The switch covers all values of the enum driver variable, so having a
default: clause is useless, even if it's only to do Assert(false).

6 years agoMake bms_prev_member work correctly with a 64 bit bitmapword
Teodor Sigaev [Mon, 23 Apr 2018 14:59:17 +0000 (17:59 +0300)]
Make bms_prev_member work correctly with a 64 bit bitmapword

5c067521 erroneously had coded bms_prev_member assuming that a bitmapword
would always hold 32 bits and started it's search on what it thought was the
highest 8-bits of the word.  This was not the case if bitmapwords were 64
bits.

In passing add a test to exercise this function a little. Previously there was
no coverage at all.

David Rowly

6 years agoUpdate trigram example in docs to correct state
Teodor Sigaev [Mon, 23 Apr 2018 13:55:13 +0000 (16:55 +0300)]
Update trigram example in docs to correct state

Author: Liudmila Mantrova

6 years agoFix wrong validation of top-parent pointer during page deletion in Btree.
Teodor Sigaev [Mon, 23 Apr 2018 12:55:10 +0000 (15:55 +0300)]
Fix wrong validation of top-parent pointer during page deletion in Btree.

After introducing usage of t_tid of inner or page high key for storing
number of attributes of tuple, validation of tuple's ItemPointer with
ItemPointerIsValid becomes incorrect, it's need to validate only blocknumber of
ItemPointer. Missing this causes a incorrect page deletion, fix that. Test is
added.

BTW, current contrib/amcheck doesn't fail on index corrupted by this way.

Also introduce BTreeTupleGetTopParent/BTreeTupleSetTopParent macroses to improve
code readability and to avoid possible confusion with page high key: high key
is used to store top-parent link for branch to remove.

Bug found by Michael Paquier, but bug doesn't exist in previous versions because
t_tid was set to P_HIKEY.

Author: Teodor Sigaev
Reviewer: Peter Geoghegan
Discussion: https://www.postgresql.org/message-id/flat/20180419052436.GA16000%40paquier.xyz

6 years agoMake PGJIT_* macros safer.
Heikki Linnakangas [Mon, 23 Apr 2018 08:48:08 +0000 (04:48 -0400)]
Make PGJIT_* macros safer.

Author: David Rowley
Discussion: https://www.postgresql.org/message-id/CAKJS1f8Ge2y0sDs6RQEJFH-vjb-bWhs86rCX4Fp4FZ+TmxtRkw@mail.gmail.com

6 years agoAdd comment explaining BGWORKER_BYPASS_ALLOWCONN
Magnus Hagander [Mon, 23 Apr 2018 08:31:22 +0000 (10:31 +0200)]
Add comment explaining BGWORKER_BYPASS_ALLOWCONN

Suggested by Michael Paquier

6 years agoAdd missing documentation for BGWORKER_BYPASS_ALLOWCONN
Magnus Hagander [Sun, 22 Apr 2018 12:03:36 +0000 (14:03 +0200)]
Add missing documentation for BGWORKER_BYPASS_ALLOWCONN

This was missed in eed1ce72e1593d3e8b7461d7744808d4d6bf402b.

Reported by Michael Paquier

6 years agoAdd missing "static" marker.
Tom Lane [Sat, 21 Apr 2018 15:21:08 +0000 (11:21 -0400)]
Add missing "static" marker.

Per pademelon.

6 years agodoc: Restructure authentication methods sections
Peter Eisentraut [Thu, 12 Apr 2018 00:33:53 +0000 (20:33 -0400)]
doc: Restructure authentication methods sections

Move the authentication methods sections up to sect1, so they are easier
to navigate in HTML.

6 years agoTest conversion of NaN between float4 and float8.
Tom Lane [Fri, 20 Apr 2018 23:54:58 +0000 (19:54 -0400)]
Test conversion of NaN between float4 and float8.

Results from buildfarm member opossum suggest that this doesn't work
quite right on that platform.  We've seen issues with NaN support on
MIPS/NetBSD before ... allegedly they fixed this stuff back in 2010,
but maybe only for small values of "fixed".

If, in fact, opossum fails this test then I plan to revert it;
it's mainly for diagnostic purposes rather than something we'd
necessarily keep long-term.  I think that the failures in window.sql
could be worked around with some code duplication, but I want to
verify my theory about the cause first.

6 years agoFix a couple minor typos
Stephen Frost [Fri, 20 Apr 2018 23:04:54 +0000 (19:04 -0400)]
Fix a couple minor typos

In commit f0e4475, GetIndexOpClass was renamed to ResolveOpClass, but
the comment in typecmds.c didn't get the memo.

In objectaddress.c, missing 'of' in a comment.

Both noticed by Vik Fearing, patch is mine though.

6 years agoDon't run fast_default regression test in parallel with other tests.
Tom Lane [Fri, 20 Apr 2018 21:27:56 +0000 (17:27 -0400)]
Don't run fast_default regression test in parallel with other tests.

Since it sets up an event trigger that would fire on DDL done by any
concurrent test script, the original scheduling is just an invitation
to irreproducible test failures.  (The fact that we found a bug through
exactly such irreproducible test failures doesn't really change the
calculus here: this script is a hazard to anything that runs in parallel
with it today or might be added to that parallel group in future.  No,
I don't believe that the trigger is protecting itself sufficiently to
avoid all possible trouble.)

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

6 years agoFix race conditions when an event trigger is added concurrently with DDL.
Tom Lane [Fri, 20 Apr 2018 21:15:31 +0000 (17:15 -0400)]
Fix race conditions when an event trigger is added concurrently with DDL.

EventTriggerTableRewrite crashed if there were table_rewrite triggers
present, but there had not been when the calling command started.

EventTriggerDDLCommandEnd called ddl_command_end triggers if present,
even if there had been no such triggers when the calling command started,
which would lead to a failure in pg_event_trigger_ddl_commands.

In both cases, fix by doing nothing; it's better to wait till the next
command when things will be properly initialized.

In passing, remove an elog(DEBUG1) call that might have seemed interesting
four years ago but surely isn't today.

We found this because of intermittent failures in the buildfarm.  Thanks
to Alvaro Herrera and Andrew Gierth for analysis.

Back-patch to 9.5; some of this code exists before that, but the specific
hazards we need to guard against don't.

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

6 years agoTweak a couple of planner APIs to save recalculating join relids.
Tom Lane [Fri, 20 Apr 2018 20:00:47 +0000 (16:00 -0400)]
Tweak a couple of planner APIs to save recalculating join relids.

Discussion: https://postgr.es/m/f8128b11-c5bf-3539-48cd-234178b2314d@proxel.se

6 years agoChange more places to be less trusting of RestrictInfo.is_pushed_down.
Tom Lane [Fri, 20 Apr 2018 19:19:16 +0000 (15:19 -0400)]
Change more places to be less trusting of RestrictInfo.is_pushed_down.

On further reflection, commit e5d83995e didn't go far enough: pretty much
everywhere in the planner that examines a clause's is_pushed_down flag
ought to be changed to use the more complicated behavior where we also
check the clause's required_relids.  Otherwise we could make incorrect
decisions about whether, say, a clause is safe to use as a hash clause.

Some (many?) of these places are safe as-is, either because they are
never reached while considering a parameterized path, or because there
are additional checks that would reject a pushed-down clause anyway.
However, it seems smarter to just code them all the same way rather
than rely on easily-broken reasoning of that sort.

In support of that, invent a new macro RINFO_IS_PUSHED_DOWN that should
be used in place of direct tests on the is_pushed_down flag.

Like the previous patch, back-patch to all supported branches.

Discussion: https://postgr.es/m/f8128b11-c5bf-3539-48cd-234178b2314d@proxel.se

6 years agoImprove consistency of comments in system catalog headers.
Tom Lane [Thu, 19 Apr 2018 21:14:09 +0000 (17:14 -0400)]
Improve consistency of comments in system catalog headers.

Use the term "system catalog" rather than "system relation" in assorted
places where it's clearly referring to a table rather than, say, an
index.  Use more natural word order in the header boilerplate, improve
some of the one-liner catalog descriptions, and fix assorted random
deviations from the normal boilerplate.  All purely neatnik-ism, but
why not.

John Naylor, some additional cleanup by me

Discussion: https://postgr.es/m/CAJVSVGUeJmFB3h-NJ18P32NPa+kzC165nm7GSoGHfPaN80Wxcw@mail.gmail.com

6 years agoFix incorrect handling of join clauses pushed into parameterized paths.
Tom Lane [Thu, 19 Apr 2018 19:49:12 +0000 (15:49 -0400)]
Fix incorrect handling of join clauses pushed into parameterized paths.

In some cases a clause attached to an outer join can be pushed down into
the outer join's RHS even though the clause is not degenerate --- this
can happen if we choose to make a parameterized path for the RHS.  If
the clause ends up attached to a lower outer join, we'd misclassify it
as being a "join filter" not a plain "filter" condition at that node,
leading to wrong query results.

To fix, teach extract_actual_join_clauses to examine each join clause's
required_relids, not just its is_pushed_down flag.  (The latter now
seems vestigial, or at least in need of rethinking, but we won't do
anything so invasive as redefining it in a bug-fix patch.)

This has been wrong since we introduced parameterized paths in 9.2,
though it's evidently hard to hit given the lack of previous reports.
The test case used here involves a lateral function call, and I think
that a lateral reference may be required to get the planner to select
a broken plan; though I wouldn't swear to that.  In any case, even if
LATERAL is needed to trigger the bug, it still affects all supported
branches, so back-patch to all.

Per report from Andreas Karlsson.  Thanks to Andrew Gierth for
preliminary investigation.

Discussion: https://postgr.es/m/f8128b11-c5bf-3539-48cd-234178b2314d@proxel.se

6 years agoRemove quick path in ExecInitPartitionInfo for equal tupdescs
Alvaro Herrera [Thu, 19 Apr 2018 19:46:53 +0000 (16:46 -0300)]
Remove quick path in ExecInitPartitionInfo for equal tupdescs

I added this "optimization" on top of Amit Langote's 158b7bc6d779, but
the quick path is never taken because the partition uses a different
pg_type oid than its parent table (causing equalTupleDescs to return
false).  Changing that requires more analysis and is too considered
dangerous at this point in the cycle, so revert it.

We might make it work someday, but not for pg11.

Discussion: https://postgr.es/m/825031be-942c-8c24-6163-13c27f217a3d@lab.ntt.co.jp

6 years agoPlural of modulus is moduli
Alvaro Herrera [Thu, 19 Apr 2018 15:37:23 +0000 (12:37 -0300)]
Plural of modulus is moduli

6 years agoRework code to determine partition pruning procedure
Alvaro Herrera [Thu, 19 Apr 2018 14:22:31 +0000 (11:22 -0300)]
Rework code to determine partition pruning procedure

Amit Langote reported that partition prune was unable to work with
arrays, enums, etc, which led him to research the appropriate way to
match query clauses to partition keys: instead of searching for an exact
match of the expression's type, it is better to rely on the fact that
the expression qual has already been resolved to a specific operator,
and that the partition key is linked to a specific operator family.
With that info, it's possible to figure out the strategy and comparison
function to use for the pruning clause in a manner that works reliably
for pseudo-types also.

Include new test cases that demonstrate pruning where pseudotypes are
involved.

Author: Amit Langote, Álvaro Herrera
Discussion: https://postgr.es/m/2b02f1e9-9812-9c41-972d-517bdc0f815d@lab.ntt.co.jp

6 years agoEnlarge find_other_exec's meager fgets buffer
Alvaro Herrera [Thu, 19 Apr 2018 13:45:15 +0000 (10:45 -0300)]
Enlarge find_other_exec's meager fgets buffer

The buffer was 100 bytes long, which is barely sufficient when the
version string gets longer (such as by configure --with-extra-version).
Set it to MAXPGPATH.

Author: Nikhil Sontakke
Discussion: https://postgr.es/m/CAMGcDxfLfpYU_Jru++L6ARPCOyxr0W+2O3Q54TDi5XdYeU36ow@mail.gmail.com

6 years agoFix datatype for number of heap tuples during last cleanup
Teodor Sigaev [Thu, 19 Apr 2018 08:28:03 +0000 (11:28 +0300)]
Fix datatype for number of heap tuples during last cleanup

It appears that new fields introduced in 857f9c36 have inconsistent datatypes:
BTMetaPageData.btm_last_cleanup_num_heap_tuples is of float4 type,
while xl_btree_metadata.last_cleanup_num_heap_tuples is of double type.
IndexVacuumInfo.num_heap_tuples, which is a source of values for
both former fields is of double type.  So, make both those fields in
BTMetaPageData and xl_btree_metadata use float8 type in order to match the
precision of the source.  That shouldn't be double type, because we always
use types with explicit width in WAL.

Patch introduces incompatibility of on-disk format since 857f9c36 commit, but
that versions never was released, so just bump catalog version to avoid
possible confusion.

Author: Alexander Korortkov

6 years agoAdjust _bt_insertonpg() comments
Teodor Sigaev [Thu, 19 Apr 2018 08:08:45 +0000 (11:08 +0300)]
Adjust _bt_insertonpg() comments

Remove an obsolete reference to the 'afteritem' argument, which was
removed by commit bc292937.  Add a comment that clarifies how
_bt_insertonpg() indirectly handles the insertion of high key items.

Author: Peter Geoghegan

6 years agoHandle XLOG_BTREE_META_CLEANUP in btree_desc() and btree_identify()
Teodor Sigaev [Thu, 19 Apr 2018 06:27:56 +0000 (09:27 +0300)]
Handle XLOG_BTREE_META_CLEANUP in btree_desc() and btree_identify()

New WAL record XLOG_BTREE_META_CLEANUP introduced in 857f9c36 has no handling
in btree_desc() and btree_identify().  This patch implements corresponding
handling.

Alexander Korotkov

6 years agoAdjust INCLUDE index truncation comments and code.
Teodor Sigaev [Thu, 19 Apr 2018 05:45:58 +0000 (08:45 +0300)]
Adjust INCLUDE index truncation comments and code.

Add several assertions that ensure that we're dealing with a pivot tuple
without non-key attributes where that's expected.  Also, remove the
assertion within _bt_isequal(), restoring the v10 function signature.  A
similar check will be performed for the page highkey within
_bt_moveright() in most cases.  Also avoid dropping all objects within
regression tests, to increase pg_dump test coverage for INCLUDE indexes.

Rather than using infrastructure that's generally intended to be used
with reference counted heap tuple descriptors during truncation, use the
same function that was introduced to store flat TupleDescs in shared
memory (we use a temp palloc'd buffer).  This isn't strictly necessary,
but seems more future-proof than the old approach.  It also lets us
avoid including rel.h within indextuple.c, which was arguably a
modularity violation.  Also, we now call index_deform_tuple() with the
truncated TupleDesc, not the source TupleDesc, since that's more robust,
and saves a few cycles.

In passing, fix a memory leak by pfree'ing truncated pivot tuple memory
during CREATE INDEX.  Also pfree during a page split, just to be
consistent.

Refactor _bt_check_natts() to be more readable.

Author: Peter Geoghegan with some editorization by me
Reviewed by: Alexander Korotkov, Teodor Sigaev
Discussion: https://www.postgresql.org/message-id/CAH2-Wz%3DkCWuXeMrBCopC-tFs3FbiVxQNjjgNKdG2sHxZ5k2y3w%40mail.gmail.com

6 years agoImprove error detection/reporting in Catalog.pm and genbki.pl.
Tom Lane [Wed, 18 Apr 2018 22:17:02 +0000 (18:17 -0400)]
Improve error detection/reporting in Catalog.pm and genbki.pl.

Clean up error messages relating to mistakes in .dat files: make sure they
provide the .dat file name and line number, not the place in the Perl
script that's reporting the problem.  Adopt more uniform message phrasing,
too.

Make genbki.pl spit up on unrecognized field names in the input hashes.
Previously, it just silently ignored such fields, which could make a
misspelled field name into a very hard-to-decipher problem.  (This is in
genbki.pl, *not* Catalog.pm, because we don't want reformat_dat_file.pl to
complain about unrecognized fields.  We'd rather it silently dropped them,
to facilitate removing unwanted fields after a reorganization.)

6 years agoBetter fix for deadlock hazard in CREATE INDEX CONCURRENTLY.
Tom Lane [Wed, 18 Apr 2018 16:07:37 +0000 (12:07 -0400)]
Better fix for deadlock hazard in CREATE INDEX CONCURRENTLY.

Commit 54eff5311 did not account for the possibility that we'd have
a transaction snapshot due to default_transaction_isolation being
set high enough to require one.  The transaction snapshot is enough
to hold back our advertised xmin and thus risk deadlock anyway.
The only way to get rid of that snap is to start a new transaction,
so let's do that instead.  Also throw in an assert checking that we
really have gotten to a state where no xmin is being advertised.

Back-patch to 9.4, like the previous commit.

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

6 years agoImprove docs for the new INCLUDE directive in CREATE/ALTER TABLE.
Heikki Linnakangas [Wed, 18 Apr 2018 09:44:29 +0000 (05:44 -0400)]
Improve docs for the new INCLUDE directive in CREATE/ALTER TABLE.

Author: Michael Paquier
Discussion: https://www.postgresql.org/message-id/20180411082020.GD19732%40paquier.xyz

6 years agoRationalize handling of single and double quotes in bootstrap data.
Tom Lane [Tue, 17 Apr 2018 23:53:50 +0000 (19:53 -0400)]
Rationalize handling of single and double quotes in bootstrap data.

Change things around so that proper quoting of values interpolated into
the BKI data by initdb is the responsibility of initdb, not something
we half-heartedly handle by putting double quotes into the raw BKI data.
(Note: experimentation shows that it still doesn't work to put a double
quote into the initial superuser username, but that's the fault of
inadequate quoting while interpolating the name into SQL scripts;
the BKI aspect of it works fine now.)

Having done that, we can remove the special-case handling of values
that look like "something" from genbki.pl, and instead teach it to
escape double --- and single --- quotes properly.  This removes the
nowhere-documented need to treat those specially in the BKI source
data; whatever you write will be passed through unchanged into the
inserted data value, modulo Perl's rules about single-quoted strings.

Add documentation explaining the (pre-existing) handling of backslashes
in the BKI data.

Per an earlier discussion with John Naylor.

Discussion: https://postgr.es/m/CAJVSVGUNao=-Q2-vAN3PYcdF5tnL5JAHwGwzZGuYHtq+Mk_9ng@mail.gmail.com

6 years agoRationalize handling of array type names in bootstrap data.
Tom Lane [Tue, 17 Apr 2018 22:29:11 +0000 (18:29 -0400)]
Rationalize handling of array type names in bootstrap data.

Formerly, Catalog.pm turned a C array type declaration in the catalog
header files into a SQL type, e.g., 'foo[]'.  Along the way, genbki.pl
turned this into '_foo' for the purpose of type lookups, but wrote 'foo[]'
to postgres.bki.  During bootstrap, bootscanner.l had to have a special
case rule to tokenize this, and then MapArrayTypeName() would turn 'foo[]'
into '_foo' one more time.

This seems unnecessarily complicated, especially since nobody cares that
much about the readability of postgres.bki.  Instead, make Catalog.pm
convert the C declaration into '_foo' to start with, and preserve that
representation of the type name throughout bootstrap data processing.
Then rip out the special-case code in bootscanner.l and bootstrap.c.

This changes postgres.bki to the extent that array fields are now
declared like
  proconfig = _text ,
rather than
  proconfig = text[] ,

No documentation update, since the SGML docs didn't mention any of this
in the first place, and it's all pretty transparent to writers of
catalog header files anyway.

John Naylor

Discussion: https://postgr.es/m/CAJVSVGUNao=-Q2-vAN3PYcdF5tnL5JAHwGwzZGuYHtq+Mk_9ng@mail.gmail.com

6 years agoSimplify genbki.pl's data quoting rules.
Tom Lane [Tue, 17 Apr 2018 22:10:16 +0000 (18:10 -0400)]
Simplify genbki.pl's data quoting rules.

During the bootstrap data format conversion, it seemed important for
verifiability's sake that the generated postgres.bki file stayed the same
as before.  That resulted in adding a bunch of ad-hoc rules about when to
quote emitted data values, to match previous manual decisions that had
often quoted values unnecessarily.  Now that the conversion is complete,
it seems fine to remove all those ad-hoc rules.  The net actual effect on
the current contents of postgres.bki is that some fields that had been
quoted despite containing only digits or only "-" lose their unnecessary
quotes.

Also, now that genbki.pl will always quote values containing a backslash,
there's no need for bootscanner.l to allow unquoted octal escapes;
so simplify its production for "id" by removing that possibility.

John Naylor, slightly modified by me

Discussion: https://postgr.es/m/CAJVSVGUNao=-Q2-vAN3PYcdF5tnL5JAHwGwzZGuYHtq+Mk_9ng@mail.gmail.com

6 years agoFix confusion on the padding of GIDs in on commit and abort records.
Heikki Linnakangas [Tue, 17 Apr 2018 20:10:42 +0000 (16:10 -0400)]
Fix confusion on the padding of GIDs in on commit and abort records.

Review of commit 1eb6d652: It's pointless to add padding to the GID fields,
when the code that follows assumes that there is no alignment, and uses
memcpy(). Remove the pointless padding.

Update comments to note the new fields in the WAL records.

Reviewed-by: Michael Paquier
Discussion: https://www.postgresql.org/message-id/33b787bf-dc20-1161-54e9-3f3b607bf59d%40iki.fi

6 years agoUpdate Append's idea of first_partial_plan
Alvaro Herrera [Tue, 17 Apr 2018 19:19:48 +0000 (16:19 -0300)]
Update Append's idea of first_partial_plan

It turns out that after runtime partition pruning, Append's
first_partial_plan does not accurately represent partial plans to run,
if any of those got pruned.  This could limit participation of workers
in some partial subplans, if other subplans got pruned.  Fix it by
keeping an index of the first valid partial subplan in the state node,
determined at execnode Init time.

Author: David Rowley, with cosmetic changes by me.
Discussion: https://postgr.es/m/CAKJS1f8o2Yd=rOP=Et3A0FWgF+gSAOkFSU6eNhnGzTPV7nN8sQ@mail.gmail.com

6 years agoFix a few typos in comments and variable names.
Heikki Linnakangas [Tue, 17 Apr 2018 15:54:57 +0000 (11:54 -0400)]
Fix a few typos in comments and variable names.

Author: Michael Paquier
Discussion: https://www.postgresql.org/message-id/20180411075223.GB19732%40paquier.xyz

6 years agoImprove coverage of nodeAppend runtime partition prune
Alvaro Herrera [Tue, 17 Apr 2018 15:16:22 +0000 (12:16 -0300)]
Improve coverage of nodeAppend runtime partition prune

coverage report indicated that mark_invalid_subplans_as_finished() and
nearby code was not getting exercised by any tests.  Add a new one which
has execution-time Params rather than only external Params to fix this.

In passing, David noticed that ab_q6 tests were not actually required to
have a generic plan. The tests were testing exec Params not external
Params, so there was no need for the PREPARE.  Remove the PREPARE,
making these plain queries.  (The new queries are called from
explain_parallel_append, which may be unnecessary since they don't
actually have a Parallel Append node, just an Append.  But it doesn't
seem to hurt anything, either.)

Author: David Rowley
Discussion: https://postgr.es/m/CAKJS1f--hopb6JBSDY4wiXTS3ZcDp-wparXjTQ1nzNdBa04Fog@mail.gmail.com

6 years agoAdd more infinite recursion detection while locking a view.
Tatsuo Ishii [Tue, 17 Apr 2018 07:59:17 +0000 (16:59 +0900)]
Add more infinite recursion detection while locking a view.

Also add regression test cases for detecting infinite recursion in
locking view tests.  Some document enhancements. Patch by Yugo Nagata.

6 years agoRestore partition_prune's usage of parallel workers
Alvaro Herrera [Mon, 16 Apr 2018 21:12:22 +0000 (18:12 -0300)]
Restore partition_prune's usage of parallel workers

This reverts commit 4d0f6d3f207d ("Attempt to stabilize partition_prune
test output (2)"), and attempts to stabilize the test by using string
replacement to hide any loop count difference in parallel nodes.

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

6 years agoFix broken collation-aware searches in SP-GiST text opclass.
Tom Lane [Mon, 16 Apr 2018 20:06:47 +0000 (16:06 -0400)]
Fix broken collation-aware searches in SP-GiST text opclass.

spg_text_leaf_consistent() supposed that it should compare only
Min(querylen, entrylen) bytes of the two strings, and then deal with
any excess bytes in one string or the other by assuming the longer
string is greater if the prefixes are equal.  Quite aside from the
fact that that's just wrong in some locales (e.g., 'ch' is not less
than 'd' in cs_CZ), it also risked passing incomplete multibyte
characters to strcoll(), with ensuing bad results.

Instead, just pass the full strings to varstr_cmp, and let it decide
what to do about unequal-length strings.

Fortunately, this error doesn't imply any index corruption, it's just
that searches might return the wrong set of entries.

Per report from Emre Hasegeli, though this is not his patch.
Thanks to Peter Geoghegan for review and discussion.

This code was born broken, so back-patch to all supported branches.
In HEAD, I failed to resist the temptation to do a bit of cosmetic
cleanup/pgindent'ing on 710d90da1, too.

Discussion: https://postgr.es/m/CAE2gYzzb6K51VnTq5i5p52z+j9p2duEa-K1T3RrC_GQEynAKEg@mail.gmail.com

6 years agoUpdate expected output of new test
Alvaro Herrera [Mon, 16 Apr 2018 19:39:32 +0000 (16:39 -0300)]
Update expected output of new test

Forgot to 'git add' the file after tweaking the test as submitted :-(

Per buildfarm

6 years agoIgnore whole-rows in INSERT/CONFLICT with partitioned tables
Alvaro Herrera [Mon, 16 Apr 2018 18:50:57 +0000 (15:50 -0300)]
Ignore whole-rows in INSERT/CONFLICT with partitioned tables

We had an Assert() preventing whole-row expressions from being used in
the SET clause of INSERT ON CONFLICT, but it seems unnecessary, given
some tests, so remove it.  Add a new test to exercise the case.

Still at ExecInitPartitionInfo, we used map_partition_varattnos (which
constructs an attribute map, then calls map_variable_attnos) using
the same two relations many times in different expressions and with
different parameters.  Constructing the map over and over is a waste.
To avoid this repeated work, construct the map once, and use
map_variable_attnos() directly instead.

Author: Amit Langote, per comments by me (Álvaro)
Discussion: https://postgr.es/m/20180326142016.m4st5e34chrzrknk@alvherre.pgsql

6 years agoFix potentially-unportable code in contrib/adminpack.
Tom Lane [Sun, 15 Apr 2018 17:02:11 +0000 (13:02 -0400)]
Fix potentially-unportable code in contrib/adminpack.

Spelling access(2)'s second argument as "2" is just horrid.
POSIX makes no promises as to the numeric values of W_OK and related
macros.  Even if it accidentally works as intended on every supported
platform, it's still unreadable and inconsistent with adjacent code.

In passing, don't spell "NULL" as "0" either.  Yes, that's legal C;
no, it's not project style.

Back-patch, just in case the unportability is real and not theoretical.
(Most likely, even if a platform had different bit assignments for
access()'s modes, there'd not be an observable behavior difference
here; but I'm being paranoid today.)

6 years agoClean up callers of JsonbIteratorNext().
Tom Lane [Sun, 15 Apr 2018 16:40:01 +0000 (12:40 -0400)]
Clean up callers of JsonbIteratorNext().

Coverity complained about the lack of a check on the return value in
parse_jsonb_index_flags' last call of JsonbIteratorNext.  Seems like
a reasonable gripe to me, especially since the code is depending on
that being WJB_DONE to not leak memory, so add a check.

In passing, improve a couple other places where the result was being
ignored, either by adding an assert or at least a cast to void.

Also, don't spell "WJB_DONE" as "0".  That's horrid coding style,
and it wasn't consistent either.

6 years agoDon't attempt to verify checksums on new pages
Magnus Hagander [Sun, 15 Apr 2018 12:05:56 +0000 (14:05 +0200)]
Don't attempt to verify checksums on new pages

Teach both base backups and pg_verify_checksums that if a page is new,
it does not have a checksum yet, so it shouldn't be verified.

Noted by Tomas Vondra, review by David Steele.

6 years agoFix build of pg_verify_checksum docs
Magnus Hagander [Sun, 15 Apr 2018 11:57:02 +0000 (13:57 +0200)]
Fix build of pg_verify_checksum docs

They were accidentally excluded when reverting the backend online
checksum functionality, and since they weren't built the incorrect
reference to a removed section also did not trigger a problem.

Author: Christoph Berg

6 years agoClarify pg_verify_checksum documentation
Magnus Hagander [Sun, 15 Apr 2018 11:51:35 +0000 (13:51 +0200)]
Clarify pg_verify_checksum documentation

Make it clear that a cluster has to be shut down cleanly before
pg_verify_checksum can be run against it.

Author: Michael Paquier
Review: Daniel Gustafsson

6 years agoRemove -f option from pg_verify_checksums
Magnus Hagander [Sun, 15 Apr 2018 11:49:47 +0000 (13:49 +0200)]
Remove -f option from pg_verify_checksums

This option makes no sense when the cluster checksum state cannot be
changed, and should have been removed in the revert.

Author: Daniel Gustafsson
Review: Michael Paquier

6 years agoSimplify view-expansion code in rewriteHandler.c.
Tom Lane [Sun, 15 Apr 2018 01:00:54 +0000 (21:00 -0400)]
Simplify view-expansion code in rewriteHandler.c.

In the wake of commit 50c6bb022, it's not necessary for ApplyRetrieveRule
to have a forUpdatePushedDown parameter.  By the time control gets here for
any given view-referencing RTE, we should already have pushed down the
effects of any FOR UPDATE/SHARE clauses affecting the view from outer query
levels.  Hence if we don't find a RowMarkClause at the current query level,
that's sufficient proof that there is no outer one either.  This in turn
means we need no forUpdatePushedDown parameter for fireRIRrules.

I wonder whether we oughtn't also revert commit cba2d2717, since it now
seems likely that that was band-aiding around the bad effects of doing
FOR UPDATE pushdown and view expansion in the wrong order.  However,
in the absence of evidence that the current coding of markQueryForLocking
is actually buggy (i.e. missing RTEs it ought to mark), it seems best to
leave it alone.

Discussion: https://postgr.es/m/24db7b8f-3de5-e25f-7ab9-d8848351d42c@gmail.com

6 years agoList src/include/partitioning in src/include/Makefile
Alvaro Herrera [Sun, 15 Apr 2018 00:33:32 +0000 (21:33 -0300)]
List src/include/partitioning in src/include/Makefile

This omission prevented partitioning header files from being installed.

Per buildfarm member crake.

6 years agoReorganize partitioning code
Alvaro Herrera [Sun, 15 Apr 2018 00:12:14 +0000 (21:12 -0300)]
Reorganize partitioning code

There's been a massive addition of partitioning code in PostgreSQL 11,
with little oversight on its placement, resulting in a
catalog/partition.c with poorly defined boundaries and responsibilities.
This commit tries to set a couple of distinct modules to separate things
a little bit.  There are no code changes here, only code movement.

There are three new files:
  src/backend/utils/cache/partcache.c
  src/include/partitioning/partdefs.h
  src/include/utils/partcache.h

The previous arrangement of #including catalog/partition.h almost
everywhere is no more.

Authors: Amit Langote and Álvaro Herrera
Discussion: https://postgr.es/m/98e8d509-790a-128c-be7f-e48a5b2d8d97@lab.ntt.co.jp
https://postgr.es/m/11aa0c50-316b-18bb-722d-c23814f39059@lab.ntt.co.jp
https://postgr.es/m/143ed9a4-6038-76d4-9a55-502035815e68@lab.ntt.co.jp
https://postgr.es/m/20180413193503.nynq7bnmgh6vs5vm@alvherre.pgsql

6 years agoImprove regression test coverage of expand_tuple().
Tom Lane [Sat, 14 Apr 2018 23:02:30 +0000 (19:02 -0400)]
Improve regression test coverage of expand_tuple().

I was dissatisfied with the code coverage report for expand_tuple() in the
wake of commit 7c44c46de: while better than no coverage at all, it was
still not exercising the core function of inserting out-of-line default
values, nor was the HeapTuple-output path covered.  So far as I can find,
the only code path that reaches the latter at present is EvalPlanQual
fetches for non-locked tables.  Hence, extend eval-plan-qual.spec to
test cases where out-of-line defaults must be inserted into a tuple
fetched from a non-locked table.

Discussion: https://postgr.es/m/87woxi24uw.fsf@ansel.ydns.eu

6 years agoFix enforcement of SELECT FOR UPDATE permissions with nested views.
Tom Lane [Sat, 14 Apr 2018 19:38:09 +0000 (15:38 -0400)]
Fix enforcement of SELECT FOR UPDATE permissions with nested views.

SELECT FOR UPDATE on a view should require UPDATE (as well as SELECT)
permissions on the view, and then the view's owner needs those same
permissions against the relations it references, and so on all the way
down to base tables.  But ApplyRetrieveRule did things in the wrong order,
resulting in failure to mark intermediate view levels as needing UPDATE
permission.  Thus for example, if user A creates a table T and an updatable
view V1 on T, then grants only SELECT permissions on V1 to user B, B could
create a second view V2 on V1 and then would be allowed to perform SELECT
FOR UPDATE via V2 (since V1 wouldn't be checked for UPDATE permissions).

To fix, just switch the order of expanding sub-views and marking referenced
objects as needing UPDATE permission.  I think additional simplifications
are now possible, but that's distinct from the bug fix proper.

This is certainly a security issue, but the consequences are pretty minor
(just the ability to lock rows that shouldn't be lockable).  Against that
we have a small risk of breaking applications that are working as-desired,
since nested views have behaved this way since such cases worked at all.
On balance I'm inclined not to back-patch.

Per report from Alexander Lakhin.

Discussion: https://postgr.es/m/24db7b8f-3de5-e25f-7ab9-d8848351d42c@gmail.com

6 years agoAdd commentary explaining why MaxIndexTuplesPerPage calculation is safe.
Tom Lane [Sat, 14 Apr 2018 16:33:15 +0000 (12:33 -0400)]
Add commentary explaining why MaxIndexTuplesPerPage calculation is safe.

MaxIndexTuplesPerPage ignores the fact that btree indexes sometimes
store tuples with no data payload.  But it also ignores the possibility
of "special space" on index pages, which offsets that, so that the
result isn't an underestimate.  This all seems worth documenting, though.

In passing, remove #define MinIndexTupleSize, which was added by
commit 2c03216d8 but not used in that commit nor later ones.

Comment text by me; issue noticed by Peter Geoghegan.

Discussion: https://postgr.es/m/CAH2-WzkQmb54Kbx-YHXstRKXcNc+_87jwV3DRb54xcybLR7Oig@mail.gmail.com

6 years agoImprove code comments
Peter Eisentraut [Sat, 14 Apr 2018 14:04:36 +0000 (10:04 -0400)]
Improve code comments

As of 0c2c81b403db420bfce36f168887db72932dbf09, the replication
parameter in libpq is no longer "deliberately undocumented".

6 years agoSupport named and default arguments in CALL
Peter Eisentraut [Fri, 13 Apr 2018 21:06:28 +0000 (17:06 -0400)]
Support named and default arguments in CALL

We need to call expand_function_arguments() to expand named and default
arguments.

In PL/pgSQL, we also need to deal with named and default INOUT arguments
when receiving the output values into variables.

Author: Pavel Stehule <pavel.stehule@gmail.com>

6 years agoPrevent segfault in expand_tuple with no missing values
Andrew Dunstan [Fri, 13 Apr 2018 20:43:33 +0000 (16:43 -0400)]
Prevent segfault in expand_tuple with no missing values

Commit 16828d5c forgot to check that it had a set of missing values
before trying to retrieve a value from it.

An additional query to add coverage for this code is added to the
regression test.

Per bug report from Andreas Seltenreich.

6 years agoImprove regression test coverage for src/backend/tsearch/spell.c.
Tom Lane [Fri, 13 Apr 2018 17:49:52 +0000 (13:49 -0400)]
Improve regression test coverage for src/backend/tsearch/spell.c.

In passing, throw an error if the AF count is too small, rather than
just silently discarding extra affix entries.

Note that the new regression test cases require installing the
updated src/backend/tsearch/dicts files.

Arthur Zakirov

Discussion: https://postgr.es/m/20180413113447.GA32474@zakirov.localdomain

6 years agoIn libpq, free any partial query result before collecting a server error.
Tom Lane [Fri, 13 Apr 2018 16:53:45 +0000 (12:53 -0400)]
In libpq, free any partial query result before collecting a server error.

We'd throw away the partial result anyway after parsing the error message.
Throwing it away beforehand costs nothing and reduces the risk of
out-of-memory failure.  Also, at least in systems that behave like
glibc/Linux, if the partial result was very large then the error PGresult
would get allocated at high heap addresses, preventing the heap storage
used by the partial result from being released to the OS until the error
PGresult is freed.

In psql >= 9.6, we hold onto the error PGresult until another error is
received (for \errverbose), so that this behavior causes a seeming
memory leak to persist for awhile, as in a recent complaint from
Darafei Praliaskouski.  This is a potential performance regression from
older versions, justifying back-patching at least that far.  But similar
behavior may occur in other client applications, so it seems worth just
back-patching to all supported branches.

Discussion: https://postgr.es/m/CAC8Q8tJ=7cOkPePyAbJE_Pf691t8nDFhJp0KZxHvnq_uicfyVg@mail.gmail.com

6 years agoUse custom hash opclass for hash partition pruning
Alvaro Herrera [Fri, 13 Apr 2018 15:27:22 +0000 (12:27 -0300)]
Use custom hash opclass for hash partition pruning

This custom opclass was already in use in other tests -- defined
independently in every such file.  Move the definition to the earliest
test that uses it, and keep it around so that later tests can reuse it.
Use it in the tests for pruning of hash partitioning, and since this
makes the second expected file unnecessary, put those tests back in
partition_prune.sql whence they sprang.

Author: Amit Langote
Discussion: https://postgr.es/m/CA%2BTgmoZ0D5kJbt8eKXtvVdvTcGGWn6ehWCRSZbWytD-uzH92mQ%40mail.gmail.com

6 years agoAttempt to stabilize partition_prune test output (2)
Alvaro Herrera [Fri, 13 Apr 2018 13:46:49 +0000 (10:46 -0300)]
Attempt to stabilize partition_prune test output (2)

Environmental conditions might cause parallel workers to be scheduled in
different ways in this test, destabilizing the EXPLAIN output.  Disable
use of workers in an attempt to make output stable.

Author: David Rowley
Diagnosed-by: Thomas Munro
Discussion: https://postgr.es/m/CAKJS1f8j24tUX_nOwACiM=UO5jrMrDz8ca0xbG0vhVgfWph0ZA@mail.gmail.com

6 years agoFix bogus affix-merging code.
Tom Lane [Thu, 12 Apr 2018 22:39:51 +0000 (18:39 -0400)]
Fix bogus affix-merging code.

NISortAffixes() compared successive compound affixes incorrectly,
thus possibly failing to merge identical affixes, or (less likely)
merging ones that shouldn't be merged.  The user-visible effects
of this are unclear, to me anyway.

Per bug #15150 from Alexander Lakhin.  It's been broken for a long time,
so back-patch to all supported branches.

Arthur Zakirov

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

6 years agoRevert lowering of lock level for ATTACH PARTITION
Alvaro Herrera [Thu, 12 Apr 2018 19:53:27 +0000 (16:53 -0300)]
Revert lowering of lock level for ATTACH PARTITION

I lowered the lock level for partitions being scanned from
AccessExclusive to ShareLock in the course of 72cf7f310c07, but that was
bogus, as pointed out by Robert Haas.  Revert that bit.  Doing this is
possible, but requires more work.

Discussion: https://postgr.es/m/CA+TgmobV7Nfmqv+TZXcdSsb9Bjc-OL-Anv6BNmCbfJVZLYPE4Q@mail.gmail.com

6 years agoAdd comment about default partition in check_new_partition_bound
Alvaro Herrera [Thu, 12 Apr 2018 19:51:55 +0000 (16:51 -0300)]
Add comment about default partition in check_new_partition_bound

The intention of the test is not immediately obvious, so we need this
much.

6 years agoYA attempt to stabilize the results of the postgres_fdw regression test.
Tom Lane [Thu, 12 Apr 2018 19:12:06 +0000 (15:12 -0400)]
YA attempt to stabilize the results of the postgres_fdw regression test.

We've made multiple attempts to stabilize the plans shown by commit
1bc0100d2, with little success so far.  The reason for the remaining
instability seems to be that if a transaction (such as auto-analyze)
is running concurrently with the test, then get_actual_variable_range may
return a maximum value for "T 1"."C 1" that's far away from the actual max,
as a result of our having transiently inserted such a value earlier in
the test.  Because we use a non-MVCC snapshot to fetch the value (for
performance reasons), the presence of other transactions can cause that
function to return entries that are actually dead.

To fix, use a less extreme value in the earlier transient insertion, so
that whether it is visible or not won't affect the selectivity estimate.
The use of 9999 there seems to have been picked with the aid of a
dartboard anyway, rather than having a specific reason.

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

6 years agoUse the right memory context for partkey's FmgrInfo
Alvaro Herrera [Thu, 12 Apr 2018 18:08:10 +0000 (15:08 -0300)]
Use the right memory context for partkey's FmgrInfo

We were using CurrentMemoryContext to put the partsupfunc fmgr_info
into, which isn't right, because we want the PartitionKey as a whole to
be in the isolated Relation->rd_partkeycxt context.  This can cause a
crash with user-defined support functions in the operator classes used
by partitioning keys.  (Maybe this can cause problems with core-supplied
opclasses too, not sure.)

This is demonstrably broken in Postgres 10, too, but the initial
proposed fix runs afoul of a problem discussed back when 8a0596cb656e
("Get rid of copy_partition_key") reorganized that code: namely that it
is possible to jump out of RelationBuildPartitionKey because of some
error and leave a dangling memory context child of CacheMemoryContext.
Also, while reviewing this I noticed that the removed-in-pg11
copy_partition_key was doing something wrong, unfixed in pg10, namely
doing memcpy() on the FmgrInfo, which is bogus (should be doing
fmgr_info_copy).  Therefore, in branch pg10, the sane fix seems to be to
backpatch both the aforementioned 8a0596cb656e and its followup
be2343221fb7 ("Protect against hypothetical memory leaks in
RelationGetPartitionKey"), so do that, then apply the fmgr_info memcxt
bugfix on top.

Add a test case exercising btree-based custom operator classes, which
causes a crash prior to this fix.  This is not a security problem,
because in order to create an operator class you need superuser
privileges anyway.

Authors: Álvaro Herrera and Amit Langote
Reported and diagnosed by: Amit Langote
Discussion: https://postgr.es/m/3041e853-b1dd-a0c6-ff21-7cc5633bffd0@lab.ntt.co.jp

6 years agoFix YA parallel-make hazard, this one in "make check" in plpython.
Tom Lane [Thu, 12 Apr 2018 14:38:48 +0000 (10:38 -0400)]
Fix YA parallel-make hazard, this one in "make check" in plpython.

We have to ensure that submake-generated-headers is finished before
the topmost make run launches any child makes.

Discussion: https://postgr.es/m/20180411235843.GG32449@paquier.xyz

6 years agoFix interference between covering indexes and partitioned tables
Teodor Sigaev [Thu, 12 Apr 2018 14:25:13 +0000 (17:25 +0300)]
Fix interference between covering indexes and partitioned tables

The bug is caused due to the original IndexStmt that DefineIndex receives
being overwritten when processing the INCLUDE columns. Use separate list of
index params to propagate to child tables. Add tests covering this case.

Amit Langote and Alexander Korotkov.

Re-commit 5c6110c6a960ad6fe1b0d0fec6ae36ef4eb913f5 because it discovered a bug
fixed in c266ed31a8a3beed3533e6a78faeca78234cbd43

Discussion: https://www.postgresql.org/message-id/CAJGNTeO%3DBguEyG8wxMpU_Vgvg3nGGzy71zUQ0RpzEn_mb0bSWA%40mail.gmail.com

6 years agoCleanup covering infrastructure
Teodor Sigaev [Thu, 12 Apr 2018 13:37:22 +0000 (16:37 +0300)]
Cleanup covering infrastructure

- Explicitly forbids opclass, collation and indoptions (like DESC/ASC etc) for
  including columns. Throw an error if user points that.
- Truncated storage arrays for such attributes to store only key atrributes,
  added assertion checks.
- Do not check opfamily and collation for including columns in
  CompareIndexInfo()

Discussion: https://www.postgresql.org/message-id/5ee72852-3c4e-ee35-e2ed-c1d053d45c08@sigaev.ru

6 years agoRevert MERGE patch
Simon Riggs [Thu, 12 Apr 2018 10:22:56 +0000 (11:22 +0100)]
Revert MERGE patch

This reverts commits d204ef63776b8a00ca220adec23979091564e465,
83454e3c2b28141c0db01c7d2027e01040df5249 and a few more commits thereafter
(complete list at the end) related to MERGE feature.

While the feature was fully functional, with sufficient test coverage and
necessary documentation, it was felt that some parts of the executor and
parse-analyzer can use a different design and it wasn't possible to do that in
the available time. So it was decided to revert the patch for PG11 and retry
again in the future.

Thanks again to all reviewers and bug reporters.

List of commits reverted, in reverse chronological order:

 f1464c5380 Improve parse representation for MERGE
 ddb4158579 MERGE syntax diagram correction
 530e69e59b Allow cpluspluscheck to pass by renaming variable
 01b88b4df5 MERGE minor errata
 3af7b2b0d4 MERGE fix variable warning in non-assert builds
 a5d86181ec MERGE INSERT allows only one VALUES clause
 4b2d44031f MERGE post-commit review
 4923550c20 Tab completion for MERGE
 aa3faa3c7a WITH support in MERGE
 83454e3c2b New files for MERGE
 d204ef6377 MERGE SQL Command following SQL:2016

Author: Pavan Deolasee
Reviewed-by: Michael Paquier
6 years agoRename IndexInfo.ii_KeyAttrNumbers array
Teodor Sigaev [Thu, 12 Apr 2018 10:02:45 +0000 (13:02 +0300)]
Rename IndexInfo.ii_KeyAttrNumbers array

Rename ii_KeyAttrNumbers to ii_IndexAttrNumbers to prevent confusion with
ii_NumIndexAttrs/ii_NumIndexKeyAttrs. ii_IndexAttrNumbers contains
all attributes including "including" columns, not only key attribute.

Discussion: https://www.postgresql.org/message-id/13123421-1d52-d0e4-c95c-6d69011e0595%40sigaev.ru

6 years agoSet relispartition correctly for index partitions
Alvaro Herrera [Thu, 12 Apr 2018 00:27:12 +0000 (21:27 -0300)]
Set relispartition correctly for index partitions

Oversight in commit 8b08f7d4820f: pg_class.relispartition was not
being set for index partitions, which is a bit odd, and was also causing
the code to unnecessarily call has_superclass() when simply checking the
flag was enough.

Author: Álvaro Herrera
Reported-by: Amit Langote
Discussion: https://postgr.es/m/12085bc4-0bc6-0f3a-4c43-57fe0681772b@lab.ntt.co.jp

6 years agoIgnore nextOid when replaying an ONLINE checkpoint.
Tom Lane [Wed, 11 Apr 2018 22:11:29 +0000 (18:11 -0400)]
Ignore nextOid when replaying an ONLINE checkpoint.

The nextOid value is from the start of the checkpoint and may well be stale
compared to values from more recent XLOG_NEXTOID records.  Previously, we
adopted it anyway, allowing the OID counter to go backwards during a crash.
While this should be harmless, it contributed to the severity of the bug
fixed in commit 0408e1ed5, by allowing duplicate TOAST OIDs to be assigned
immediately following a crash.  Without this error, that issue would only
have arisen when TOAST objects just younger than a multiple of 2^32 OIDs
were deleted and then not vacuumed in time to avoid a conflict.

Pavan Deolasee

Discussion: https://postgr.es/m/CABOikdOgWT2hHkYG3Wwo2cyZJq2zfs1FH0FgX-=h4OLosXHf9w@mail.gmail.com

6 years agoDo not select new object OIDs that match recently-dead entries.
Tom Lane [Wed, 11 Apr 2018 21:41:09 +0000 (17:41 -0400)]
Do not select new object OIDs that match recently-dead entries.

When selecting a new OID, we take care to avoid picking one that's already
in use in the target table, so as not to create duplicates after the OID
counter has wrapped around.  However, up to now we used SnapshotDirty when
scanning for pre-existing entries.  That ignores committed-dead rows, so
that we could select an OID matching a deleted-but-not-yet-vacuumed row.
While that mostly worked, it has two problems:

* If recently deleted, the dead row might still be visible to MVCC
snapshots, creating a risk for duplicate OIDs when examining the catalogs
within our own transaction.  Such duplication couldn't be visible outside
the object-creating transaction, though, and we've heard few if any field
reports corresponding to such a symptom.

* When selecting a TOAST OID, deleted toast rows definitely *are* visible
to SnapshotToast, and will remain so until vacuumed away.  This leads to
a conflict that will manifest in errors like "unexpected chunk number 0
(expected 1) for toast value nnnnn".  We've been seeing reports of such
errors from the field for years, but the cause was unclear before.

The fix is simple: just use SnapshotAny to search for conflicting rows.
This results in a slightly longer window before object OIDs can be
recycled, but that seems unlikely to create any large problems.

Pavan Deolasee

Discussion: https://postgr.es/m/CABOikdOgWT2hHkYG3Wwo2cyZJq2zfs1FH0FgX-=h4OLosXHf9w@mail.gmail.com

6 years agoAllocate enough shared string memory for stats of auxiliary processes.
Heikki Linnakangas [Wed, 11 Apr 2018 20:39:49 +0000 (23:39 +0300)]
Allocate enough shared string memory for stats of auxiliary processes.

This fixes a bug whereby the st_appname, st_clienthostname, and
st_activity_raw fields for auxiliary processes point beyond the end of
their respective shared memory segments. As a result, the application_name
of a backend might show up as the client hostname of an auxiliary process.

Backpatch to v10, where this bug was introduced, when the auxiliary
processes were added to the array.

Author: Edmund Horner
Reviewed-by: Michael Paquier
Discussion: https://www.postgresql.org/message-id/CAMyN-kA7aOJzBmrYFdXcc7Z0NmW%2B5jBaf_m%3D_-77uRNyKC9r%3DA%40mail.gmail.com

6 years agoMake local copy of client hostnames in backend status array.
Heikki Linnakangas [Wed, 11 Apr 2018 20:39:48 +0000 (23:39 +0300)]
Make local copy of client hostnames in backend status array.

The other strings, application_name and query string, were snapshotted to
local memory in pgstat_read_current_status(), but we forgot to do that for
client hostnames. As a result, the client hostname would appear to change in
the local copy, if the client disconnected.

Backpatch to all supported versions.

Author: Edmund Horner
Reviewed-by: Michael Paquier
Discussion: https://www.postgresql.org/message-id/CAMyN-kA7aOJzBmrYFdXcc7Z0NmW%2B5jBaf_m%3D_-77uRNyKC9r%3DA%40mail.gmail.com

6 years agoFix ALTER TABLE .. ATTACH PARTITION ... DEFAULT
Alvaro Herrera [Wed, 11 Apr 2018 18:29:31 +0000 (15:29 -0300)]
Fix ALTER TABLE .. ATTACH PARTITION ... DEFAULT

If the table being attached contained values that contradict the default
partition's partition constraint, it would fail to complain, because
CommandCounterIncrement changes in 4dba331cb3dc coupled with some bogus
coding in the existing ValidatePartitionConstraints prevented the
partition constraint from being validated after all -- or rather, it
caused to constraint to become an empty one, always succeeding.

Fix by not re-reading the OID of the default partition in
ATExecAttachPartition.  To forestall similar problems, revise the
existing code:
* rename routine from ValidatePartitionConstraints() to
  QueuePartitionConstraintValidation, to better represent what it
  actually does.
* add an Assert() to make sure that when queueing a constraint for a
  partition we're not overwriting a constraint previously queued.
* add an Assert() that we don't try to invoke the special-purpose
  validation of the default partition when attaching the default
  partition itself.

While at it, change some loops to obtain partition OIDs from
partdesc->oids rather than find_all_inheritors; reduce the lock level
of partitions being scanned from AccessExclusiveLock to ShareLock;
rewrite QueuePartitionConstraintValidation in a recursive fashion rather
than repetitive.

Author: Álvaro Herrera.  Tests written by Amit Langote
Reported-by: Rushabh Lathia
Diagnosed-by: Kyotaro HORIGUCHI, who also provided the initial fix.
Reviewed-by: Kyotaro HORIGUCHI, Amit Langote, Jeevan Ladhe
Discussion: https://postgr.es/m/CAGPqQf0W+v-Ci_qNV_5R3A=Z9LsK4+jO7LzgddRncpp_rrnJqQ@mail.gmail.com

6 years agoInvoke submake-generated-headers during "make check", too.
Tom Lane [Wed, 11 Apr 2018 17:18:50 +0000 (13:18 -0400)]
Invoke submake-generated-headers during "make check", too.

The MAKELEVEL hack to prevent submake-generated-headers from doing
anything in child make runs means that we have to explicitly invoke
it at top level for "make check", too, in case somebody proceeds
directly to that without an explicit "make all".  (I think this
usage had parallel-make hazards even before the addition of more
generated headers; but it was totally broken as of 3b8f6e75f.)

Out of paranoia, force the submake-libpq target to depend on
submake-generated-headers, too.  This seems to not be absolutely
necessary today, but it's not really saving us anything to omit
the ordering dependency, and it'll likely break someday without it.

Discussion: https://postgr.es/m/20180411103930.GB31461@momjian.us

6 years agoTemporary revert 5c6110c6a960ad6fe1b0d0fec6ae36ef4eb913f5
Teodor Sigaev [Wed, 11 Apr 2018 16:32:19 +0000 (19:32 +0300)]
Temporary revert 5c6110c6a960ad6fe1b0d0fec6ae36ef4eb913f5

It discovers one more bug in CompareIndexInfo(), should be fixed first.

6 years agoFix clashing function names between jsonb_plperl and jsonb_plperlu
Peter Eisentraut [Wed, 11 Apr 2018 14:34:53 +0000 (10:34 -0400)]
Fix clashing function names between jsonb_plperl and jsonb_plperlu

This prevented them from being installed at the same time.

Author: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>

6 years agoFix interference between cavering indexes and partitioned tables
Teodor Sigaev [Wed, 11 Apr 2018 13:44:26 +0000 (16:44 +0300)]
Fix interference between cavering indexes and partitioned tables

The bug is caused due to the original IndexStmt that DefineIndex receives
being overwritten when processing the INCLUDE columns. Use separate list of
index params to propagate to child tables. Add tests covering this case.

Amit Langote and Alexander Korotkov.

6 years agodoc: Add more information about logical replication privileges
Peter Eisentraut [Wed, 11 Apr 2018 13:01:57 +0000 (09:01 -0400)]
doc: Add more information about logical replication privileges

In particular, the requirement to have SELECT privilege for the initial
table copy was previously not documented.

Author: Shinoda, Noriyoshi <noriyoshi.shinoda@hpe.com>

6 years agodoc: Fix typos in pgbench documentation
Peter Eisentraut [Wed, 11 Apr 2018 12:34:30 +0000 (08:34 -0400)]
doc: Fix typos in pgbench documentation

Author: Fabien COELHO <coelho@cri.ensmp.fr>
Reviewed-by: Edmund Horner <ejrh00@gmail.com>
6 years agominor comment fixes in nbtinsert.c
Andrew Dunstan [Tue, 10 Apr 2018 22:35:56 +0000 (18:35 -0400)]
minor comment fixes in nbtinsert.c

6 years agoFix incorrect close() call in dsm_impl_mmap().
Tom Lane [Tue, 10 Apr 2018 22:34:40 +0000 (18:34 -0400)]
Fix incorrect close() call in dsm_impl_mmap().

One improbable error-exit path in this function used close() where
it should have used CloseTransientFile().  This is unlikely to be
hit in the field, and I think the consequences wouldn't be awful
(just an elog(LOG) bleat later).  But a bug is a bug, so back-patch
to 9.4 where this code came in.

Pan Bian

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

6 years agoAdjustments to the btree fastpath optimization.
Andrew Dunstan [Tue, 10 Apr 2018 22:21:03 +0000 (18:21 -0400)]
Adjustments to the btree fastpath optimization.

This optimization was introduced in commit 2b272734. The changes include
some additional comments and documentation, and also these more
substantive changes:
. ensure the optimization is only applied on the leaf node of a tree
whose root is on level 2 or more. It's of little value on small trees.
. Delay calling RelationSetTargetBlock() until after the critical
section of _bt_insertonpg
. ensure the optimization is also applied to unlogged tables.

Pavan Deolasee and Peter Geoghegan with some very light editing from me.

Discussion: https://postgr.es/m/CABOikdO8jhRarNC60nZLktZYhxt+TK8z_V97+Ny499YQdyAfug@mail.gmail.com

6 years agoPut back parallel-safety guards in plpython and src/test/regress/.
Tom Lane [Tue, 10 Apr 2018 20:14:55 +0000 (16:14 -0400)]
Put back parallel-safety guards in plpython and src/test/regress/.

I'd hoped that commit 3b8f6e75f was sufficient to ensure parallel safety
even when a build started in a subdirectory requires rebuilding of
generated headers.  This isn't so, because making submake-generated-headers
a prerequisite of "all" isn't enough to ensure it's completed before
starting on "all"'s other prerequisites.  The explicit dependencies we put
on the recursive make targets ensure safe ordering before we recurse into
child directories, but they don't protect targets to be made in the current
directory.  Hence, put back some ordering dependencies in directories that
we've traditionally expected to be starting points for "standalone" builds,
to wit src/pl/plpython and src/test/regress.  (The former needs this in
order to minimize the work involved in building for both python 2 and
python 3; the latter to support packagings that make the regression tests
available for out-of-build-tree execution.)  Adjust some other dependencies
so that these two cases work correctly even at high -j settings.

I'm not terribly happy with this partial solution, but I don't see a
way to do better without massive makefile restructuring, which we surely
aren't doing at this point in the development cycle.  In any case, it's
little if any worse than what we had in prior releases.

Discussion: https://postgr.es/m/1523353963.8169.26.camel@gunduz.org

6 years agoFix IndexOnlyScan counter for heap fetches in parallel mode
Alvaro Herrera [Tue, 10 Apr 2018 18:56:15 +0000 (15:56 -0300)]
Fix IndexOnlyScan counter for heap fetches in parallel mode

The HeapFetches counter was using a simple value in IndexOnlyScanState,
which fails to propagate values from parallel workers; so the counts are
wrong when IndexOnlyScan runs in parallel.  Move it to Instrumentation,
like all the other counters.

While at it, change INSERT ON CONFLICT conflicting tuple counter to use
the new ntuples2 instead of nfiltered2, which is a blatant misuse.

Discussion: https://postgr.es/m/20180409215851.idwc75ct2bzi6tea@alvherre.pgsql

6 years agoFix pgxs.mk to not try to build generated headers in external builds.
Tom Lane [Tue, 10 Apr 2018 16:41:51 +0000 (12:41 -0400)]
Fix pgxs.mk to not try to build generated headers in external builds.

Per Julien Rouhaud and the buildfarm.  This is not quite Julien's
patch: there's no need to lobotomize this build rule when building
contrib modules in-tree, so set NO_GENERATED_HEADERS only if PGXS.

In passing, also set NO_TEMP_INSTALL in external builds.  This doesn't
seem to be fixing any live bug, because "make check" in an external
build just produces the expected error message without first trying to
make a temp install ... but it's far from obvious why it doesn't, so
this change seems like good future-proofing.

Julien Rouhaud and Tom Lane

Discussion: https://postgr.es/m/CAOBaU_YH=g68opbbMk8is3jNwhoXGa8ckRSre1nx0Obe1C7i-Q@mail.gmail.com