]> granicus.if.org Git - postgresql/log
postgresql
9 years agoFix deadlock at startup, if max_prepared_transactions is too small.
Heikki Linnakangas [Thu, 23 Apr 2015 18:25:44 +0000 (21:25 +0300)]
Fix deadlock at startup, if max_prepared_transactions is too small.

When the startup process recovers transactions by scanning pg_twophase
directory, it should clear MyLockedGxact after it's done processing each
transaction. Like we do during normal operation, at PREPARE TRANSACTION.
Otherwise, if the startup process exits due to an error, it will try to
clear the locking_backend field of the last recovered transaction. That's
usually harmless, but if the error happens in MarkAsPreparing, while
holding TwoPhaseStateLock, the shmem-exit hook will try to acquire
TwoPhaseStateLock again, and deadlock with itself.

This fixes bug #13128 reported by Grant McAlister. The bug was introduced
by commit bb38fb0d, so backpatch to all supported versions like that
commit.

9 years agopg_upgrade: document need for text search files to be copied
Bruce Momjian [Fri, 17 Apr 2015 01:38:00 +0000 (21:38 -0400)]
pg_upgrade:  document need for text search files to be copied

Report by CJ Estel

Backpatch through 9.4

9 years agoFix typo in comment
Alvaro Herrera [Tue, 14 Apr 2015 15:12:18 +0000 (12:12 -0300)]
Fix typo in comment

SLRU_SEGMENTS_PER_PAGE -> SLRU_PAGES_PER_SEGMENT

I introduced this ancient typo in subtrans.c and later propagated it to
multixact.c.  I fixed the latter in f741300c, but only back to 9.3;
backpatch to all supported branches for consistency.

9 years agoDon't archive bogus recycled or preallocated files after timeline switch.
Heikki Linnakangas [Mon, 13 Apr 2015 13:53:49 +0000 (16:53 +0300)]
Don't archive bogus recycled or preallocated files after timeline switch.

After a timeline switch, we would leave behind recycled WAL segments that
are in the future, but on the old timeline. After promotion, and after they
become old enough to be recycled again, we would notice that they don't have
a .ready or .done file, create a .ready file for them, and archive them.
That's bogus, because the files contain garbage, recycled from an older
timeline (or prealloced as zeros). We shouldn't archive such files.

This could happen when we're following a timeline switch during replay, or
when we switch to new timeline at end-of-recovery.

To fix, whenever we switch to a new timeline, scan the data directory for
WAL segments on the old timeline, but with a higher segment number, and
remove them. Those don't belong to our timeline history, and are most
likely bogus recycled or preallocated files. They could also be valid files
that we streamed from the primary ahead of time, but in any case, they're
not needed to recover to the new timeline.

9 years agoRemove duplicated words in comments.
Heikki Linnakangas [Sun, 12 Apr 2015 07:46:17 +0000 (10:46 +0300)]
Remove duplicated words in comments.

David Rowley

9 years agoFix incorrect punctuation
Magnus Hagander [Thu, 9 Apr 2015 11:35:30 +0000 (13:35 +0200)]
Fix incorrect punctuation

Amit Langote

9 years agoFix autovacuum launcher shutdown sequence
Alvaro Herrera [Wed, 8 Apr 2015 16:19:49 +0000 (13:19 -0300)]
Fix autovacuum launcher shutdown sequence

It was previously possible to have the launcher re-execute its main loop
before shutting down if some other signal was received or an error
occurred after getting SIGTERM, as reported by Qingqing Zhou.

While investigating, Tom Lane further noticed that if autovacuum had
been disabled in the config file, it would misbehave by trying to start
a new worker instead of bailing out immediately -- it would consider
itself as invoked in emergency mode.

Fix both problems by checking the shutdown flag in a few more places.
These problems have existed since autovacuum was introduced, so
backpatch all the way back.

9 years agoFix assorted inconsistent function declarations.
Tom Lane [Tue, 7 Apr 2015 20:56:21 +0000 (16:56 -0400)]
Fix assorted inconsistent function declarations.

While gcc doesn't complain if you declare a function "static" and then
define it not-static, other compilers do; and in any case the code is
highly misleading this way.  Add the missing "static" keywords to a
couple of recent patches.  Per buildfarm member pademelon.

9 years agoFix spelling of author's name
Simon Riggs [Tue, 7 Apr 2015 18:05:05 +0000 (14:05 -0400)]
Fix spelling of author's name

9 years agoFix typo in libpq.sgml.
Fujii Masao [Mon, 6 Apr 2015 03:15:20 +0000 (12:15 +0900)]
Fix typo in libpq.sgml.

Back-patch to all supported versions.

Michael Paquier

9 years agoSuppress clang's unhelpful gripes about -pthread switch being unused.
Tom Lane [Sun, 5 Apr 2015 17:01:55 +0000 (13:01 -0400)]
Suppress clang's unhelpful gripes about -pthread switch being unused.

Considering the number of cases in which "unused" command line arguments
are silently ignored by compilers, it's fairly astonishing that anybody
thought this warning was useful; it's certainly nothing but an annoyance
when building Postgres.  One such case is that neither gcc nor clang
complain about unrecognized -Wno-foo switches, making it more difficult
to figure out whether the switch does anything than one could wish.

Back-patch to 9.3, which is as far back as the patch applies conveniently
(we'd have to back-patch PGAC_PROG_CC_VAR_OPT to go further, and it doesn't
seem worth that).

9 years agoFix incorrect matching of subexpressions in outer-join plan nodes.
Tom Lane [Sat, 4 Apr 2015 23:55:15 +0000 (19:55 -0400)]
Fix incorrect matching of subexpressions in outer-join plan nodes.

Previously we would re-use input subexpressions in all expression trees
attached to a Join plan node.  However, if it's an outer join and the
subexpression appears in the nullable-side input, this is potentially
incorrect for apparently-matching subexpressions that came from above
the outer join (ie, targetlist and qpqual expressions), because the
executor will treat the subexpression value as NULL when maybe it should
not be.

The case is fairly hard to hit because (a) you need a non-strict
subexpression (else NULL is correct), and (b) we don't usually compute
expressions in the outputs of non-toplevel plan nodes.  But we might do
so if the expressions are sort keys for a mergejoin, for example.

Probably in the long run we should make a more explicit distinction between
Vars appearing above and below an outer join, but that will be a major
planner redesign and not at all back-patchable.  For the moment, just hack
set_join_references so that it will not match any non-Var expressions
coming from nullable inputs to expressions that came from above the join.
(This is somewhat overkill, in that a strict expression could still be
matched, but it doesn't seem worth the effort to check that.)

Per report from Qingqing Zhou.  The added regression test case is based
on his example.

This has been broken for a very long time, so back-patch to all active
branches.

9 years agoFix TAP tests to use only standard command-line argument ordering.
Tom Lane [Sat, 4 Apr 2015 17:34:23 +0000 (13:34 -0400)]
Fix TAP tests to use only standard command-line argument ordering.

Some of the TAP tests were supposing that PG programs would accept switches
after non-switch arguments on their command lines.  While GNU getopt_long()
does allow that, our own implementation does not, and it's nowhere
suggested in our documentation that such cases should work.  Adjust the
tests to use only the documented syntax.

Back-patch to 9.4, since without this the TAP tests fail when run with
src/port's getopt_long() implementation.

Michael Paquier

9 years agoRemove unnecessary variables in _hash_splitbucket().
Tom Lane [Fri, 3 Apr 2015 20:49:11 +0000 (16:49 -0400)]
Remove unnecessary variables in _hash_splitbucket().

Commit ed9cc2b5df59fdbc50cce37399e26b03ab2c1686 made it unnecessary to pass
start_nblkno to _hash_splitbucket(), and for that matter unnecessary to
have the internal nblkno variable either.  My compiler didn't complain
about that, but some did.  I also rearranged the use of oblkno a bit to
make that case more parallel.

Report and initial patch by Petr Jelinek, rearranged a bit by me.
Back-patch to all branches, like the previous patch.

9 years agoFix rare startup failure induced by MVCC-catalog-scans patch.
Tom Lane [Fri, 3 Apr 2015 04:07:29 +0000 (00:07 -0400)]
Fix rare startup failure induced by MVCC-catalog-scans patch.

While a new backend nominally participates in sinval signaling starting
from the SharedInvalBackendInit call near the top of InitPostgres, it
cannot recognize sinval messages for unshared catalogs of its database
until it has set up MyDatabaseId.  This is not problematic for the catcache
or relcache, which by definition won't have loaded any data from or about
such catalogs before that point.  However, commit 568d4138c646cd7c
introduced a mechanism for re-using MVCC snapshots for catalog scans, and
made invalidation of those depend on recognizing relevant sinval messages.
So it's possible to establish a catalog snapshot to read pg_authid and
pg_database, then before we set MyDatabaseId, receive sinval messages that
should result in invalidating that snapshot --- but do not, because we
don't realize they are for our database.  This mechanism explains the
intermittent buildfarm failures we've seen since commit 31eae6028eca4365.
That commit was not itself at fault, but it introduced a new regression
test that does reconnections concurrently with the "vacuum full pg_am"
command in vacuum.sql.  This allowed the pre-existing error to be exposed,
given just the right timing, because we'd fail to update our information
about how to access pg_am.  In principle any VACUUM FULL on a system
catalog could have created a similar hazard for concurrent incoming
connections.  Perhaps there are more subtle failure cases as well.

To fix, force invalidation of the catalog snapshot as soon as we've
set MyDatabaseId.

Back-patch to 9.4 where the error was introduced.

9 years agoAfter a crash, don't restart workers with BGW_NEVER_RESTART.
Robert Haas [Thu, 2 Apr 2015 18:38:06 +0000 (14:38 -0400)]
After a crash, don't restart workers with BGW_NEVER_RESTART.

Amit Khandekar

9 years agoCorrect comment to use RS_EPHEMERAL
Simon Riggs [Thu, 2 Apr 2015 11:49:48 +0000 (07:49 -0400)]
Correct comment to use RS_EPHEMERAL

9 years agopsql: fix \connect with URIs and conninfo strings
Alvaro Herrera [Wed, 1 Apr 2015 23:00:07 +0000 (20:00 -0300)]
psql: fix \connect with URIs and conninfo strings

psql was already accepting conninfo strings as the first parameter in
\connect, but the way it worked wasn't sane; some of the other
parameters would get the previous connection's values, causing it to
connect to a completely unexpected server or, more likely, not finding
any server at all because of completely wrong combinations of
parameters.

Fix by explicitely checking for a conninfo-looking parameter in the
dbname position; if one is found, use its complete specification rather
than mix with the other arguments.  Also, change tab-completion to not
try to complete conninfo/URI-looking "dbnames" and document that
conninfos are accepted as first argument.

There was a weak consensus to backpatch this, because while the behavior
of using the dbname as a conninfo is nowhere documented for \connect, it
is reasonable to expect that it works because it does work in many other
contexts.  Therefore this is backpatched all the way back to 9.0.

To implement this, routines previously private to libpq have been
duplicated so that psql can decide what looks like a conninfo/URI
string.  In back branches, just duplicate the same code all the way back
to 9.2, where URIs where introduced; 9.0 and 9.1 have a simpler version.
In master, the routines are moved to src/common and renamed.

Author: David Fetter, Andrew Dunstan.  Some editorialization by me
(probably earning a Gierth's "Sloppy" badge in the process.)
Reviewers: Andrew Gierth, Erik Rijkers, Pavel StÄ›hule, Stephen Frost,
Robert Haas, Andrew Dunstan.

9 years agoFix incorrect markup in documentation of window frame clauses.
Tom Lane [Wed, 1 Apr 2015 00:02:40 +0000 (20:02 -0400)]
Fix incorrect markup in documentation of window frame clauses.

You're required to write either RANGE or ROWS to start a frame clause,
but the documentation incorrectly implied this is optional.  Noted by
David Johnston.

9 years agoRemove spurious semicolons.
Heikki Linnakangas [Tue, 31 Mar 2015 12:12:27 +0000 (15:12 +0300)]
Remove spurious semicolons.

Petr Jelinek

9 years agoRun pg_upgrade and pg_resetxlog with restricted token on Windows
Andrew Dunstan [Mon, 30 Mar 2015 21:16:57 +0000 (17:16 -0400)]
Run pg_upgrade and pg_resetxlog with restricted token on Windows

As with initdb these programs need to run with a restricted token, and
if they don't pg_upgrade will fail when run as a user with Adminstrator
privileges.

Backpatch to all live branches. On the development branch the code is
reorganized so that the restricted token code is now in a single
location. On the stable bramches a less invasive change is made by
simply copying the relevant code to pg_upgrade.c and pg_resetxlog.c.

Patches and bug report from Muhammad Asif Naeem, reviewed by Michael
Paquier, slightly edited by me.

9 years agoFix bogus concurrent use of _hash_getnewbuf() in bucket split code.
Tom Lane [Mon, 30 Mar 2015 20:40:05 +0000 (16:40 -0400)]
Fix bogus concurrent use of _hash_getnewbuf() in bucket split code.

_hash_splitbucket() obtained the base page of the new bucket by calling
_hash_getnewbuf(), but it held no exclusive lock that would prevent some
other process from calling _hash_getnewbuf() at the same time.  This is
contrary to _hash_getnewbuf()'s API spec and could in fact cause failures.
In practice, we must only call that function while holding write lock on
the hash index's metapage.

An additional problem was that we'd already modified the metapage's bucket
mapping data, meaning that failure to extend the index would leave us with
a corrupt index.

Fix both issues by moving the _hash_getnewbuf() call to just before we
modify the metapage in _hash_expandtable().

Unfortunately there's still a large problem here, which is that we could
also incur ENOSPC while trying to get an overflow page for the new bucket.
That would leave the index corrupt in a more subtle way, namely that some
index tuples that should be in the new bucket might still be in the old
one.  Fixing that seems substantially more difficult; even preallocating as
many pages as we could possibly need wouldn't entirely guarantee that the
bucket split would complete successfully.  So for today let's just deal
with the base case.

Per report from Antonin Houska.  Back-patch to all active branches.

9 years agoFix rare core dump in BackendIdGetTransactionIds().
Tom Lane [Mon, 30 Mar 2015 17:05:27 +0000 (13:05 -0400)]
Fix rare core dump in BackendIdGetTransactionIds().

BackendIdGetTransactionIds() neglected the possibility that the PROC
pointer in a ProcState array entry is null.  In current usage, this could
only crash if the other backend had exited since pgstat_read_current_status
saw it as active, which is a pretty narrow window.  But it's reachable in
the field, per bug #12918 from Vladimir Borodin.

Back-patch to 9.4 where the faulty code was introduced.

9 years agoAdd vacuum_delay_point call in compute_index_stats's per-sample-row loop.
Tom Lane [Sun, 29 Mar 2015 19:04:09 +0000 (15:04 -0400)]
Add vacuum_delay_point call in compute_index_stats's per-sample-row loop.

Slow functions in index expressions might cause this loop to take long
enough to make it worth being cancellable.  Probably it would be enough
to call CHECK_FOR_INTERRUPTS here, but for consistency with other
per-sample-row loops in this file, let's use vacuum_delay_point.

Report and patch by Jeff Janes.  Back-patch to all supported branches.

9 years agoMake SyncRepWakeQueue to a static function
Tatsuo Ishii [Thu, 26 Mar 2015 01:38:11 +0000 (10:38 +0900)]
Make SyncRepWakeQueue to a static function

It is only used in src/backend/replication/syncrep.c.

Back-patch to all supported branches except 9.1 which declares the
function as static.

9 years agoFix ExecOpenScanRelation to take a lock on a ROW_MARK_COPY relation.
Tom Lane [Tue, 24 Mar 2015 19:53:06 +0000 (15:53 -0400)]
Fix ExecOpenScanRelation to take a lock on a ROW_MARK_COPY relation.

ExecOpenScanRelation assumed that any relation listed in the ExecRowMark
list has been locked by InitPlan; but this is not true if the rel's
markType is ROW_MARK_COPY, which is possible if it's a foreign table.

In most (possibly all) cases, failure to acquire a lock here isn't really
problematic because the parser, planner, or plancache would have taken the
appropriate lock already.  In principle though it might leave us vulnerable
to working with a relation that we hold no lock on, and in any case if the
executor isn't depending on previously-taken locks otherwise then it should
not do so for ROW_MARK_COPY relations.

Noted by Etsuro Fujita.  Back-patch to all active versions, since the
inconsistency has been there a long time.  (It's almost certainly
irrelevant in 9.0, since that predates foreign tables, but the code's
still wrong on its own terms.)

9 years agoDon't delay replication for less than recovery_min_apply_delay's resolution.
Andres Freund [Mon, 23 Mar 2015 15:40:10 +0000 (16:40 +0100)]
Don't delay replication for less than recovery_min_apply_delay's resolution.

Recovery delays are implemented by waiting on a latch, and latches take
milliseconds as a parameter. The required amount of waiting was computed
using microsecond resolution though and the wait loop's abort condition
was checking the delay in microseconds as well.  This could lead to
short spurts of busy looping when the overall wait time was below a
millisecond, but above 0 microseconds.

Instead just formulate the wait loop's abort condition in millisecond
granularity as well. Given that that's recovery_min_apply_delay
resolution, it seems harmless to not wait for less than a millisecond.

Backpatch to 9.4 where recovery_min_apply_delay was introduced.

Discussion: 20150323141819.GH26995@alap3.anarazel.de

9 years agoFix status reporting for terminated bgworkers that were never started.
Robert Haas [Thu, 19 Mar 2015 14:56:34 +0000 (10:56 -0400)]
Fix status reporting for terminated bgworkers that were never started.

Previously, GetBackgroundWorkerPid() would return BGWH_NOT_YET_STARTED
if the slot used for the worker registration had not been reused by
unrelated activity, and BGWH_STOPPED if it had.  Either way, a process
that had requested notification when the state of one of its
background workers changed did not receive such notifications.  Fix
things so that GetBackgroundWorkerPid() always returns BGWH_STOPPED in
this situation, so that we do not erroneously give waiters the
impression that the worker will eventually be started; and send
notifications just as we would if the process terminated after having
been started, so that it's possible to wait for the postmaster to
process a worker termination request without polling.

Discovered by Amit Kapila during testing of parallel sequential scan.
Analysis and fix by me.  Back-patch to 9.4; there may not be anyone
relying on this interface yet, but if anyone is, the new behavior is a
clear improvement.

9 years agoReplace insertion sort in contrib/intarray with qsort().
Tom Lane [Mon, 16 Mar 2015 03:22:03 +0000 (23:22 -0400)]
Replace insertion sort in contrib/intarray with qsort().

It's all very well to claim that a simplistic sort is fast in easy
cases, but O(N^2) in the worst case is not good ... especially if the
worst case is as easy to hit as "descending order input".  Replace that
bit with our standard qsort.

Per bug #12866 from Maksym Boguk.  Back-patch to all active branches.

9 years agosrc/port/dirmod.c needs to be built on Cygwin too.
Tom Lane [Sun, 15 Mar 2015 18:14:24 +0000 (14:14 -0400)]
src/port/dirmod.c needs to be built on Cygwin too.

Oversight in my commit 91f4a5a976500517e492320e389342d7436cf9d4.
Per buildfarm member brolga.

9 years agoBuild src/port/dirmod.c only on Windows.
Tom Lane [Sat, 14 Mar 2015 18:08:45 +0000 (14:08 -0400)]
Build src/port/dirmod.c only on Windows.

Since commit ba7c5975adea74c6f17bdb0e0427ad85962092a2, port/dirmod.c
has contained only Windows-specific functions.  Most platforms don't
seem to mind uselessly building an empty file, but OS X for one issues
warnings.  Hence, treat dirmod.c as a Windows-specific file selected
by configure rather than one that's always built.  We can revert this
change if dirmod.c ever gains any non-Windows functionality again.

Back-patch to 9.4 where the mentioned commit appeared.

9 years agoRemove workaround for ancient incompatibility between readline and libedit.
Tom Lane [Sat, 14 Mar 2015 17:43:00 +0000 (13:43 -0400)]
Remove workaround for ancient incompatibility between readline and libedit.

GNU readline defines the return value of write_history() as "zero if OK,
else an errno code".  libedit's version of that function used to have a
different definition (to wit, "-1 if error, else the number of lines
written to the file").  We tried to work around that by checking whether
errno had become nonzero, but this method has never been kosher according
to the published API of either library.  It's reportedly completely broken
in recent Ubuntu releases: psql bleats about "No such file or directory"
when saving ~/.psql_history, even though the write worked fine.

However, libedit has been following the readline definition since somewhere
around 2006, so it seems all right to finally break compatibility with
ancient libedit releases and trust that the return value is what readline
specifies.  (I'm not sure when the various Linux distributions incorporated
this fix, but I did find that OS X has been shipping fixed versions since
10.5/Leopard.)

If anyone is still using such an ancient libedit, they will find that psql
complains it can't write ~/.psql_history at exit, even when the file was
written correctly.  This is no worse than the behavior we're fixing for
current releases.

Back-patch to all supported branches.

9 years agoFix integer overflow in debug message of walreceiver
Tatsuo Ishii [Fri, 13 Mar 2015 23:16:50 +0000 (08:16 +0900)]
Fix integer overflow in debug message of walreceiver

The message tries to tell the replication apply delay which fails if
the first WAL record is not applied yet. Fix is, instead of telling
overflowed minus numeric, showing "N/A" which indicates that the delay
data is not yet available. Problem reported by me and patch by
Fabrízio de Royes Mello.

Back patched to 9.4, 9.3 and 9.2 stable branches (9.1 and 9.0 do not
have the debug message).

9 years agoEnsure tableoid reads correctly in EvalPlanQual-manufactured tuples.
Tom Lane [Thu, 12 Mar 2015 17:38:49 +0000 (13:38 -0400)]
Ensure tableoid reads correctly in EvalPlanQual-manufactured tuples.

The ROW_MARK_COPY path in EvalPlanQualFetchRowMarks() was just setting
tableoid to InvalidOid, I think on the assumption that the referenced
RTE must be a subquery or other case without a meaningful OID.  However,
foreign tables also use this code path, and they do have meaningful
table OIDs; so failure to set the tuple field can lead to user-visible
misbehavior.  Fix that by fetching the appropriate OID from the range
table.

There's still an issue about whether CTID can ever have a meaningful
value in this case; at least with postgres_fdw foreign tables, it does.
But that is a different problem that seems to require a significantly
different patch --- it's debatable whether postgres_fdw really wants to
use this code path at all.

Simplified version of a patch by Etsuro Fujita, who also noted the
problem to begin with.  The issue can be demonstrated in all versions
having FDWs, so back-patch to 9.1.

9 years agoFix memory leaks in GIN index vacuum.
Heikki Linnakangas [Thu, 12 Mar 2015 14:29:58 +0000 (15:29 +0100)]
Fix memory leaks in GIN index vacuum.

Per bug #12850 by Walter Nordmann. Backpatch to 9.4 where the leak was
introduced.

9 years agoCast to (void *) rather than (int *) when passing int64's to PQfn().
Tom Lane [Sun, 8 Mar 2015 17:58:28 +0000 (13:58 -0400)]
Cast to (void *) rather than (int *) when passing int64's to PQfn().

This is a possibly-vain effort to silence a Coverity warning about
bogus endianness dependency.  The code's fine, because it takes care
of endianness issues for itself, but Coverity sees an int64 being
passed to an int* argument and not unreasonably suspects something's
wrong.  I'm not sure if putting the void* cast in the way will shut it
up; but it can't hurt and seems better from a documentation standpoint
anyway, since the pointer is not used as an int* in this code path.

Just for a bit of additional safety, verify that the result length
is 8 bytes as expected.

Back-patch to 9.3 where the code in question was added.

9 years agoFix documentation for libpq's PQfn().
Tom Lane [Sun, 8 Mar 2015 17:35:28 +0000 (13:35 -0400)]
Fix documentation for libpq's PQfn().

The SGML docs claimed that 1-byte integers could be sent or received with
the "isint" options, but no such behavior has ever been implemented in
pqGetInt() or pqPutInt().  The in-code documentation header for PQfn() was
even less in tune with reality, and the code itself used parameter names
matching neither the SGML docs nor its libpq-fe.h declaration.  Do a bit
of additional wordsmithing on the SGML docs while at it.

Since the business about 1-byte integers is a clear documentation bug,
back-patch to all supported branches.

9 years agoRethink function argument sorting in pg_dump.
Tom Lane [Fri, 6 Mar 2015 18:27:46 +0000 (13:27 -0500)]
Rethink function argument sorting in pg_dump.

Commit 7b583b20b1c95acb621c71251150beef958bb603 created an unnecessary
dump failure hazard by applying pg_get_function_identity_arguments()
to every function in the database, even those that won't get dumped.
This could result in snapshot-related problems if concurrent sessions are,
for example, creating and dropping temporary functions, as noted by Marko
Tiikkaja in bug #12832.  While this is by no means pg_dump's only such
issue with concurrent DDL, it's unfortunate that we added a new failure
mode for cases that used to work, and even more so that the failure was
created for basically cosmetic reasons (ie, to sort overloaded functions
more deterministically).

To fix, revert that patch and instead sort function arguments using
information that pg_dump has available anyway, namely the names of the
argument types.  This will produce a slightly different sort ordering for
overloaded functions than the previous coding; but applying strcmp
directly to the output of pg_get_function_identity_arguments really was
a bit odd anyway.  The sorting will still be name-based and hence
independent of possibly-installation-specific OID assignments.  A small
additional benefit is that sorting now works regardless of server version.

Back-patch to 9.3, where the previous commit appeared.

9 years agoFix contrib/file_fdw's expected file
Alvaro Herrera [Fri, 6 Mar 2015 14:47:09 +0000 (11:47 -0300)]
Fix contrib/file_fdw's expected file

I forgot to update it on yesterday's cf34e373fcf.

9 years agoFix user mapping object description
Alvaro Herrera [Thu, 5 Mar 2015 21:03:16 +0000 (18:03 -0300)]
Fix user mapping object description

We were using "user mapping for user XYZ" as description for user mappings, but
that's ambiguous because users can have mappings on multiple foreign
servers; therefore change it to "for user XYZ on server UVW" instead.
Object identities for user mappings are also updated in the same way, in
branches 9.3 and above.

The incomplete description string was introduced together with the whole
SQL/MED infrastructure by commit cae565e503 of 8.4 era, so backpatch all
the way back.

9 years agoAdd comment for "is_internal" parameter
Alvaro Herrera [Tue, 3 Mar 2015 17:03:33 +0000 (14:03 -0300)]
Add comment for "is_internal" parameter

This was missed in my commit f4c4335 of 9.3 vintage, so backpatch to
that.

9 years agoFix pg_dump handling of extension config tables
Stephen Frost [Mon, 2 Mar 2015 19:12:28 +0000 (14:12 -0500)]
Fix pg_dump handling of extension config tables

Since 9.1, we've provided extensions with a way to denote
"configuration" tables- tables created by an extension which the user
may modify.  By marking these as "configuration" tables, the extension
is asking for the data in these tables to be pg_dump'd (tables which
are not marked in this way are assumed to be entirely handled during
CREATE EXTENSION and are not included at all in a pg_dump).

Unfortunately, pg_dump neglected to consider foreign key relationships
between extension configuration tables and therefore could end up
trying to reload the data in an order which would cause FK violations.

This patch teaches pg_dump about these dependencies, so that the data
dumped out is done so in the best order possible.  Note that there's no
way to handle circular dependencies, but those have yet to be seen in
the wild.

The release notes for this should include a caution to users that
existing pg_dump-based backups may be invalid due to this issue.  The
data is all there, but restoring from it will require extracting the
data for the configuration tables and then loading them in the correct
order by hand.

Discussed initially back in bug #6738, more recently brought up by
Gilles Darold, who provided an initial patch which was further reworked
by Michael Paquier.  Further modifications and documentation updates
by me.

Back-patch to 9.1 where we added the concept of extension configuration
tables.

9 years agoFix targetRelation initializiation in prepsecurity
Stephen Frost [Sun, 1 Mar 2015 20:27:06 +0000 (15:27 -0500)]
Fix targetRelation initializiation in prepsecurity

In 6f9bd50eabb0a4960e94c83dac8855771c9f340d, we modified
expand_security_quals() to tell expand_security_qual() about when the
current RTE was the targetRelation.  Unfortunately, that commit
initialized the targetRelation variable used outside of the loop over
the RTEs instead of at the start of it.

This patch moves the variable and the initialization of it into the
loop, where it should have been to begin with.

Pointed out by Dean Rasheed.

Back-patch to 9.4 as the original commit was.

9 years agoUnlink static libraries before rebuilding them.
Noah Misch [Sun, 1 Mar 2015 18:05:23 +0000 (13:05 -0500)]
Unlink static libraries before rebuilding them.

When the library already exists in the build directory, "ar" preserves
members not named on its command line.  This mattered when, for example,
a "configure" rerun dropped a file from $(LIBOBJS).  libpgport carried
the obsolete member until "make clean".  Back-patch to 9.0 (all
supported versions).

9 years agoFix planning of star-schema-style queries.
Tom Lane [Sat, 28 Feb 2015 17:43:04 +0000 (12:43 -0500)]
Fix planning of star-schema-style queries.

Part of the intent of the parameterized-path mechanism was to handle
star-schema queries efficiently, but some overly-restrictive search
limiting logic added in commit e2fa76d80ba571d4de8992de6386536867250474
prevented such cases from working as desired.  Fix that and add a
regression test about it.  Per gripe from Marc Cousin.

This is arguably a bug rather than a new feature, so back-patch to 9.2
where parameterized paths were introduced.

9 years agoSuppress uninitialized-variable warning from less-bright compilers.
Tom Lane [Fri, 27 Feb 2015 23:19:22 +0000 (18:19 -0500)]
Suppress uninitialized-variable warning from less-bright compilers.

The type variable must get set on first iteration of the while loop,
but there are reasonably modern gcc versions that don't realize that.
Initialize it with a dummy value.  This undoes a removal of initialization
in commit 654809e770ce270c0bb9de726c5df1ab193d60f0.

9 years agoFix a couple of trivial issues in jsonb.c
Alvaro Herrera [Fri, 27 Feb 2015 21:54:49 +0000 (18:54 -0300)]
Fix a couple of trivial issues in jsonb.c

Typo "aggreagate" appeared three times, and the return value of function
JsonbIteratorNext() was being assigned to an int variable in a bunch of
places.

9 years agoRender infinite date/timestamps as 'infinity' for json/jsonb
Andrew Dunstan [Thu, 26 Feb 2015 17:34:43 +0000 (12:34 -0500)]
Render infinite date/timestamps as 'infinity' for json/jsonb

Commit ab14a73a6c raised an error in these cases and later the
behaviour was copied to jsonb. This is what the XML code, which we
then adopted, does, as the XSD types don't accept infinite values.
However, json dates and timestamps are just strings as far as json is
concerned, so there is no reason not to render these values as
'infinity'.

The json portion of this is backpatched to 9.4 where the behaviour was
introduced. The jsonb portion only affects the development branch.

Per gripe on pgsql-general.

9 years agoReconsider when to wait for WAL flushes/syncrep during commit.
Andres Freund [Thu, 26 Feb 2015 11:50:07 +0000 (12:50 +0100)]
Reconsider when to wait for WAL flushes/syncrep during commit.

Up to now RecordTransactionCommit() waited for WAL to be flushed (if
synchronous_commit != off) and to be synchronously replicated (if
enabled), even if a transaction did not have a xid assigned. The primary
reason for that is that sequence's nextval() did not assign a xid, but
are worthwhile to wait for on commit.

This can be problematic because sometimes read only transactions do
write WAL, e.g. HOT page prune records. That then could lead to read only
transactions having to wait during commit. Not something people expect
in a read only transaction.

This lead to such strange symptoms as backends being seemingly stuck
during connection establishment when all synchronous replicas are
down. Especially annoying when said stuck connection is the standby
trying to reconnect to allow syncrep again...

This behavior also is involved in a rather complicated <= 9.4 bug where
the transaction started by catchup interrupt processing waited for
syncrep using latches, but didn't get the wakeup because it was already
running inside the same overloaded signal handler. Fix the issue here
doesn't properly solve that issue, merely papers over the problems. In
9.5 catchup interrupts aren't processed out of signal handlers anymore.

To fix all this, make nextval() acquire a top level xid, and only wait for
transaction commit if a transaction both acquired a xid and emitted WAL
records.  If only a xid has been assigned we don't uselessly want to
wait just because of writes to temporary/unlogged tables; if only WAL
has been written we don't want to wait just because of HOT prunes.

The xid assignment in nextval() is unlikely to cause overhead in
real-world workloads. For one it only happens SEQ_LOG_VALS/32 values
anyway, for another only usage of nextval() without using the result in
an insert or similar is affected.

Discussion: 20150223165359.GF30784@awork2.anarazel.de,
    369698E947874884A77849D8FE3680C2@maumau,
    5CF4ABBA67674088B3941894E22A0D25@maumau

Per complaint from maumau and Thom Brown

Backpatch all the way back; 9.0 doesn't have syncrep, but it seems
better to be consistent behavior across all maintained branches.

9 years agoFree SQLSTATE and SQLERRM no earlier than other PL/pgSQL variables.
Noah Misch [Thu, 26 Feb 2015 04:48:28 +0000 (23:48 -0500)]
Free SQLSTATE and SQLERRM no earlier than other PL/pgSQL variables.

"RETURN SQLERRM" prompted plpgsql_exec_function() to read from freed
memory.  Back-patch to 9.0 (all supported versions).  Little code ran
between the premature free and the read, so non-assert builds are
unlikely to witness user-visible consequences.

9 years agoAdd locking clause for SB views for update/delete
Stephen Frost [Thu, 26 Feb 2015 02:36:40 +0000 (21:36 -0500)]
Add locking clause for SB views for update/delete

In expand_security_qual(), we were handling locking correctly when a
PlanRowMark existed, but not when we were working with the target
relation (which doesn't have any PlanRowMarks, but the subquery created
for the security barrier quals still needs to lock the rows under it).

Noted by Etsuro Fujita when working with the Postgres FDW, which wasn't
properly issuing a SELECT ... FOR UPDATE to the remote side under a
DELETE.

Back-patch to 9.4 where updatable security barrier views were
introduced.

Per discussion with Etsuro and Dean Rasheed.

9 years agoFix dumping of views that are just VALUES(...) but have column aliases.
Tom Lane [Wed, 25 Feb 2015 17:01:12 +0000 (12:01 -0500)]
Fix dumping of views that are just VALUES(...) but have column aliases.

The "simple" path for printing VALUES clauses doesn't work if we need
to attach nondefault column aliases, because there's noplace to do that
in the minimal VALUES() syntax.  So modify get_simple_values_rte() to
detect nondefault aliases and treat that as a non-simple case.  This
further exposes that the "non-simple" path never actually worked;
it didn't produce valid syntax.  Fix that too.  Per bug #12789 from
Curtis McEnroe, and analysis by Andrew Gierth.

Back-patch to all supported branches.  Before 9.3, this also requires
back-patching the part of commit 092d7ded29f36b0539046b23b81b9f0bf2d637f1
that created get_simple_values_rte() to begin with; inserting the extra
test into the old factorization of that logic would've been too messy.

9 years agoGuard against spurious signals in LockBufferForCleanup.
Andres Freund [Mon, 23 Feb 2015 15:11:11 +0000 (16:11 +0100)]
Guard against spurious signals in LockBufferForCleanup.

When LockBufferForCleanup() has to wait for getting a cleanup lock on a
buffer it does so by setting a flag in the buffer header and then wait
for other backends to signal it using ProcWaitForSignal().
Unfortunately LockBufferForCleanup() missed that ProcWaitForSignal() can
return for other reasons than the signal it is hoping for. If such a
spurious signal arrives the wait flags on the buffer header will still
be set. That then triggers "ERROR: multiple backends attempting to wait
for pincount 1".

The fix is simple, unset the flag if still set when retrying. That
implies an additional spinlock acquisition/release, but that's unlikely
to matter given the cost of waiting for a cleanup lock.  Alternatively
it'd have been possible to move responsibility for maintaining the
relevant flag to the waiter all together, but that might have had
negative consequences due to possible floods of signals. Besides being
more invasive.

This looks to be a very longstanding bug. The relevant code in
LockBufferForCleanup() hasn't changed materially since its introduction
and ProcWaitForSignal() was documented to return for unrelated reasons
since 8.2.  The master only patch series removing ImmediateInterruptOK
made it much easier to hit though, as ProcSendSignal/ProcWaitForSignal
now uses a latch shared with other tasks.

Per discussion with Kevin Grittner, Tom Lane and me.

Backpatch to all supported branches.

Discussion: 11553.1423805224@sss.pgh.pa.us

9 years agoFix potential deadlock with libpq non-blocking mode.
Heikki Linnakangas [Mon, 23 Feb 2015 11:32:34 +0000 (13:32 +0200)]
Fix potential deadlock with libpq non-blocking mode.

If libpq output buffer is full, pqSendSome() function tries to drain any
incoming data. This avoids deadlock, if the server e.g. sends a lot of
NOTICE messages, and blocks until we read them. However, pqSendSome() only
did that in blocking mode. In non-blocking mode, the deadlock could still
happen.

To fix, take a two-pronged approach:

1. Change the documentation to instruct that when PQflush() returns 1, you
should wait for both read- and write-ready, and call PQconsumeInput() if it
becomes read-ready. That fixes the deadlock, but applications are not going
to change overnight.

2. In pqSendSome(), drain the input buffer before returning 1. This
alleviates the problem for applications that only wait for write-ready. In
particular, a slow but steady stream of NOTICE messages during COPY FROM
STDIN will no longer cause a deadlock. The risk remains that the server
attempts to send a large burst of data and fills its output buffer, and at
the same time the client also sends enough data to fill its output buffer.
The application will deadlock if it goes to sleep, waiting for the socket
to become write-ready, before the server's data arrives. In practice,
NOTICE messages and such that the server might be sending are usually
short, so it's highly unlikely that the server would fill its output buffer
so quickly.

Backpatch to all supported versions.

9 years agoFix misparsing of empty value in conninfo_uri_parse_params().
Tom Lane [Sat, 21 Feb 2015 17:59:25 +0000 (12:59 -0500)]
Fix misparsing of empty value in conninfo_uri_parse_params().

After finding an "=" character, the pointer was advanced twice when it
should only advance once.  This is harmless as long as the value after "="
has at least one character; but if it doesn't, we'd miss the terminator
character and include too much in the value.

In principle this could lead to reading off the end of memory.  It does not
seem worth treating as a security issue though, because it would happen on
client side, and besides client logic that's taking conninfo strings from
untrusted sources has much worse security problems than this.

Report and patch received off-list from Thomas Fanghaenel.
Back-patch to 9.2 where the faulty code was introduced.

9 years agoFix object identities for pg_conversion objects
Alvaro Herrera [Wed, 18 Feb 2015 17:28:12 +0000 (14:28 -0300)]
Fix object identities for pg_conversion objects

We were neglecting to schema-qualify them.

Backpatch to 9.3, where object identities were introduced as a concept
by commit f8348ea32ec8.

9 years agoFix failure to honor -Z compression level option in pg_dump -Fd.
Tom Lane [Wed, 18 Feb 2015 16:43:00 +0000 (11:43 -0500)]
Fix failure to honor -Z compression level option in pg_dump -Fd.

cfopen() and cfopen_write() failed to pass the compression level through
to zlib, so that you always got the default compression level if you got
any at all.

In passing, also fix these and related functions so that the correct errno
is reliably returned on failure; the original coding supposes that free()
cannot change errno, which is untrue on at least some platforms.

Per bug #12779 from Christoph Berg.  Back-patch to 9.1 where the faulty
code was introduced.

Michael Paquier

9 years agoRemove code to match IPv4 pg_hba.conf entries to IPv4-in-IPv6 addresses.
Tom Lane [Tue, 17 Feb 2015 17:49:18 +0000 (12:49 -0500)]
Remove code to match IPv4 pg_hba.conf entries to IPv4-in-IPv6 addresses.

In investigating yesterday's crash report from Hugo Osvaldo Barrera, I only
looked back as far as commit f3aec2c7f51904e7 where the breakage occurred
(which is why I thought the IPv4-in-IPv6 business was undocumented).  But
actually the logic dates back to commit 3c9bb8886df7d56a and was simply
broken by erroneous refactoring in the later commit.  A bit of archives
excavation shows that we added the whole business in response to a report
that some 2003-era Linux kernels would report IPv4 connections as having
IPv4-in-IPv6 addresses.  The fact that we've had no complaints since 9.0
seems to be sufficient confirmation that no modern kernels do that, so
let's just rip it all out rather than trying to fix it.

Do this in the back branches too, thus essentially deciding that our
effective behavior since 9.0 is correct.  If there are any platforms on
which the kernel reports IPv4-in-IPv6 addresses as such, yesterday's fix
would have made for a subtle and potentially security-sensitive change in
the effective meaning of IPv4 pg_hba.conf entries, which does not seem like
a good thing to do in minor releases.  So let's let the post-9.0 behavior
stand, and change the documentation to match it.

In passing, I failed to resist the temptation to wordsmith the description
of pg_hba.conf IPv4 and IPv6 address entries a bit.  A lot of this text
hasn't been touched since we were IPv4-only.

9 years agoImprove pg_check_dir code and comments.
Robert Haas [Tue, 17 Feb 2015 15:19:30 +0000 (10:19 -0500)]
Improve pg_check_dir code and comments.

Avoid losing errno if readdir() fails and closedir() works.  Consistently
return 4 rather than 3 if both a lost+found directory and other files are
found, rather than returning one value or the other depending on the
order of the directory listing.  Update comments to match the actual
behavior.

These oversights date to commits 6f03927fce038096f53ca67eeab9adb24938f8a6
and 17f15239325a88581bb4f9cf91d38005f1f52d69.

Marco Nenciarini

9 years agoFix misuse of memcpy() in check_ip().
Tom Lane [Mon, 16 Feb 2015 21:17:48 +0000 (16:17 -0500)]
Fix misuse of memcpy() in check_ip().

The previous coding copied garbage into a local variable, pretty much
ensuring that the intended test of an IPv6 connection address against a
promoted IPv4 address from pg_hba.conf would never match.  The lack of
field complaints likely indicates that nobody realized this was supposed
to work, which is unsurprising considering that no user-facing docs suggest
it should work.

In principle this could have led to a SIGSEGV due to reading off the end of
memory, but since the source address would have pointed to somewhere in the
function's stack frame, that's quite unlikely.  What led to discovery of
the bug is Hugo Osvaldo Barrera's report of a crash after an OS upgrade,
which is probably because he is now running a system in which memcpy raises
abort() upon detecting overlapping source and destination areas.  (You'd
have to additionally suppose some things about the stack frame layout to
arrive at this conclusion, but it seems plausible.)

This has been broken since the code was added, in commit f3aec2c7f51904e7,
so back-patch to all supported branches.

9 years agoFix null-pointer-deref crash while doing COPY IN with check constraints.
Tom Lane [Mon, 16 Feb 2015 04:26:45 +0000 (23:26 -0500)]
Fix null-pointer-deref crash while doing COPY IN with check constraints.

In commit bf7ca15875988a88e97302e012d7c4808bef3ea9 I introduced an
assumption that an RTE referenced by a whole-row Var must have a valid eref
field.  This is false for RTEs constructed by DoCopy, and there are other
places taking similar shortcuts.  Perhaps we should make all those places
go through addRangeTableEntryForRelation or its siblings instead of having
ad-hoc logic, but the most reliable fix seems to be to make the new code in
ExecEvalWholeRowVar cope if there's no eref.  We can reasonably assume that
there's no need to insert column aliases if no aliases were provided.

Add a regression test case covering this, and also verifying that a sane
column name is in fact available in this situation.

Although the known case only crashes in 9.4 and HEAD, it seems prudent to
back-patch the code change to 9.2, since all the ingredients for a similar
failure exist in the variant patch applied to 9.3 and 9.2.

Per report from Jean-Pierre Pelletier.

9 years agopg_regress: Write processed input/*.source into output dir
Peter Eisentraut [Sun, 15 Feb 2015 02:33:41 +0000 (21:33 -0500)]
pg_regress: Write processed input/*.source into output dir

Before, it was writing the processed files into the input directory,
which is incorrect in a vpath build.

9 years agoFix broken #ifdef for __sparcv8
Heikki Linnakangas [Fri, 13 Feb 2015 21:51:23 +0000 (23:51 +0200)]
Fix broken #ifdef for __sparcv8

Rob Rowan. Backpatch to all supported versions, like the patch that added
the broken #ifdef.

9 years agopg_upgrade: quote directory names in delete_old_cluster script
Bruce Momjian [Thu, 12 Feb 2015 03:06:04 +0000 (22:06 -0500)]
pg_upgrade:  quote directory names in delete_old_cluster script

This allows the delete script to properly function when special
characters appear in directory paths, e.g. spaces.

Backpatch through 9.0

9 years agopg_upgrade: preserve freeze info for postgres/template1 dbs
Bruce Momjian [Thu, 12 Feb 2015 02:02:07 +0000 (21:02 -0500)]
pg_upgrade:  preserve freeze info for postgres/template1 dbs

pg_database.datfrozenxid and pg_database.datminmxid were not preserved
for the 'postgres' and 'template1' databases.  This could cause missing
clog file errors on access to user tables and indexes after upgrades in
these databases.

Backpatch through 9.0

9 years agoFix typo in logicaldecoding.sgml.
Andres Freund [Thu, 12 Feb 2015 00:16:32 +0000 (01:16 +0100)]
Fix typo in logicaldecoding.sgml.

Author: Tatsuo Ishii

Backpatch to 9.4, where logicaldecoding was introduced.

9 years agoFix missing PQclear() in libpqrcv_endstreaming().
Tom Lane [Thu, 12 Feb 2015 00:20:49 +0000 (19:20 -0500)]
Fix missing PQclear() in libpqrcv_endstreaming().

This omission leaked one PGresult per WAL streaming cycle, which possibly
would never be enough to notice in the real world, but it's still a leak.

Per Coverity.  Back-patch to 9.3 where the error was introduced.

9 years agoFix minor memory leak in ident_inet().
Tom Lane [Thu, 12 Feb 2015 00:09:54 +0000 (19:09 -0500)]
Fix minor memory leak in ident_inet().

We'd leak the ident_serv data structure if the second pg_getaddrinfo_all
(the one for the local address) failed.  This is not of great consequence
because a failure return here just leads directly to backend exit(), but
if this function is going to try to clean up after itself at all, it should
not have such holes in the logic.  Try to fix it in a future-proof way by
having all the failure exits go through the same cleanup path, rather than
"optimizing" some of them.

Per Coverity.  Back-patch to 9.2, which is as far back as this patch
applies cleanly.

9 years agoFix more memory leaks in failure path in buildACLCommands.
Tom Lane [Wed, 11 Feb 2015 23:35:23 +0000 (18:35 -0500)]
Fix more memory leaks in failure path in buildACLCommands.

We already had one go at this issue in commit d73b7f973db5ec7e, but we
failed to notice that buildACLCommands also leaked several PQExpBuffers
along with a simply malloc'd string.  This time let's try to make the
fix a bit more future-proof by eliminating the separate exit path.

It's still not exactly critical because pg_dump will curl up and die on
failure; but since the amount of the potential leak is now several KB,
it seems worth back-patching as far as 9.2 where the previous fix landed.

Per Coverity, which evidently is smarter than clang's static analyzer.

9 years agoFixed array handling in ecpg.
Michael Meskes [Wed, 11 Feb 2015 09:45:46 +0000 (10:45 +0100)]
Fixed array handling in ecpg.

When ecpg was rewritten to the new protocol version not all variable types
were corrected. This patch rewrites the code for these types to fix that. It
also fixes the documentation to correctly tell the status of array handling.

9 years agoFix pg_dump's heuristic for deciding which casts to dump.
Tom Lane [Wed, 11 Feb 2015 03:38:17 +0000 (22:38 -0500)]
Fix pg_dump's heuristic for deciding which casts to dump.

Back in 2003 we had a discussion about how to decide which casts to dump.
At the time pg_dump really only considered an object's containing schema
to decide what to dump (ie, dump whatever's not in pg_catalog), and so
we chose a complicated idea involving whether the underlying types were to
be dumped (cf commit a6790ce85752b67ad994f55fdf1a450262ccc32e).  But users
are allowed to create casts between built-in types, and we failed to dump
such casts.  Let's get rid of that heuristic, which has accreted even more
ugliness since then, in favor of just looking at the cast's OID to decide
if it's a built-in cast or not.

In passing, also fix some really ancient code that supposed that it had to
manufacture a dependency for the cast on its cast function; that's only
true when dumping from a pre-7.3 server.  This just resulted in some wasted
cycles and duplicate dependency-list entries with newer servers, but we
might as well improve it.

Per gripes from a number of people, most recently Greg Sabino Mullane.
Back-patch to all supported branches.

9 years agoFix GEQO to not assume its join order heuristic always works.
Tom Lane [Wed, 11 Feb 2015 01:37:22 +0000 (20:37 -0500)]
Fix GEQO to not assume its join order heuristic always works.

Back in commit 400e2c934457bef4bc3cc9a3e49b6289bd761bc0 I rewrote GEQO's
gimme_tree function to improve its heuristic for modifying the given tour
into a legal join order.  In what can only be called a fit of hubris,
I supposed that this new heuristic would *always* find a legal join order,
and ripped out the old logic that allowed gimme_tree to sometimes fail.

The folly of this is exposed by bug #12760, in which the "greedy" clumping
behavior of merge_clump() can lead it into a dead end which could only be
recovered from by un-clumping.  We have no code for that and wouldn't know
exactly what to do with it if we did.  Rather than try to improve the
heuristic rules still further, let's just recognize that it *is* a
heuristic and probably must always have failure cases.  So, put back the
code removed in the previous commit to allow for failure (but comment it
a bit better this time).

It's possible that this code was actually fully correct at the time and
has only been broken by the introduction of LATERAL.  But having seen this
example I no longer have much faith in that proposition, so back-patch to
all supported branches.

9 years agoMinor cleanup/code review for "indirect toast" stuff.
Tom Lane [Mon, 9 Feb 2015 17:30:55 +0000 (12:30 -0500)]
Minor cleanup/code review for "indirect toast" stuff.

Fix some issues I noticed while fooling with an extension to allow an
additional kind of toast pointer.  Much of this is just comment
improvement, but there are a couple of actual bugs, which might or might
not be reachable today depending on what can happen during logical
decoding.  An example is that toast_flatten_tuple() failed to cover the
possibility of an indirection pointer in its input.  Back-patch to 9.4
just in case that is reachable now.

In HEAD, also correct some really minor issues with recent compression
reorganization, such as dangerously underparenthesized macros.

9 years agoReport WAL flush, not insert, position in replication IDENTIFY_SYSTEM
Heikki Linnakangas [Fri, 6 Feb 2015 09:18:14 +0000 (11:18 +0200)]
Report WAL flush, not insert, position in replication IDENTIFY_SYSTEM

When beginning streaming replication, the client usually issues the
IDENTIFY_SYSTEM command, which used to return the current WAL insert
position. That's not suitable for the intended purpose of that field,
however. pg_receivexlog uses it to start replication from the reported
point, but if it hasn't been flushed to disk yet, it will fail. Change
IDENTIFY_SYSTEM to report the flush position instead.

Backpatch to 9.1 and above. 9.0 doesn't report any WAL position.

9 years agoFix reference-after-free when waiting for another xact due to constraint.
Heikki Linnakangas [Wed, 4 Feb 2015 14:00:34 +0000 (16:00 +0200)]
Fix reference-after-free when waiting for another xact due to constraint.

If an insertion or update had to wait for another transaction to finish,
because there was another insertion with conflicting key in progress,
we would pass a just-free'd item pointer to XactLockTableWait().

All calls to XactLockTableWait() and MultiXactIdWait() had similar issues.
Some passed a pointer to a buffer in the buffer cache, after already
releasing the lock. The call in EvalPlanQualFetch had already released the
pin too. All but the call in execUtils.c would merely lead to reporting a
bogus ctid, however (or an assertion failure, if enabled).

All the callers that passed HeapTuple->t_data->t_ctid were slightly bogus
anyway: if the tuple was updated (again) in the same transaction, its ctid
field would point to the next tuple in the chain, not the tuple itself.

Backpatch to 9.4, where the 'ctid' argument to XactLockTableWait was added
(in commit f88d4cfc)

9 years agoAdd missing float.h include to snprintf.c.
Andres Freund [Wed, 4 Feb 2015 12:27:31 +0000 (13:27 +0100)]
Add missing float.h include to snprintf.c.

On windows _isnan() (which isnan() is redirected to in port/win32.h)
is declared in float.h, not math.h.

Per buildfarm animal currawong.

Backpatch to all supported branches.

9 years agodoc: Fix markup
Fujii Masao [Wed, 4 Feb 2015 10:00:09 +0000 (19:00 +0900)]
doc: Fix markup

Ian Barwick

9 years agoFix breakage in GEODEBUG debug code.
Tom Lane [Tue, 3 Feb 2015 20:20:48 +0000 (15:20 -0500)]
Fix breakage in GEODEBUG debug code.

LINE doesn't have an "m" field (anymore anyway).  Also fix unportable
assumption that %x can print the result of pointer subtraction.

In passing, improve single_decode() in minor ways:
* Remove unnecessary leading-whitespace skip (strtod does that already).
* Make GEODEBUG message more intelligible.
* Remove entirely-useless test to see if strtod returned a silly pointer.
* Don't bother computing trailing-whitespace skip unless caller wants
  an ending pointer.

This has been broken since 261c7d4b653bc3e44c31fd456d94f292caa50d8f.
Although it's only debug code, might as well fix the 9.4 branch too.

9 years agoStamp 9.4.1. REL9_4_1
Tom Lane [Mon, 2 Feb 2015 20:42:55 +0000 (15:42 -0500)]
Stamp 9.4.1.

9 years agoLast-minute updates for release notes.
Tom Lane [Mon, 2 Feb 2015 16:24:02 +0000 (11:24 -0500)]
Last-minute updates for release notes.

Add entries for security issues.

Security: CVE-2015-0241 through CVE-2015-0244

9 years agoBe more careful to not lose sync in the FE/BE protocol.
Heikki Linnakangas [Mon, 2 Feb 2015 15:08:56 +0000 (17:08 +0200)]
Be more careful to not lose sync in the FE/BE protocol.

If any error occurred while we were in the middle of reading a protocol
message from the client, we could lose sync, and incorrectly try to
interpret a part of another message as a new protocol message. That will
usually lead to an "invalid frontend message" error that terminates the
connection. However, this is a security issue because an attacker might
be able to deliberately cause an error, inject a Query message in what's
supposed to be just user data, and have the server execute it.

We were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other
operations that could ereport(ERROR) in the middle of processing a message,
but a query cancel interrupt or statement timeout could nevertheless cause
it to happen. Also, the V2 fastpath and COPY handling were not so careful.
It's very difficult to recover in the V2 COPY protocol, so we will just
terminate the connection on error. In practice, that's what happened
previously anyway, as we lost protocol sync.

To fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set
whenever we're in the middle of reading a message. When it's set, we cannot
safely ERROR out and continue running, because we might've read only part
of a message. PqCommReadingMsg acts somewhat similarly to critical sections
in that if an error occurs while it's set, the error handler will force the
connection to be terminated, as if the error was FATAL. It's not
implemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted
to PANIC in critical sections, because we want to be able to use
PG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes
advantage of that to prevent an OOM error from terminating the connection.

To prevent unnecessary connection terminations, add a holdoff mechanism
similar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel
interrupts, but still allow die interrupts. The rules on which interrupts
are processed when are now a bit more complicated, so refactor
ProcessInterrupts() and the calls to it in signal handlers so that the
signal handlers always call it if ImmediateInterruptOK is set, and
ProcessInterrupts() can decide to not do anything if the other conditions
are not met.

Reported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund.
Backpatch to all supported versions.

Security: CVE-2015-0244

9 years agoPrevent Valgrind Memcheck errors around px_acquire_system_randomness().
Noah Misch [Mon, 2 Feb 2015 15:00:45 +0000 (10:00 -0500)]
Prevent Valgrind Memcheck errors around px_acquire_system_randomness().

This function uses uninitialized stack and heap buffers as supplementary
entropy sources.  Mark them so Memcheck will not complain.  Back-patch
to 9.4, where Valgrind Memcheck cooperation first appeared.

Marko Tiikkaja

9 years agoCherry-pick security-relevant fixes from upstream imath library.
Noah Misch [Mon, 2 Feb 2015 15:00:45 +0000 (10:00 -0500)]
Cherry-pick security-relevant fixes from upstream imath library.

This covers alterations to buffer sizing and zeroing made between imath
1.3 and imath 1.20.  Valgrind Memcheck identified the buffer overruns
and reliance on uninitialized data; their exploit potential is unknown.
Builds specifying --with-openssl are unaffected, because they use the
OpenSSL BIGNUM facility instead of imath.  Back-patch to 9.0 (all
supported versions).

Security: CVE-2015-0243

9 years agoFix buffer overrun after incomplete read in pullf_read_max().
Noah Misch [Mon, 2 Feb 2015 15:00:45 +0000 (10:00 -0500)]
Fix buffer overrun after incomplete read in pullf_read_max().

Most callers pass a stack buffer.  The ensuing stack smash can crash the
server, and we have not ruled out the viability of attacks that lead to
privilege escalation.  Back-patch to 9.0 (all supported versions).

Marko Tiikkaja

Security: CVE-2015-0243

9 years agoport/snprintf(): fix overflow and do padding
Bruce Momjian [Mon, 2 Feb 2015 15:00:45 +0000 (10:00 -0500)]
port/snprintf():  fix overflow and do padding

Prevent port/snprintf() from overflowing its local fixed-size
buffer and pad to the desired number of digits with zeros, even
if the precision is beyond the ability of the native sprintf().
port/snprintf() is only used on systems that lack a native
snprintf().

Reported by Bruce Momjian. Patch by Tom Lane. Backpatch to all
supported versions.

Security: CVE-2015-0242

9 years agoto_char(): prevent writing beyond the allocated buffer
Bruce Momjian [Mon, 2 Feb 2015 15:00:45 +0000 (10:00 -0500)]
to_char():  prevent writing beyond the allocated buffer

Previously very long localized month and weekday strings could
overflow the allocated buffers, causing a server crash.

Reported and patch reviewed by Noah Misch.  Backpatch to all
supported versions.

Security: CVE-2015-0241

9 years agoto_char(): prevent accesses beyond the allocated buffer
Bruce Momjian [Mon, 2 Feb 2015 15:00:44 +0000 (10:00 -0500)]
to_char():  prevent accesses beyond the allocated buffer

Previously very long field masks for floats could access memory
beyond the existing buffer allocated to hold the result.

Reported by Andres Freund and Peter Geoghegan. Backpatch to all
supported versions.

Security: CVE-2015-0241

9 years agoDoc: fix syntax description for psql's \setenv.
Tom Lane [Mon, 2 Feb 2015 05:18:54 +0000 (00:18 -0500)]
Doc: fix syntax description for psql's \setenv.

The variable name isn't optional --- looks like a copy-and-paste-o from
the \set command, where it is.

Dilip Kumar

9 years agoTranslation updates
Peter Eisentraut [Mon, 2 Feb 2015 04:18:42 +0000 (23:18 -0500)]
Translation updates

Source-Git-URL: git://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 19c72ea8d856d7b1d4f5d759a766c8206bf9ce53

9 years agodoc: Improve claim about location of pg_service.conf
Peter Eisentraut [Mon, 2 Feb 2015 03:36:44 +0000 (22:36 -0500)]
doc: Improve claim about location of pg_service.conf

The previous wording claimed that the file was always in /etc, but of
course this varies with the installation layout.  Write instead that it
can be found via `pg_config --sysconfdir`.  Even though this is still
somewhat incorrect because it doesn't account of moved installations, it
at least conveys that the location depends on the installation.

9 years agoRelease notes for 9.4.1, 9.3.6, 9.2.10, 9.1.15, 9.0.19.
Tom Lane [Sun, 1 Feb 2015 21:53:17 +0000 (16:53 -0500)]
Release notes for 9.4.1, 9.3.6, 9.2.10, 9.1.15, 9.0.19.

9 years agoFix documentation of psql's ECHO all mode.
Tom Lane [Sat, 31 Jan 2015 23:35:17 +0000 (18:35 -0500)]
Fix documentation of psql's ECHO all mode.

"ECHO all" is ignored for interactive input, and has been for a very long
time, though possibly not for as long as the documentation has claimed the
opposite.  Fix that, and also note that empty lines aren't echoed, which
while dubious is another longstanding behavior (it's embedded in our
regression test files for one thing).  Per bug #12721 from Hans Ginzel.

In HEAD, also improve the code comments in this area, and suppress an
unnecessary fflush(stdout) when we're not echoing.  That would likely
be safe to back-patch, but I'll not risk it mere hours before a release
wrap.

9 years agoUpdate time zone data files to tzdata release 2015a.
Tom Lane [Sat, 31 Jan 2015 03:45:44 +0000 (22:45 -0500)]
Update time zone data files to tzdata release 2015a.

DST law changes in Chile and Mexico (state of Quintana Roo).
Historical changes for Iceland.

9 years agoFix jsonb Unicode escape processing, and in consequence disallow \u0000.
Tom Lane [Fri, 30 Jan 2015 19:44:49 +0000 (14:44 -0500)]
Fix jsonb Unicode escape processing, and in consequence disallow \u0000.

We've been trying to support \u0000 in JSON values since commit
78ed8e03c67d7333, and have introduced increasingly worse hacks to try to
make it work, such as commit 0ad1a816320a2b53.  However, it fundamentally
can't work in the way envisioned, because the stored representation looks
the same as for \\u0000 which is not the same thing at all.  It's also
entirely bogus to output \u0000 when de-escaped output is called for.

The right way to do this would be to store an actual 0x00 byte, and then
throw error only if asked to produce de-escaped textual output.  However,
getting to that point seems likely to take considerable work and may well
never be practical in the 9.4.x series.

To preserve our options for better behavior while getting rid of the nasty
side-effects of 0ad1a816320a2b53, revert that commit in toto and instead
throw error if \u0000 is used in a context where it needs to be de-escaped.
(These are the same contexts where non-ASCII Unicode escapes throw error
if the database encoding isn't UTF8, so this behavior is by no means
without precedent.)

In passing, make both the \u0000 case and the non-ASCII Unicode case report
ERRCODE_UNTRANSLATABLE_CHARACTER / "unsupported Unicode escape sequence"
rather than claiming there's something wrong with the input syntax.

Back-patch to 9.4, where we have to do something because 0ad1a816320a2b53
broke things for many cases having nothing to do with \u0000.  9.3 also has
bogus behavior, but only for that specific escape value, so given the lack
of field complaints it seems better to leave 9.3 alone.

9 years agoFix Coverity warning about contrib/pgcrypto's mdc_finish().
Tom Lane [Fri, 30 Jan 2015 18:04:59 +0000 (13:04 -0500)]
Fix Coverity warning about contrib/pgcrypto's mdc_finish().

Coverity points out that mdc_finish returns a pointer to a local buffer
(which of course is gone as soon as the function returns), leaving open
a risk of misbehaviors possibly as bad as a stack overwrite.

In reality, the only possible call site is in process_data_packets()
which does not examine the returned pointer at all.  So there's no
live bug, but nonetheless the code is confusing and risky.  Refactor
to avoid the issue by letting process_data_packets() call mdc_finish()
directly instead of going through the pullf_read() API.

Although this is only cosmetic, it seems good to back-patch so that
the logic in pgp-decrypt.c stays in sync across all branches.

Marko Kreen

9 years agoFix assorted oversights in range selectivity estimation.
Tom Lane [Fri, 30 Jan 2015 17:30:41 +0000 (12:30 -0500)]
Fix assorted oversights in range selectivity estimation.

calc_rangesel() failed outright when comparing range variables to empty
constant ranges with < or >=, as a result of missing cases in a switch.
It also produced a bogus estimate for > comparison to an empty range.

On top of that, the >= and > cases were mislabeled throughout.  For
nonempty constant ranges, they managed to produce the right answers
anyway as a result of counterbalancing typos.

Also, default_range_selectivity() omitted cases for elem <@ range,
range &< range, and range &> range, so that rather dubious defaults
were applied for these operators.

In passing, rearrange the code in rangesel() so that the elem <@ range
case is handled in a less opaque fashion.

Report and patch by Emre Hasegeli, some additional work by me

9 years agoFix query-duration memory leak with GIN rescans.
Heikki Linnakangas [Fri, 30 Jan 2015 16:58:23 +0000 (17:58 +0100)]
Fix query-duration memory leak with GIN rescans.

The requiredEntries / additionalEntries arrays were not freed in
freeScanKeys() like other per-key stuff.

It's not obvious, but startScanKey() was only ever called after the keys
have been initialized with ginNewScanKey(). That's why it doesn't need to
worry about freeing existing arrays. The ginIsNewKey() test in gingetbitmap
was never true, because ginrescan free's the existing keys, and it's not OK
to call gingetbitmap twice in a row without calling ginrescan in between.
To make that clear, remove the unnecessary ginIsNewKey(). And just to be
extra sure that nothing funny happens if there is an existing key after all,
call freeScanKeys() to free it if it exists. This makes the code more
straightforward.

(I'm seeing other similar leaks in testing a query that rescans an GIN index
scan, but that's a different issue. This just fixes the obvious leak with
those two arrays.)

Backpatch to 9.4, where GIN fast scan was added.

9 years agoAllow pg_dump to use jobs and serializable transactions together.
Kevin Grittner [Fri, 30 Jan 2015 14:57:53 +0000 (08:57 -0600)]
Allow pg_dump to use jobs and serializable transactions together.

Since 9.3, when the --jobs option was introduced, using it together
with the --serializable-deferrable option generated multiple
errors.  We can get correct behavior by allowing the connection
which acquires the snapshot to use SERIALIZABLE, READ ONLY,
DEFERRABLE and pass that to the workers running the other
connections using REPEATABLE READ, READ ONLY.  This is a bit of a
kluge since the SERIALIZABLE behavior is achieved by running some
of the participating connections at a different isolation level,
but it is a simple and safe change, suitable for back-patching.

This will be followed by a proposal for a more invasive fix with
some slight behavioral changes on just the master branch, based on
suggestions from Andres Freund, but the kluge will be applied to
master until something is agreed along those lines.

Back-patched to 9.3, where the --jobs option was added.

Based on report from Alexander Korotkov

9 years agoFix BuildIndexValueDescription for expressions
Stephen Frost [Fri, 30 Jan 2015 02:59:43 +0000 (21:59 -0500)]
Fix BuildIndexValueDescription for expressions

In 804b6b6db4dcfc590a468e7be390738f9f7755fb we modified
BuildIndexValueDescription to pay attention to which columns are visible
to the user, but unfortunatley that commit neglected to consider indexes
which are built on expressions.

Handle error-reporting of violations of constraint indexes based on
expressions by not returning any detail when the user does not have
table-level SELECT rights.

Backpatch to 9.0, as the prior commit was.

Pointed out by Tom.

9 years agoHandle unexpected query results, especially NULLs, safely in connectby().
Tom Lane [Fri, 30 Jan 2015 01:18:37 +0000 (20:18 -0500)]
Handle unexpected query results, especially NULLs, safely in connectby().

connectby() didn't adequately check that the constructed SQL query returns
what it's expected to; in fact, since commit 08c33c426bfebb32 it wasn't
checking that at all.  This could result in a null-pointer-dereference
crash if the constructed query returns only one column instead of the
expected two.  Less excitingly, it could also result in surprising data
conversion failures if the constructed query returned values that were
not I/O-conversion-compatible with the types specified by the query
calling connectby().

In all branches, insist that the query return at least two columns;
this seems like a minimal sanity check that can't break any reasonable
use-cases.

In HEAD, insist that the constructed query return the types specified by
the outer query, including checking for typmod incompatibility, which the
code never did even before it got broken.  This is to hide the fact that
the implementation does a conversion to text and back; someday we might
want to improve that.

In back branches, leave that alone, since adding a type check in a minor
release is more likely to break things than make people happy.  Type
inconsistencies will continue to work so long as the actual type and
declared type are I/O representation compatible, and otherwise will fail
the same way they used to.

Also, in all branches, be on guard for NULL results from the constructed
query, which formerly would cause null-pointer dereference crashes.
We now print the row with the NULL but don't recurse down from it.

In passing, get rid of the rather pointless idea that
build_tuplestore_recursively() should return the same tuplestore that's
passed to it.

Michael Paquier, adjusted somewhat by me