]> granicus.if.org Git - postgresql/log
postgresql
6 years agoSupport parallel btree index builds.
Robert Haas [Fri, 2 Feb 2018 18:25:55 +0000 (13:25 -0500)]
Support parallel btree index builds.

To make this work, tuplesort.c and logtape.c must also support
parallelism, so this patch adds that infrastructure and then applies
it to the particular case of parallel btree index builds.  Testing
to date shows that this can often be 2-3x faster than a serial
index build.

The model for deciding how many workers to use is fairly primitive
at present, but it's better than not having the feature.  We can
refine it as we get more experience.

Peter Geoghegan with some help from Rushabh Lathia.  While Heikki
Linnakangas is not an author of this patch, he wrote other patches
without which this feature would not have been possible, and
therefore the release notes should possibly credit him as an author
of this feature.  Reviewed by Claudio Freire, Heikki Linnakangas,
Thomas Munro, Tels, Amit Kapila, me.

Discussion: http://postgr.es/m/CAM3SWZQKM=Pzc=CAHzRixKjp2eO5Q0Jg1SoFQqeXFQ647JiwqQ@mail.gmail.com
Discussion: http://postgr.es/m/CAH2-Wz=AxWqDoVvGU7dq856S4r6sJAj6DBn7VMtigkB33N5eyg@mail.gmail.com

6 years agoRefactor code for partition bound searching
Robert Haas [Fri, 2 Feb 2018 14:23:42 +0000 (09:23 -0500)]
Refactor code for partition bound searching

Remove partition_bound_cmp() and partition_bound_bsearch(), whose
void * argument could be, depending on the situation, of any of
three different types: PartitionBoundSpec *, PartitionRangeBound *,
Datum *.

Instead, introduce separate bound-searching functions for each
situation: partition_list_bsearch, partition_range_bsearch,
partition_range_datum_bsearch, and partition_hash_bsearch.  This
requires duplicating the code for binary search, but it makes the
code much more type safe, involves fewer branches at runtime, and
at least in my opinion, is much easier to understand.

Along the way, add an option to partition_range_datum_bsearch
allowing the number of keys to be specified, so that we can search
for partitions based on a prefix of the full list of partition
keys.  This is important for pending work to improve partition
pruning.

Amit Langote, per a suggestion from me.

Discussion: http://postgr.es/m/CA+TgmoaVLDLc8=YESRwD32gPhodU_ELmXyKs77gveiYp+JE4vQ@mail.gmail.com

6 years agoAdd new function WaitForParallelWorkersToAttach.
Robert Haas [Fri, 2 Feb 2018 14:00:59 +0000 (09:00 -0500)]
Add new function WaitForParallelWorkersToAttach.

Once this function has been called, we know that all workers have
started and attached to their error queues -- so if any of them
subsequently exit uncleanly, we'll be sure to throw an ERROR promptly.
Otherwise, users of the ParallelContext machinery must be careful not
to wait forever for a worker that has failed to start.  Parallel query
manages to work without needing this for reasons explained in new
comments added by this patch, but it's a useful primitive for other
parallel operations, such as the pending patch to make creating a
btree index run in parallel.

Amit Kapila, revised by me.  Additional review by Peter Geoghegan.

Discussion: http://postgr.es/m/CAA4eK1+e2MzyouF5bg=OtyhDSX+=Ao=3htN=T-r_6s3gCtKFiw@mail.gmail.com

6 years agoImprove ALTER TABLE synopsis
Stephen Frost [Fri, 2 Feb 2018 10:30:04 +0000 (05:30 -0500)]
Improve ALTER TABLE synopsis

Add into the ALTER TABLE synopsis the definition of
partition_bound_spec, column_constraint, index_parameters and
exclude_element.

Initial patch by Lætitia Avrot, with further improvements by Amit
Langote and Thomas Munro.

Discussion: https://postgr.es/m/flat/27ec4df3-d1ab-3411-f87f-647f944897e1%40lab.ntt.co.jp

6 years agoFix possible failure to mark hash metapage dirty.
Robert Haas [Thu, 1 Feb 2018 20:21:13 +0000 (15:21 -0500)]
Fix possible failure to mark hash metapage dirty.

Report and suggested fix by Lixian Zou.  Amit Kapila put it
in the form of a patch and reviewed.

Discussion: http://postgr.es/m/151739848647.1239.12528851873396651946@wrigleys.postgresql.org

6 years agopsql: Add quit/help behavior/hint, for other tool portability
Bruce Momjian [Thu, 1 Feb 2018 13:30:43 +0000 (08:30 -0500)]
psql:  Add quit/help behavior/hint, for other tool portability

Issuing 'quit'/'exit' in an empty psql buffer exits psql.  Issuing
'quit'/'exit' in a non-empty psql buffer alone on a line with no prefix
whitespace issues a hint on how to exit.

Also add similar 'help' hints for 'help' in a non-empty psql buffer.

Reported-by: Everaldo Canuto
Discussion: https://postgr.es/m/flat/CALVFHFb-C_5_94hueWg6Dd0zu7TfbpT7hzsh9Zf0DEDOSaAnfA%40mail.gmail.com

Author: original author Robert Haas, modified by me

6 years agodoc: fix trigger inheritance wording
Bruce Momjian [Wed, 31 Jan 2018 22:52:47 +0000 (17:52 -0500)]
doc:  fix trigger inheritance wording

Fix wording from commit 1cf1112990cff432b53a74a0ac9ca897ce8a7688

Reported-by: Robert Haas
Backpatch-through: 10

6 years agodoc: clarify major/minor pg_upgrade versions with examples
Bruce Momjian [Wed, 31 Jan 2018 22:09:59 +0000 (17:09 -0500)]
doc:  clarify major/minor pg_upgrade versions with examples

The previous docs added in PG 10 were not clear enough for someone who
didn't understand the PG 10 version change, so give more specific
examples.

Reported-by: jim@room118solutions.com
Discussion: https://postgr.es/m/20171218213041.25744.8414@wrigleys.postgresql.org

Backpatch-through: 10

6 years agodoc: clearify trigger behavior for inheritance
Bruce Momjian [Wed, 31 Jan 2018 22:00:17 +0000 (17:00 -0500)]
doc:  clearify trigger behavior for inheritance

The previous wording added in PG 10 wasn't specific enough about the
behavior of statement and row triggers when using inheritance.

Reported-by: ian@thepathcentral.com
Discussion: https://postgr.es/m/20171129193934.27108.30796@wrigleys.postgresql.org

Backpatch-through: 10

6 years agodoc: in contrib-spi, mention and link to the meaning of SPI
Bruce Momjian [Wed, 31 Jan 2018 21:54:33 +0000 (16:54 -0500)]
doc:  in contrib-spi, mention and link to the meaning of SPI

Also remove outdated comment about SPI subtransactions.

Reported-by: gregory@arenius.com
Discussion: https://postgr.es/m/151726276676.1240.10501743959198501067@wrigleys.postgresql.org

Backpatch-through: 9.3

6 years agoFix typo: colums -> columns.
Robert Haas [Wed, 31 Jan 2018 21:45:37 +0000 (16:45 -0500)]
Fix typo: colums -> columns.

Along the way, also fix code indentation.

Alexander Lakhin, reviewed by Michael Paquier

Discussion: http://postgr.es/m/45c44aa7-7cfa-7f3b-83fd-d8300677fdda@gmail.com

6 years agodoc: Improve pg_upgrade rsync examples to use clusterdir
Bruce Momjian [Wed, 31 Jan 2018 21:43:32 +0000 (16:43 -0500)]
doc: Improve pg_upgrade rsync examples to use clusterdir

Commit 9521ce4a7a1125385fb4de9689f345db594c516a from Sep 13, 2017 and
backpatched through 9.5 used rsync examples with datadir.  The reporter
has pointed out, and testing has verified, that clusterdir must be used,
so update the docs accordingly.

Reported-by: Don Seiler
Discussion: https://postgr.es/m/CAHJZqBD0u9dCERpYzK6BkRv=663AmH==DFJpVC=M4Xg_rq2=CQ@mail.gmail.com

Backpatch-through: 9.5

6 years agopgcrypto's encrypt() supports AES-128, AES-192, and AES-256
Robert Haas [Wed, 31 Jan 2018 21:28:11 +0000 (16:28 -0500)]
pgcrypto's encrypt() supports AES-128, AES-192, and AES-256

Previously, only 128 was mentioned, but the others are also supported.

Thomas Munro, reviewed by Michael Paquier and extended a bit by me.

Discussion: http://postgr.es/m/CAEepm=1XbBHXYJKofGjnM2Qfz-ZBVqhGU4AqvtgR+Hegy4fdKg@mail.gmail.com

6 years agodoc: mention datadir locations are actually config locations
Bruce Momjian [Wed, 31 Jan 2018 21:25:21 +0000 (16:25 -0500)]
doc:  mention datadir locations are actually config locations

Technically, pg_upgrade's --old-datadir and --new-datadir are
configuration directories, not necessarily data directories.  This is
reflected in the 'postgres' manual page, so do the same for pg_upgrade.

Reported-by: Yves Goergen
Bug: 14898

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

Backpatch-through: 10

6 years agoFix list partition constraints for partition keys of array type.
Robert Haas [Wed, 31 Jan 2018 20:43:11 +0000 (15:43 -0500)]
Fix list partition constraints for partition keys of array type.

The old code generated always generated a constraint of the form
col = ANY(ARRAY[val1, val2, ...]), but that's invalid when col is an
array type.  Instead, generate col = val when there's only one value,
col = val1 OR col = val2 OR ... when there are multiple values and
col is of array type, and the old form when there are multiple values
and col is not of an array type.

As a side benefit, this makes constraint exclusion able to prune
a list partition declared to accept a single Boolean value, which
didn't work before.

Amit Langote, reviewed by Etsuro Fujita

Discussion: http://postgr.es/m/97267195-e235-89d1-a41a-c110198dfce9@lab.ntt.co.jp

6 years agopg_prewarm: Add missing LWLockRegisterTranche call.
Robert Haas [Wed, 31 Jan 2018 20:12:33 +0000 (15:12 -0500)]
pg_prewarm: Add missing LWLockRegisterTranche call.

Commit 79ccd7cbd5ca44bee0191d12e9e65abf702899e7, which added automatic
prewarming, neglected this.

Kyotaro Horiguchi, reviewed by me.

Discussion: http://postgr.es/m/20171215.173219.38055760.horiguchi.kyotaro@lab.ntt.co.jp

6 years agoRefactor client-side SSL certificate checking code
Peter Eisentraut [Sat, 27 Jan 2018 18:47:52 +0000 (13:47 -0500)]
Refactor client-side SSL certificate checking code

Separate the parts specific to the SSL library from the general logic.

The previous code structure was

open_client_SSL()
calls verify_peer_name_matches_certificate()
calls verify_peer_name_matches_certificate_name()
calls wildcard_certificate_match()

and was completely in fe-secure-openssl.c.  The new structure is

open_client_SSL() [openssl]
calls pq_verify_peer_name_matches_certificate() [generic]
calls pgtls_verify_peer_name_matches_certificate_guts() [openssl]
calls openssl_verify_peer_name_matches_certificate_name() [openssl]
calls pq_verify_peer_name_matches_certificate_name() [generic]
calls wildcard_certificate_match() [generic]

Move the generic functions into a new file fe-secure-common.c, so the
calls generally go fe-connect.c -> fe-secure.c -> fe-secure-${impl}.c ->
fe-secure-common.c, although there is a bit of back-and-forth between
the last two.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agoFix up references to scram-sha-256
Peter Eisentraut [Tue, 30 Jan 2018 21:50:30 +0000 (16:50 -0500)]
Fix up references to scram-sha-256

pg_hba_file_rules erroneously reported this as scram-sha256.  Fix that.

To avoid future errors and confusion, also adjust documentation links
and internal symbols to have a separator between "sha" and "256".

Reported-by: Christophe Courtois <christophe.courtois@dalibo.com>
Author: Michael Paquier <michael.paquier@gmail.com>

6 years agoFix test case for 'outer pathkeys do not match mergeclauses' fix.
Robert Haas [Tue, 30 Jan 2018 19:27:38 +0000 (14:27 -0500)]
Fix test case for 'outer pathkeys do not match mergeclauses' fix.

Commit 4bbf6edfbd5d03743ff82dda2f00c738fb3208f5 added a test case,
but it turns out that the test case doesn't reliably test for the
bug, and in the context of the regression test suite did not because
ANALYZE had not been run.

Report and patch by Etsuro Fujita.  I added a comment along lines
previously suggested by Tom Lane.

Discussion: http://postgr.es/m/5A6195D8.8060206@lab.ntt.co.jp

6 years agoAdd some noreturn attributes to help static analyzers
Peter Eisentraut [Tue, 30 Jan 2018 01:44:35 +0000 (20:44 -0500)]
Add some noreturn attributes to help static analyzers

6 years agoSilence complaint about dead assignment
Peter Eisentraut [Tue, 30 Jan 2018 01:42:15 +0000 (20:42 -0500)]
Silence complaint about dead assignment

The preferred place for "placate compiler" assignments is after
elog(ERROR), not before it.  Otherwise, scan-build complains about a
dead assignment.

6 years agoRemove dead assignment
Peter Eisentraut [Tue, 30 Jan 2018 01:41:36 +0000 (20:41 -0500)]
Remove dead assignment

per scan-build

6 years agoIntroduce ExecQualAndReset() helper.
Andres Freund [Mon, 29 Jan 2018 20:16:53 +0000 (12:16 -0800)]
Introduce ExecQualAndReset() helper.

It's a common task to evaluate a qual and reset the corresponding
expression context. Currently that requires storing the result of the
qual eval, resetting the context, and then reacting on the result. As
that's awkward several places only reset the context next time through
a node. That's not great, so introduce a helper that evaluates and
resets.

It's a bit ugly that it currently uses MemoryContextReset() instead of
ResetExprContext(), but that seems easier than reordering all of
executor.h.

Author: Andres Freund
Discussion: https://postgr.es/m/20180109222544.f7loxrunqh3xjl5f@alap3.anarazel.de

6 years agoSave a few bytes by removing useless last argument to SearchCatCacheList.
Tom Lane [Mon, 29 Jan 2018 20:13:07 +0000 (15:13 -0500)]
Save a few bytes by removing useless last argument to SearchCatCacheList.

There's never any value in giving a fully specified cache key to
SearchCatCacheList: you might as well call SearchCatCache instead,
since there could be only one match.  So the maximum useful number of
key arguments is one less than the supported number of key columns.
We might as well remove the useless extra argument and save some few
bytes per call site, as well as a cycle or so per call.

I believe the reason it was coded like this is that originally, callers
had to write out all the dummy arguments in each call, and so it seemed
less confusing if SearchCatCache and SearchCatCacheList took the same
number of key arguments.  But since commit e26c539e9, callers only write
their live arguments explicitly, making that a non-factor; and there's
surely been enough time for third-party modules to adapt to that coding
style.  So this is only an ABI break not an API break for callers.

Per discussion with Oliver Ford, this might also make it less confusing
how to use SearchCatCacheList correctly.

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

6 years agoInitialize unused ExprEvalStep fields.
Andres Freund [Wed, 24 Jan 2018 07:20:02 +0000 (23:20 -0800)]
Initialize unused ExprEvalStep fields.

ExecPushExprSlots didn't initialize ExprEvalStep's resvalue/resnull
steps as it didn't use them. That caused wrong valgrind warnings for
an upcoming patch, so zero-intialize.

Also zero-initialize all scratch ExprEvalStep's allocated on the
stack, to avoid issues with similar future omissions of non-critial
data.

6 years agodoc: Clarify pg_upgrade documentation
Peter Eisentraut [Mon, 29 Jan 2018 19:26:17 +0000 (14:26 -0500)]
doc: Clarify pg_upgrade documentation

Clarify that the restriction against reg* types only applies to table
columns using these types, not to the type appearing in any other way,
for example as a function argument.

6 years agoPrevent growth of simplehash tables when they're "too empty".
Andres Freund [Mon, 29 Jan 2018 19:02:09 +0000 (11:02 -0800)]
Prevent growth of simplehash tables when they're "too empty".

In cases where simplehash tables where filled with either a lot of
conflicting hash-values, or values that hash to consecutive
values (i.e. build "chains") the growth heuristics in
d4c62a6b623d6eef88218158e9fa3cf974c6c7e5 could trigger rather
explosively.

To fix that, address some of the reasons (see previous commit) of why
the growth heuristics where needed, and only allow growth when the
table isn't too empty. While that means there's a few cases of bad
input that can be slower, that seems a lot better than running very
quickly out of memory.

Author: Tomas Vondra and Andres Freund, with additional input by
    Thomas Munro, Tom Lane Todd A. Cook
Reported-By: Todd A. Cook, Tomas Vondra, Thomas Munro
Discussion: https://postgr.es/m/20171127185700.1470.20362@wrigleys.postgresql.org
Backpatch: 10, where simplehash was introduced

6 years agoImprove bit perturbation in TupleHashTableHash.
Andres Freund [Mon, 29 Jan 2018 19:02:09 +0000 (11:02 -0800)]
Improve bit perturbation in TupleHashTableHash.

The changes in b81b5a96f424531b97cdd1dba97d9d1b9c9d372e did not fully
address the issue, because the bit-mixing of the IV into the final
hash-key didn't prevent clustering in the input-data survive in the
output data.

This didn't cause a lot of problems because of the additional growth
conditions added d4c62a6b623d6eef88218158e9fa3cf974c6c7e5. But as we
want to rein those in due to explosive growth in some edges, this
needs to be fixed.

Author: Andres Freund
Discussion: https://postgr.es/m/20171127185700.1470.20362@wrigleys.postgresql.org
Backpatch: 10, where simplehash was introduced

6 years agoAvoid misleading psql password prompt when username is multiply specified.
Tom Lane [Mon, 29 Jan 2018 17:57:09 +0000 (12:57 -0500)]
Avoid misleading psql password prompt when username is multiply specified.

When a password is needed, cases such as
psql -d "postgresql://alice@localhost/testdb" -U bob
would incorrectly prompt for "Password for user bob: ", when actually the
connection will be attempted with username alice.  The priority order of
which name to use isn't that important here, but the misleading prompt is.

When we are prompting for a password after initial connection failure,
we can fix this reliably by looking at PQuser(conn) to see how libpq
interpreted the connection arguments.  But when we're doing a forced
password prompt because of a -W switch, we can't use that solution.
Fortunately, because the main use of -W is for noninteractive situations,
it's less critical to produce a helpful prompt in such cases.  I made
the startup prompt for -W just say "Password: " all the time, rather
than expending extra code on trying to identify which username to use.
In the case of a \c command (after -W has been given), there's already
logic in do_connect that determines whether the "dbname" is a connstring
or URI, so we can avoid lobotomizing the prompt except in cases that
are actually dubious.  (We could do similarly in startup.c if anyone
complains, but for now it seems not worthwhile, especially since that
would still be only a partial solution.)

Per bug #15025 from Akos Vandra.  Although this is arguably a bug fix,
it doesn't seem worth back-patching.  The case where it matters seems
like a very corner-case usage, and someone might complain that we'd
changed the behavior of -W in a minor release.

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

6 years agoAdd stack-overflow guards in set-operation planning.
Tom Lane [Sun, 28 Jan 2018 18:39:07 +0000 (13:39 -0500)]
Add stack-overflow guards in set-operation planning.

create_plan_recurse lacked any stack depth check.  This is not per
our normal coding rules, but I'd supposed it was safe because earlier
planner processing is more complex and presumably should eat more
stack.  But bug #15033 from Andrew Grossman shows this isn't true,
at least not for queries having the form of a many-thousand-way
INTERSECT stack.

Further testing showed that recurse_set_operations is also capable
of being crashed in this way, since it likewise will recurse to the
bottom of a parsetree before calling any support functions that
might themselves contain any stack checks.  However, its stack
consumption is only perhaps a third of create_plan_recurse's.

It's possible that this particular problem with create_plan_recurse can
only manifest in 9.6 and later, since before that we didn't build a Path
tree for set operations.  But having seen this example, I now have no
faith in the proposition that create_plan_recurse doesn't need a stack
check, so back-patch to all supported branches.

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

6 years agoC includes: Reorder C includes in partition.c
Bruce Momjian [Sun, 28 Jan 2018 04:05:52 +0000 (23:05 -0500)]
C includes: Reorder C includes in partition.c

Discussion: https://postgr.es/m/5A69AA50.2060600@lab.ntt.co.jp

Author: Etsuro Fujita

6 years agoUpdate time zone data files to tzdata release 2018c.
Tom Lane [Sat, 27 Jan 2018 21:42:28 +0000 (16:42 -0500)]
Update time zone data files to tzdata release 2018c.

DST law changes in Brazil, Sao Tome and Principe.  Historical corrections
for Bolivia, Japan, and South Sudan.  The "US/Pacific-New" zone has been
removed (it was only a link to America/Los_Angeles anyway).

6 years agoAvoid crash during EvalPlanQual recheck of an inner indexscan.
Tom Lane [Sat, 27 Jan 2018 18:52:24 +0000 (13:52 -0500)]
Avoid crash during EvalPlanQual recheck of an inner indexscan.

Commit 09529a70b changed nodeIndexscan.c and nodeIndexonlyscan.c to
postpone initialization of the indexscan proper until the first tuple
fetch.  It overlooked the question of mark/restore behavior, which means
that if some caller attempts to mark the scan before the first tuple fetch,
you get a null pointer dereference.

The only existing user of mark/restore is nodeMergejoin.c, which (somewhat
accidentally) will never attempt to set a mark before the first inner tuple
unless the inner child node is a Material node.  Hence the case can't arise
normally, so it seems sufficient to document the assumption at both ends.
However, during an EvalPlanQual recheck, ExecScanFetch doesn't call
IndexNext but just returns the jammed-in test tuple.  Therefore, if we're
doing a recheck in a plan tree with a mergejoin with inner indexscan,
it's possible to reach ExecIndexMarkPos with iss_ScanDesc still null,
as reported by Guo Xiang Tan in bug #15032.

Really, when there's a test tuple supplied during an EPQ recheck, touching
the index at all is the wrong thing: rather, the behavior of mark/restore
ought to amount to saving and restoring the es_epqScanDone flag.  We can
avoid finding a place to actually save the flag, for the moment, because
given the assumption that no caller will set a mark before fetching a
tuple, es_epqScanDone must always be set by the time we try to mark.
So the actual behavior change required is just to not reach the index
access if a test tuple is supplied.

The set of plan node types that need to consider this issue are those
that support EPQ test tuples (i.e., call ExecScan()) and also support
mark/restore; which is to say, IndexScan, IndexOnlyScan, and perhaps
CustomScan.  It's tempting to try to fix the problem in one place by
teaching ExecMarkPos() itself about EPQ; but ExecMarkPos supports some
plan types that aren't Scans, and also it seems risky to make assumptions
about what a CustomScan wants to do here.  Also, the most likely future
change here is to decide that we do need to support marks placed before
the first tuple, which would require additional work in IndexScan and
IndexOnlyScan in any case.  Hence, fix the EPQ issue in nodeIndexscan.c
and nodeIndexonlyscan.c, accepting the small amount of code duplicated
thereby, and leave it to CustomScan providers to fix this bug if they
have it.

Back-patch to v10 where commit 09529a70b came in.  In earlier branches,
the index_markpos() call is a waste of cycles when EPQ is active, but
no more than that, so it doesn't seem appropriate to back-patch further.

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

6 years agoAdd missing semicolons in documentation examples
Magnus Hagander [Sat, 27 Jan 2018 12:13:52 +0000 (13:13 +0100)]
Add missing semicolons in documentation examples

Author: Daniel Gustafsson <daniel@yesql.se>

6 years agoAvoid unnecessary use of pg_strcasecmp for already-downcased identifiers.
Tom Lane [Fri, 26 Jan 2018 23:25:02 +0000 (18:25 -0500)]
Avoid unnecessary use of pg_strcasecmp for already-downcased identifiers.

We have a lot of code in which option names, which from the user's
viewpoint are logically keywords, are passed through the grammar as plain
identifiers, and then matched to string literals during command execution.
This approach avoids making words into lexer keywords unnecessarily.  Some
places matched these strings using plain strcmp, some using pg_strcasecmp.
But the latter should be unnecessary since identifiers would have been
downcased on their way through the parser.  Aside from any efficiency
concerns (probably not a big factor), the lack of consistency in this area
creates a hazard of subtle bugs due to different places coming to different
conclusions about whether two option names are the same or different.
Hence, standardize on using strcmp() to match any option names that are
expected to have been fed through the parser.

This does create a user-visible behavioral change, which is that while
formerly all of these would work:
alter table foo set (fillfactor = 50);
alter table foo set (FillFactor = 50);
alter table foo set ("fillfactor" = 50);
alter table foo set ("FillFactor" = 50);
now the last case will fail because that double-quoted identifier is
different from the others.  However, none of our documentation says that
you can use a quoted identifier in such contexts at all, and we should
discourage doing so since it would break if we ever decide to parse such
constructs as true lexer keywords rather than poor man's substitutes.
So this shouldn't create a significant compatibility issue for users.

Daniel Gustafsson, reviewed by Michael Paquier, small changes by me

Discussion: https://postgr.es/m/29405B24-564E-476B-98C0-677A29805B84@yesql.se

6 years agoFactor some code out of create_grouping_paths.
Robert Haas [Fri, 26 Jan 2018 20:03:12 +0000 (15:03 -0500)]
Factor some code out of create_grouping_paths.

This is preparatory refactoring to prepare the way for partition-wise
aggregate, which will reuse the new subroutines for child grouping
rels.  It also does not seem like a bad idea on general principle,
as the function was getting pretty long.

Jeevan Chalke.  The larger patch series of which this patch is a part
was reviewed and tested by Antonin Houska, Rajkumar Raghuwanshi,
Ashutosh Bapat, David Rowley, Dilip Kumar, Konstantin Knizhnik,
Pascal Legrand, and me.  Some cosmetic changes by me.

Discussion: http://postgr.es/m/CAM2+6=V64_xhstVHie0Rz=KPEQnLJMZt_e314P0jaT_oJ9MR8A@mail.gmail.com

6 years agoRemove the obsolete WITH clause of CREATE FUNCTION.
Tom Lane [Fri, 26 Jan 2018 17:25:44 +0000 (12:25 -0500)]
Remove the obsolete WITH clause of CREATE FUNCTION.

This clause was superseded by SQL-standard syntax back in 7.3.
We've kept it around for backwards-compatibility purposes ever since;
but 15 years seems like long enough for that, especially seeing that
there are undocumented weirdnesses in how it interacts with the
SQL-standard syntax for specifying the same options.

Michael Paquier, per an observation by Daniel Gustafsson;
some small cosmetic adjustments to nearby code by me.

Discussion: https://postgr.es/m/20180115022748.GB1724@paquier.xyz

6 years agopageinspect: Fix use of wrong memory context by hash_page_items.
Robert Haas [Fri, 26 Jan 2018 14:51:15 +0000 (09:51 -0500)]
pageinspect: Fix use of wrong memory context by hash_page_items.

This can cause it to produce incorrect output.

Report and patch by Masahiko Sawada.

Discussion: http://postgr.es/m/CAD21AoBc5Asx7pXdUWu6NqU_g=Ysn95EGL9SMeYhLLduYoO_OA@mail.gmail.com

6 years agoUse abstracted SSL API in server connection log messages
Peter Eisentraut [Thu, 25 Jan 2018 13:58:00 +0000 (08:58 -0500)]
Use abstracted SSL API in server connection log messages

The existing "connection authorized" server log messages used OpenSSL
API calls directly, even though similar abstracted API calls exist.
Change to use the latter instead.

Change the function prototype for the functions that return the TLS
version and the cipher to return const char * directly instead of
copying into a buffer.  That makes them slightly easier to use.

Add bits= to the message.  psql shows that, so we might as well show the
same information on the client and server.

Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agoRemove byte-masking macros for Datum conversion macros
Peter Eisentraut [Tue, 23 Jan 2018 16:19:12 +0000 (11:19 -0500)]
Remove byte-masking macros for Datum conversion macros

As the comment there stated, these were needed for old-style
user-defined functions, but since we removed support for those, we don't
need this anymore.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agoFix C comment typo
Bruce Momjian [Fri, 26 Jan 2018 01:13:25 +0000 (20:13 -0500)]
Fix C comment typo

Reported-by: Masahiko Sawada
Discussion: https://postgr.es/m/CAD21AoBgnHy2YKAUuB6iVG4ibvLYepHr+RDRkr1arqWwc1AHCw@mail.gmail.com

Author: Masahiko Sawada

6 years agoSupport --no-comments in pg_dump, pg_dumpall, pg_restore.
Tom Lane [Thu, 25 Jan 2018 20:27:24 +0000 (15:27 -0500)]
Support --no-comments in pg_dump, pg_dumpall, pg_restore.

We have switches already to suppress other subsidiary object properties,
such as ACLs, security labels, ownership, and tablespaces, so just on
the grounds of symmetry we should allow suppressing comments as well.
Also, commit 0d4e6ed30 added a positive reason to have this feature,
i.e. to allow obtaining the old behavior of selective pg_restore should
anyone desire that.

Recent commits have removed the cases where pg_dump emitted comments on
built-in objects that the restoring user might not have privileges to
comment on, so the original primary motivation for this feature is gone,
but it still seems at least somewhat useful in its own right.

Robins Tharakan, reviewed by Fabrízio Mello

Discussion: https://postgr.es/m/CAEP4nAx22Z4ch74oJGzr5RyyjcyUSbpiFLyeYXX8pehfou92ug@mail.gmail.com

6 years agoAdd missing "static" markers.
Tom Lane [Thu, 25 Jan 2018 19:32:28 +0000 (14:32 -0500)]
Add missing "static" markers.

Per buildfarm.

6 years agoClean up some aspects of pg_dump/pg_restore item-selection logic.
Tom Lane [Thu, 25 Jan 2018 19:26:07 +0000 (14:26 -0500)]
Clean up some aspects of pg_dump/pg_restore item-selection logic.

Ensure that CREATE DATABASE and related commands are issued when, and
only when, --create is specified.  Previously there were scenarios
where using selective-dump switches would prevent --create from having
any effect.  For example, it would fail to do anything in pg_restore
if the archive file had been made by a selective dump, because there
would be no TOC entry for the database.

Since we don't issue \connect either if we don't issue CREATE DATABASE,
this could result in unexpectedly restoring objects into the wrong
database.

Also fix pg_restore's selective restore logic so that when an object is
selected to be restored, we also restore its ACL, comment, and security
label if any.  Previously there was no way to get the latter properties
except through tedious mucking about with a -L file.  If, for some
reason, you don't want these properties, you can match the old behavior
by adding --no-acl etc.

While at it, try to make _tocEntryRequired() a little better organized
and better documented.

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

6 years agoIgnore partitioned indexes where appropriate
Alvaro Herrera [Thu, 25 Jan 2018 19:11:51 +0000 (16:11 -0300)]
Ignore partitioned indexes where appropriate

get_relation_info() was too optimistic about opening indexes in
partitioned tables, which would raise errors when any queries were
planned on such tables.  Fix by ignoring any indexes of the partitioned
kind.

CLUSTER (and ALTER TABLE CLUSTER ON) had a similar problem.  Fix by
disallowing these commands in partitioned tables.

Fallout from 8b08f7d4820f.

6 years agoImprove pg_dump's handling of "special" built-in objects.
Tom Lane [Thu, 25 Jan 2018 18:54:42 +0000 (13:54 -0500)]
Improve pg_dump's handling of "special" built-in objects.

We had some pretty ad-hoc handling of the public schema and the plpgsql
extension, which are both presumed to exist in template0 but might be
modified or deleted in the database being dumped.

Up to now, by default pg_dump would emit a CREATE EXTENSION IF NOT EXISTS
command as well as a COMMENT command for plpgsql.  The usefulness of the
former is questionable, and the latter caused annoying errors in
non-superuser dump/restore scenarios.  Let's instead install a rule that
built-in extensions (identified by having low-numbered OIDs) are not to be
dumped.  We were doing it that way already in binary-upgrade mode, so this
just makes regular mode behave the same.  It remains true that if someone
has installed a non-default ACL on the plpgsql language, that will get
dumped thanks to the pg_init_privs mechanism.  This is more consistent with
the handling of built-in objects of other kinds.

Also, change the very ad-hoc mechanism that was used to avoid dumping
creation and comment commands for the public schema.  Instead of hardwiring
a test in _printTocEntry(), make use of the DUMP_COMPONENT_ infrastructure
to mark that schema up-front about what we want to do with it.  This has
the visible effect that the public schema won't be mentioned in the output
at all, except for updating its ACL if it has a non-default ACL.
Previously, while it was normally not mentioned, --clean mode would drop
and recreate it, again causing headaches for non-superuser usage.  This
change likewise makes the public schema less special and more like other
built-in objects.

If plpgsql, or the public schema, has been removed entirely in the source
DB, that situation won't be reproduced in the destination ... but that
was true before.

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

6 years agoUpdate documentation to mention huge pages on other OSes
Peter Eisentraut [Thu, 25 Jan 2018 16:14:24 +0000 (11:14 -0500)]
Update documentation to mention huge pages on other OSes

Previously, the docs implied that only Linux and Windows could use huge
pages.  That's not quite true: it's just that we only know how to
request them explicitly on those OSes.  Be more explicit about what
huge_pages really does and mention that some OSes may use huge pages
automatically.

Author: Thomas Munro and Catalin Iacob
Reviewed-By: Justin Pryzby, Peter Eisentraut
Discussion: https://postgr.es/m/CAEepm=3qzR-hfjepymohuC4XO5phxoSoipOjm6BEhnJHjNR+jg@mail.gmail.com

6 years agoRemove use of byte-masking macros in record_image_cmp
Peter Eisentraut [Tue, 23 Jan 2018 15:55:40 +0000 (10:55 -0500)]
Remove use of byte-masking macros in record_image_cmp

These were introduced in 4cbb646334b3b998a29abef0d57608d42097e6c9, but
after further analysis and testing, they should not be necessary and
probably weren't the part of that commit that fixed anything.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agoAllow spaces in connection strings in SSL tests
Peter Eisentraut [Thu, 25 Jan 2018 14:14:24 +0000 (09:14 -0500)]
Allow spaces in connection strings in SSL tests

Connection strings can have items with spaces in them, wrapped in
quotes.  The tests however ran a SELECT '$connstr' upon connection which
broke on the embedded quotes.  Use dollar quotes on the connstr to
protect against this.  This was hit during the development of the macOS
Secure Transport patch, but is independent of it.

Author: Daniel Gustafsson <daniel@yesql.se>

6 years agoAvoid referencing off the end of subplan_partition_offsets.
Robert Haas [Wed, 24 Jan 2018 21:34:51 +0000 (16:34 -0500)]
Avoid referencing off the end of subplan_partition_offsets.

Report by buildfarm member skink and Tom Lane.  Analysis by me.
Patch by Amit Khandekar.

Discussion: http://postgr.es/m/CAJ3gD9fVA1iXQYhfqHP5n_TEd4U9=V8TL_cc-oKRnRmxgdvJrQ@mail.gmail.com

6 years agodoc: properly indent CREATE TRIGGER paragraph
Bruce Momjian [Wed, 24 Jan 2018 20:13:04 +0000 (15:13 -0500)]
doc:  properly indent CREATE TRIGGER paragraph

This was done to match the surrounding indentation.  Text added in PG
10.

Backpatch-through: 10

6 years agoAdd tests for record_image_eq and record_image_cmp
Peter Eisentraut [Tue, 23 Jan 2018 15:13:45 +0000 (10:13 -0500)]
Add tests for record_image_eq and record_image_cmp

record_image_eq was covered a bit by the materialized view code that it
is meant to support, but record_image_cmp was not tested at all.

While we're here, add more tests to record_eq and record_cmp as well,
for symmetry.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agodoc: clarify use of RegisterDynamicBackgroundWorker
Bruce Momjian [Wed, 24 Jan 2018 18:20:37 +0000 (13:20 -0500)]
doc:  clarify use of RegisterDynamicBackgroundWorker

Document likely use of RegisterDynamicBackgroundWorker by another
background worker.

Reported-by: Chapman Flack
Discussion: https://postgr.es/m/CAB7nPqTdi=J9HH8PPPiEOohebdd+xkgbbhdY7=VbGnZ3CkZXxA@mail.gmail.com

Author: Chapman Flack

6 years agoImprove implementation of pg_attribute_always_inline.
Tom Lane [Wed, 24 Jan 2018 04:07:13 +0000 (23:07 -0500)]
Improve implementation of pg_attribute_always_inline.

Avoid compiler warnings on MSVC (which doesn't want to see both
__forceinline and inline) and ancient GCC (which doesn't have
__attribute__((always_inline))).

Don't force inline-ing when building at -O0, as the programmer is probably
hoping for exact source-to-object-line correspondence in that case.
(For the moment this only works for GCC; maybe we can extend it later.)

Make pg_attribute_always_inline be syntactically a drop-in replacement
for inline, rather than an additional wart.

And improve the comments.

Thomas Munro and Michail Nikolaev, small tweaks by me

Discussion: https://postgr.es/m/32278.1514863068@sss.pgh.pa.us
Discussion: https://postgr.es/m/CANtu0oiYp74brgntKOxgg1FK5+t8uQ05guSiFU6FYz_5KUhr6Q@mail.gmail.com

6 years agodoc: mention psql -l uses the 'postgres' database by default
Bruce Momjian [Tue, 23 Jan 2018 23:22:56 +0000 (18:22 -0500)]
doc:  mention psql -l uses the 'postgres' database by default

Reported-by: Mark Wood
Bug: 14912

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

Author: David G. Johnston

Backpatch-through: 10

6 years agoTeach reparameterize_path() to handle AppendPaths.
Tom Lane [Tue, 23 Jan 2018 21:50:34 +0000 (16:50 -0500)]
Teach reparameterize_path() to handle AppendPaths.

If we're inside a lateral subquery, there may be no unparameterized paths
for a particular child relation of an appendrel, in which case we *must*
be able to create similarly-parameterized paths for each other child
relation, else the planner will fail with "could not devise a query plan
for the given query".  This means that there are situations where we'd
better be able to reparameterize at least one path for each child.

This calls into question the assumption in reparameterize_path() that
it can just punt if it feels like it.  However, the only case that is
known broken right now is where the child is itself an appendrel so that
all its paths are AppendPaths.  (I think possibly I disregarded that in
the original coding on the theory that nested appendrels would get folded
together --- but that only happens *after* reparameterize_path(), so it's
not excused from handling a child AppendPath.)  Given that this code's been
like this since 9.3 when LATERAL was introduced, it seems likely we'd have
heard of other cases by now if there were a larger problem.

Per report from Elvis Pranskevichus.  Back-patch to 9.3.

Discussion: https://postgr.es/m/5981018.zdth1YWmNy@hammer.magicstack.net

6 years agoRemove unnecessary include
Alvaro Herrera [Tue, 23 Jan 2018 18:22:13 +0000 (15:22 -0300)]
Remove unnecessary include

autovacuum.c no longer needs dsa.h, since commit 31ae1638ce3.
Author: Masahiko Sawada
Discussion: https://postgr.es/m/CAD21AoCWvYyXrvdANSHWWWEWJH5TeAWAkJ_2gqrHhukG+OBo1g@mail.gmail.com

6 years agoDocumentation fix: pg_ctl no longer makes connection attempts.
Tom Lane [Tue, 23 Jan 2018 17:41:35 +0000 (12:41 -0500)]
Documentation fix: pg_ctl no longer makes connection attempts.

Overlooked in commit f13ea95f9.  Noted by Nick Barnes.

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

6 years agopgbench: Remove accidental garbage in test file
Peter Eisentraut [Tue, 23 Jan 2018 17:31:01 +0000 (12:31 -0500)]
pgbench: Remove accidental garbage in test file

Author: Fabien COELHO <coelho@cri.ensmp.fr>

6 years agoUpdate obsolete sentence in README.parallel.
Robert Haas [Tue, 23 Jan 2018 16:20:18 +0000 (11:20 -0500)]
Update obsolete sentence in README.parallel.

Since 9.6, heavyweight locking is not an abstract and unhandled
concern of the parallel machinery, but rather something to which
we have a specific approach.

6 years agoReport an ERROR if a parallel worker fails to start properly.
Robert Haas [Tue, 23 Jan 2018 16:03:03 +0000 (11:03 -0500)]
Report an ERROR if a parallel worker fails to start properly.

Commit 28724fd90d2f85a0573a8107b48abad062a86d83 fixed things so that
if a background worker fails to start due to fork() failure or because
it is terminated before startup succeeds, BGWH_STOPPED will be
reported.  However, that only helps if the code that uses the
background worker machinery notices the change in status, and the code
in parallel.c did not.

To fix that, do two things.  First, make sure that when a worker
exits, it triggers the leader to read from error queues.  That way, if
a worker which has attached to an error queue exits uncleanly, the
leader is sure to throw some error, either the contents of the
ErrorResponse sent by the worker, or "lost connection to parallel
worker" if it exited without sending one.  To cover the case where
the worker never starts up in the first place or exits before
attaching to the error queue, the ParallelContext now keeps track
of which workers have sent at least one message via the error
queue.  A worker which sends no messages by the time the parallel
operation finishes will be checked to see whether it exited before
attaching to the error queue; if so, a new error message, "parallel
worker failed to initialize", will be reported.  If not, we'll
continue to wait until it either starts up and exits cleanly, starts
up and exits uncleanly, or fails to start, and then take the
appropriate action.

Patch by me, reviewed by Amit Kapila.

Discussion: http://postgr.es/m/CA+TgmoYnBgXgdTu6wk5YPdWhmgabYc9nY_pFLq=tB=FSLYkD8Q@mail.gmail.com

6 years agoIn pg_dump, force reconnection after issuing ALTER DATABASE SET command(s).
Tom Lane [Tue, 23 Jan 2018 15:55:08 +0000 (10:55 -0500)]
In pg_dump, force reconnection after issuing ALTER DATABASE SET command(s).

The folly of not doing this was exposed by the buildfarm: in some cases,
the GUC settings applied through ALTER DATABASE SET may be essential to
interpreting the reloaded data correctly.  Another argument why we can't
really get away with the scheme proposed in commit b3f840120 is that it
cannot work for parallel restore: even if the parent process manages to
hang onto the previous GUC state, worker processes would see the state
post-ALTER-DATABASE.  (Perhaps we could have dodged that bullet by
delaying DATABASE PROPERTIES restoration to the end of the run, but
that does nothing for the data semantics problem.)

This leaves us with no solution for the default_transaction_read_only issue
that commit 4bd371f6f intended to work around, other than "you gotta remove
such settings before dumping/upgrading".  However, in view of the fact that
parallel restore broke that hack years ago and no one has noticed, it's
fair to question how many people care.  I'm unexcited about adding a large
dollop of new complexity to handle that corner case.

This would be a one-liner fix, except it turns out that ReconnectToServer
tries to optimize away "redundant" reconnections.  While that may have been
valuable when coded, a quick survey of current callers shows that there are
no cases where that's actually useful, so just remove that check.  While at
it, remove the function's useless return value.

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

6 years agodoc: simplify intermediate certificate mention in libpq docs
Bruce Momjian [Tue, 23 Jan 2018 15:18:21 +0000 (10:18 -0500)]
doc:  simplify intermediate certificate mention in libpq docs

Backpatch-through: 9.3

6 years agoExtract common bits from OpenSSL implementation
Peter Eisentraut [Fri, 19 Jan 2018 15:17:56 +0000 (10:17 -0500)]
Extract common bits from OpenSSL implementation

Some things in be-secure-openssl.c and fe-secure-openssl.c were not
actually specific to OpenSSL but could also be used by other
implementations.  In order to avoid copy-and-pasting, move some of that
code to common files.

6 years agoMove SSL API comments to header files
Peter Eisentraut [Fri, 19 Jan 2018 00:53:22 +0000 (19:53 -0500)]
Move SSL API comments to header files

Move the documentation of the SSL API calls are supposed to do into the
headers files, instead of keeping them in the files for the OpenSSL
implementation.  That way, they don't have to be duplicated or be
inconsistent when other implementations are added.

6 years agoMove EDH support to common files
Peter Eisentraut [Fri, 19 Jan 2018 17:18:42 +0000 (12:18 -0500)]
Move EDH support to common files

The EDH support is not really specific to the OpenSSL implementation, so
move the support and documentation comments to common files.

6 years agoSplit out documentation of SSL parameters into their own section
Peter Eisentraut [Fri, 19 Jan 2018 00:12:05 +0000 (19:12 -0500)]
Split out documentation of SSL parameters into their own section

Split the "Authentication and Security" section into two separate
sections "Authentication" and "SSL".  The latter part has gotten much
longer over time, and doesn't primarily have to do with authentication.

Also, the row_security parameter was inconsistently categorized, so
clean that up while we're here.

6 years agoAdd installcheck support to more test suites
Peter Eisentraut [Fri, 19 Jan 2018 17:17:35 +0000 (12:17 -0500)]
Add installcheck support to more test suites

Several of the test suites under src/test/ were missing an installcheck
target.

6 years agoMove handling of database properties from pg_dumpall into pg_dump.
Tom Lane [Mon, 22 Jan 2018 19:09:09 +0000 (14:09 -0500)]
Move handling of database properties from pg_dumpall into pg_dump.

This patch rearranges the division of labor between pg_dump and pg_dumpall
so that pg_dump itself handles all properties attached to a single
database.  Notably, a database's ACL (GRANT/REVOKE status) and local GUC
settings established by ALTER DATABASE SET and ALTER ROLE IN DATABASE SET
can be dumped and restored by pg_dump.  This is a long-requested
improvement.

"pg_dumpall -g" will now produce only role- and tablespace-related output,
nothing about individual databases.  The total output of a regular
pg_dumpall run remains the same.

pg_dump (or pg_restore) will restore database-level properties only when
creating the target database with --create.  This applies not only to
ACLs and GUCs but to the other database properties it already handled,
that is database comments and security labels.  This is more consistent
and useful, but does represent an incompatibility in the behavior seen
without --create.

(This change makes the proposed patch to have pg_dump use "COMMENT ON
DATABASE CURRENT_DATABASE" unnecessary, since there is no case where
the command is issued that we won't know the true name of the database.
We might still want that patch as a feature in its own right, but pg_dump
no longer needs it.)

pg_dumpall with --clean will now drop and recreate the "postgres" and
"template1" databases in the target cluster, allowing their locale and
encoding settings to be changed if necessary, and providing a cleaner
way to set nondefault tablespaces for them than we had before.  This
means that such a script must now always be started in the "postgres"
database; the order of drops and reconnects will not work otherwise.
Without --clean, the script will not adjust any database-level properties
of those two databases (including their comments, ACLs, and security
labels, which it formerly would try to set).

Another minor incompatibility is that the CREATE DATABASE commands in a
pg_dumpall script will now always specify locale and encoding settings.
Formerly those would be omitted if they matched the cluster's default.
While that behavior had some usefulness in some migration scenarios,
it also posed a significant hazard of unwanted locale/encoding changes.
To migrate to another locale/encoding, it's now necessary to use pg_dump
without --create to restore into a database with the desired settings.

Commit 4bd371f6f's hack to emit "SET default_transaction_read_only = off"
is gone: we now dodge that problem by the expedient of not issuing ALTER
DATABASE SET commands until after reconnecting to the target database.
Therefore, such settings won't apply during the restore session.

In passing, improve some shaky grammar in the docs, and add a note pointing
out that pg_dumpall's output can't be expected to load without any errors.
(Someday we might want to fix that, but this is not that patch.)

Haribabu Kommi, reviewed at various times by Andreas Karlsson,
Vaishnavi Prabakaran, and Robert Haas; further hacking by me.

Discussion: https://postgr.es/m/CAJrrPGcUurV0eWTeXODwsOYFN=Ekq36t1s0YnFYUNzsmRfdAyA@mail.gmail.com

6 years agoReorder code in pg_dump to dump comments etc in a uniform order.
Tom Lane [Mon, 22 Jan 2018 17:37:11 +0000 (12:37 -0500)]
Reorder code in pg_dump to dump comments etc in a uniform order.

Most of the code in pg_dump dumps an object's comment, security label,
and ACL auxiliary TOC entries, in that order, immediately after the
object's main TOC entry, and at least dumpComment's API spec says this
isn't optional.  dumpDatabase was significantly violating that when
in binary-upgrade mode, by inserting totally unrelated stuff between.
Also, dumpForeignDataWrapper and dumpForeignServer were being randomly
inconsistent.  Reorder code so everybody does it the same.

This may be future-proofing us against some code growing a requirement for
such auxiliary entries to be adjacent to their main entry.  But for now
it's just neatnik-ism, so I see no need for back-patch.

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

6 years agoPL/Python: Fix tests for older Python versions
Peter Eisentraut [Mon, 22 Jan 2018 17:09:52 +0000 (12:09 -0500)]
PL/Python: Fix tests for older Python versions

Commit 8561e4840c81f7e345be2df170839846814fa004 neglected to handle
older Python versions that don't support the "with" statement.  So write
the tests in a way that older versions can handle as well.

6 years agoMake pg_dump's ACL, sec label, and comment entries reliably identifiable.
Tom Lane [Mon, 22 Jan 2018 17:06:18 +0000 (12:06 -0500)]
Make pg_dump's ACL, sec label, and comment entries reliably identifiable.

_tocEntryRequired() expects that it can identify ACL, SECURITY LABEL,
and COMMENT TOC entries that are for large objects by seeing whether
the tag for them starts with "LARGE OBJECT ".  While that works fine
for actual large objects, which are indeed tagged that way, it's
subject to false positives unless every such entry's tag starts with an
appropriate type ID.  And in fact it does not work for ACLs, because
up to now we customarily tagged those entries with just the bare name
of the object.  This means that an ACL for an object named
"LARGE OBJECT something" would be misclassified as data not schema,
with undesirable results in a schema-only or data-only dump ---
although pg_upgrade seems unaffected, due to the special case for
binary-upgrade mode further down in _tocEntryRequired().

We can fix this by changing all the dumpACL calls to use the label
strings already in use for comments and security labels, which do
follow the convention of starting with an object type indicator.

Well, mostly they follow it.  dumpDatabase() got it wrong, using
just the bare database name for those purposes, so that a database
named "LARGE OBJECT something" would similarly be subject to having
its comment or security label dropped or included when not wanted.
Bring that into line too.  (Note that up to now, database ACLs have
not been processed by pg_dump, so that this issue doesn't affect them.)

_tocEntryRequired() itself is not free of fault: it was overly liberal
about matching object tags to "LARGE OBJECT " in binary-upgrade mode.
This looks like it is probably harmless because there would be no data
component to strip anyway in that mode, but at best it's trouble
waiting to happen, so tighten that up too.

The possible misclassification of SECURITY LABEL entries for databases is
in principle a security problem, but the opportunities for actual exploits
seem too narrow to be interesting.  The other cases seem like just bugs,
since an object owner can change its ACL or comment for himself, he needn't
try to trick someone else into doing it by choosing a strange name.

This has been broken since per-large-object TOC entries were introduced
in 9.0, so back-patch to all supported branches.

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

6 years agoTransaction control in PL procedures
Peter Eisentraut [Mon, 22 Jan 2018 13:30:16 +0000 (08:30 -0500)]
Transaction control in PL procedures

In each of the supplied procedural languages (PL/pgSQL, PL/Perl,
PL/Python, PL/Tcl), add language-specific commit and rollback
functions/commands to control transactions in procedures in that
language.  Add similar underlying functions to SPI.  Some additional
cleanup so that transaction commit or abort doesn't blow away data
structures still used by the procedure call.  Add execution context
tracking to CALL and DO statements so that transaction control commands
can only be issued in top-level procedure and block calls, not function
calls or other procedure or block calls.

- SPI

Add a new function SPI_connect_ext() that is like SPI_connect() but
allows passing option flags.  The only option flag right now is
SPI_OPT_NONATOMIC.  A nonatomic SPI connection can execute transaction
control commands, otherwise it's not allowed.  This is meant to be
passed down from CALL and DO statements which themselves know in which
context they are called.  A nonatomic SPI connection uses different
memory management.  A normal SPI connection allocates its memory in
TopTransactionContext.  For nonatomic connections we use PortalContext
instead.  As the comment in SPI_connect_ext() (previously SPI_connect())
indicates, one could potentially use PortalContext in all cases, but it
seems safest to leave the existing uses alone, because this stuff is
complicated enough already.

SPI also gets new functions SPI_start_transaction(), SPI_commit(), and
SPI_rollback(), which can be used by PLs to implement their transaction
control logic.

- portalmem.c

Some adjustments were made in the code that cleans up portals at
transaction abort.  The portal code could already handle a command
*committing* a transaction and continuing (e.g., VACUUM), but it was not
quite prepared for a command *aborting* a transaction and continuing.

In AtAbort_Portals(), remove the code that marks an active portal as
failed.  As the comment there already predicted, this doesn't work if
the running command wants to keep running after transaction abort.  And
it's actually not necessary, because pquery.c is careful to run all
portal code in a PG_TRY block and explicitly runs MarkPortalFailed() if
there is an exception.  So the code in AtAbort_Portals() is never used
anyway.

In AtAbort_Portals() and AtCleanup_Portals(), we need to be careful not
to clean up active portals too much.  This mirrors similar code in
PreCommit_Portals().

- PL/Perl

Gets new functions spi_commit() and spi_rollback()

- PL/pgSQL

Gets new commands COMMIT and ROLLBACK.

Update the PL/SQL porting example in the documentation to reflect that
transactions are now possible in procedures.

- PL/Python

Gets new functions plpy.commit and plpy.rollback.

- PL/Tcl

Gets new commands commit and rollback.

Reviewed-by: Andrew Dunstan <andrew.dunstan@2ndquadrant.com>
6 years agoFix docs typo
Magnus Hagander [Mon, 22 Jan 2018 09:18:09 +0000 (10:18 +0100)]
Fix docs typo

Spotted by Thomas Munro

6 years agoSupport huge pages on Windows
Magnus Hagander [Sun, 21 Jan 2018 14:40:46 +0000 (15:40 +0100)]
Support huge pages on Windows

Add support for huge pages (called large pages on Windows) to the
Windows build.

This (probably) breaks compatibility with Windows versions prior to
Windows 2003 or Windows Vista.

Authors: Takayuki Tsunakawa and Thomas Munro
Reviewed by: Magnus Hagander, Amit Kapila

6 years agoFix wording of "hostaddrs"
Magnus Hagander [Sun, 21 Jan 2018 12:40:55 +0000 (13:40 +0100)]
Fix wording of "hostaddrs"

The field is still called "hostaddr", so make sure references use
"hostaddr values" instead.

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

6 years agodoc: update intermediate certificate instructions
Bruce Momjian [Sun, 21 Jan 2018 02:47:02 +0000 (21:47 -0500)]
doc:  update intermediate certificate instructions

Document how to properly create root and intermediate certificates using
v3_ca extensions and where to place intermediate certificates so they
are properly transferred to the remote side with the leaf certificate to
link to the remote root certificate.  This corrects docs that used to
say that intermediate certificates must be stored with the root
certificate.

Also add instructions on how to create root, intermediate, and leaf
certificates.

Discussion: https://postgr.es/m/20180116002238.GC12724@momjian.us

Reviewed-by: Michael Paquier
Backpatch-through: 9.3

6 years agoImprove type conversion of SPI_processed in Python
Peter Eisentraut [Sat, 20 Jan 2018 13:02:01 +0000 (08:02 -0500)]
Improve type conversion of SPI_processed in Python

The previous code converted SPI_processed to a Python float if it didn't
fit into a Python int.  But Python longs have unlimited precision, so
use that instead in all cases.

As in eee50a8d4c389171ad5180568a7221f7e9b28f09, we use the Python
LongLong API unconditionally for simplicity.

Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
6 years agoSuppress possibly-uninitialized-variable warnings.
Tom Lane [Sat, 20 Jan 2018 03:16:25 +0000 (22:16 -0500)]
Suppress possibly-uninitialized-variable warnings.

Apparently, Peter's compiler has faith that the switch test values here
could never not be valid values of their enums.  Mine does not, and
I tend to agree with it.

6 years agoPL/Python: Simplify PLyLong_FromInt64
Peter Eisentraut [Fri, 19 Jan 2018 22:22:38 +0000 (17:22 -0500)]
PL/Python: Simplify PLyLong_FromInt64

We don't actually need two code paths, one for 32 bits and one for 64
bits.  Since the existing code already assumed that "long long" is
available, we can just use PyLong_FromLongLong() for 64 bits as well.
In Python 2.5 and later, PyLong_FromLong() and PyLong_FromLongLong() use
the same code, so there will be no difference for 64-bit platforms.  In
Python 2.4, the code is different, but performance testing showed no
noticeable difference in PL/Python, and that Python version is ancient
anyway.

Discussion: https://www.postgresql.org/message-id/0a02203c-e157-55b2-464e-6087066a1849@2ndquadrant.com

6 years agoAllow UPDATE to move rows between partitions.
Robert Haas [Fri, 19 Jan 2018 20:33:06 +0000 (15:33 -0500)]
Allow UPDATE to move rows between partitions.

When an UPDATE causes a row to no longer match the partition
constraint, try to move it to a different partition where it does
match the partition constraint.  In essence, the UPDATE is split into
a DELETE from the old partition and an INSERT into the new one.  This
can lead to surprising behavior in concurrency scenarios because
EvalPlanQual rechecks won't work as they normally did; the known
problems are documented.  (There is a pending patch to improve the
situation further, but it needs more review.)

Amit Khandekar, reviewed and tested by Amit Langote, David Rowley,
Rajkumar Raghuwanshi, Dilip Kumar, Amul Sul, Thomas Munro, Álvaro
Herrera, Amit Kapila, and me.  A few final revisions by me.

Discussion: http://postgr.es/m/CAJ3gD9do9o2ccQ7j7+tSgiE1REY65XRiMb=yJO3u3QhyP8EEPQ@mail.gmail.com

6 years agoFix CompareIndexInfo's attnum comparisons
Alvaro Herrera [Fri, 19 Jan 2018 19:34:44 +0000 (16:34 -0300)]
Fix CompareIndexInfo's attnum comparisons

When an index column is an expression, it makes no sense to compare its
attribute numbers.

This seems to account for remaining buildfarm fallout from 8b08f7d4820f.
At least, it solves the issue in my local 32bit VM -- let's see what the
rest thinks.

6 years agoReplace AclObjectKind with ObjectType
Peter Eisentraut [Sat, 2 Dec 2017 14:26:34 +0000 (09:26 -0500)]
Replace AclObjectKind with ObjectType

AclObjectKind was basically just another enumeration for object types,
and we already have a preferred one for that.  It's only used in
aclcheck_error.  By using ObjectType instead, we can also give some more
precise error messages, for example "index" instead of "relation".

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
6 years agoReplace GrantObjectType with ObjectType
Peter Eisentraut [Wed, 11 Oct 2017 22:35:19 +0000 (18:35 -0400)]
Replace GrantObjectType with ObjectType

There used to be a lot of different *Type and *Kind symbol groups to
address objects within different commands, most of which have been
replaced by ObjectType, starting with
b256f2426433c56b4bea3a8102757749885b81ba.  But this conversion was never
done for the ACL commands until now.

This change ends up being just a plain replacement of the types and
symbols, without any code restructuring needed, except deleting some now
redundant code.

Reviewed-by: Michael Paquier <michael.paquier@gmail.com>
Reviewed-by: Stephen Frost <sfrost@snowman.net>
6 years agoFix pg_dump version comparison
Alvaro Herrera [Fri, 19 Jan 2018 16:23:49 +0000 (13:23 -0300)]
Fix pg_dump version comparison

I missed a '0' in the version number string ...

Per buildfarm member crake.

6 years agoFix regression tests for better stability
Alvaro Herrera [Fri, 19 Jan 2018 15:31:34 +0000 (12:31 -0300)]
Fix regression tests for better stability

Per buildfarm

6 years agoLocal partitioned indexes
Alvaro Herrera [Fri, 19 Jan 2018 14:49:22 +0000 (11:49 -0300)]
Local partitioned indexes

When CREATE INDEX is run on a partitioned table, create catalog entries
for an index on the partitioned table (which is just a placeholder since
the table proper has no data of its own), and recurse to create actual
indexes on the existing partitions; create them in future partitions
also.

As a convenience gadget, if the new index definition matches some
existing index in partitions, these are picked up and used instead of
creating new ones.  Whichever way these indexes come about, they become
attached to the index on the parent table and are dropped alongside it,
and cannot be dropped on isolation unless they are detached first.

To support pg_dump'ing these indexes, add commands
    CREATE INDEX ON ONLY <table>
(which creates the index on the parent partitioned table, without
recursing) and
    ALTER INDEX ATTACH PARTITION
(which is used after the indexes have been created individually on each
partition, to attach them to the parent index).  These reconstruct prior
database state exactly.

Reviewed-by: (in alphabetical order) Peter Eisentraut, Robert Haas, Amit
Langote, Jesper Pedersen, Simon Riggs, David Rowley
Discussion: https://postgr.es/m/20171113170646.gzweigyrgg6pwsg4@alvherre.pgsql

6 years agoFix StoreCatalogInheritance1 to use 32bit inhseqno
Alvaro Herrera [Fri, 19 Jan 2018 13:15:08 +0000 (10:15 -0300)]
Fix StoreCatalogInheritance1 to use 32bit inhseqno

For no apparent reason, this function was using a 16bit-wide inhseqno
value, rather than the correct 32 bit width which is what is stored in
the pg_inherits catalog.  This becomes evident if you try to create a
table with more than 65535 parents, because this error appears:

ERROR:  duplicate key value violates unique constraint «pg_inherits_relid_seqno_index»
DETAIL:  Key (inhrelid, inhseqno)=(329371, 0) already exists.

Needless to say, having so many parents is an uncommon situations, which
explains why this error has never been reported despite being having
been introduced with the Postgres95 1.01 sources in commit d31084e9d111:
https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/commands/creatinh.c;hb=d31084e9d111#l349

Backpatch all the way back.

David Rowley noticed this while reviewing a patch of mine.
Discussion: https://postgr.es/m/CAKJS1f8Dn7swSEhOWwzZzssW7747YB=2Hi+T7uGud40dur69-g@mail.gmail.com

6 years agoTransfer state pertaining to pending REINDEX operations to workers.
Robert Haas [Fri, 19 Jan 2018 12:48:44 +0000 (07:48 -0500)]
Transfer state pertaining to pending REINDEX operations to workers.

This will allow the pending patch for parallel CREATE INDEX to work
on system catalogs, and to provide the same level of protection
against use of user indexes while they are being rebuilt that we
have for non-parallel CREATE INDEX.

Patch by me, reviewed by Peter Geoghegan.

Discussion: http://postgr.es/m/CA+TgmoYN-YQU9JsGQcqFLovZ-C+Xgp1_xhJQad=cunGG-_p5gg@mail.gmail.com
Discussion: http://postgr.es/m/CAH2-Wzkv4UNkXYhqQRqk-u9rS7h5c-4cCW+EqQ8K_WSeS43aZg@mail.gmail.com

6 years agoFix typo in recent commit
Simon Riggs [Fri, 19 Jan 2018 06:36:17 +0000 (06:36 +0000)]
Fix typo in recent commit

Typo in 9c7d06d60680c7f00d931233873dee81fdb311c6

Reported-by: Masahiko Sawada
6 years agoUpdate comment
Peter Eisentraut [Fri, 19 Jan 2018 00:36:34 +0000 (19:36 -0500)]
Update comment

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

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

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

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

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

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

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

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

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

Marina Polyakova, Victor Wagner, Tom Lane

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

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

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

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

Author: Etsuro Fujita

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

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

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

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

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

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

Etsuro Fujita, reviewed by Amit Langote

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

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

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

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

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