Fix longstanding race condition in plancache.c.

When creating or manipulating a cached plan for a transaction control
command (particularly ROLLBACK), we must not perform any catalog accesses,
since we might be in an aborted transaction.  However, plancache.c busily
saved or examined the search_path for every cached plan.  If we were
unlucky enough to do this at a moment where the path's expansion into
schema OIDs wasn't already cached, we'd do some catalog accesses; and with
some more bad luck such as an ill-timed signal arrival, that could lead to
crashes or Assert failures, as exhibited in bug #8095 from Nachiket Vaidya.
Fortunately, there's no real need to consider the search path for such
commands, so we can just skip the relevant steps when the subject statement
is a TransactionStmt.  This is somewhat related to bug #5269, though the
failure happens during initial cached-plan creation rather than
revalidation.

This bug has been there since the plan cache was invented, so back-patch
to all supported branches.
Fix typo in comment.

Peter Geoghegan
Avoid deadlock between concurrent CREATE INDEX CONCURRENTLY commands.

There was a high probability of two or more concurrent C.I.C. commands
deadlocking just before completion, because each would wait for the others
to release their reference snapshots.  Fix by releasing the snapshot
before waiting for other snapshots to go away.

Per report from Paul Hinze.  Back-patch to all active branches.
Ensure that user created rows in extension tables get dumped if the table is explicitly requested, either with a -t/--table switch of the table itself, or by -n/--schema switch of the schema containing the extension table. Patch reviewed by Vibhor Kumar and Dimitri Fontaine.

Backpatched to 9.1 when the extension management facility was added.
Ensure ANALYZE phase is not skipped because of canceled truncate.

Patch b19e4250b45e91c9cbdd18d35ea6391ab5961c8d attempted to
preserve existing behavior regarding statistics generation in the
case that a truncation attempt was canceled due to lock conflicts.
It failed to do this accurately in two regards: (1) autovacuum had
previously generated statistics if the truncate attempt failed to
initially get the lock rather than having started the attempt, and
(2) the VACUUM ANALYZE command had always generated statistics.

Both of these changes were unintended, and are reverted by this
patch.  On review, there seems to be consensus that the previous
failure to generate statistics when the truncate was terminated
was more an unfortunate consequence of how that effort was
previously terminated than a feature we want to keep; so this
patch generates statistics even when an autovacuum truncation
attempt terminates early.  Another unintended change which is kept
on the basis that it is an improvement is that when a VACUUM
command is truncating, it will the new heuristic for avoiding
blocking other processes, rather than keeping an
AccessExclusiveLock on the table for however long the truncation
takes.

Per multiple reports, with some renaming per patch by Jeff Janes.

Backpatch to 9.0, where problem was created.
Install recycled WAL segments with current timeline ID during recovery.

This is a follow-up to the earlier fix, which changed the recycling logic
to recycle WAL segments under the current recovery target timeline. That
turns out to be a bad idea, because installing a recycled segment with
a TLI higher than what we're recovering at the moment means that the recovery
logic will find the recycled WAL segment and try to replay it. It will fail,
but but the mere presence of such a WAL segment will mask any other, real,
file with the same log/seg, but smaller TLI.

Per report from Mitsumasa Kondo. Apply to 9.1 and 9.2, like the previous
fix. Master was already doing this differently; this patch makes 9.1 and
9.2 to do the same thing as master.
Fix thinko in comment.

WAL segment means a 16 MB physical WAL file; this comment meant a logical
4 GB log file.

Amit Langote. Apply to backbranches only, as the comment is gone in master.
doc: fix log_line_prefix session_id %c item

Backpatch to 9.1 and earlier

Report from Ian Lawrence Barwick
docs:  log_line_prefix session id fix

Restore 4-byte designation for docs.  Fix 9.3 doc query to properly pad
to four digits.

Backpatch to all active branches

Per suggestions from Ian Lawrence Barwick
Use pg_dump's --quote-all-identifiers option in pg_upgrade.

This helps guard against changes in the set of reserved keywords from
one version to another.  In theory it should only be an issue if we
de-reserve a keyword in a newer release, since that can create the type
of problem shown in bug #8128.

Back-patch to 9.1 where the --quote-all-identifiers option was added.
Fix pgp_pub_decrypt() so it works for secret keys with passwords.

Per report from Keith Fiske.

Marko Kreen
Guard against input_rows == 0 in estimate_num_groups().

This case doesn't normally happen, because the planner usually clamps
all row estimates to at least one row; but I found that it can arise
when dealing with relations excluded by constraints.  Without a defense,
estimate_num_groups() can return zero, which leads to divisions by zero
inside the planner as well as assertion failures in the executor.

An alternative fix would be to change set_dummy_rel_pathlist() to make
the size estimate for a dummy relation 1 row instead of 0, but that seemed
pretty ugly; and probably someday we'll want to drop the convention that
the minimum rowcount estimate is 1 row.

Back-patch to 8.4, as the problem can be demonstrated that far back.
Fix handling of OID wraparound while in standalone mode.

If OID wraparound should occur while in standalone mode (unlikely but
possible), we want to advance the counter to FirstNormalObjectId not
FirstBootstrapObjectId.  Otherwise, user objects might be created with OIDs
in the system-reserved range.  That isn't immediately harmful but it poses
a risk of conflicts during future pg_upgrade operations.

Noted by Andres Freund.  Back-patch to all supported branches, since all of
them are supported sources for pg_upgrade operations.
Fix fd.c to preserve errno where needed.

PathNameOpenFile failed to ensure that the correct value of errno was
returned to its caller after a failure (because it incorrectly supposed
that free() can never change errno).  In some cases this would result
in a user-visible failure because an expected ENOENT errno was replaced
with something else.  Bogus EINVAL failures have been observed on OS X,
for example.

There were also a couple of places that could mangle an important value
of errno if FDDEBUG was defined.  While the usefulness of that debug
support is highly debatable, we might as well make it safe to use,
so add errno save/restore logic to the DO_DB macro.

Per bug #8167 from Nelson Minar, diagnosed by RhodiumToad.
Back-patch to all supported branches.
Fix typo in comment.

Pavan Deolasee
Documentation fix for ALTER TYPE .. RENAME

The documentation for ALTER TYPE .. RENAME claimed to support a
RESTRICT/CASCADE option at the 'type' level, which wasn't implemented
and doesn't make a whole lot of sense to begin with.  What is supported,
and previously undocumented, is

ALTER TYPE .. RENAME ATTRIBUTE .. RESTRICT/CASCADE.

I've updated the documentation and back-patched this to 9.1 where it was
first introduced.
Allow type_func_name_keywords in some places where they weren't before.

This change makes type_func_name_keywords less reserved than they were
before, by allowing them for role names, language names, EXPLAIN and COPY
options, and SET values for GUCs; which are all places where few if any
actual keywords could appear instead, so no new ambiguities are introduced.

The main driver for this change is to allow "COPY ... (FORMAT BINARY)"
to work without quoting the word "binary".  That is an inconsistency that
has been complained of repeatedly over the years (at least by Pavel Golub,
Kurt Lidl, and Simon Riggs); but we hadn't thought of any non-ugly solution
until now.

Back-patch to 9.0 where the COPY (FORMAT BINARY) syntax was introduced.
Add semicolons to eval'd strings to hide a minor Perl behavioral change.

"eval q{foo}" used to complain that the error was on line 2 of the eval'd
string, because eval internally tacked on "\n;" so that the end of the
erroneous command was indeed on line 2.  But as of Perl 5.18 it more
sanely says that the error is on line 1.  To avoid Perl-version-dependent
regression test results, use "eval q{foo;}" instead in the two places
where this matters.  Per buildfarm.

Since people might try to use newer Perl versions with older PG releases,
back-patch as far as 9.0 where these test cases were added.
Fix memory leak in LogStandbySnapshot().

The array allocated by GetRunningTransactionLocks() needs to be pfree'd
when we're done with it.  Otherwise we leak some memory during each
checkpoint, if wal_level = hot_standby.  This manifests as memory bloat
in the checkpointer process, or in bgwriter in versions before we made
the checkpointer separate.

Reported and fixed by Naoya Anzai.  Back-patch to 9.0 where the issue
was introduced.

In passing, improve comments for GetRunningTransactionLocks(), and add
an Assert that we didn't overrun the palloc'd array.
Provide better message when CREATE EXTENSION can't find a target schema.

The new message (and SQLSTATE) matches the corresponding error cases in
namespace.c.

This was thought to be a "can't happen" case when extension.c was written,
so we didn't think hard about how to report it.  But it definitely can
happen in 9.2 and later, since we no longer require search_path to contain
any valid schema names.  It's probably also possible in 9.1 if search_path
came from a noninteractive source.  So, back-patch to all releases
containing this code.

Per report from Sean Chittenden, though this isn't exactly his patch.