]> granicus.if.org Git - postgresql/log
postgresql
7 years agoAvoid pin scan for replay of XLOG_BTREE_VACUUM in all cases
Alvaro Herrera [Thu, 17 Nov 2016 16:31:30 +0000 (13:31 -0300)]
Avoid pin scan for replay of XLOG_BTREE_VACUUM in all cases

Replay of XLOG_BTREE_VACUUM during Hot Standby was previously thought to
require complex interlocking that matched the requirements on the
master. This required an O(N) operation that became a significant
problem with large indexes, causing replication delays of seconds or in
some cases minutes while the XLOG_BTREE_VACUUM was replayed.

This commit skips the “pin scan” that was previously required, by
observing in detail when and how it is safe to do so, with full
documentation. The pin scan is skipped only in replay; the VACUUM code
path on master is not touched here.

No tests included. Manual tests using an additional patch to view WAL records
and their timing have shown the change in WAL records and their handling has
successfully reduced replication delay.

This is a back-patch of commits 687f2cd7a0153e4b7d87988fb60284261375
by Simon Riggs, to branches 9.4 and 9.5.  No further backpatch is
possible because this depends on catalog scans being MVCC.  I (Álvaro)
additionally updated a slight problem in the README, which explains why
this touches the 9.6 and master branches.

7 years agodoc: Further XSLT HTML build performance optimization
Peter Eisentraut [Wed, 16 Nov 2016 20:00:00 +0000 (12:00 -0800)]
doc: Further XSLT HTML build performance optimization

Cut out some expensive stuff from the HTML head element that we don't
really need.

This was previously discussed as part of
e8306745e3504c642f7abad411139d5630e29fac, but ended up separate because
it changes the output contents slightly.

7 years agoBuild HTML documentation using XSLT stylesheets by default
Peter Eisentraut [Tue, 8 Nov 2016 17:00:00 +0000 (12:00 -0500)]
Build HTML documentation using XSLT stylesheets by default

The old DSSSL build is still available for a while using the make target
"oldhtml".

7 years agoCheck that result tupdesc has exactly 1 column in return_next scalar case.
Tom Lane [Tue, 15 Nov 2016 21:48:12 +0000 (16:48 -0500)]
Check that result tupdesc has exactly 1 column in return_next scalar case.

This should always be true, but since we're relying on a tuple descriptor
passed from outside pltcl itself, let's check.  Per a gripe from Coverity.

7 years agoReserve zero as an invalid DSM handle.
Robert Haas [Tue, 15 Nov 2016 21:30:35 +0000 (16:30 -0500)]
Reserve zero as an invalid DSM handle.

Previously, the handle for the control segment could not be zero, but
some other DSM segment could potentially have a handle value of zero.
However, that means that if someone wanted to store a dsm_handle that
might or might not be valid, they would need a separate boolean to
keep track of whether the associated value is legal.  That's annoying,
so change things so that no DSM segment can ever have a handle of 0 -
or as we call it here, DSM_HANDLE_INVALID.

Thomas Munro.  This was submitted as part of a much larger patch to
add an malloc-like allocator for dynamic shared memory, but this part
seems like a good idea independently of the rest of the patch.

7 years agoAllow DOS-style line endings in ~/.pgpass files.
Tom Lane [Tue, 15 Nov 2016 21:17:19 +0000 (16:17 -0500)]
Allow DOS-style line endings in ~/.pgpass files.

On Windows, libc will mask \r\n line endings for us, since we read the
password file in text mode.  But that doesn't happen on Unix.  People
who share password files across both systems might have \r\n line endings
in a file they use on Unix, so as a convenience, ignore trailing \r.
Per gripe from Josh Berkus.

In passing, put the existing check for empty line somewhere where it's
actually useful, ie after stripping the newline not before.

Vik Fearing, adjusted a bit by me

Discussion: <0de37763-5843-b2cc-855e-5d0e5df25807@agliodbs.com>

7 years agoAccount for catalog snapshot in PGXACT->xmin updates.
Tom Lane [Tue, 15 Nov 2016 20:55:35 +0000 (15:55 -0500)]
Account for catalog snapshot in PGXACT->xmin updates.

The CatalogSnapshot was not plugged into SnapshotResetXmin()'s accounting
for whether MyPgXact->xmin could be cleared or advanced.  In normal
transactions this was masked by the fact that the transaction snapshot
would be older, but during backend startup and certain utility commands
it was possible to re-use the CatalogSnapshot after MyPgXact->xmin had
been cleared, meaning that recently-deleted rows could be pruned even
though this snapshot could still see them, causing unexpected catalog
lookup failures.  This effect appears to be the explanation for a recent
failure on buildfarm member piculet.

To fix, add the CatalogSnapshot to the RegisteredSnapshots heap whenever
it is valid.

In the previous logic, it was possible for the CatalogSnapshot to remain
valid across waits for client input, but with this change that would mean
it delays advance of global xmin in cases where it did not before.  To
avoid possibly causing new table-bloat problems with clients that sit idle
for long intervals, add code to invalidate the CatalogSnapshot before
waiting for client input.  (When the backend is busy, it's unlikely that
the CatalogSnapshot would be the oldest snap for very long, so we don't
worry about forcing early invalidation of it otherwise.)

In passing, remove the CatalogSnapshotStale flag in favor of using
"CatalogSnapshot != NULL" to represent validity, as we do for the other
special snapshots in snapmgr.c.  And improve some obsolete comments.

No regression test because I don't know a deterministic way to cause this
failure.  But the stress test shown in the original discussion provokes
"cache lookup failed for relation 1255" within a few dozen seconds for me.

Back-patch to 9.4 where MVCC catalog scans were introduced.  (Note: it's
quite easy to produce similar failures with the same test case in branches
before 9.4.  But MVCC catalog scans were supposed to fix that.)

Discussion: <16447.1478818294@sss.pgh.pa.us>

7 years agoLimit the number of number of tapes used for a sort to 501.
Robert Haas [Tue, 15 Nov 2016 15:28:46 +0000 (10:28 -0500)]
Limit the number of number of tapes used for a sort to 501.

Gigantic numbers of tapes don't work out well.

Original patch by Peter Geoghegan; comments entirely rewritten by me.

7 years agoFix broken statement in UCS_to_most.pl.
Robert Haas [Tue, 15 Nov 2016 14:41:53 +0000 (09:41 -0500)]
Fix broken statement in UCS_to_most.pl.

This has been wrong for a very long time, and it's puzzling to me how
it ever worked for anyone.

Kyotaro Horiguchi

7 years agopgbench: Increase maximum size of log filename from 64 to MAXPGPATH.
Robert Haas [Tue, 15 Nov 2016 14:11:51 +0000 (09:11 -0500)]
pgbench: Increase maximum size of log filename from 64 to MAXPGPATH.

Commit 41124a91e61fc6d9681c1e8b15ba30494e84d643 allowed the
transaction log file prefix to be changed but left in place the
existing 64-character limit on the total length of a log file name.
It's possible that could be inconvenient for somebody, so increase the
limit to MAXPGPATH, which ought to be enough for anybody.

Per a suggestion from Tom Lane.

7 years agoProvide NO_INSTALLCHECK option for pgxs.
Andres Freund [Mon, 14 Nov 2016 22:53:07 +0000 (14:53 -0800)]
Provide NO_INSTALLCHECK option for pgxs.

This allows us to avoid running the regression tests in contrib modules
like pg_stat_statement in a less ugly manner.

Discussion: <22432.1478968242@sss.pgh.pa.us>

7 years agoFix typo in comment
Magnus Hagander [Mon, 14 Nov 2016 16:31:35 +0000 (17:31 +0100)]
Fix typo in comment

The function was renamed in 908e23473, but the comment never learned
about it.

7 years agoAllow individual TAP tests to be run via PROVE_TESTS
Peter Eisentraut [Mon, 14 Nov 2016 17:00:00 +0000 (12:00 -0500)]
Allow individual TAP tests to be run via PROVE_TESTS

Add a new optional Makefile variable PROVE_TESTS that, if passed as a
space-separated list of paths relative to the Makefile invoking
$(prove_check) or $(prove_installcheck), runs just those tests instead
of t/*.pl .

From: Craig Ringer <craig@2ndquadrant.com>
Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agoFix duplication in ALTER MATERIALIZE VIEW synopsis
Alvaro Herrera [Mon, 14 Nov 2016 14:14:34 +0000 (11:14 -0300)]
Fix duplication in ALTER MATERIALIZE VIEW synopsis

Commit 3c4cf080879b should have removed SET TABLESPACE from the synopsis
of ALTER MATERIALIZE VIEW as a possible "action" when it added a
separate line for it in the main command listing, but failed to.
Repair.

Backpatch to 9.4, like the aforementioned commit.

7 years agopg_upgrade: Upgrade sequence data via pg_dump
Peter Eisentraut [Tue, 23 Aug 2016 16:00:00 +0000 (12:00 -0400)]
pg_upgrade: Upgrade sequence data via pg_dump

Previously, pg_upgrade migrated sequence data like tables by copying the
on-disk file.  This does not allow any changes in the on-disk format for
sequences.  It's simpler to just have pg_dump set the new sequence
values as it normally does.  To do that, create a hidden submode in
pg_dump that dumps sequence data even when a schema-only dump is
requested, and trigger that submode in binary upgrade mode.  (This new
submode could easily be exposed as a command-line option, but it has
limited use outside of pg_dump and would probably cause some confusion,
so we don't do that at this time.)

Reviewed-by: Anastasia Lubennikova <a.lubennikova@postgrespro.ru>
Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agopg_dump: Separate table and sequence data object types
Peter Eisentraut [Tue, 23 Aug 2016 16:00:00 +0000 (12:00 -0400)]
pg_dump: Separate table and sequence data object types

Instead of handling both sequence data and table data internally as
"table data", handle sequences separately under a "sequence set" type.
We already handled materialized view data differently, so it makes the
code somewhat cleaner to handle each relation kind separately at the top
level.

This does not change the output format, since there already was a
separate "SEQUENCE SET" archive entry type.  A noticeable difference is
that SEQUENCE SET entries now always appear after TABLE DATA entries.
And in parallel mode there is less sorting to do, because the sequence
data entries are no longer considered table data.

Reviewed-by: Anastasia Lubennikova <a.lubennikova@postgrespro.ru>
Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agoDoc: remove obsolete example.
Tom Lane [Sun, 13 Nov 2016 18:12:35 +0000 (13:12 -0500)]
Doc: remove obsolete example.

The documentation for ts_headline() recommends using a sub-select to
avoid extra evaluations of ts_headline() in a query with ORDER BY+LIMIT.
Since commit 9118d03a8 this contortionism is unnecessary, so remove the
recommendation.  Noted by Oleg Bartunov.

Discussion: <CAF4Au4w6rrH_j1bvVhzpOsRiHCog7sGJ3LSX0tY8ZdwhHT88LQ@mail.gmail.com>

7 years agopg_stat_statements: Add .gitignore file for tests
Peter Eisentraut [Sun, 13 Nov 2016 17:00:00 +0000 (12:00 -0500)]
pg_stat_statements: Add .gitignore file for tests

7 years agoAdd minimal set of regression tests for pg_stat_statements.
Andres Freund [Sat, 12 Nov 2016 13:01:48 +0000 (05:01 -0800)]
Add minimal set of regression tests for pg_stat_statements.

While the set of covered functionality is fairly small, the added tests
still are useful to get some basic buildfarm testing of
pg_stat_statements itself, but also to exercise the lwlock tranch code
on the buildfarm.

Author: Amit Kapila, slightly editorialized by me
Reviewed-By: Ashutosh Sharma, Andres Freund
Discussion: <CAA4eK1JOjkdXYtHxh=2aDK4VgDtN-LNGKY_YqX0N=YEvuzQVWg@mail.gmail.com>

7 years agoDoc: fix data types of FuncCallContext's call_cntr and max_calls fields.
Tom Lane [Fri, 11 Nov 2016 17:03:49 +0000 (12:03 -0500)]
Doc: fix data types of FuncCallContext's call_cntr and max_calls fields.

Commit 23a27b039 widened these from uint32 to uint64, but I overlooked
that the documentation explicitly showed them as uint32.  Per report
from Vicky Vergara.

Report: <20161111135422.8761.36733@wrigleys.postgresql.org>

7 years agoCleanup of rewriter and planner handling of Query.hasRowSecurity flag.
Tom Lane [Thu, 10 Nov 2016 21:16:33 +0000 (16:16 -0500)]
Cleanup of rewriter and planner handling of Query.hasRowSecurity flag.

Be sure to pull up the subquery's hasRowSecurity flag when flattening a
subquery in pull_up_simple_subquery().  This isn't a bug today because
we don't look at the hasRowSecurity flag during planning, but it could
easily be a bug tomorrow.

Likewise, make rewriteRuleAction() pull up the hasRowSecurity flag when
absorbing RTEs from a rule action.  This isn't a bug either, for the
opposite reason: the flag should never be set yet.  But again, it seems
like good future proofing.

Add a comment explaining why rewriteTargetView() should *not* set
hasRowSecurity when adding stuff to securityQuals.

Improve some nearby comments about securityQuals processing, and document
that field more completely in parsenodes.h.

Patch by me, analysis by Dean Rasheed.

Discussion: <CAEZATCXZ8tb2DV6f=bkhsMV6u_gRcZ0CZBw2J-qU84RxSukZog@mail.gmail.com>

7 years agoRe-allow user_catalog_table option for materialized views.
Tom Lane [Thu, 10 Nov 2016 20:00:58 +0000 (15:00 -0500)]
Re-allow user_catalog_table option for materialized views.

The reloptions stuff allows this option to be set on a matview.
While it's questionable whether that is useful or was really intended,
it does work, and we shouldn't change that in minor releases.  Commit
e3e66d8a9 disabled the option since I didn't realize that it was
possible for it to be set on a matview.  Tweak the test to re-allow it.

Discussion: <19749.1478711862@sss.pgh.pa.us>

7 years agoSupport "COPY view FROM" for views with INSTEAD OF INSERT triggers.
Tom Lane [Thu, 10 Nov 2016 19:13:43 +0000 (14:13 -0500)]
Support "COPY view FROM" for views with INSTEAD OF INSERT triggers.

We just pass the data to the INSTEAD trigger.

Haribabu Kommi, reviewed by Dilip Kumar

Patch: <CAJrrPGcSQkrNkO+4PhLm4B8UQQQmU9YVUuqmtgM=pmzMfxWaWQ@mail.gmail.com>

7 years agoFix partial aggregation for the case of a degenerate GROUP BY clause.
Tom Lane [Thu, 10 Nov 2016 16:31:56 +0000 (11:31 -0500)]
Fix partial aggregation for the case of a degenerate GROUP BY clause.

The plan generated for sorted partial aggregation with "GROUP BY constant"
included a Sort node with no sort keys, which the executor does not like.

Per report from Steve Randall.  I'd add a regression test case if I could
think of a compact one, but it doesn't seem worth expending lots of cycles
on.

Report: <CABVd52UAdGXpg_rCk46egpNKYdXOzCjuJ1zG26E2xBe_8bj+Fg@mail.gmail.com>

7 years agoDoc: improve link.
Tom Lane [Thu, 10 Nov 2016 15:37:14 +0000 (10:37 -0500)]
Doc: improve link.

Discussion: <5019.1478790246@sss.pgh.pa.us>

7 years agopgbench: Allow the transaction log file prefix to be changed.
Robert Haas [Wed, 9 Nov 2016 21:26:32 +0000 (16:26 -0500)]
pgbench: Allow the transaction log file prefix to be changed.

Masahiko Sawada, reviewed by Fabien Coelho and Beena Emerson, with
some a bit of wordsmithing and cosmetic adjustment by me.

7 years agodoc: Improve whitespace use in XSL
Peter Eisentraut [Wed, 9 Nov 2016 17:00:00 +0000 (12:00 -0500)]
doc: Improve whitespace use in XSL

7 years agoSimplify code by getting rid of SPI_push, SPI_pop, SPI_restore_connection.
Tom Lane [Tue, 8 Nov 2016 22:39:45 +0000 (17:39 -0500)]
Simplify code by getting rid of SPI_push, SPI_pop, SPI_restore_connection.

The idea behind SPI_push was to allow transitioning back into an
"unconnected" state when a SPI-using procedure calls unrelated code that
might or might not invoke SPI.  That sounds good, but in practice the only
thing it does for us is to catch cases where a called SPI-using function
forgets to call SPI_connect --- which is a highly improbable failure mode,
since it would be exposed immediately by direct testing of said function.
As against that, we've had multiple bugs induced by forgetting to call
SPI_push/SPI_pop around code that might invoke SPI-using functions; these
are much harder to catch and indeed have gone undetected for years in some
cases.  And we've had to band-aid around some problems of this ilk by
introducing conditional push/pop pairs in some places, which really kind
of defeats the purpose altogether; if we can't draw bright lines between
connected and unconnected code, what's the point?

Hence, get rid of SPI_push[_conditional], SPI_pop[_conditional], and the
underlying state variable _SPI_curid.  It turns out SPI_restore_connection
can go away too, which is a nice side benefit since it was never more than
a kluge.  Provide no-op macros for the deleted functions so as to avoid an
API break for external modules.

A side effect of this removal is that SPI_palloc and allied functions no
longer permit being called when unconnected; they'll throw an error
instead.  The apparent usefulness of the previous behavior was a mirage
as well, because it was depended on by only a few places (which I fixed in
preceding commits), and it posed a risk of allocations being unexpectedly
long-lived if someone forgot a SPI_push call.

Discussion: <20808.1478481403@sss.pgh.pa.us>

7 years agopsql: Tab completion for renaming enum values.
Robert Haas [Tue, 8 Nov 2016 21:27:09 +0000 (16:27 -0500)]
psql: Tab completion for renaming enum values.

For ALTER TYPE .. RENAME, add "VALUE" to the list of possible
completions.  Complete ALTER TYPE .. RENAME VALUE with possible
enum values.  After that, complete with "TO".

Dagfinn Ilmari Mannsåker, reviewed by Artur Zakirov.

7 years agoReplace uses of SPI_modifytuple that intend to allocate in current context.
Tom Lane [Tue, 8 Nov 2016 20:36:36 +0000 (15:36 -0500)]
Replace uses of SPI_modifytuple that intend to allocate in current context.

Invent a new function heap_modify_tuple_by_cols() that is functionally
equivalent to SPI_modifytuple except that it always allocates its result
by simple palloc.  I chose however to make the API details a bit more
like heap_modify_tuple: pass a tupdesc rather than a Relation, and use
bool convention for the isnull array.

Use this function in place of SPI_modifytuple at all call sites where the
intended behavior is to allocate in current context.  (There actually are
only two call sites left that depend on the old behavior, which makes me
wonder if we should just drop this function rather than keep it.)

This new function is easier to use than heap_modify_tuple() for purposes
of replacing a single column (or, really, any fixed number of columns).
There are a number of places where it would simplify the code to change
over, but I resisted that temptation for the moment ... everywhere except
in plpgsql's exec_assign_value(); changing that might offer some small
performance benefit, so I did it.

This is on the way to removing SPI_push/SPI_pop, but it seems like
good code cleanup in its own right.

Discussion: <9633.1478552022@sss.pgh.pa.us>

7 years agoFix typo.
Robert Haas [Tue, 8 Nov 2016 20:33:57 +0000 (15:33 -0500)]
Fix typo.

Michael Paquier

7 years agoMake SPI_fnumber() reject dropped columns.
Tom Lane [Tue, 8 Nov 2016 18:11:15 +0000 (13:11 -0500)]
Make SPI_fnumber() reject dropped columns.

There's basically no scenario where it's sensible for this to match
dropped columns, so put a test for dropped-ness into SPI_fnumber()
itself, and excise the test from the small number of callers that
were paying attention to the case.  (Most weren't :-(.)

In passing, normalize tests at call sites: always reject attnum <= 0
if we're disallowing system columns.  Previously there was a mixture
of "< 0" and "<= 0" tests.  This makes no practical difference since
SPI_fnumber() never returns 0, but I'm feeling pedantic today.

Also, in the places that are actually live user-facing code and not
legacy cruft, distinguish "column not found" from "can't handle
system column".

Per discussion with Jim Nasby; thi supersedes his original patch
that just changed the behavior at one call site.

Discussion: <b2de8258-c4c0-1cb8-7b97-e8538e5c975c@BlueTreble.com>

7 years agoFix typo
Magnus Hagander [Tue, 8 Nov 2016 17:34:59 +0000 (18:34 +0100)]
Fix typo

7 years agoFix mistake in XLOG_SEG_SIZE test.
Robert Haas [Tue, 8 Nov 2016 17:09:18 +0000 (12:09 -0500)]
Fix mistake in XLOG_SEG_SIZE test.

The intent of the test is to check whether XLOG_SEG_SIZE is in a
particular range, but actually in one case it compares XLOG_BLCKSZ
by mistake.  Repair.

Commit 88e982302684246e8af785e78a467ac37c76dee9 introduced this
faulty test.

Kuntal Ghosh, reviewed by Michael Paquier.

7 years agoUse heap_modify_tuple not SPI_modifytuple in pl/python triggers.
Tom Lane [Tue, 8 Nov 2016 17:00:24 +0000 (12:00 -0500)]
Use heap_modify_tuple not SPI_modifytuple in pl/python triggers.

The code here would need some change anyway given planned change in
SPI_modifytuple semantics, since this executes after we've exited the
SPI environment.  But really it's better to just use heap_modify_tuple.

While at it, normalize use of SPI_fnumber: make error messages distinguish
no-such-column from can't-set-system-column, and remove test for deleted
column which is going to migrate into SPI_fnumber.  The lack of a check
for system column names is actually a pre-existing bug here, and might
even qualify as a security bug except that we don't have any trusted
version of plpython.

7 years agoUse heap_modify_tuple not SPI_modifytuple in pl/perl triggers.
Tom Lane [Tue, 8 Nov 2016 16:35:01 +0000 (11:35 -0500)]
Use heap_modify_tuple not SPI_modifytuple in pl/perl triggers.

The code here would need some change anyway given planned change in
SPI_modifytuple semantics, since this executes after we've exited the
SPI environment.  But really it's better to just use heap_modify_tuple.
The code's actually shorter this way, and this avoids depending on some
rather indirect reasoning about why the temporary arrays can't be overrun.
(I think the old code is safe, as long as Perl hashes can't contain
duplicate keys; but with this way we don't need that assumption, only
the assumption that SPI_fnumber doesn't return an out-of-range attnum.)

While at it, normalize use of SPI_fnumber: make error messages distinguish
no-such-column from can't-set-system-column, and remove test for deleted
column which is going to migrate into SPI_fnumber.

7 years agoImprove handling of dead tuples in hash indexes.
Robert Haas [Tue, 8 Nov 2016 15:47:52 +0000 (10:47 -0500)]
Improve handling of dead tuples in hash indexes.

When squeezing a bucket during vacuum, it's not necessary to retain
any tuples already marked as dead, so ignore them when deciding which
tuples must be moved in order to empty a bucket page.  Similarly, when
splitting a bucket, relocating dead tuples to the new bucket is a
waste of effort; instead, just ignore them.

Amit Kapila, reviewed by me.  Testing help provided by Ashutosh
Sharma.

7 years agoChange qr/foo$/m to qr/foo\n/m, for Perl 5.8.8.
Noah Misch [Tue, 8 Nov 2016 01:27:30 +0000 (20:27 -0500)]
Change qr/foo$/m to qr/foo\n/m, for Perl 5.8.8.

In each case, absence of a trailing newline would itself constitute a
PostgreSQL bug.  Therefore, this slightly enhances the changed tests.
This works around a bug that last appeared in Perl 5.8.8, fixing
src/test/modules/test_pg_dump when run against that version.  Commit
e7293e3271bf618eeb2d4779a15fc516a69fe463 worked around the bug, but the
subsequent addition of test_pg_dump introduced affected code.  As that
commit had shown, slight increases in pattern complexity can suppress
the bug.  This commit edits qr/foo$/m patterns too complex to encounter
the bug today, for style consistency and robustness against unrelated
pattern changes.  Back-patch to 9.6, where test_pg_dump was introduced.

As of this writing, a fresh MSYS installation includes an affected Perl
5.8.8.  The Perl 5.8.8 in Red Hat Enterprise Linux 5.11 carries a patch
that renders it unaffected, but the Perl 5.8.5 of Red Hat Enterprise
Linux 4.4 is affected.

7 years agoBand-aid fix for incorrect use of view options as StdRdOptions.
Tom Lane [Mon, 7 Nov 2016 17:08:18 +0000 (12:08 -0500)]
Band-aid fix for incorrect use of view options as StdRdOptions.

We really ought to make StdRdOptions and the other decoded forms of
reloptions self-identifying, but for the moment, assume that only plain
relations could possibly be user_catalog_tables.  Fixes problem with bogus
"ON CONFLICT is not supported on table ... used as a catalog table" error
when target is a view with cascade option.

Discussion: <26681.1477940227@sss.pgh.pa.us>

7 years agoRevert "Delete contrib/xml2's legacy implementation of xml_is_well_formed()."
Tom Lane [Mon, 7 Nov 2016 15:27:52 +0000 (10:27 -0500)]
Revert "Delete contrib/xml2's legacy implementation of xml_is_well_formed()."

This partly reverts commit 20540710e83f2873707c284a0c0693f0b57156c4.
Since we've given up on adding PGDLLEXPORT markers to PG_FUNCTION_INFO_V1,
there's no need to remove the legacy compatibility function.  I kept the
documentation changes, though, as they seem appropriate anyway.

7 years agoRevert "Provide DLLEXPORT markers for C functions via PG_FUNCTION_INFO_V1 macro."
Tom Lane [Mon, 7 Nov 2016 15:19:22 +0000 (10:19 -0500)]
Revert "Provide DLLEXPORT markers for C functions via PG_FUNCTION_INFO_V1 macro."

This reverts commit c8ead2a3974d3eada145a0e18940150039493cc9.
Seems there is no way to do this that doesn't cause MSVC to give
warnings, so let's just go back to the way we've been doing it.

Discussion: <11843.1478358206@sss.pgh.pa.us>

7 years agopg_upgrade: Add NLS
Peter Eisentraut [Fri, 14 Oct 2016 16:00:00 +0000 (12:00 -0400)]
pg_upgrade: Add NLS

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agopg_rewing pg_upgrade: Fix translation markers
Peter Eisentraut [Mon, 7 Nov 2016 17:00:00 +0000 (12:00 -0500)]
pg_rewing pg_upgrade: Fix translation markers

In pg_log_v(), we need to translate the fmt before processing, not the
formatted message afterwards.

7 years agoSave redundant code for pseudotype I/O functions
Peter Eisentraut [Thu, 27 Oct 2016 16:00:00 +0000 (12:00 -0400)]
Save redundant code for pseudotype I/O functions

Use a macro to generate the in and out functions for pseudotypes that
reject all input and output, saving many lines of redundant code.
Parameterize the error messages to reduce translatable strings.

7 years agoSync pltcl_build_tuple_result's error handling with pltcl_trigger_handler.
Tom Lane [Mon, 7 Nov 2016 00:22:12 +0000 (19:22 -0500)]
Sync pltcl_build_tuple_result's error handling with pltcl_trigger_handler.

Meant to do this in 26abb50c4, but forgot.

7 years agoSupport PL/Tcl functions that return composite types and/or sets.
Tom Lane [Sun, 6 Nov 2016 22:56:05 +0000 (17:56 -0500)]
Support PL/Tcl functions that return composite types and/or sets.

Jim Nasby, rather heavily editorialized by me

Patch: <f2134651-14b3-efeb-f274-c69f3c084031@BlueTreble.com>

7 years agoModernize result-tuple construction in pltcl_trigger_handler().
Tom Lane [Sun, 6 Nov 2016 21:09:57 +0000 (16:09 -0500)]
Modernize result-tuple construction in pltcl_trigger_handler().

Use Tcl_ListObjGetElements instead of Tcl_SplitList.  Aside from being
possibly more efficient in its own right, this means we are no longer
responsible for freeing a malloc'd result array, so we can get rid of
a PG_TRY/PG_CATCH block.

Use heap_form_tuple instead of SPI_modifytuple.  We don't need the
extra generality of the latter, since we're always replacing all
columns.  Nor do we need its memory-context-munging, since at this
point we're already out of the SPI environment.

Per comparison of this code to tuple-building code submitted by Jim Nasby.
I've abandoned the thought of merging the two cases into a single routine,
but we may as well make the older code simpler and faster where we can.

7 years agoRationalize and document pltcl's handling of magic ".tupno" array element.
Tom Lane [Sun, 6 Nov 2016 19:43:13 +0000 (14:43 -0500)]
Rationalize and document pltcl's handling of magic ".tupno" array element.

For a very long time, pltcl's spi_exec and spi_execp commands have had
a behavior of storing the current row number as an element of output
arrays, but this was never documented.  Fix that.

For an equally long time, pltcl_trigger_handler had a behavior of silently
ignoring ".tupno" as an output column name, evidently so that the result
of spi_exec could be used directly as a trigger result tuple.  Not sure
how useful that really is, but in any case it's bad that it would break
attempts to use ".tupno" as an actual column name.  We can fix it by not
checking for ".tupno" until after we check for a column name match.  This
comports with the effective behavior of spi_exec[p] that ".tupno" is only
magic when you don't have an actual column named that.

In passing, wordsmith the description of returning modified tuples from
a pltcl trigger.

Noted while working on Jim Nasby's patch to support composite results
from pltcl.  The inability to return trigger tuples using ".tupno" as
a column name is a bug, so back-patch to all supported branches.

7 years agoNeed to do SPI_push/SPI_pop around expression evaluation in plpgsql.
Tom Lane [Sun, 6 Nov 2016 17:09:36 +0000 (12:09 -0500)]
Need to do SPI_push/SPI_pop around expression evaluation in plpgsql.

We must do this in case the expression evaluation results in calling
another plpgsql function (or, really, anything using SPI).  I missed
the need for this when I converted exec_cast_value() from doing a
simple InputFunctionCall() to doing ExecEvalExpr() in commit 1345cc67b.
There is a SPI_push_conditional in InputFunctionCall(), so that there
was no bug before that.

Per bug #14414 from Marcos Castedo.  Add a regression test based on his
example, which was that a plpgsql function in a domain check constraint
didn't work when assigning to a domain-type variable within plpgsql.

Report: <20161106010947.1387.66380@wrigleys.postgresql.org>

7 years agoFix silly nil-pointer-dereference bug introduced in commit d5f6f13f8.
Tom Lane [Sun, 6 Nov 2016 16:29:40 +0000 (11:29 -0500)]
Fix silly nil-pointer-dereference bug introduced in commit d5f6f13f8.

Don't fetch record->xl_info before we've verified that record isn't
NULL.  Per Coverity.

Michael Paquier

7 years agoMore zic cleanup.
Tom Lane [Sun, 6 Nov 2016 15:45:58 +0000 (10:45 -0500)]
More zic cleanup.

The workaround the IANA guys chose to get rid of the clang warning
we'd silenced in commit 23ed2ba81 turns out not to satisfy Coverity.
Go back to the previous solution, ie, remove the useless comparison
to SIZE_MAX.  (In principle, there could be machines out there where
it's not useless because ptrdiff_t is wider than size_t.  But the whole
thing is pretty academic anyway, as we could never approach this limit
for any sane estimate of the amount of data that zic will ever be asked
to work with.)

Also, s/lineno/lineno_t/g, because if we accept their decision to start
using "lineno" as a typedef, it is going to have very unpleasant
consequences in our next pgindent run.  Noted that while fooling with
pltcl yesterday.

7 years agoImprove minor error-handling details in pltcl.
Tom Lane [Sat, 5 Nov 2016 21:32:29 +0000 (17:32 -0400)]
Improve minor error-handling details in pltcl.

Don't ask Tcl_GetIndexFromObj to store an error message in the interpreter
in cases where the next argument isn't necessarily one of the options
we're asking it to check for.  At best that is a waste of time, and at
worst it might cause an inappropriate error result to get left behind.

Be sure to check for valid syntax (ie, no command arguments) in
pltcl_SPI_lastoid.

Extracted from a larger and otherwise-unrelated patch.

Jim Nasby

Patch: <f2134651-14b3-efeb-f274-c69f3c084031@BlueTreble.com>

7 years agoAdjust cost_merge_append() to reflect use of binaryheap_replace_first().
Tom Lane [Sat, 5 Nov 2016 17:48:11 +0000 (13:48 -0400)]
Adjust cost_merge_append() to reflect use of binaryheap_replace_first().

Commit 7a2fe9bd0 improved merge append so that replacement of a tuple
takes log(N) operations, not twice log(N).  Since cost_merge_append knew
about that explicitly, we should adjust it.  This probably makes little
difference in practice, but the obsolete comment is confusing.

Ideally this would have been put in in 9.3 with the underlying behavior
change; but I'm not going to back-patch it, since there's some small chance
of changing a plan choice that somebody's optimized for.

Thomas Munro

Discussion: <CAEepm=0WQBSvuYcMOUj4Ga4NXpu2J=ejZcE=e=eiTjTX-6_gDw@mail.gmail.com>

7 years agoRemove duplicate macro definition.
Tom Lane [Sat, 5 Nov 2016 15:51:46 +0000 (11:51 -0400)]
Remove duplicate macro definition.

Seems to be a copy-and-pasteo.  Odd that we heard no reports of
compiler warnings about it.

Thomas Munro

7 years agopgwin32_is_junction's argument should be "const char *" not "char *".
Tom Lane [Sat, 5 Nov 2016 15:14:10 +0000 (11:14 -0400)]
pgwin32_is_junction's argument should be "const char *" not "char *".

We're passing const strings to it in places, and that's not an
unreasonable thing to do.  Per buildfarm (noted on frogmouth
in particular).

7 years agodoc: Don't reformat .fo files before processing by fop
Peter Eisentraut [Fri, 4 Nov 2016 16:00:00 +0000 (12:00 -0400)]
doc: Don't reformat .fo files before processing by fop

This messes up the whitespace in the output PDF document in some places.

7 years agodoc: Port page header customizations to XSLT
Peter Eisentraut [Fri, 4 Nov 2016 16:00:00 +0000 (12:00 -0400)]
doc: Port page header customizations to XSLT

7 years agoProvide DLLEXPORT markers for C functions via PG_FUNCTION_INFO_V1 macro.
Tom Lane [Fri, 4 Nov 2016 23:04:56 +0000 (19:04 -0400)]
Provide DLLEXPORT markers for C functions via PG_FUNCTION_INFO_V1 macro.

Second try at the change originally made in commit 8518583cd;
this time with contrib updates so that manual extern declarations
are also marked with PGDLLEXPORT.  The release notes should point
this out as a significant source-code change for extension authors,
since they'll have to make similar additions to avoid trouble on Windows.

Laurenz Albe, doc change by me

Patch: <A737B7A37273E048B164557ADEF4A58B53962ED8@ntex2010a.host.magwien.gv.at>

7 years agoDelete contrib/xml2's legacy implementation of xml_is_well_formed().
Tom Lane [Fri, 4 Nov 2016 22:29:53 +0000 (18:29 -0400)]
Delete contrib/xml2's legacy implementation of xml_is_well_formed().

This function is unreferenced in modern usage; it was superseded in 9.1
by a core function of the same name.  It has been left in place in the C
code only so that pre-9.1 SQL definitions of the contrib/xml2 functions
would continue to work.  Six years seems like enough time for people to
have updated to the extension-style version of the xml2 module, so let's
drop this.

The key reason for not keeping it any longer is that we want to stick
an explicit PGDLLEXPORT into PG_FUNCTION_INFO_V1(), and the similarity
of name to the core function creates a conflict that compilers will
complain about.

Extracted from a larger patch for that purpose.  I'm committing this
change separately to give it more visibility in the commit logs.

While at it, remove the documentation entry that claimed that
xml_is_well_formed() is a function provided by contrib/xml2, and
instead mention the even more ancient alias xml_valid().

Laurenz Albe, doc change by me

Patch: <A737B7A37273E048B164557ADEF4A58B53962ED8@ntex2010a.host.magwien.gv.at>

7 years agoBe more consistent about masking xl_info with ~XLR_INFO_MASK.
Tom Lane [Fri, 4 Nov 2016 17:26:49 +0000 (13:26 -0400)]
Be more consistent about masking xl_info with ~XLR_INFO_MASK.

Generally, WAL resource managers are only supposed to examine the
top 4 bits of a WAL record's xl_info; the rest are reserved for
the WAL mechanism itself.  A few places were not consistent about
doing this with respect to XLOG_CHECKPOINT and XLOG_SWITCH records.
There's no bug currently, since no additional bits ever get set in
these specific record types, but that might not be true forever.
Let's follow the generic coding rule here too.

Michael Paquier

7 years agoFix gin_leafpage_items().
Tom Lane [Fri, 4 Nov 2016 16:11:47 +0000 (12:11 -0400)]
Fix gin_leafpage_items().

On closer inspection, commit 84ad68d64 broke gin_leafpage_items(),
because the aligned copy of the page got palloc'd in a short-lived
context whereas it needs to be in the SRF's multi_call_memory_ctx.
This was not exposed by the regression test, because the regression
test doesn't actually exercise the function in a meaningful way.
Fix the code bug, and extend the test in what I hope is a portable
fashion.

7 years agoImprove tab completion for CREATE TRIGGER.
Kevin Grittner [Fri, 4 Nov 2016 16:02:07 +0000 (11:02 -0500)]
Improve tab completion for CREATE TRIGGER.

This includes support for the new REFERENCING clause.

7 years agoImplement syntax for transition tables in AFTER triggers.
Kevin Grittner [Fri, 4 Nov 2016 15:49:50 +0000 (10:49 -0500)]
Implement syntax for transition tables in AFTER triggers.

This is infrastructure for the complete SQL standard feature.  No
support is included at this point for execution nodes or PLs.  The
intent is to add that soon.

As this patch leaves things, standard syntax can create tuplestores
to contain old and/or new versions of rows affected by a statement.
References to these tuplestores are in the TriggerData structure.
C triggers can access the tuplestores directly, so they are usable,
but they cannot yet be referenced within a SQL statement.

7 years agopg_xlogdump: Add NLS
Peter Eisentraut [Sat, 15 Oct 2016 16:00:00 +0000 (12:00 -0400)]
pg_xlogdump: Add NLS

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agopg_test_timing: Add NLS
Peter Eisentraut [Fri, 14 Oct 2016 16:00:00 +0000 (12:00 -0400)]
pg_test_timing: Add NLS

Also straighten out use of time unit abbreviations a bit.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agopg_test_fsync: Add NLS
Peter Eisentraut [Fri, 14 Oct 2016 16:00:00 +0000 (12:00 -0400)]
pg_test_fsync: Add NLS

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agopg_archivecleanup: Add NLS
Peter Eisentraut [Fri, 14 Oct 2016 16:00:00 +0000 (12:00 -0400)]
pg_archivecleanup: Add NLS

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
7 years agopageinspect: Fix unaligned struct access in GIN functions
Peter Eisentraut [Fri, 4 Nov 2016 16:00:00 +0000 (12:00 -0400)]
pageinspect: Fix unaligned struct access in GIN functions

The raw page data that is passed into the functions will not be aligned
at 8-byte boundaries.  Casting that to a struct and accessing int64
fields will result in unaligned access.  On most platforms, you get away
with it, but it will result on a crash on pickier platforms such as ia64
and sparc64.

7 years agoAdd API to check if an existing exclusive lock allows cleanup.
Robert Haas [Fri, 4 Nov 2016 13:27:49 +0000 (09:27 -0400)]
Add API to check if an existing exclusive lock allows cleanup.

LockBufferForCleanup() acquires a cleanup lock unconditionally, and
ConditionalLockBufferForCleanup() acquires a cleanup lock if it is
possible to do so without waiting; this patch adds a new API,
IsBufferCleanupOK(), which tests whether an exclusive lock already
held happens to be a cleanup lock.  This is possible because a cleanup
lock simply means an exclusive lock plus the assurance any other pins
on the buffer are newer than our own pin.  Therefore, just as the
existing functions decide that the exclusive lock that they've just
taken is a cleanup lock if they observe the pin count to be 1, this
new function allows us to observe that the pin count is 1 on a buffer
we've already locked.

This is useful in situations where a backend definitely wishes to
modify the buffer and also wishes to perform cleanup operations if
possible.  The patch to eliminate heavyweight locking by hash indexes
uses this, and it may have other applications as well.

Amit Kapila, per a suggestion from me.  Some comment adjustments by me
as well.

7 years agopostgres_fdw: Fix typo in comment.
Robert Haas [Fri, 4 Nov 2016 13:03:42 +0000 (09:03 -0400)]
postgres_fdw: Fix typo in comment.

Etsuro Fujita

7 years agodoc: Add index letter links to XSLT HTML build
Peter Eisentraut [Thu, 3 Nov 2016 16:00:00 +0000 (12:00 -0400)]
doc: Add index letter links to XSLT HTML build

This matches what was already implemented in the DSSSL HTML build.

7 years agoSync our copy of the timezone library with IANA tzcode master.
Tom Lane [Fri, 4 Nov 2016 02:24:34 +0000 (22:24 -0400)]
Sync our copy of the timezone library with IANA tzcode master.

This patch absorbs some unreleased fixes for symlink manipulation bugs
introduced in tzcode 2016g.  Ordinarily I'd wait around for a released
version, but in this case it seems like we could do with extra testing,
in particular checking whether it works in EDB's VMware build environment.
This corresponds to commit aec59156abbf8472ba201b6c7ca2592f9c10e077 in
https://github.com/eggert/tz.

Per a report from Sandeep Thakkar, building in an environment where hard
links are not supported in the timezone data installation directory failed,
because upstream code refactoring had broken the case of symlinking from an
existing symlink.  Further experimentation also showed that the symlinks
were sometimes made incorrectly, with too many or too few "../"'s in the
symlink contents.

This should get back-patched, but first let's see what the buildfarm
makes of it.  I'm not too sure about the new dependency on linkat(2).

Report: <CANFyU94_p6mqRQc2i26PFp5QAOQGB++AjGX=FO8LDpXw0GSTjw@mail.gmail.com>
Discussion: http://mm.icann.org/pipermail/tz/2016-November/024431.html

7 years agopsql: Split up "Modifiers" column in \d and \dD
Peter Eisentraut [Thu, 3 Nov 2016 16:00:00 +0000 (12:00 -0400)]
psql: Split up "Modifiers" column in \d and \dD

Make separate columns "Collation", "Nullable", "Default".

Reviewed-by: Kuntal Ghosh <kuntalghosh.2007@gmail.com>
7 years agopsql: Tab-complete LOCK [TABLE] ... IN {ACCESS|ROW|SHARE}.
Robert Haas [Thu, 3 Nov 2016 15:42:13 +0000 (11:42 -0400)]
psql: Tab-complete LOCK [TABLE] ... IN {ACCESS|ROW|SHARE}.

Suggest the lock modes that begin with the word in question.

Thomas Munro, reviewed by Marllius Ribeiro.  Comments tweaked by me.

7 years agoUse NIL instead of NULL for an empty List.
Robert Haas [Thu, 3 Nov 2016 15:24:01 +0000 (11:24 -0400)]
Use NIL instead of NULL for an empty List.

Tatsuro Yamada, reviewed by Ashutosh Bapat

7 years agolibpq: Allow connection strings and URIs to specify multiple hosts.
Robert Haas [Thu, 3 Nov 2016 13:25:20 +0000 (09:25 -0400)]
libpq: Allow connection strings and URIs to specify multiple hosts.

It's also possible to specify a separate port for each host.

Previously, we'd loop over every address returned by looking up the
host name; now, we'll try every address for every host name.

Patch by me.  Victor Wagner wrote an earlier patch for this feature,
which I read, but I didn't use any of his code.  Review by Mithun Cy.

7 years agoDon't make FK-based selectivity estimates in inheritance situations.
Tom Lane [Wed, 2 Nov 2016 19:50:15 +0000 (15:50 -0400)]
Don't make FK-based selectivity estimates in inheritance situations.

The foreign-key-aware logic for estimation of join sizes (added in commit
100340e2d) blindly tried to apply the concept to rels that are actually
parents of inheritance trees.  This is just plain wrong so far as the
referenced relation is concerned, since the inheritance scan may well
produce lots of rows that are not participating in the constraint.  It's
wrong for the referencing relation too, for the same reason; although on
that end we could conceivably detect whether all members of the inheritance
tree have equivalent FK constraints pointing to the same referenced rel,
and then proceed more or less as we do now.  But pending somebody writing
code to do that, we must disable this, because it's producing completely
silly estimates when there's an FK linking the heads of inheritance trees.

Per bug #14404 from Clinton Adams.  Back-patch to 9.6 where the new
estimation logic came in.

Report: <20161028200412.15987.96482@wrigleys.postgresql.org>

7 years agoDon't convert Consts into Vars during setrefs.c processing.
Tom Lane [Wed, 2 Nov 2016 18:32:13 +0000 (14:32 -0400)]
Don't convert Consts into Vars during setrefs.c processing.

While converting expressions in an upper-level plan node so that they
reference Vars and expressions provided by the input plan node(s),
don't convert plain Const items, even if there happens to be a matching
Const in the input.  It's silly to do so because a Var is more expensive to
execute than a Const.  Moreover, converting can fool ExecCheckPlanOutput's
check that an insert or update query inserts nulls into dropped columns,
leading to "query provides a value for a dropped column" errors during
INSERT or UPDATE on a table with a dropped column.  We could solve this
by making that check more complicated, but I don't see the point; this fix
should save a marginal number of cycles, and it also makes for less messy
EXPLAIN output, as shown by the ensuing regression test result changes.

Per report from Pavel Hanák.  I have not incorporated a test case based
on that example, as there doesn't seem to be a simple way of checking
this in isolation without making a bunch of assumptions about other
planner and SQL-function behavior.

Back-patch to 9.6.  This setrefs.c behavior exists much further back,
but there is not currently reason to think that it causes problems
before 9.6.

Discussion: <83shraampf.fsf@is-it.eu>

7 years agopageinspect: Make page test more portable
Peter Eisentraut [Tue, 1 Nov 2016 16:00:00 +0000 (12:00 -0400)]
pageinspect: Make page test more portable

Choose test data that makes the output independent of endianness.

7 years agoFix portability bug in gin_page_opaque_info().
Tom Lane [Wed, 2 Nov 2016 04:09:27 +0000 (00:09 -0400)]
Fix portability bug in gin_page_opaque_info().

Somebody apparently thought that "if Int32GetDatum is good,
Int64GetDatum must be better".  Per buildfarm failures now
that Peter has added some regression tests here.

7 years agopageinspect: Make btree test more portable
Peter Eisentraut [Tue, 1 Nov 2016 16:00:00 +0000 (12:00 -0400)]
pageinspect: Make btree test more portable

Choose test data that makes the output independent of endianness and
alignment.

7 years agopostgres_fdw: Fix typo in comment.
Robert Haas [Tue, 1 Nov 2016 20:21:29 +0000 (16:21 -0400)]
postgres_fdw: Fix typo in comment.

Etsuro Fujita

7 years agoAdd subsection headers in pageinspect documentation
Peter Eisentraut [Tue, 1 Nov 2016 16:00:00 +0000 (12:00 -0400)]
Add subsection headers in pageinspect documentation

extracted from a patch from Jesper Pedersen <jesper.pedersen@redhat.com>

7 years agopageinspect: Add tests
Peter Eisentraut [Thu, 29 Sep 2016 16:00:00 +0000 (12:00 -0400)]
pageinspect: Add tests

7 years agoAdd make rules to download raw Unicode mapping files
Peter Eisentraut [Fri, 28 Oct 2016 16:00:00 +0000 (12:00 -0400)]
Add make rules to download raw Unicode mapping files

This serves as implicit documentation and is handy if someone wants to
tweak things.  The rules are not part of a normal build, like this
entire directory.

7 years agoRemove declarations for pq_putmessage_hook and pq_flush_hook.
Robert Haas [Mon, 31 Oct 2016 13:14:46 +0000 (09:14 -0400)]
Remove declarations for pq_putmessage_hook and pq_flush_hook.

Commit 2bd9e412f92bc6a68f3e8bcb18e04955cc35001d added these in error.
They were part of an earlier design for that patch and survived in the
committed version only by inadvertency.

Julien Rouhaud

7 years agoFix typo in sources.sgml.
Tatsuo Ishii [Sun, 30 Oct 2016 22:30:46 +0000 (07:30 +0900)]
Fix typo in sources.sgml.

Per Shinichi Matsuda.

7 years agoFix nasty performance problem in tsquery_rewrite().
Tom Lane [Sun, 30 Oct 2016 21:35:42 +0000 (17:35 -0400)]
Fix nasty performance problem in tsquery_rewrite().

tsquery_rewrite() tries to find matches to subsets of AND/OR conditions;
for example, in the query 'a | b | c' the substitution subquery 'a | c'
should match and lead to replacement of the first and third items.
That's fine, but the matching algorithm apparently takes about O(2^N)
for an N-clause query (I say "apparently" because the code is also both
unintelligible and uncommented).  We could probably do better than that
even without any extra assumptions --- but actually, we know that the
subclauses are sorted, indeed are depending on that elsewhere in this very
same function.  So we can just scan the two lists a single time to detect
matches, as though we were doing a merge join.

Also do a re-flattening call (QTNTernary()) in tsquery_rewrite_query, just
to make sure that the tree fits the expectations of the next search cycle.
I didn't try to devise a test case for this, but I'm pretty sure that the
oversight could have led to failure to match in some cases where a match
would be expected.

Improve comments, and also stick a CHECK_FOR_INTERRUPTS into
dofindsubquery, just in case it's still too slow for somebody.

Per report from Andreas Seltenreich.  Back-patch to all supported branches.

Discussion: <8760oasf2y.fsf@credativ.de>

7 years agoFix bogus tree-flattening logic in QTNTernary().
Tom Lane [Sun, 30 Oct 2016 19:24:40 +0000 (15:24 -0400)]
Fix bogus tree-flattening logic in QTNTernary().

QTNTernary() contains logic to flatten, eg, '(a & b) & c' into 'a & b & c',
which is all well and good, but it tries to do that to NOT nodes as well,
so that '!!a' gets changed to '!a'.  Explicitly restrict the conversion to
be done only on AND and OR nodes, and add a test case illustrating the bug.

In passing, provide some comments for the sadly naked functions in
tsquery_util.c, and simplify some baroque logic in QTNFree(), which
I think may have been leaking some items it intended to free.

Noted while investigating a complaint from Andreas Seltenreich.
Back-patch to all supported versions.

7 years agoImprove speed of aggregates that use array_append as transition function.
Tom Lane [Sun, 30 Oct 2016 16:27:41 +0000 (12:27 -0400)]
Improve speed of aggregates that use array_append as transition function.

In the previous coding, if an aggregate's transition function returned an
expanded array, nodeAgg.c and nodeWindowAgg.c would always copy it and thus
force it into the flat representation.  This led to ping-ponging between
flat and expanded formats, which costs a lot.  For an aggregate using
array_append as transition function, I measured about a 15X slowdown
compared to the pre-9.5 code, when working on simple int[] arrays.
Of course, the old code was already O(N^2) in this usage due to copying
flat arrays all the time, but it wasn't quite this inefficient.

To fix, teach nodeAgg.c and nodeWindowAgg.c to allow expanded transition
values without copying, so long as the transition function takes care to
return the transition value already properly parented under the aggcontext.
That puts a bit of extra responsibility on the transition function, but
doing it this way allows us to not need any extra logic in the fast path
of advance_transition_function (ie, with a pass-by-value transition value,
or with a modified-in-place pass-by-reference value).  We already know
that that's a hot spot so I'm loath to add any cycles at all there.  Also,
while only array_append currently knows how to follow this convention,
this solution allows other transition functions to opt-in without needing
to have a whitelist in the core aggregation code.

(The reason we would need a whitelist is that currently, if you pass a
R/W expanded-object pointer to an arbitrary function, it's allowed to do
anything with it including deleting it; that breaks the core agg code's
assumption that it should free discarded values.  Returning a value under
aggcontext is the transition function's signal that it knows it is an
aggregate transition function and will play nice.  Possibly the API rules
for expanded objects should be refined, but that would not be a
back-patchable change.)

With this fix, an aggregate using array_append is no longer O(N^2), so it's
much faster than pre-9.5 code rather than much slower.  It's still a bit
slower than the bespoke infrastructure for array_agg, but the differential
seems to be only about 10%-20% rather than orders of magnitude.

Discussion: <6315.1477677885@sss.pgh.pa.us>

7 years agoFix memory leak in tar file padding
Magnus Hagander [Sun, 30 Oct 2016 13:10:39 +0000 (14:10 +0100)]
Fix memory leak in tar file padding

Spotted by Coverity, patch by Michael Paquier

7 years agopgstattuple: Don't take heavyweight locks when examining a hash index.
Robert Haas [Fri, 28 Oct 2016 16:21:15 +0000 (12:21 -0400)]
pgstattuple: Don't take heavyweight locks when examining a hash index.

It's currently necessary to take a heavyweight lock when scanning a
hash bucket, but pgstattuple only examines individual pages, so it
doesn't need to do this.  If, for some hypothetical reason, it did
need to do any heavyweight locking here, this logic would probably
still be incorrect, because most of the locks that it is taking are
meaningless.  Only a heavyweight lock on a primary bucket page has any
meaning, but this takes heavyweight locks on all pages regardless of
function - and in particular overflow pages, where you might imagine
that we'd want to lock the primary bucket page if we needed to lock
anything at all.

This is arguably a bug that has existed since this code was added in
commit dab42382f483c3070bdce14a4d93c5d0cf61e82b, but I'm not going to
bother back-patching it because in most cases the only consequence is
that running pgstattuple() on a hash index is a little slower than it
otherwise might be, which is no big deal.

Extracted from a vastly larger patch by Amit Kapila which heavyweight
locking for hash indexes entirely; analysis of why this can be done
independently of the rest by me.

7 years agoFix leftover reference to background writer performing checkpoints.
Robert Haas [Fri, 28 Oct 2016 13:07:36 +0000 (09:07 -0400)]
Fix leftover reference to background writer performing checkpoints.

This was changed in PostgreSQL 9.2, but somehow this comment never
got updated.

7 years agodoc: Small style improvements
Peter Eisentraut [Thu, 27 Oct 2016 16:00:00 +0000 (12:00 -0400)]
doc: Small style improvements

7 years agoRemove invitation to report a bug about unknown encoding
Peter Eisentraut [Thu, 27 Oct 2016 16:00:00 +0000 (12:00 -0400)]
Remove invitation to report a bug about unknown encoding

The error message when we couldn't determine the encoding from a locale
said to report a bug about that.  That might have been appropriate when
this code was first added, but by now this works pretty solidly and any
encodings we don't recognize we probably just don't support.  We still
print the warning, but no longer invite the bug report.

7 years agoAdd function name to PyArg_ParseTuple()
Peter Eisentraut [Thu, 27 Oct 2016 16:00:00 +0000 (12:00 -0400)]
Add function name to PyArg_ParseTuple()

This causes the supplied function name to appear in any error message,
making the error message friendlier and relieving us from having to
provide our own in some cases.

7 years agoFormat PL/Python module contents test vertically
Peter Eisentraut [Wed, 19 Oct 2016 16:00:00 +0000 (12:00 -0400)]
Format PL/Python module contents test vertically

It makes it readable again and makes merges more manageable.

7 years agoIf the stats collector dies during Hot Standby, restart it.
Robert Haas [Thu, 27 Oct 2016 18:27:40 +0000 (14:27 -0400)]
If the stats collector dies during Hot Standby, restart it.

This bug exists as far back as 9.0, when Hot Standby was introduced,
so back-patch to all supported branches.

Report and patch by Takayuki Tsunakawa, reviewed by Michael Paquier
and Kuntal Ghosh.

7 years agoFix possible pg_basebackup failure on standby with "include WAL".
Robert Haas [Thu, 27 Oct 2016 15:19:51 +0000 (11:19 -0400)]
Fix possible pg_basebackup failure on standby with "include WAL".

If a restartpoint flushed no dirty buffers, it could fail to update
the minimum recovery point, leading to a minimum recovery point prior
to the starting REDO location.  perform_base_backup() would interpret
that as meaning that no WAL files at all needed to be included in the
backup, failing an internal sanity check.  To fix, have restartpoints
always update the minimum recovery point to just after the checkpoint
record itself, so that the file (or files) containing the checkpoint
record will always be included in the backup.

Code by Amit Kapila, per a design suggestion by me, with some
additional work on the code comment by me.  Test case by Michael
Paquier.  Report by Kyotaro Horiguchi.

7 years agoAvoid using a C++ keyword in header file
Peter Eisentraut [Wed, 26 Oct 2016 16:00:00 +0000 (12:00 -0400)]
Avoid using a C++ keyword in header file

per cpluspluscheck