postgres-xl.git
6 years agoMark (char *) variable as const, to quiet compilers XL9_5_STABLE
Tomas Vondra [Fri, 12 Oct 2018 13:17:42 +0000 (15:17 +0200)]
Mark (char *) variable as const, to quiet compilers

6 years agoRemove unused variable from ClusterMonitorGetGlobalXmin
Tomas Vondra [Fri, 12 Oct 2018 13:16:13 +0000 (15:16 +0200)]
Remove unused variable from ClusterMonitorGetGlobalXmin

6 years agoRemove unused variable from init_execution_state
Tomas Vondra [Fri, 12 Oct 2018 13:08:25 +0000 (15:08 +0200)]
Remove unused variable from init_execution_state

Another compiler warning gone.

6 years agoFix confusing indentation in gtm_client.c
Tomas Vondra [Sat, 29 Jul 2017 16:51:55 +0000 (18:51 +0200)]
Fix confusing indentation in gtm_client.c

GCC 6.3 complains that the indentation in gtm_sync_standby() is somewhat
confusing, as it might mislead people to think that a command is part of
an if branch. So fix that by removing the unnecessary indentation.

6 years agoFix compiler warnings due to unused variables
Tomas Vondra [Thu, 8 Jun 2017 15:55:47 +0000 (17:55 +0200)]
Fix compiler warnings due to unused variables

Removes a few variables that were either entirely unused, or just set
and never read again.

6 years agoFix incorrect comparison in pgxcnode_gethash
Tomas Vondra [Fri, 12 Oct 2018 12:32:54 +0000 (14:32 +0200)]
Fix incorrect comparison in pgxcnode_gethash

The check is supposed to ensure NULL/empty nodename gets hashed to 0,
but (nodename == '\0') is comparing the pointer itself, not the first
character. So dereference that correctly.

6 years agoUse sufficiently large buffer in SharedQueueWrite
Tomas Vondra [Fri, 12 Oct 2018 12:23:29 +0000 (14:23 +0200)]
Use sufficiently large buffer in SharedQueueWrite

The sq_key alone may be up to 64 bytes, so we need more than that.
We could use dynamic memory instead, but 128 bytes should be enough
both for the sq_key and the other pieces.

6 years agoRemove extra snprintf call in pg_tablespace_databases
Tomas Vondra [Sat, 29 Jul 2017 16:54:59 +0000 (18:54 +0200)]
Remove extra snprintf call in pg_tablespace_databases

The XL code did two function calls in the else branch, about like this:

    else
        /* Postgres-XC tablespaces also include node name in path */
        sprintf(fctx->location, "pg_tblspc/%u/%s_%s", tablespaceOid,
                TABLESPACE_VERSION_DIRECTORY, PGXCNodeName);
        fctx->location = psprintf("pg_tblspc/%u/%s_%s", tablespaceOid,
                                  TABLESPACE_VERSION_DIRECTORY,
                                  PGXCNodeName);

which is wrong, as only the first call is actually the else branch, the
second call is executed unconditionally.

In fact, the two calls attempt to construct the same location string,
but the sprintf call assumes the 'fctx->location' string is already
allocated. But it actually is not, so it's likely to cause a segfault.

Fixed by removing the sprintf() call, keeping just the psprintf() one.

Noticed thanks to GCC 6.3 complaining about incorrect indentation.

Backpatch to XL 9.5.

6 years agoUse dynamic buffer to parse NODE_LIST_RESULT in GTM
Tomas Vondra [Thu, 11 Oct 2018 14:51:09 +0000 (16:51 +0200)]
Use dynamic buffer to parse NODE_LIST_RESULT in GTM

When processing NODE_LIST_RESULT messages, gtmpqParseSuccess() used
a static buffer, defined as "char buf[8092]".  This is an issue, as
the message has variable length, and may get long enough to exceed
any hard-coded limit.  While that's not very common (it requires
long paths, node names and/or many GTM sessions on the node), it
may happen, in which case the memcpy() causes a buffer overflow and
corrupts the stack.

Fixing this is simple - allocate the buffer using malloc() intead,
requesting exactly the right amount of memory.  This however hits
a latent pre-existing issue in the code, because the code was doing
memcpy(&buf,...) instead of memcpy(buf,...).  With static buffers
this was harmless, because (buf == &buf), so the code was working
as intended (except when there were more than 8092 bytes).  With
dynamic memory this is no longer true, becase (buf != &buf), and
the stack corruption was much easier to trigger (just 8 bytes).

Per report and debug info by Hengbing. Patch by Pavan and me.

6 years agoInitialise a variable correctly.
Pavan Deolasee [Wed, 12 Sep 2018 09:15:55 +0000 (14:45 +0530)]
Initialise a variable correctly.

This was leading to unexpected/unexplained crashes in the cluster monitor
process. Per reprot by Hengbing

6 years agoFetch sn_xcnt just once to ensure consistent msg
Pavan Deolasee [Fri, 7 Sep 2018 06:08:51 +0000 (11:38 +0530)]
Fetch sn_xcnt just once to ensure consistent msg

We're seeing some reports when fetching snapshot from the GTM hangs forever on
the client side, waiting for data which never arrives. One theory is that the
snapshot->sn_xcnt value changes while sending snapshot from the GTM, thus
causing a mismatch between what the server sends and what the client expects.
We fixed a similar problem in 1078b079d5476e3447bd5268b317eacb4c455f5d, but may
be it's not complete. Put in this experimental patch (which can't make things
any worse for sure) while we also investigate other bugs in that area.

6 years agoFix problems associated with globalXmin tracking by ClusterMonitor
Pavan Deolasee [Thu, 6 Sep 2018 08:12:48 +0000 (13:42 +0530)]
Fix problems associated with globalXmin tracking by ClusterMonitor

The very first report by the cluster monitor may be discarded by the GTM if the
reporting xmin has fallen far behind GTM's view. This leads to the globalXmin
value remaining Invalid in the shared memory state, as tracked by the
ClusterMonitor. ClusterMonitor process usually naps for CLUSTER_MONITOR_NAPTIME
(default 5s) between two successive reporting. But discard that during the
bootup process and report the xmin a bit more aggressively. This should in all
likelihood set the globalXmin correctly, before the regular backends start
processing.

The other major problem with the current code was that when the globalXmin
tracked in the shared memory state is Invalid, the callers were using
FirstNormalXid as the globalXmin. This could be disastrous especially when XID
counter has wrapped around. We could accidentally remove visible rows by using
a wrong value of globalXmin. We now fix that by computing the globalXmin using
the local state (just like we would have computed globalXmin in vanilla PG).
This should ensure that we never use a wrong or a newer value for globalXmin
than what is allowed.

Accept regression diff in txid test case resulting from the fix. The new
expected output actually matches with what upstream produces.

Per report by Hengbing and investigations/fix by me.

6 years agoUse correct format specifier for transaction ids
Pavan Deolasee [Wed, 5 Sep 2018 07:56:02 +0000 (13:26 +0530)]
Use correct format specifier for transaction ids

6 years agoForce restart cluster monitor process if the GTM restarts
Pavan Deolasee [Fri, 31 Aug 2018 09:42:42 +0000 (15:12 +0530)]
Force restart cluster monitor process if the GTM restarts

If GTM loses node registration information and returns
GTM_ERRCODE_NODE_NOT_REGISTERED to the coordinator/datanode, restart the
cluster monitor process (by simply exiting with exit code 0). This would ensure
that the cluster monitor re-registers with the GTM and start cleanly.

Per report by Virendra Kumar

6 years agoFix an oversight in 32025718755c4bbf100563fdc88e96225fc1b250
Pavan Deolasee [Mon, 20 Aug 2018 10:47:31 +0000 (16:17 +0530)]
Fix an oversight in 32025718755c4bbf100563fdc88e96225fc1b250

In passing, add test cases and fix other issues around fetching table sizes
from remote nodes. For example, temp handling and names requiring quoting was
broken for long too.

Per report by Virendra Kumar and further tests by me.

6 years agoCorrectly track XID obtained by autovac as one from the GTM
Pavan Deolasee [Thu, 9 Aug 2018 07:33:58 +0000 (13:03 +0530)]
Correctly track XID obtained by autovac as one from the GTM

We were observing that a transaction started by the autovac process was left
open on the GTM, thus holding back xmin. This must have been a regression after
recent changes to track autocommit and regular transactions. We now correctly
track and close such transactions on the GTM.

6 years agoAdd a test to do sanity check at the end
Pavan Deolasee [Wed, 8 Aug 2018 05:17:21 +0000 (10:47 +0530)]
Add a test to do sanity check at the end

Right now it only contains a test to check replicated tables and confirm that
all nodes have the same number of rows. More to be added later.

6 years agoUse correct path for tablspaces while creating a basebackup
Pavan Deolasee [Fri, 3 Aug 2018 08:39:12 +0000 (14:09 +0530)]
Use correct path for tablspaces while creating a basebackup

In XL, we embed the nodename in the tablespace subdir name to ensure that
non-conflicting paths are created when multiple coordinators/datanodes are
running on the same server. The code to handle tablespace mapping in basebackup
was missing this support.

Per report and patch by Wanglin.

6 years agoEnsure that bad protocol ERROR message is sent to the frontend
Pavan Deolasee [Tue, 31 Jul 2018 06:00:01 +0000 (11:30 +0530)]
Ensure that bad protocol ERROR message is sent to the frontend

In case of receiving bad protocol messages received by the GTM proxy, let
the client know about the error messages.

6 years agoCorrect select the GTM proxy for a new node being added
Pavan Deolasee [Tue, 31 Jul 2018 05:58:21 +0000 (11:28 +0530)]
Correct select the GTM proxy for a new node being added

This fixes an oversight in array index lookup. We should have been using
0-based indexes but were instead using 1-based index.

6 years agoTeach pgxc_exec_sizefunc() to use pg_my_temp_schema() to get temp schema
Pavan Deolasee [Thu, 19 Jul 2018 09:31:07 +0000 (15:01 +0530)]
Teach pgxc_exec_sizefunc() to use pg_my_temp_schema() to get temp schema

Similar to what we did in 63233568d6c4646882d97f8f4e87b35729d67846, we must not
rely on the temporary namespace on the coordinator since it may change on the
remote nodes. Instead we use the pg_my_temp_schema() function to find the
currently active temporary schema on the remote node.

6 years agoFix handling of REFRESH MATERIALIZED VIEW CONCURRENTLY
Pavan Deolasee [Tue, 17 Jul 2018 05:50:59 +0000 (11:20 +0530)]
Fix handling of REFRESH MATERIALIZED VIEW CONCURRENTLY

We create a coordinator-only LOCAL temporary table for REFRESH MATERIALIZED
VIEW CONCURRENTLY. Since this table does not exist on the remote nodes, we must
not use explicit "ANALYZE <temptable>". Instead, just analyze it locally like
we were doing at other places.

Restore the matview test case to use REFRESH MATERIALIZED VIEW CONCURRENTLY now
that the underlying bug is fixed.

6 years agoImprove locking semantics in GTM and GTM Proxy
Pavan Deolasee [Tue, 10 Jul 2018 16:12:16 +0000 (21:42 +0530)]
Improve locking semantics in GTM and GTM Proxy

While GTM allows long jump in case of errors, we were not careful to release
locks currently held by the executing thread. That could lead to threads
leaving a critical section still holding a lock and thus causing deadlocks.

We now properly track currently held locks in the thread-specific information
and release those locks in case of an error. Same is done for mutex locks as
well, though there is only one that gets used.

This change required using a malloc-ed memory for thread-specific info. While
due care has been taken to free the structure, we should keep an eye on it for
any possible memory leaks.

In passing also improve handling of bad-protocol startup messages which may
have caused deadlock and resource starvation.

6 years agoFix a compiler warning introduced in the previous commit
Pavan Deolasee [Tue, 10 Jul 2018 12:23:18 +0000 (17:53 +0530)]
Fix a compiler warning introduced in the previous commit

6 years agoEnsure that typename is schema qualified while sending row description
Pavan Deolasee [Tue, 10 Jul 2018 09:10:56 +0000 (14:40 +0530)]
Ensure that typename is schema qualified while sending row description

A row description messages contains the type information for the attributes in
the column. But if the type does not exist in the search_path then the
coordinator fails to parse the typename back to the type. So the datanode must
send the schema name along with the type name.

Per report and test case by Hengbing Wang @ Microfun.

Added a new test file and a few test cases to cover this area.

6 years agoEnsure pooler process follows consistent model for SIGQUIT handling
Pavan Deolasee [Mon, 18 Jun 2018 09:16:08 +0000 (14:46 +0530)]
Ensure pooler process follows consistent model for SIGQUIT handling

We'd occassionally seen that the pooler process fails to respond to SIGQUIT and
gets stuck in a non recoverable state. Code inspection reveals that we're not
following the model followed by rest of the background worker processes in
handling SIGQUIT. So get that fixed, with the hope that this will fix the
problem case.

6 years agoProperly quote typename before calling parseTypeString
Pavan Deolasee [Mon, 18 Jun 2018 09:14:08 +0000 (14:44 +0530)]
Properly quote typename before calling parseTypeString

Without this, parseTypeString() might throw an error or resolve to a wrong type
in case the type name requires quoting.

Per report by Hengbing Wang

6 years agoRemove some accidentally added elog(LOG) messages
Pavan Deolasee [Mon, 21 May 2018 06:35:11 +0000 (12:05 +0530)]
Remove some accidentally added elog(LOG) messages

7 years agoFix broken implementation of recovery to barrier.
Pavan Deolasee [Fri, 18 May 2018 09:30:36 +0000 (15:00 +0530)]
Fix broken implementation of recovery to barrier.

Per report from Hengbing, the current implementation of PITR recovery to a
BARRIER failed to correctly stop at the given recovery_target_barrier. It seems
there are two bugs here. 1) we failed to write the XLOG record correctly and 2)
we also failed to mark the end-of-recovery upon seeing the XLOG record during
the recovery.

Fix both these problems and also fix pg_xlogdump in passing to ensure we can
dump the BARRIER XLOG records correctly.

7 years agoFix a long standing bug in vacuum/analyze of temp tables
Pavan Deolasee [Fri, 18 May 2018 06:16:17 +0000 (11:46 +0530)]
Fix a long standing bug in vacuum/analyze of temp tables

The system may and very likely choose different namespace for temporary tables
on different nodes. So it was erroneous to explicitly add the coordinator side
nampspace to the queries constructed for fetching stats from the remote nodes.
A regression test was non-deterministically failing for this reason for long,
but only now we could fully understand the problem and fix it. We now use
pg_my_temp_schema() to derive the current temporary schema used by the remote
node instead of hardcoding that in the query using coordinator side
information.

7 years agoAccept regression diffs post merge with 9.5.12
Pavan Deolasee [Wed, 16 May 2018 10:00:46 +0000 (15:30 +0530)]
Accept regression diffs post merge with 9.5.12

Two of the diffs are simply because of the addition of a Remote Subquery Scan
node on top of the plan. But two other diffs are actually error messages
resulting from a bug. But this bug is an old bug and there are already expected
output files with similar errors, hence accepting the diff for the time being.

7 years agoAccept regression diffs in join test case
Pavan Deolasee [Tue, 15 May 2018 12:25:35 +0000 (17:55 +0530)]
Accept regression diffs in join test case

The plans now look the same as vanilla PG except for additional Remote Fast
Query Execution nodes

7 years agoAccept regression diffs in plpgsql test case
Pavan Deolasee [Tue, 15 May 2018 10:39:12 +0000 (16:09 +0530)]
Accept regression diffs in plpgsql test case

The new output looks correct and has been fixed because of our work to get
transaction handling correct.

7 years agoAccept regression diff.
Pavan Deolasee [Tue, 15 May 2018 10:30:12 +0000 (16:00 +0530)]
Accept regression diff.

We no longer see "DROP INDEX CONCURRENTLY cannot run inside a transaction
block" if the index does not exists and we're running DROP IF EXISTS
command

7 years agoTrack clearly whether to run a remote transaction in autocommit or a block
Pavan Deolasee [Mon, 9 Apr 2018 10:42:54 +0000 (16:12 +0530)]
Track clearly whether to run a remote transaction in autocommit or a block

Chi Gao and Hengbing Wang reported certain issues around transaction handling
and demonstrated via xlogdump how certain transactions were getting marked
committed/aborted repeatedly on a datanode. When an already committed
transaction is attempted to be aborted again, it results in a PANIC. Upon
investigation, this uncovered a very serious yet long standing bug in
transaction handling.

If the client is running in autocommit mode, we try to avoid starting a
transaction block on the datanode side if only one datanode is going to be
involved in the transaction. This is an optimisation to speed up short queries
touching only a single node. But when the query rewriter transforms a single
statement into multiple statements, we would still (and incorrectly) run each
statement in an autocommit mode on the datanode. This can cause inconsistencies
when one statement commits but the next statement aborts. And it may also lead
to the PANIC situations if we continue to use the same global transaction
identifier for the statements.

This can also happen when the user invokes a user-defined function. If the
function has multiple statements, each statement will run in an autocommit
mode, if it's FQSed, thus again creating inconsistency if a following statement
in the function fails.

We now have a more elaborate mechanism to tackle autocommit and transaction
block needs. The special casing for force_autocommit is now removed, thus
making it more predictable. We also have specific conditions to check to ensure
that we don't mixup autocommit and transaction block for the same global xid.
Finally, if a query rewriter transforms a single statement into multiple
statements, we run those statements in a transaction block. Together these
changes should help us fix the problems.

7 years agoQualify the sequence name per changes in PG 9.5.12
Pavan Deolasee [Fri, 11 May 2018 10:47:43 +0000 (16:17 +0530)]
Qualify the sequence name per changes in PG 9.5.12

7 years agoDo not try to show targetlist of a RemoteSubplan on top of ModifyTable
Pavan Deolasee [Mon, 7 May 2018 04:54:21 +0000 (10:24 +0530)]
Do not try to show targetlist of a RemoteSubplan on top of ModifyTable

We do some special processing for RemoteSubplan with returning lists. But the
EXPLAIN plan mechanism is not adequetly trained to handle that special
crafting. So for now do not try to print the target list in the EXPLAIN output.

7 years agoAccept expected output differences for EXPLAIN
Pavan Deolasee [Tue, 17 Apr 2018 06:22:15 +0000 (11:52 +0530)]
Accept expected output differences for EXPLAIN

After the merge with 9.5.12, we see reduction in the redundant columns in the
targetlists for certain nodes. While we are yet to fully understand the
underlying change that's causing this, the changes loook quite benign and in
fact correct. So accept the changes.

7 years agoAccept expected output diffs in xml test case
Pavan Deolasee [Tue, 17 Apr 2018 06:21:11 +0000 (11:51 +0530)]
Accept expected output diffs in xml test case

We don't support subtransactions in XL

7 years agoAccept expected output diffs in privileges test case
Pavan Deolasee [Tue, 17 Apr 2018 06:20:03 +0000 (11:50 +0530)]
Accept expected output diffs in privileges test case

This is on account of merge errors and new test added to the test case

7 years agoAccept expected output diffs in groupingsets test
Pavan Deolasee [Tue, 17 Apr 2018 06:19:09 +0000 (11:49 +0530)]
Accept expected output diffs in groupingsets test

GROUPING SETs are not yet supported in XL

7 years agoMerge tag 'REL9_5_12' into XL9_5_STABLE
Pavan Deolasee [Tue, 17 Apr 2018 05:22:28 +0000 (10:52 +0530)]
Merge tag 'REL9_5_12' into XL9_5_STABLE

7 years agoMerge tag 'REL9_5_9' into XL9_5_STABLE
Pavan Deolasee [Tue, 17 Apr 2018 05:17:45 +0000 (10:47 +0530)]
Merge tag 'REL9_5_9' into XL9_5_STABLE

7 years agoDo not send the new protocol message to non-XL client.
Pavan Deolasee [Mon, 9 Apr 2018 11:35:13 +0000 (17:05 +0530)]
Do not send the new protocol message to non-XL client.

The new message 'W' to report waited-for XIDs must not be sent to a non-XL
client since it's not capable of handling that and might just cause unpleasant
problems. In fact, we should change 'W' to something else since standard libpq
understands that message and hangs forever expecting more data. With a new
protocol message, it would have failed, thus providing a more user friend
error. But postponing that for now since we should think through implications
of protocol change carefully before doing that.

7 years agoRevert restructuring of bin/scripts/Makefile
Magnus Hagander [Tue, 27 Feb 2018 13:08:53 +0000 (14:08 +0100)]
Revert restructuring of bin/scripts/Makefile

The Makefile portion of 91f3ffc5249eff99c311fb27e7b29a44d9c62be1 broke
the MSVC build. This patch reverts the changes to the Makefile and
adjusts it to work with the new code, while keeping the actual code
changes from the original patch.

Author: Victor Wagner <[email protected]>

7 years agoStamp 9.5.12.
Tom Lane [Mon, 26 Feb 2018 22:15:49 +0000 (17:15 -0500)]
Stamp 9.5.12.

7 years agoSchema-qualify references in test_ddl_deparse test script.
Tom Lane [Mon, 26 Feb 2018 17:22:39 +0000 (12:22 -0500)]
Schema-qualify references in test_ddl_deparse test script.

This omission seems to be what is causing buildfarm failures on crake.

Security: CVE-2018-1058

7 years agoLast-minute updates for release notes.
Tom Lane [Mon, 26 Feb 2018 17:14:05 +0000 (12:14 -0500)]
Last-minute updates for release notes.

Security: CVE-2018-1058

7 years agoDocument security implications of search_path and the public schema.
Noah Misch [Mon, 26 Feb 2018 15:39:44 +0000 (07:39 -0800)]
Document security implications of search_path and the public schema.

The ability to create like-named objects in different schemas opens up
the potential for users to change the behavior of other users' queries,
maliciously or accidentally.  When you connect to a PostgreSQL server,
you should remove from your search_path any schema for which a user
other than yourself or superusers holds the CREATE privilege.  If you do
not, other users holding CREATE privilege can redefine the behavior of
your commands, causing them to perform arbitrary SQL statements under
your identity.  "SET search_path = ..." and "SELECT
pg_catalog.set_config(...)" are not vulnerable to such hijacking, so one
can use either as the first command of a session.  As special
exceptions, the following client applications behave as documented
regardless of search_path settings and schema privileges: clusterdb
createdb createlang createuser dropdb droplang dropuser ecpg (not
programs it generates) initdb oid2name pg_archivecleanup pg_basebackup
pg_config pg_controldata pg_ctl pg_dump pg_dumpall pg_isready
pg_receivewal pg_recvlogical pg_resetwal pg_restore pg_rewind pg_standby
pg_test_fsync pg_test_timing pg_upgrade pg_waldump reindexdb vacuumdb
vacuumlo.  Not included are core client programs that run user-specified
SQL commands, namely psql and pgbench.  PostgreSQL encourages non-core
client applications to do likewise.

Document this in the context of libpq connections, psql connections,
dblink connections, ECPG connections, extension packaging, and schema
usage patterns.  The principal defense for applications is "SELECT
pg_catalog.set_config('search_path', '', false)", and the principal
defense for databases is "REVOKE CREATE ON SCHEMA public FROM PUBLIC".
Either one is sufficient to prevent attack.  After a REVOKE, consider
auditing the public schema for objects named like pg_catalog objects.

Authors of SECURITY DEFINER functions use some of the same defenses, and
the CREATE FUNCTION reference page already covered them thoroughly.
This is a good opportunity to audit SECURITY DEFINER functions for
robust security practice.

Back-patch to 9.3 (all supported versions).

Reviewed by Michael Paquier and Jonathan S. Katz.  Reported by Arseniy
Sharoglazov.

Security: CVE-2018-1058

7 years agoEmpty search_path in Autovacuum and non-psql/pgbench clients.
Noah Misch [Mon, 26 Feb 2018 15:39:44 +0000 (07:39 -0800)]
Empty search_path in Autovacuum and non-psql/pgbench clients.

This makes the client programs behave as documented regardless of the
connect-time search_path and regardless of user-created objects.  Today,
a malicious user with CREATE permission on a search_path schema can take
control of certain of these clients' queries and invoke arbitrary SQL
functions under the client identity, often a superuser.  This is
exploitable in the default configuration, where all users have CREATE
privilege on schema "public".

This changes behavior of user-defined code stored in the database, like
pg_index.indexprs and pg_extension_config_dump().  If they reach code
bearing unqualified names, "does not exist" or "no schema has been
selected to create in" errors might appear.  Users may fix such errors
by schema-qualifying affected names.  After upgrading, consider watching
server logs for these errors.

The --table arguments of src/bin/scripts clients have been lax; for
example, "vacuumdb -Zt pg_am\;CHECKPOINT" performed a checkpoint.  That
now fails, but for now, "vacuumdb -Zt 'pg_am(amname);CHECKPOINT'" still
performs a checkpoint.

Back-patch to 9.3 (all supported versions).

Reviewed by Tom Lane, though this fix strategy was not his first choice.
Reported by Arseniy Sharoglazov.

Security: CVE-2018-1058

7 years agoAvoid using unsafe search_path settings during dump and restore.
Tom Lane [Mon, 26 Feb 2018 15:18:22 +0000 (10:18 -0500)]
Avoid using unsafe search_path settings during dump and restore.

Historically, pg_dump has "set search_path = foo, pg_catalog" when
dumping an object in schema "foo", and has also caused that setting
to be used while restoring the object.  This is problematic because
functions and operators in schema "foo" could capture references meant
to refer to pg_catalog entries, both in the queries issued by pg_dump
and those issued during the subsequent restore run.  That could
result in dump/restore misbehavior, or in privilege escalation if a
nefarious user installs trojan-horse functions or operators.

This patch changes pg_dump so that it does not change the search_path
dynamically.  The emitted restore script sets the search_path to what
was used at dump time, and then leaves it alone thereafter.  Created
objects are placed in the correct schema, regardless of the active
search_path, by dint of schema-qualifying their names in the CREATE
commands, as well as in subsequent ALTER and ALTER-like commands.

Since this change requires a change in the behavior of pg_restore
when processing an archive file made according to this new convention,
bump the archive file version number; old versions of pg_restore will
therefore refuse to process files made with new versions of pg_dump.

Security: CVE-2018-1058

7 years agoTranslation updates
Peter Eisentraut [Mon, 26 Feb 2018 13:36:39 +0000 (08:36 -0500)]
Translation updates

Source-Git-URL: git://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 4b11a4320dc2d543629ae1b61cc39112cc8f3947

7 years agoRelease notes for 10.3, 9.6.8, 9.5.12, 9.4.17, 9.3.22.
Tom Lane [Sun, 25 Feb 2018 19:52:51 +0000 (14:52 -0500)]
Release notes for 10.3, 9.6.8, 9.5.12, 9.4.17, 9.3.22.

7 years agoAllow auto_explain.log_min_duration to go up to INT_MAX.
Tom Lane [Fri, 23 Feb 2018 19:38:19 +0000 (14:38 -0500)]
Allow auto_explain.log_min_duration to go up to INT_MAX.

The previous limit of INT_MAX / 1000 seems to have been cargo-culted in
from somewhere else.  Or possibly the value was converted to microseconds
at some point; but in all supported releases, it's just compared to other
values, so there's no need for the restriction.  This change raises the
effective limit from ~35 minutes to ~24 days, which conceivably is useful
to somebody, and anyway it's more consistent with the range of the core
log_min_duration_statement GUC.

Per complaint from Kevin Bloch.  Back-patch to all supported releases.

Discussion: https://postgr.es/m/8ea82d7e-cb78-8e05-0629-73aa14d2a0ca@codingthat.com

7 years agoSynchronize doc/ copies of src/test/examples/.
Noah Misch [Fri, 23 Feb 2018 19:24:04 +0000 (11:24 -0800)]
Synchronize doc/ copies of src/test/examples/.

This is mostly cosmetic, but it might fix build failures, on some
platform, when copying from the documentation.

Back-patch to 9.3 (all supported versions).

7 years agoFix planner failures with overlapping mergejoin clauses in an outer join.
Tom Lane [Fri, 23 Feb 2018 18:47:33 +0000 (13:47 -0500)]
Fix planner failures with overlapping mergejoin clauses in an outer join.

Given overlapping or partially redundant join clauses, for example
t1 JOIN t2 ON t1.a = t2.x AND t1.b = t2.x
the planner's EquivalenceClass machinery will ordinarily refactor the
clauses as "t1.a = t1.b AND t1.a = t2.x", so that join processing doesn't
see multiple references to the same EquivalenceClass in a list of join
equality clauses.  However, if the join is outer, it's incorrect to derive
a restriction clause on the outer side from the join conditions, so the
clause refactoring does not happen and we end up with overlapping join
conditions.  The code that attempted to deal with such cases had several
subtle bugs, which could result in "left and right pathkeys do not match in
mergejoin" or "outer pathkeys do not match mergeclauses" planner errors,
if the selected join plan type was a mergejoin.  (It does not appear that
any actually incorrect plan could have been emitted.)

The core of the problem really was failure to recognize that the outer and
inner relations' pathkeys have different relationships to the mergeclause
list.  A join's mergeclause list is constructed by reference to the outer
pathkeys, so it will always be ordered the same as the outer pathkeys, but
this cannot be presumed true for the inner pathkeys.  If the inner sides of
the mergeclauses contain multiple references to the same EquivalenceClass
({t2.x} in the above example) then a simplistic rendering of the required
inner sort order is like "ORDER BY t2.x, t2.x", but the pathkey machinery
recognizes that the second sort column is redundant and throws it away.
The mergejoin planning code failed to account for that behavior properly.
One error was to try to generate cut-down versions of the mergeclause list
from cut-down versions of the inner pathkeys in the same way as the initial
construction of the mergeclause list from the outer pathkeys was done; this
could lead to choosing a mergeclause list that fails to match the outer
pathkeys.  The other problem was that the pathkey cross-checking code in
create_mergejoin_plan treated the inner and outer pathkey lists
identically, whereas actually the expectations for them must be different.
That led to false "pathkeys do not match" failures in some cases, and in
principle could have led to failure to detect bogus plans in other cases,
though there is no indication that such bogus plans could be generated.

Reported by Alexander Kuzmenkov, who also reviewed this patch.  This has
been broken for years (back to around 8.3 according to my testing), so
back-patch to all supported branches.

Discussion: https://postgr.es/m/5dad9160-4632-0e47-e120-8e2082000c01@postgrespro.ru

7 years agoRepair pg_upgrade's failure to preserve relfrozenxid for matviews.
Tom Lane [Wed, 21 Feb 2018 23:40:24 +0000 (18:40 -0500)]
Repair pg_upgrade's failure to preserve relfrozenxid for matviews.

This oversight led to data corruption in matviews, manifesting as
"could not access status of transaction" before our most recent releases,
and "found xmin from before relfrozenxid" errors since then.

The proximate cause of the problem seems to have been confusion between
the task of preserving dropped-column status and the task of preserving
frozenxid status.  Those are required for distinct sets of relkinds,
and the reasoning was entirely undocumented in the source code.  In hopes
of forestalling future errors of the same kind, try to improve the
commentary in this area.

In passing, also improve the remarkably unhelpful comments around
pg_upgrade's set_frozenxids().  That's not actually buggy AFAICS,
but good luck figuring out what it does from the old comments.

Per report from Claudio Freire.  It appears that bug #14852 from Alexey
Ermakov is an earlier report of the same issue, and there may be other
cases that we failed to identify at the time.

Patch by me based on analysis by Andres Freund.  The bug dates back
to the introduction of matviews, so back-patch to all supported branches.

Discussion: https://postgr.es/m/CAGTBQpbrY9CdRGGhyBZ9yqY4jWaGC85rUF4X+R7d-aim=mBNsw@mail.gmail.com
Discussion: https://postgr.es/m/20171013115320[email protected]

7 years agoFix misbehavior of CTE-used-in-a-subplan during EPQ rechecks.
Tom Lane [Mon, 19 Feb 2018 21:00:18 +0000 (16:00 -0500)]
Fix misbehavior of CTE-used-in-a-subplan during EPQ rechecks.

An updating query that reads a CTE within an InitPlan or SubPlan could get
incorrect results if it updates rows that are concurrently being modified.
This is caused by CteScanNext supposing that nothing inside its recursive
ExecProcNode call could change which read pointer is selected in the CTE's
shared tuplestore.  While that's normally true because of scoping
considerations, it can break down if an EPQ plan tree gets built during the
call, because EvalPlanQualStart builds execution trees for all subplans
whether they're going to be used during the recheck or not.  And it seems
like a pretty shaky assumption anyway, so let's just reselect our own read
pointer here.

Per bug #14870 from Andrei Gorita.  This has been broken since CTEs were
implemented, so back-patch to all supported branches.

Discussion: https://postgr.es/m/20171024155358[email protected]

7 years agoDoc: fix minor bug in CREATE TABLE example.
Tom Lane [Thu, 15 Feb 2018 18:56:38 +0000 (13:56 -0500)]
Doc: fix minor bug in CREATE TABLE example.

One example in create_table.sgml claimed to be showing table constraint
syntax, but it was really column constraint syntax due to the omission
of a comma.  This is both wrong and confusing, so fix it in all
supported branches.

Per report from [email protected].

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

7 years agoFix broken logic for reporting PL/Python function names in errcontext.
Tom Lane [Wed, 14 Feb 2018 19:47:18 +0000 (14:47 -0500)]
Fix broken logic for reporting PL/Python function names in errcontext.

plpython_error_callback() reported the name of the function associated
with the topmost PL/Python execution context.  This was not merely
wrong if there were nested PL/Python contexts, but it risked a core
dump if the topmost one is an inline code block rather than a named
function.  That will have proname = NULL, and so we were passing a NULL
pointer to snprintf("%s").  It seems that none of the PL/Python-testing
machines in the buildfarm will dump core for that, but some platforms do,
as reported by Marina Polyakova.

Investigation finds that there actually is an existing regression test
that used to prove that the behavior was wrong, though apparently no one
had noticed that it was printing the wrong function name.  It stopped
showing the problem in 9.6 when we adjusted psql to not print CONTEXT
by default for NOTICE messages.  The problem is masked (if your platform
avoids the core dump) in error cases, because PL/Python will throw away
the originally generated error info in favor of a new traceback produced
at the outer level.

Repair by using ErrorContextCallback.arg to pass the correct context to
the error callback.  Add a regression test illustrating correct behavior.

Back-patch to all supported branches, since they're all broken this way.

Discussion: https://postgr.es/m/156b989dbc6fe7c4d3223cf51da61195@postgrespro.ru

7 years agoChange default git repo URL to https
Magnus Hagander [Wed, 7 Feb 2018 10:03:55 +0000 (11:03 +0100)]
Change default git repo URL to https

Since we now support the server side handler for git over https (so
we're no longer using the "dumb protocol"), make https the primary
choice for cloning the repository, and the git protocol the secondary
choice.

In passing, also change the links to git-scm.com from http to https.

Reviewed by Stefan Kaltenbrunner and David G.  Johnston

7 years agoStamp 9.5.11.
Tom Lane [Mon, 5 Feb 2018 21:05:21 +0000 (16:05 -0500)]
Stamp 9.5.11.

7 years agoLast-minute updates for release notes.
Tom Lane [Mon, 5 Feb 2018 19:43:40 +0000 (14:43 -0500)]
Last-minute updates for release notes.

Security: CVE-2018-1052, CVE-2018-1053

7 years agoTranslation updates
Peter Eisentraut [Mon, 5 Feb 2018 17:41:09 +0000 (12:41 -0500)]
Translation updates

Source-Git-URL: git://git.postgresql.org/git/pgtranslation/messages.git
Source-Git-Hash: 729c338a50b452e86cd740cb9878554be4264f32

7 years agoEnsure that all temp files made during pg_upgrade are non-world-readable.
Tom Lane [Mon, 5 Feb 2018 15:58:27 +0000 (10:58 -0500)]
Ensure that all temp files made during pg_upgrade are non-world-readable.

pg_upgrade has always attempted to ensure that the transient dump files
it creates are inaccessible except to the owner.  However, refactoring
in commit 76a7650c4 broke that for the file containing "pg_dumpall -g"
output; since then, that file was protected according to the process's
default umask.  Since that file may contain role passwords (hopefully
encrypted, but passwords nonetheless), this is a particularly unfortunate
oversight.  Prudent users of pg_upgrade on multiuser systems would
probably run it under a umask tight enough that the issue is moot, but
perhaps some users are depending only on pg_upgrade's umask changes to
protect their data.

To fix this in a future-proof way, let's just tighten the umask at
process start.  There are no files pg_upgrade needs to write at a
weaker security level; and if there were, transiently relaxing the
umask around where they're created would be a safer approach.

Report and patch by Tom Lane; the idea for the fix is due to Noah Misch.
Back-patch to all supported branches.

Security: CVE-2018-1053

7 years agoRelease notes for 10.2, 9.6.7, 9.5.11, 9.4.16, 9.3.21.
Tom Lane [Sun, 4 Feb 2018 20:13:44 +0000 (15:13 -0500)]
Release notes for 10.2, 9.6.7, 9.5.11, 9.4.16, 9.3.21.

7 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: [email protected]
Discussion: https://postgr.es/m/151726276676.1240.10501743959198501067@wrigleys.postgresql.org

Backpatch-through: 9.3

7 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

7 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

7 years agopsql documentation fixes
Peter Eisentraut [Mon, 29 Jan 2018 19:04:32 +0000 (14:04 -0500)]
psql documentation fixes

Update the documentation for \pset to mention
columns|linestyle|pager_min_lines.

Author: Дилян Палаузов <[email protected]>

7 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[email protected]

7 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).

7 years agoTeach reparameterize_path() to handle AppendPaths.
Tom Lane [Tue, 23 Jan 2018 21:50:35 +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[email protected]

7 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

7 years agoMake pg_dump's ACL, sec label, and comment entries reliably identifiable.
Tom Lane [Mon, 22 Jan 2018 17:06:19 +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

7 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[email protected]

Reviewed-by: Michael Paquier
Backpatch-through: 9.3

7 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

7 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

7 years agoCope with indicator arrays that do not have the correct length.
Michael Meskes [Sat, 13 Jan 2018 13:56:49 +0000 (14:56 +0100)]
Cope with indicator arrays that do not have the correct length.

Patch by: "Rader, David" <[email protected]>

7 years agoAvoid unnecessary failure in SELECT concurrent with ALTER NO INHERIT.
Tom Lane [Fri, 12 Jan 2018 20:46:37 +0000 (15:46 -0500)]
Avoid unnecessary failure in SELECT concurrent with ALTER NO INHERIT.

If a query against an inheritance tree runs concurrently with an ALTER
TABLE that's disinheriting one of the tree members, it's possible to get
a "could not find inherited attribute" error because after obtaining lock
on the removed member, make_inh_translation_list sees that its columns
have attinhcount=0 and decides they aren't the columns it's looking for.

An ideal fix, perhaps, would avoid including such a just-removed member
table in the query at all; but there seems no way to accomplish that
without adding expensive catalog rechecks or creating a likelihood of
deadlocks.  Instead, let's just drop the check on attinhcount.  In this
way, a query that's included a just-disinherited child will still
succeed, which is not a completely unreasonable behavior.

This problem has existed for a long time, so back-patch to all supported
branches.  Also add an isolation test verifying related behaviors.

Patch by me; the new isolation test is based on Kyotaro Horiguchi's work.

Discussion: https://postgr.es/m/20170626.174612.23936762[email protected]

7 years agoFix incorrect handling of subquery pullup in the presence of grouping sets.
Tom Lane [Fri, 12 Jan 2018 17:24:50 +0000 (12:24 -0500)]
Fix incorrect handling of subquery pullup in the presence of grouping sets.

If we flatten a subquery whose target list contains constants or
expressions, when those output columns are used in GROUPING SET columns,
the planner was capable of doing the wrong thing by merging a pulled-up
expression into the surrounding expression during const-simplification.
Then the late processing that attempts to match subexpressions to grouping
sets would fail to match those subexpressions to grouping sets, with the
effect that they'd not go to null when expected.

To fix, wrap such subquery outputs in PlaceHolderVars, ensuring that
they preserve their separate identity throughout the planner's expression
processing.  This is a bit of a band-aid, because the wrapper defeats
const-simplification even in places where it would be safe to allow.
But a nicer fix would likely be too invasive to back-patch, and the
consequences of the missed optimizations probably aren't large in most
cases.

Back-patch to 9.5 where grouping sets were introduced.

Heikki Linnakangas, with small mods and better test cases by me;
additional review by Andrew Gierth

Discussion: https://postgr.es/m/7dbdcf5c-b5a6-ef89-4958-da212fe10176@iki.fi

7 years agoFix sample INSTR() functions in the plpgsql documentation.
Tom Lane [Wed, 10 Jan 2018 22:13:29 +0000 (17:13 -0500)]
Fix sample INSTR() functions in the plpgsql documentation.

These functions are stated to be Oracle-compatible, but they weren't.
Yugo Nagata noticed that while our code returns zero for a zero or
negative fourth parameter (occur_index), Oracle throws an error.
Further testing by me showed that there was also a discrepancy in the
interpretation of a negative third parameter (beg_index): Oracle thinks
that a negative beg_index indicates the last place where the target
substring can *begin*, whereas our code thinks it is the last place
where the target can *end*.

Adjust the sample code to behave like Oracle in both these respects.
Also change it to be a CDATA[] section, simplifying copying-and-pasting
out of the documentation source file.  And fix minor problems in the
introductory comment, which wasn't very complete or accurate.

Back-patch to all supported branches.  Although this patch only touches
documentation, we should probably call it out as a bug fix in the next
minor release notes, since users who have adopted the functions will
likely want to update their versions.

Yugo Nagata and Tom Lane

Discussion: https://postgr.es/m/20171229191705.c0b43a8c[email protected]

7 years agoChange some bogus PageGetLSN calls to BufferGetLSNAtomic
Alvaro Herrera [Tue, 9 Jan 2018 18:54:38 +0000 (15:54 -0300)]
Change some bogus PageGetLSN calls to BufferGetLSNAtomic

As src/backend/access/transam/README says, PageGetLSN may only be called
by processes holding either exclusive lock on buffer, or a shared lock
on buffer plus buffer header lock.  Therefore any place that only holds
a shared buffer lock must use BufferGetLSNAtomic instead of PageGetLSN,
which internally obtains buffer header lock prior to reading the LSN.

A few callsites failed to comply with this rule.  This was detected by
running all tests under a new (not committed) assertion that verifies
PageGetLSN locking contract.  All but one of the callsites that failed
the assertion are fixed by this patch.  Remaining callsites were
inspected manually and determined not to need any change.

The exception (unfixed callsite) is in TestForOldSnapshot, which only
has a Page argument, making it impossible to access the corresponding
Buffer from it.  Fixing that seems a much larger patch that will have to
be done separately; and that's just as well, since it was only
introduced in 9.6 and other bugs are much older.

Some of these bugs are ancient; backpatch all the way back to 9.3.

Authors: Jacob Champion, Asim Praveen, Ashwin Agrawal
Reviewed-by: Michaël Paquier
Discussion: https://postgr.es/m/CABAq_6GXgQDVu3u12mK9O5Xt5abBZWQ0V40LZCE+oUf95XyNFg@mail.gmail.com

7 years agopg_upgrade: simplify code layout in a few places
Bruce Momjian [Fri, 5 Jan 2018 19:11:14 +0000 (14:11 -0500)]
pg_upgrade:  simplify code layout in a few places

Backpatch-through: 9.4 (9.3 didn't need improving)

7 years agoFix failure to delete spill files of aborted transactions
Alvaro Herrera [Fri, 5 Jan 2018 15:17:10 +0000 (12:17 -0300)]
Fix failure to delete spill files of aborted transactions

Logical decoding's reorderbuffer.c may spill transaction files to disk
when transactions are large.  These are supposed to be removed when they
become "too old" by xid; but file removal requires the boundary LSNs of
the transaction to be known.  The final_lsn is only set when we see the
commit or abort record for the transaction, but nothing sets the value
for transactions that crash, so the removal code misbehaves -- in
assertion-enabled builds, it crashes by a failed assertion.

To fix, modify the final_lsn of transactions that don't have a value
set, to the LSN of the very latest change in the transaction.  This
causes the spilled files to be removed appropriately.

Author: Atsushi Torikoshi
Reviewed-by: Kyotaro HORIGUCHI, Craig Ringer, Masahiko Sawada
Discussion: https://postgr.es/m/54e4e488-186b-a056-6628-50628e4e4ebc@lab.ntt.co.jp

7 years agoRename pg_rewind's copy_file_range() to avoid conflict with new linux syscall.
Andres Freund [Wed, 3 Jan 2018 20:00:11 +0000 (12:00 -0800)]
Rename pg_rewind's copy_file_range() to avoid conflict with new linux syscall.

Upcoming versions of glibc will contain copy_file_range(2), a wrapper
around a new linux syscall for in-kernel copying of data ranges. This
conflicts with pg_rewinds function of the same name.

Therefore rename pg_rewinds version. As our version isn't a generic
copying facility we decided to choose a rewind specific function name.

Per buildfarm animal caiman and subsequent discussion with Tom Lane.

Author: Andres Freund
Discussion:
    https://postgr.es/m/20180103033425[email protected]
    https://postgr.es/m/31122.1514951044@sss.pgh.pa.us
Backpatch: 9.5-, where pg_rewind was introduced

7 years agoFix use of config-specific libraries for Windows OpenSSL
Andrew Dunstan [Wed, 3 Jan 2018 20:26:39 +0000 (15:26 -0500)]
Fix use of config-specific libraries for Windows OpenSSL

Commit 614350a3 allowed for an different builds of OpenSSL libraries on
Windows, but ignored the fact that the alternative builds don't have
config-specific libraries. This patch fixes the Solution file to ask for
the correct libraries.

per offline discussions with Leonardo Cecchi and Marco Nenciarini,

Backpatch to all live branches.

7 years agoMake XactLockTableWait work for transactions that are not yet self-locked
Alvaro Herrera [Wed, 3 Jan 2018 20:26:20 +0000 (17:26 -0300)]
Make XactLockTableWait work for transactions that are not yet self-locked

XactLockTableWait assumed that its xid argument has already added itself
to the lock table.  That assumption led to another assumption that if
locking the xid has succeeded but the xid is reported as still in
progress, then the input xid must have been a subtransaction.

These assumptions hold true for the original uses of this code in
locking related to on-disk tuples, but they break down in logical
replication slot snapshot building -- in particular, when a standby
snapshot logged contains an xid that's already in ProcArray but not yet
in the lock table.  This leads to assertion failures that can be
reproduced all the way back to 9.4, when logical decoding was
introduced.

To fix, change SubTransGetParent to SubTransGetTopmostTransaction which
has a slightly different API: it returns the argument Xid if there is no
parent, and it goes all the way to the top instead of moving up the
levels one by one.  Also, to avoid busy-waiting, add a 1ms sleep to give
the other process time to register itself in the lock table.

For consistency, change ConditionalXactLockTableWait the same way.

Author: Petr Jelínek
Discussion: https://postgr.es/m/1B3E32D8-FCF4-40B4-AEF9-5C0E3AC57969@postgrespro.ru
Reported-by: Konstantin Knizhnik
Diagnosed-by: Stas Kelvich, Petr Jelínek
Reviewed-by: Andres Freund, Robert Haas
7 years agoUpdate copyright for 2018
Bruce Momjian [Wed, 3 Jan 2018 04:30:12 +0000 (23:30 -0500)]
Update copyright for 2018

Backpatch-through: certain files through 9.3

7 years agoFix deadlock hazard in CREATE INDEX CONCURRENTLY
Alvaro Herrera [Tue, 2 Jan 2018 22:16:16 +0000 (19:16 -0300)]
Fix deadlock hazard in CREATE INDEX CONCURRENTLY

Multiple sessions doing CREATE INDEX CONCURRENTLY simultaneously are
supposed to be able to work in parallel, as evidenced by fixes in commit
c3d09b3bd23f specifically to support this case.  In reality, one of the
sessions would be aborted by a misterious "deadlock detected" error.

Jeff Janes diagnosed that this is because of leftover snapshots used for
system catalog scans -- this was broken by 8aa3e47510b9 keeping track of
(registering) the catalog snapshot.  To fix the deadlocks, it's enough
to de-register that snapshot prior to waiting.

Backpatch to 9.4, which introduced MVCC catalog scans.

Include an isolationtester spec that 8 out of 10 times reproduces the
deadlock with the unpatched code for me (Álvaro).

Author: Jeff Janes
Diagnosed-by: Jeff Janes
Reported-by: Jeremy Finzel
Discussion: https://postgr.es/m/CAMa1XUhHjCv8Qkx0WOr1Mpm_R4qxN26EibwCrj0Oor2YBUFUTg%40mail.gmail.com

7 years agoDisallow UNION/INTERSECT/EXCEPT over no columns.
Tom Lane [Fri, 22 Dec 2017 17:08:34 +0000 (12:08 -0500)]
Disallow UNION/INTERSECT/EXCEPT over no columns.

Since 9.4, we've allowed the syntax "select union select" and variants
of that.  However, the planner wasn't expecting a no-column set operation
and ended up treating the set operation as if it were UNION ALL.

Pre-v10, there seem to be some executor issues that would need to be
fixed to support such cases, and it doesn't really seem worth expending
much effort on.  Just disallow it, instead.

Per report from Victor Yegorov.

Discussion: https://postgr.es/m/CAGnEbojGJrRSOgJwNGM7JSJZpVAf8xXcVPbVrGdhbVEHZ-BUMw@mail.gmail.com

7 years agodoc: Fix figures in example description
Peter Eisentraut [Mon, 18 Dec 2017 21:00:35 +0000 (16:00 -0500)]
doc: Fix figures in example description

oversight in 244c8b466a743d1ec18a7d841bf42669699b3b56

Reported-by: Blaz Merela <[email protected]>
7 years agoPerform a lot more sanity checks when freezing tuples.
Andres Freund [Tue, 14 Nov 2017 02:45:47 +0000 (18:45 -0800)]
Perform a lot more sanity checks when freezing tuples.

The previous commit has shown that the sanity checks around freezing
aren't strong enough. Strengthening them seems especially important
because the existance of the bug has caused corruption that we don't
want to make even worse during future vacuum cycles.

The errors are emitted with ereport rather than elog, despite being
"should never happen" messages, so a proper error code is emitted. To
avoid superflous translations, mark messages as internal.

Author: Andres Freund and Alvaro Herrera
Reviewed-By: Alvaro Herrera, Michael Paquier
Discussion: https://postgr.es/m/20171102112019[email protected]
Backpatch: 9.3-

7 years agoFix pruning of locked and updated tuples.
Andres Freund [Fri, 3 Nov 2017 14:52:29 +0000 (07:52 -0700)]
Fix pruning of locked and updated tuples.

Previously it was possible that a tuple was not pruned during vacuum,
even though its update xmax (i.e. the updating xid in a multixact with
both key share lockers and an updater) was below the cutoff horizon.

As the freezing code assumed, rightly so, that that's not supposed to
happen, xmax would be preserved (as a member of a new multixact or
xmax directly). That causes two problems: For one the tuple is below
the xmin horizon, which can cause problems if the clog is truncated or
once there's an xid wraparound. The bigger problem is that that will
break HOT chains, which in turn can lead two to breakages: First,
failing index lookups, which in turn can e.g lead to constraints being
violated. Second, future hot prunes / vacuums can end up making
invisible tuples visible again. There's other harmful scenarios.

Fix the problem by recognizing that tuples can be DEAD instead of
RECENTLY_DEAD, even if the multixactid has alive members, if the
update_xid is below the xmin horizon. That's safe because newer
versions of the tuple will contain the locking xids.

A followup commit will harden the code somewhat against future similar
bugs and already corrupted data.

Author: Andres Freund, with changes by Alvaro Herrera
Reported-By: Daniel Wood
Analyzed-By: Andres Freund, Alvaro Herrera, Robert Haas, Peter
   Geoghegan, Daniel Wood, Yi Wen Wong, Michael Paquier
Reviewed-By: Alvaro Herrera, Robert Haas, Michael Paquier
Discussion:
    https://postgr.es/m/E5711E62-8FDF-4DCA-A888-C200BF6B5742@amazon.com
    https://postgr.es/m/20171102112019[email protected]
Backpatch: 9.3-

7 years agoFix walsender timeouts when decoding a large transaction
Andrew Dunstan [Thu, 14 Dec 2017 16:31:13 +0000 (11:31 -0500)]
Fix walsender timeouts when decoding a large transaction

The logical slots have a fast code path for sending data so as not to
impose too high a per message overhead. The fast path skips checks for
interrupts and timeouts. However, the existing coding failed to consider
the fact that a transaction with a large number of changes may take a
very long time to be processed and sent to the client. This causes the
walsender to ignore interrupts for potentially a long time and more
importantly it will result in the walsender being killed due to
timeout at the end of such a transaction.

This commit changes the fast path to also check for interrupts and only
allows calling the fast path when the last keepalive check happened less
than half the walsender timeout ago. Otherwise the slower code path will
be taken.

Backpatched to 9.4

Petr Jelinek, reviewed by  Kyotaro HORIGUCHI, Yura Sokolov,  Craig
Ringer and Robert Haas.

Discussion: https://postgr.es/m/e082a56a-fd95-a250-3bae-0fff93832510@2ndquadrant.com

7 years agoFix corner-case coredump in _SPI_error_callback().
Tom Lane [Mon, 11 Dec 2017 21:33:20 +0000 (16:33 -0500)]
Fix corner-case coredump in _SPI_error_callback().

I noticed that _SPI_execute_plan initially sets spierrcontext.arg = NULL,
and only fills it in some time later.  If an error were to happen in
between, _SPI_error_callback would try to dereference the null pointer.
This is unlikely --- there's not much between those points except
push-snapshot calls --- but it's clearly not impossible.  Tweak the
callback to do nothing if the pointer isn't set yet.

It's been like this for awhile, so back-patch to all supported branches.

7 years agoMSVC 2012+: Permit linking to 32-bit, MinGW-built libraries.
Noah Misch [Sat, 9 Dec 2017 08:58:55 +0000 (00:58 -0800)]
MSVC 2012+: Permit linking to 32-bit, MinGW-built libraries.

Notably, this permits linking to the 32-bit Perl binaries advertised on
perl.org, namely Strawberry Perl and ActivePerl.  This has a side effect
of permitting linking to binaries built with obsolete MSVC versions.

By default, MSVC 2012 and later require a "safe exception handler table"
in each binary.  MinGW-built, 32-bit DLLs lack the relevant exception
handler metadata, so linking to them failed with error LNK2026.  Restore
the semantics of MSVC 2010, which omits the table from a given binary if
some linker input lacks metadata.  This has no effect on 64-bit builds
or on MSVC 2010 and earlier.  Back-patch to 9.3 (all supported
versions).

Reported by Victor Wagner.

Discussion: https://postgr.es/m/20160326154321.7754ab8f@wagner.wagner.home

7 years agoMSVC: Test whether 32-bit Perl needs -D_USE_32BIT_TIME_T.
Noah Misch [Sat, 9 Dec 2017 02:06:05 +0000 (18:06 -0800)]
MSVC: Test whether 32-bit Perl needs -D_USE_32BIT_TIME_T.

Commits 5a5c2feca3fd858e70ea348822595547e6fa6c15 and
b5178c5d08ca59e30f9d9428fa6fdb2741794e65 introduced support for modern
MSVC-built, 32-bit Perl, but they broke use of MinGW-built, 32-bit Perl
distributions like Strawberry Perl and modern ActivePerl.  Perl has no
robust means to report whether it expects a -D_USE_32BIT_TIME_T ABI, so
test this.  Back-patch to 9.3 (all supported versions).

The chief alternative was a heuristic of adding -D_USE_32BIT_TIME_T when
$Config{gccversion} is nonempty.  That banks on every gcc-built Perl
using the same ABI.  gcc could change its default ABI the way MSVC once
did, and one could build Perl with gcc and the non-default ABI.

The GNU make build system could benefit from a similar test, without
which it does not support MSVC-built Perl.  For now, just add a comment.
Most users taking the special step of building Perl with MSVC probably
build PostgreSQL with MSVC.

Discussion: https://postgr.es/m/20171130041441[email protected]

7 years agoMSVC: Remove cosmetic, cross-branch differences pertaining to Perl.
Noah Misch [Sat, 9 Dec 2017 02:04:45 +0000 (18:04 -0800)]
MSVC: Remove cosmetic, cross-branch differences pertaining to Perl.

This simplifies back-patch of the next change to v9.5 and v9.6.

7 years agoFix mistake in comment
Peter Eisentraut [Fri, 8 Dec 2017 16:16:23 +0000 (11:16 -0500)]
Fix mistake in comment

Reported-by: Masahiko Sawada <[email protected]>