users/rhaas/postgres.git
5 years agoEmit parameter values during query bind/execute errors
Alvaro Herrera [Wed, 11 Dec 2019 21:03:35 +0000 (18:03 -0300)]
Emit parameter values during query bind/execute errors

This makes such log entries more useful, since the cause of the error
can be dependent on the parameter values.

Author: Alexey Bashtanov, Álvaro Herrera
Discussion: https://postgr.es/m/0146a67b-a22a-0519-9082-bc29756b93a2@imap.cc
Reviewed-by: Peter Eisentraut, Andres Freund, Tom Lane
5 years agoUse only one thread to handle incoming signals on Windows.
Tom Lane [Wed, 11 Dec 2019 20:09:54 +0000 (15:09 -0500)]
Use only one thread to handle incoming signals on Windows.

Since its inception, our Windows signal emulation code has worked by
running a main signal thread that just watches for incoming signal
requests, and then spawns a new thread to handle each such request.
That design is meant for servers in which requests can take substantial
effort to process, and it's worth parallelizing the handling of
requests.  But those assumptions are just bogus for our signal code.
It's not much more than pg_queue_signal(), which is cheap and can't
parallelize at all, plus we don't really expect lots of signals to
arrive at the same backend at once.  More importantly, this approach
creates failure modes that we could do without: either inability to
spawn a new thread or inability to create a new pipe handle will risk
loss of signals.  Hence, dispense with the separate per-signal threads
and just service each request in-line in the main signal thread.  This
should be a bit faster (for the normal case of one signal at a time)
as well as more robust.

 by me; thanks to Andrew Dunstan for testing and Amit Kapila
for review.

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

5 years agoRemove ATPrepSetStatistics
Peter Eisentraut [Wed, 11 Dec 2019 07:59:18 +0000 (08:59 +0100)]
Remove ATPrepSetStatistics

It was once possible to do ALTER TABLE ... SET STATISTICS on system
tables without allow_sytem_table_mods.  This was changed apparently by
accident between PostgreSQL 9.1 and 9.2, but a code comment still
claimed this was possible.  Without that functionality, having a
separate ATPrepSetStatistics() is useless, so use the generic
ATSimplePermissions() instead and move the remaining custom code into
ATExecSetStatistics().

Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/cc8d2648-a0ec-7a86-13e5-db473484e19e%402ndquadrant.com

5 years agoFix output of Unicode normalization test
Peter Eisentraut [Wed, 11 Dec 2019 07:42:17 +0000 (08:42 +0100)]
Fix output of Unicode normalization test

Several off-by-more-than-one errors caused the output in case of a
test failure to be truncated and unintelligible.

Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/6a7a8516-7d11-8fbd-0e8b-eadb4f0679eb%402ndquadrant.com

5 years agoFix some compiler warnings with timestamp parsing in formatting.c
Michael Paquier [Wed, 11 Dec 2019 01:01:06 +0000 (10:01 +0900)]
Fix some compiler warnings with timestamp parsing in formatting.c

gcc-7 used with a sufficient optimization level complains about warnings
around do_to_timestamp() regarding the initialization and handling of
some of its variables.  Recent commits 66c74f8 and d589f94 made things
made the interface more confusing, so document which variables are
always expected and initialize properly the optional ones when they are
set.

Author: Andrey Lepikhov, Michael Paquier
Discussion: https://postgr.es/m/a7e28b83-27b1-4e1c-c76b-4268c4b785bc@postgrespro.ru

5 years agoFix tuple column count in pg_control_init().
Tom Lane [Tue, 10 Dec 2019 22:51:46 +0000 (17:51 -0500)]
Fix tuple column count in pg_control_init().

Oversight in commit 2e4db241b.

Nathan Bossart

Discussion: https://postgr.es/m/1B616360-396A-4482-AA28-375566C86160@amazon.com

5 years agoCosmetic cleaning of pg_config.h.win32
Peter Eisentraut [Tue, 10 Dec 2019 20:15:30 +0000 (21:15 +0100)]
Cosmetic cleaning of pg_config.h.win32

Clean up some comments (some generated by old versions of autoconf)
and some random ordering differences, so it's easier to diff this
against the default pg_config.h or pg_config.h.in.  Remove LOCALEDIR
handling from pg_config.h.win32 altogether because it's already in
pg_config_paths.h.

5 years agoAdd backend-only appendStringInfoStringQuoted
Alvaro Herrera [Tue, 10 Dec 2019 20:09:32 +0000 (17:09 -0300)]
Add backend-only appendStringInfoStringQuoted

This provides a mechanism to emit literal values in informative
messages, such as query parameters.  The new code is more complex than
what it replaces, primarily because it wants to be more efficient.
It also has the (currently unused) additional optional capability of
specifying a maximum size to print.

The new function lives out of common/stringinfo.c so that frontend users
of that file need not pull in unnecessary multibyte-encoding support
code.

Author: Álvaro Herrera and Alexey Bashtanov, after a suggestion from Andres Freund
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/20190920203905[email protected]

5 years agoIn pg_ctl, work around ERROR_SHARING_VIOLATION on the postmaster log file.
Tom Lane [Tue, 10 Dec 2019 18:17:08 +0000 (13:17 -0500)]
In pg_ctl, work around ERROR_SHARING_VIOLATION on the postmaster log file.

On Windows, we use CMD.EXE to redirect the postmaster's stdout/stderr
into a log file.  CMD.EXE will open that file with non-sharing-friendly
parameters, and the file will remain open for a short time after the
postmaster has removed postmaster.pid.  This can result in an
ERROR_SHARING_VIOLATION failure if we attempt to start a new postmaster
immediately with the same log file (e.g. during "pg_ctl restart").
This seems to explain intermittent buildfarm failures we've been seeing
on Windows machines.

To fix, just open and close the log file using our own pgwin32_open(),
which will wait if necessary to avoid the failure.  (Perhaps someday
we should stop using CMD.EXE, but that would be a far more complex
, and it doesn't seem worth the trouble ... yet.)

Back- to v12.  This only solves the problem when frontend fopen()
is redirected to pgwin32_fopen(), which has only been true since commit
0ba06e0bf.  Hence, no point in back-ing further, unless we care
to back- that change too.

Diagnosis and  by Alexander Lakhin (bug #16154).

Discussion: https://postgr.es/m/16154-1ccf0b537b24d5e0@postgresql.org

5 years agoFix handling of multiple AFTER ROW triggers on a foreign table.
Etsuro Fujita [Tue, 10 Dec 2019 09:00:30 +0000 (18:00 +0900)]
Fix handling of multiple AFTER ROW triggers on a foreign table.

AfterTriggerExecute() retrieves a fresh tuple or pair of tuples from a
tuplestore and then stores the tuple(s) in the passed-in slot(s) if
AFTER_TRIGGER_FDW_FETCH, while it uses the most-recently-retrieved
tuple(s) stored in the slot(s) if AFTER_TRIGGER_FDW_REUSE.  This was
done correctly before 12, but commit ff11e7f4b broke it by mistakenly
clearing the tuple(s) stored in the slot(s) in that function, leading to
an assertion failure as reported in bug #16139 from Alexander Lakhin.

Also, fix some other issues with the aforementioned commit in passing:

* For tg_newslot, which is a slot added to the TriggerData struct by the
  commit to store new updated tuples, it didn't ensure the slot was NULL
  if there was no such tuple.
* The commit failed to update the documentation about the trigger
  interface.

Author: Etsuro Fujita
Back-through: 12
Discussion: https://postgr.es/m/16139-94f9ccf0db6119ec%40postgresql.org

5 years agoFix race condition in our Windows signal emulation.
Tom Lane [Mon, 9 Dec 2019 20:03:51 +0000 (15:03 -0500)]
Fix race condition in our Windows signal emulation.

pg_signal_dis_thread() responded to the client (signal sender)
and disconnected the pipe before actually setting the shared variables
that make the signal visible to the backend process's main thread.
In the worst case, it seems, effective delivery of the signal could be
postponed for as long as the machine has any other work to do.

To fix, just move the pg_queue_signal() call so that we do it before
responding to the client.  This essentially makes pgkill() synchronous,
which is a stronger guarantee than we have on Unix.  That may be
overkill, but on the other hand we have not seen comparable timing bugs
on any Unix platform.

While at it, add some comments to this sadly underdocumented code.

Problem diagnosis and fix by Amit Kapila; I just added the comments.

Back- to all supported versions, as it appears that this can cause
visible NOTIFY timing oddities on all of them, and there might be
other misbehavior due to slow delivery of other signals.

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

5 years agoImprove isolationtester's timeout management.
Tom Lane [Mon, 9 Dec 2019 19:31:57 +0000 (14:31 -0500)]
Improve isolationtester's timeout management.

isolationtester.c had a hard-wired limit of 3 minutes per test step.
It now emerges that this isn't quite enough for some of the slowest
buildfarm animals.  This isn't the first time we've had to raise
this limit (cf. 1db439ad4), so let's make it configurable.  This
 raises the default to 5 minutes, and introduces an environment
variable PGISOLATIONTIMEOUT that can be set if more time is needed,
following the precedent of PGCTLTIMEOUT.

Also, modify isolationtester so that when the timeout is hit,
it explicitly reports having sent a cancel.  This makes the regression
failure log considerably more intelligible.  (In the worst case, a
timed-out test might actually be reported as "passing" without this
extra output, so arguably this is a bug fix in itself.)

In passing, update the README file, which had apparently not gotten
touched when we added "make check" support here.

Back- to 9.6; older versions don't have comparable timeout logic.

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

5 years agoFix typos in miscinit.c.
Amit Kapila [Mon, 9 Dec 2019 03:09:34 +0000 (08:39 +0530)]
Fix typos in miscinit.c.

Commit f13ea95f9e moved the description of postmaster.pid file contents
from miscadmin.h to pidfile.h, but missed to update the comments in
miscinit.c.

Author: Hadi Moshayedi
Reviewed-by: Amit Kapila
Back-through: 10
Discussion: https://postgr.es/m/CAK=1=WpYEM9x3LGkaxgXaxeYQjnkdW8XLsxrYRTE2Gq-H83FMw@mail.gmail.com

5 years agoDocument search_path security with untrusted dbowner or CREATEROLE.
Noah Misch [Sun, 8 Dec 2019 19:06:26 +0000 (11:06 -0800)]
Document search_path security with untrusted dbowner or CREATEROLE.

Commit 5770172cb0c9df9e6ce27c507b449557e5b45124 wrote, incorrectly, that
certain schema usage patterns are secure against CREATEROLE users and
database owners.  When an untrusted user is the database owner or holds
CREATEROLE privilege, a query is secure only if its session started with
SELECT pg_catalog.set_config('search_path', '', false) or equivalent.
Back- to 9.4 (all supported versions).

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

5 years agoDoc: improve documentation about run-time pruning's effects on EXPLAIN.
Tom Lane [Sun, 8 Dec 2019 15:36:29 +0000 (10:36 -0500)]
Doc: improve documentation about run-time pruning's effects on EXPLAIN.

Tatsuo Ishii complained that this para wasn't very intelligible.
Try to make it better.

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

5 years agoRemove PQsslpassword function
Andrew Dunstan [Sat, 7 Dec 2019 14:20:53 +0000 (09:20 -0500)]
Remove PQsslpassword function

This partially reverts commit 4dc6355210.

The information returned by the function can be obtained by calling
PQconninfo(), so the function is redundant.

5 years agoImprove test coverage of ruleutils.c.
Tom Lane [Fri, 6 Dec 2019 22:40:24 +0000 (17:40 -0500)]
Improve test coverage of ruleutils.c.

While fooling around with the EXPLAIN improvements I've been working
on, I noticed that there were some large gaps in our test coverage
of ruleutils.c, according to the code coverage report.  This commit
just adds a few test cases to improve coverage of:
get_name_for_var_field()
get_update_query_targetlist_def()
isSimpleNode()
get_sublink_expr()

5 years agoFix comments in execGrouping.c
Jeff Davis [Fri, 6 Dec 2019 19:47:59 +0000 (11:47 -0800)]
Fix comments in execGrouping.c

Commit 5dfc1981 missed updating some comments.

Also, fix a comment typo found in passing.

Author: Jeff Davis
Discussion: https://postgr.es/m/9723131d247b919f94699152647fa87ee0bc02c2.camel%40j-davis.com

5 years agoDisallow non-default collation in ADD PRIMARY KEY/UNIQUE USING INDEX.
Tom Lane [Fri, 6 Dec 2019 16:25:09 +0000 (11:25 -0500)]
Disallow non-default collation in ADD PRIMARY KEY/UNIQUE USING INDEX.

When creating a uniqueness constraint using a pre-existing index,
we have always required that the index have the same properties you'd
get if you just let a new index get built.  However, when collations
were added, we forgot to add the index's collation to that check.

It's hard to trip over this without intentionally trying to break it:
you'd have to explicitly specify a different collation in CREATE
INDEX, then convert it to a pkey or unique constraint.  Still, if you
did that, pg_dump would emit a script that fails to reproduce the
index's collation.  The main practical problem is that after a
pg_upgrade the index would be corrupt, because its actual physical
order wouldn't match what pg_index says.  A more theoretical issue,
which is new as of v12, is that if you create the index with a
nondeterministic collation then it wouldn't be enforcing the normal
notion of uniqueness, causing the constraint to mean something
different from a normally-created constraint.

To fix, just add collation to the conditions checked for index
acceptability in ADD PRIMARY KEY/UNIQUE USING INDEX.  We won't try
to clean up after anybody who's already created such a situation;
it seems improbable enough to not be worth the effort involved.
(If you do get into trouble, a REINDEX should be enough to fix it.)

In principle this is a long-standing bug, but I chose not to
back- --- the odds of causing trouble seem about as great
as the odds of preventing it, and both risks are very low anyway.

Per report from Alexey Bashtanov, though this is not his preferred
fix.

Discussion: https://postgr.es/m/b05ce36a-cefb-ca5e-b386-a400535b1c0b@imap.cc

5 years agoFix handling of OpenSSL's SSL_clear_options
Michael Paquier [Fri, 6 Dec 2019 06:13:55 +0000 (15:13 +0900)]
Fix handling of OpenSSL's SSL_clear_options

This function is supported down to OpenSSL 0.9.8, which is the oldest
version supported since 593d4e4 (from Postgres 10 onwards), and is used
since e3bdb2d (from 11 onwards).  It is defined as a macro from OpenSSL
0.9.8 to 1.0.2, and as a function in 1.1.0 and newer versions.  However,
the configure check present is only adapted for functions.  So, even if
the code would be able to compile, configure fails to detect the macro,
causing it to be ignored when compiling the code with OpenSSL from 0.9.8
to 1.0.2.

The code needs a configure check as per a364dfa, which has fixed a
compilation issue with a past version of LibreSSL in NetBSD 5.1.  On
HEAD, just remove the configure check as the last release of NetBSD 5 is
from 2014 (and we have no more buildfarm members for it).  In 11 and 12,
improve the configure logic so as both macros and functions are
correctly detected.  This makes NetBSD 5 still work on already-released
branches, but not for 13 onwards.

The  for HEAD is from me, and Daniel has written the version to use
for the back-branches.

Author: Michael Paquier, Daniel Gustaffson
Reviewed-by: Tom Lane
Discussion: https://postgr.es/m/20191205083252[email protected]
Discussion: https://postgr.es/m/98F7F99E-1129-41D8-B86B-FE3B1E286881@yesql.se
Back-through: 11

5 years agoImprove some comments in pg_upgrade.c
Michael Paquier [Fri, 6 Dec 2019 02:55:04 +0000 (11:55 +0900)]
Improve some comments in pg_upgrade.c

When restoring database schemas on a new cluster, database "template1"
is processed first, followed by all other databases in parallel,
including "postgres".  Both "postgres" and "template1" have some extra
handling to propagate each one's properties, but comments were confusing
regarding which one is processed where.

Author: Julien Rouhaud
Reviewed-by: Daniel Gustafsson
Discussion: https://postgr.es/m/CAOBaU_a2iviTG7FE10yO_gcW+zQCHNFhRA_NDiktf3UR65BHdw@mail.gmail.com

5 years agoRemove configure check for OpenSSL's SSL_get_current_compression()
Michael Paquier [Fri, 6 Dec 2019 00:41:32 +0000 (09:41 +0900)]
Remove configure check for OpenSSL's SSL_get_current_compression()

This function has been added in OpenSSL 0.9.8, which is the oldest
version supported on HEAD, so checking for it at configure time is
useless.  Both the frontend and backend code did not even bother to use
it.

Reported-by: Daniel Gustafsson
Author: Michael Paquier
Reviewed-by: Daniel Gustafsson, Tom Lane
Discussion: https://postgr.es/m/20191205083252[email protected]
Discussion: https://postgr.es/m/98F7F99E-1129-41D8-B86B-FE3B1E286881@yesql.se

5 years agopg_basebackup: Refactor code for reading COPY and tar data.
Robert Haas [Thu, 5 Dec 2019 20:14:09 +0000 (15:14 -0500)]
pg_basebackup: Refactor code for reading COPY and tar data.

Add a new function ReceiveCopyData that does just that, taking a
callback as an argument to specify what should be done with each chunk
as it is received. This allows a single copy of the logic to be shared
between ReceiveTarFile and ReceiveAndUnpackTarFile, and eliminates
a few #ifdef conditions based on HAVE_LIBZ.

While this is slightly more code, it's arguably clearer, and
there is a pending  that introduces additional calls to
ReceiveCopyData.

This commit is not intended to result in any functional change.

Discussion: http://postgr.es/m/CA+TgmoYZDTHbSpwZtW=JDgAhwVAYvmdSrRUjOd+AYdfNNXVBDg@mail.gmail.com

5 years agoMinor comment improvements for instrumentation.h
Robert Haas [Thu, 5 Dec 2019 12:53:12 +0000 (07:53 -0500)]
Minor comment improvements for instrumentation.h

Remove a duplicated word. Add "of" or "# of" in a couple places
for clarity and consistency. Start comments with a lower case
letter as we do elsewhere in this file.

Rafia Sabih

5 years agoBlind attempt at fixing ecpg/compatlib's build
Alvaro Herrera [Wed, 4 Dec 2019 23:15:11 +0000 (20:15 -0300)]
Blind attempt at fixing ecpg/compatlib's build

It now needs libpgcommon in order to get pnstrdup.

Per buildfarm.

5 years agoOffer pnstrdup to frontend code
Alvaro Herrera [Wed, 4 Dec 2019 22:36:06 +0000 (19:36 -0300)]
Offer pnstrdup to frontend code

We already had it on the backend.  Frontend can also use it now.

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

5 years agoUpdate minimum SSL version
Peter Eisentraut [Wed, 4 Dec 2019 20:40:17 +0000 (21:40 +0100)]
Update minimum SSL version

Change default of ssl_min_protocol_version to TLSv1.2 (from TLSv1,
which means 1.0).  Older versions are still supported, just not by
default.

TLS 1.0 is widely deprecated, and TLS 1.1 only slightly less so.  All
OpenSSL versions that support TLS 1.1 also support TLS 1.2, so there
would be very little reason to, say, set the default to TLS 1.1
instead on grounds of better compatibility.

The test suite overrides this new setting, so it can still run with
older OpenSSL versions.

Discussion: https://www.postgresql.org/message-id/flat/b327f8df-da98-054d-0cc5-b76a857cfed9%402ndquadrant.com

5 years agoFix whitespace.
Etsuro Fujita [Wed, 4 Dec 2019 03:45:00 +0000 (12:45 +0900)]
Fix whitespace.

5 years agoUse carriage returns for data insertion logs in pgbench on terminal
Michael Paquier [Wed, 4 Dec 2019 02:33:14 +0000 (11:33 +0900)]
Use carriage returns for data insertion logs in pgbench on terminal

This is similar to what pg_basebackup and pg_rewind do when reporting
cumulative data, and that's more user-friendly.  Carriage returns are
now used when stderr points to a terminal, and newlines are used in
other cases, like a redirection to a log file.

Author: Amit Langote
Reviewed-by: Fabien Coelho
Discussion: https://postgr.es/m/CA+HiwqFNwEjPeVaQsp2L7DyCPv1Eg1guwhrVhzMYqUJUk8ULKg@mail.gmail.com

5 years agoRemove unnecessary definition of CancelRequested in bin/scripts/
Michael Paquier [Wed, 4 Dec 2019 01:06:45 +0000 (10:06 +0900)]
Remove unnecessary definition of CancelRequested in bin/scripts/

This variable is now part of the refactored code for query cancellation
in fe_utils.  This fixes an oversight in commit a4fd3aa.  While on it,
improve some header includes in bin/scripts/.

Author: Michael Paquier
Reviewed-by: Fabien Coelho
Discussion: https://postgr.es/m/20191203101625[email protected]

5 years agoEnsure maxlen is at leat 1 in dict_int
Tomas Vondra [Tue, 3 Dec 2019 15:55:51 +0000 (16:55 +0100)]
Ensure maxlen is at leat 1 in dict_int

The dict_int text search dictionary template accepts maxlen parameter,
which is then used to cap the length of input strings. The value was
not properly checked, and the code simply does

    txt[d->maxlen] = '\0';

to insert a terminator, leading to segfaults with negative values.

This commit simply rejects values less than 1. The issue was there since
dct_int was introduced in 9.3, so back all the way back to 9.4
which is the oldest supported version.

Reported-by: cili
Discussion: https://postgr.es/m/16144-a36a5bef7657047d@postgresql.org
Back-through: 9.4

5 years agoFurther sync postgres_fdw's "Relations" output with the rest of EXPLAIN.
Tom Lane [Tue, 3 Dec 2019 17:25:56 +0000 (12:25 -0500)]
Further sync postgres_fdw's "Relations" output with the rest of EXPLAIN.

EXPLAIN generally only adds schema qualifications to table names when
VERBOSE is specified.  In postgres_fdw's "Relations" output, table
names were always so qualified, but that was an implementation
restriction: in the original coding, we didn't have access to the
verbose flag at the time the string was generated.  After the code
rearrangement of commit 4526951d5, we do have that info available
at the right time, so make this output follow the normal rule.

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

5 years agoFix thinkos from commit 9989d37
Michael Paquier [Tue, 3 Dec 2019 09:59:09 +0000 (18:59 +0900)]
Fix thinkos from commit 9989d37

Error messages referring to incorrect WAL segment names could have been
generated for a fsync() failure or when creating a new segment at the
end of recovery.

5 years agoFix alter_system_table test
Peter Eisentraut [Tue, 3 Dec 2019 08:14:35 +0000 (09:14 +0100)]
Fix alter_system_table test

Add workaround for disabling ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
warning for the test that tries to create a tablespace with a reserved
name.

Discussion: https://www.postgresql.org/message-id/flat/E1iacW7-0003h6-6U%40gemulon.postgresql.org

5 years agoRemove XLogFileNameP() from the tree
Michael Paquier [Tue, 3 Dec 2019 06:06:04 +0000 (15:06 +0900)]
Remove XLogFileNameP() from the tree

XLogFileNameP() is a wrapper routine able to build a palloc'd string for
a WAL segment name, which is used for error string generation.  There
were several code paths where it gets called in a critical section,
where memory allocation is not allowed.  This results in triggering
an assertion failure instead of generating the wanted error message.

Another, more annoying, problem is that if the allocation to generate
the WAL segment name fails on OOM, then the failure would be escalated
to a PANIC.

This removes the routine and all its callers are replaced with a logic
using a fixed-size buffer.  This way, all the existing mistakes are
fixed and future ones are prevented.

Author: Masahiko Sawada
Reviewed-by: Michael Paquier, Álvaro Herrera
Discussion: https://postgr.es/m/CA+fd4k5gC9H4uoWMLg9K_QfNrnkkdEw+-AFveob9YX7z8JnKTA@mail.gmail.com

5 years agoFix failures with TAP tests of pg_ctl on Windows
Michael Paquier [Tue, 3 Dec 2019 04:01:06 +0000 (13:01 +0900)]
Fix failures with TAP tests of pg_ctl on Windows

On Windows, all the hosts spawned by the TAP tests bind to 127.0.0.1.
Hence, if there is a port conflict, starting a cluster would immediately
fail.  One of the test scripts of pg_ctl initializes a node without
PostgresNode.pm, using the default port 5432.  This could cause
unexpected startup failures in the tests if an independent server was up
and running on the same host (the reverse is also possible, though more
unlikely).  Fix this issue by assigning properly a free port to the node
configured, in the same range used as for the other nodes part of the
tests.

Author: Michael Paquier
Reviewed-by: Andrew Dunstan
Discussion: https://postgr.es/m/20191202031444[email protected]
Back-through: 11

5 years agoFix EXPLAIN's column alias output for mismatched child tables.
Tom Lane [Tue, 3 Dec 2019 00:08:10 +0000 (19:08 -0500)]
Fix EXPLAIN's column alias output for mismatched child tables.

If an inheritance/partitioning parent table is assigned some column
alias names in the query, EXPLAIN mapped those aliases onto the
child tables' columns by physical position, resulting in bogus output
if a child table's columns aren't one-for-one with the parent's.

To fix, make expand_single_inheritance_child() generate a correctly
re-mapped column alias list, rather than just copying the parent
RTE's alias node.  (We have to fill the alias field, not just
adjust the eref field, because ruleutils.c will ignore eref in
favor of looking at the real column names.)

This means that child tables will now always have alias fields in
plan rtables, where before they might not have.  That results in
a rather substantial set of regression test output changes:
EXPLAIN will now always show child tables with aliases that match
the parent table (usually with "_N" appended for uniqueness).
But that seems like a net positive for understandability, since
the parent alias corresponds to something that actually appeared
in the original query, while the child table names didn't.
(Note that this does not change anything for cases where an explicit
table alias was written in the query for the parent table; it
just makes cases without such aliases behave similarly to that.)
Hence, while we could avoid these subsidiary changes if we made
inherit.c more complicated, we choose not to.

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

5 years agoAdd a reverse-translation column number array to struct AppendRelInfo.
Tom Lane [Mon, 2 Dec 2019 23:05:29 +0000 (18:05 -0500)]
Add a reverse-translation column number array to struct AppendRelInfo.

This provides for cheaper mapping of child columns back to parent
columns.  The one existing use-case in examine_simple_variable()
would hardly justify this by itself; but an upcoming bug fix will
make use of this array in a mainstream code path, and it seems
likely that we'll find other uses for it as we continue to build
out the partitioning infrastructure.

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

5 years agoMake postgres_fdw's "Relations" output agree with the rest of EXPLAIN.
Tom Lane [Mon, 2 Dec 2019 21:31:03 +0000 (16:31 -0500)]
Make postgres_fdw's "Relations" output agree with the rest of EXPLAIN.

The relation aliases shown in the "Relations" line for a foreign scan
didn't always agree with those used in the rest of EXPLAIN's output.
The regression test result changes appearing here provide examples.

It's really impossible for postgres_fdw to duplicate EXPLAIN's alias
assignment logic during postgresGetForeignRelSize(), because of the
de-duplication that EXPLAIN does on a global basis --- and anyway,
trying to duplicate that would be unmaintainable.  Instead, just put
numeric rangetable indexes into the string, and convert those to
table names/aliases in postgresExplainForeignScan, which does have
access to the results of ruleutils.c's alias assignment logic.
Aside from being more reliable, this shifts some work from planning
to EXPLAIN, which is a good tradeoff for performance.  (I also
changed from using StringInfo to using psprintf, which makes the
code slightly simpler and reduces its memory consumption.)

A kluge required by this solution is that we have to reverse-engineer
the rtoffset applied by setrefs.c.  If that logic ever fails
(presumably because the member tables of a join got offset by
different amounts), we'll need some more cooperation with setrefs.c
to keep things straight.  But for now, there's no need for that.

Arguably this is a back-able bug fix, but since this is a mostly
cosmetic issue and there have been no field complaints, I'll refrain
for now.

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

5 years agoAdd query cancellation capabilities in pgbench init phase
Michael Paquier [Mon, 2 Dec 2019 02:42:28 +0000 (11:42 +0900)]
Add query cancellation capabilities in pgbench init phase

This can be useful to stop data generation happening on the server for
long-running queries caused by large scale factors.  This cannot happen
by default as data is generated on the client, but it is possible to
control the initialization steps of pgbench to do that.

Reported-by: Fujii Masao
Author: Fabien Coelho
Discussion: https://postgr.es/m/alpine.DEB.2.21.1910311939430.27369@lancre
Discussion: https://postgr.es/m/CAHGQGwHWEyTXxZh46qgFY8a2bDF_EYeUdp3+_Hy=qLZSzwVPKg@mail.gmail.com

5 years agoRefactor query cancellation code into src/fe_utils/
Michael Paquier [Mon, 2 Dec 2019 02:18:56 +0000 (11:18 +0900)]
Refactor query cancellation code into src/fe_utils/

Originally, this code was duplicated in src/bin/psql/ and
src/bin/scripts/, but it can be useful for other frontend applications,
like pgbench.  This refactoring offers the possibility to setup a custom
callback which would get called in the signal handler for SIGINT or when
the interruption console events happen on Windows.

Author: Fabien Coelho, with contributions from Michael Paquier
Reviewed-by: Álvaro Herrera, Ibrar Ahmed
Discussion: https://postgr.es/m/alpine.DEB.2.21.1910311939430.27369@lancre

5 years agoAdd dummy versions of new SSL functions for non-SSL builds
Andrew Dunstan [Sun, 1 Dec 2019 22:49:43 +0000 (17:49 -0500)]
Add dummy versions of new SSL functions for non-SSL builds

This rectifies an oversight in commit 4dc6355210, which caused certain
builds to fail, especially on Windows.

5 years agoFix misbehavior with expression indexes on ON COMMIT DELETE ROWS tables.
Tom Lane [Sun, 1 Dec 2019 18:09:26 +0000 (13:09 -0500)]
Fix misbehavior with expression indexes on ON COMMIT DELETE ROWS tables.

We implement ON COMMIT DELETE ROWS by truncating tables marked that
way, which requires also truncating/rebuilding their indexes.  But
RelationTruncateIndexes asks the relcache for up-to-date copies of any
index expressions, which may cause execution of eval_const_expressions
on them, which can result in actual execution of subexpressions.
This is a bad thing to have happening during ON COMMIT.  Manuel Rigger
reported that use of a SQL function resulted in crashes due to
expectations that ActiveSnapshot would be set, which it isn't.
The most obvious fix perhaps would be to push a snapshot during
PreCommit_on_commit_actions, but I think that would just open the door
to more problems: CommitTransaction explicitly expects that no
user-defined code can be running at this point.

Fortunately, since we know that no tuples exist to be indexed, there
seems no need to use the real index expressions or predicates during
RelationTruncateIndexes.  We can set up dummy index expressions
instead (we do need something that will expose the right data type,
as there are places that build index tupdescs based on this), and
just ignore predicates and exclusion constraints.

In a green field it'd likely be better to reimplement ON COMMIT DELETE
ROWS using the same "init fork" infrastructure used for unlogged
relations.  That seems impractical without catalog changes though,
and even without that it'd be too big a change to back-.
So for now do it like this.

Per private report from Manuel Rigger.  This has been broken forever,
so back- to all supported branches.

5 years agolibq support for sslpassword connection param, DER format keys
Andrew Dunstan [Sat, 30 Nov 2019 20:27:13 +0000 (15:27 -0500)]
libq support for sslpassword connection param,  DER format keys

This  providies for support for password protected SSL client
keys in libpq, and for DER format keys, both encrypted and unencrypted.
There is a new connection parameter sslpassword, which is supplied to
the OpenSSL libraries via a callback function. The callback function can
also be set by an application by calling PQgetSSLKeyPassHook(). There is
also a function to retreive the connection setting, PQsslpassword().

Craig Ringer and Andrew Dunstan

Reviewed by: Greg Nancarrow

Discussion: https://postgr.es/m/f7ee88ed-95c4-95c1-d4bf-7b415363ab62@2ndQuadrant.com

5 years agoFix off-by-one error in PGTYPEStimestamp_fmt_asc
Tomas Vondra [Sat, 30 Nov 2019 13:51:27 +0000 (14:51 +0100)]
Fix off-by-one error in PGTYPEStimestamp_fmt_asc

When using %b or %B patterns to format a date, the code was simply using
tm_mon as an index into array of month names. But that is wrong, because
tm_mon is 1-based, while array indexes are 0-based. The result is we
either use name of the next month, or a segfault (for December).

Fix by subtracting 1 from tm_mon for both patterns, and add a regression
test triggering the issue. Back to all supported versions (the bug
is there far longer, since at least 2003).

Reported-by: Paul Spencer
Back-through: 9.4
Discussion: https://postgr.es/m/16143-0d861eb8688d3fef%40postgresql.org

5 years agoRevert commits 290acac92b and 8a7e9e9dad.
Amit Kapila [Sat, 30 Nov 2019 02:13:42 +0000 (07:43 +0530)]
Revert commits 290acac92b and 8a7e9e9dad.

This commit revert the commits to add a test case that tests the 'force'
option when there is an active backend connected to the database being
dropped.

This feature internally sends SIGTERM to all the backends connected to the
database being dropped and then the same is reported to the client.  We
found that on Windows, the client end of the socket is not able to read
the data once we close the socket in the server which leads to loss of
error message which is not what we expect.  We also observed  similar
behavior in other cases like pg_terminate_backend(),
pg_ctl kill TERM <pid>.  There are probably a few others like that.  The
fix for this requires further study.

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

5 years agoSmall code simplification
Peter Eisentraut [Fri, 29 Nov 2019 09:55:31 +0000 (10:55 +0100)]
Small code simplification

FLOAT8PASSBYVAL can be used instead of USE_FLOAT8_BYVAL here.

5 years agoAdd a regression test for allow_system_table_mods
Peter Eisentraut [Fri, 29 Nov 2019 09:04:45 +0000 (10:04 +0100)]
Add a regression test for allow_system_table_mods

Add a regression test file that exercises the kinds of commands that
allow_system_table_mods allows.

This is put in the "unsafe_tests" suite, so it won't accidentally
create a mess if someone runs the normal regression tests against an
instance that they care about.

Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/8b00ea5e-28a7-88ba-e848-21528b632354%402ndquadrant.com

5 years agoMake allow_system_table_mods settable at run time
Peter Eisentraut [Fri, 29 Nov 2019 09:04:45 +0000 (10:04 +0100)]
Make allow_system_table_mods settable at run time

Make allow_system_table_mods settable at run time by superusers.  It
was previously postmaster start only.

We don't want to make system catalog DDL wide-open, but there are
occasionally useful things to do like setting reloptions or statistics
on a busy system table, and blocking those doesn't help anyone.  Also,
this enables the possibility of writing a test suite for this setting.

Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/8b00ea5e-28a7-88ba-e848-21528b632354%402ndquadrant.com

5 years agoRemove any-user DML capability from allow_system_table_mods
Peter Eisentraut [Fri, 29 Nov 2019 09:04:45 +0000 (10:04 +0100)]
Remove any-user DML capability from allow_system_table_mods

Previously, allow_system_table_mods allowed a non-superuser to do DML
on a system table without further permission checks.  This has been
removed, as it was quite inconsistent with the rest of the meaning of
this setting.  (Since allow_system_table_mods was previously only
accessible with a server restart, it is unlikely that anyone was using
this possibility.)

Reviewed-by: Tom Lane <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/8b00ea5e-28a7-88ba-e848-21528b632354%402ndquadrant.com

5 years agoAdd error position to an error message
Peter Eisentraut [Fri, 29 Nov 2019 08:10:17 +0000 (09:10 +0100)]
Add error position to an error message

Reviewed-by: Pavel Stehule <[email protected]>
Discussion: https://www.postgresql.org/message-id/flat/6e7aa4a1-be6a-1a75-b1f9-83a678e5184a@2ndquadrant.com

5 years agoUse memcpy instead of a byte loop in pglz_decompress
Tomas Vondra [Thu, 28 Nov 2019 22:29:30 +0000 (23:29 +0100)]
Use memcpy instead of a byte loop in pglz_decompress

The byte loop used in pglz_decompress() because of possible overlap may
be quite inefficient, so this commit replaces it with memcpy. The gains
do depend on the data (compressibility) and hardware, but seem to be
quite significant.

Author: Andrey Borodin
Reviewed-by: Michael Paquier, Konstantin Knizhnik, Tels
Discussion: https://postgr.es/m/469C9ED9-348C-4FE7-A7A7-B0FA671BEE4C@yandex-team.ru

5 years agoRemove unnecessary clauses_attnums variable
Tomas Vondra [Thu, 28 Nov 2019 22:25:14 +0000 (23:25 +0100)]
Remove unnecessary clauses_attnums variable

Commit c676e659b2 reworked how choose_best_statistics() picks the best
extended statistics, but failed to remove clauses_attnums which is now
unnecessary. So get rid of it and back to 12, same as c676e659b2.

Author: Tomas Vondra
Discussion: https://postgr.es/m/CA+u7OA7H5rcE2=8f263w4NZD6ipO_XOrYB816nuLXbmSTH9pQQ@mail.gmail.com
Back-through: 12

5 years agoFix choose_best_statistics to check clauses individually
Tomas Vondra [Thu, 28 Nov 2019 21:20:28 +0000 (22:20 +0100)]
Fix choose_best_statistics to check clauses individually

When picking the best extended statistics object for a list of clauses,
it's not enough to look at attnums extracted from the clause list as a
whole. Consider for example this query with OR clauses:

   SELECT * FROM t WHERE (t.a = 1) OR (t.b = 1) OR (t.c = 1)

with a statistics defined on columns (a,b). Relying on attnums extracted
from the whole OR clause, we'd consider the statistics usable. That does
not work, as we see the conditions as a single OR-clause, referencing an
attribute not covered by the statistic, leading to empty list of clauses
to be estimated using the statistics and an assert failure.

This changes choose_best_statistics to check which clauses are actually
covered, and only using attributes from the fully covered ones. For the
previous example this means the statistics object will not be considered
as compatible with the OR-clause.

Back to 12, where MCVs were introduced. The issue does not affect
older versions because functional dependencies don't handle OR clauses.

Author: Tomas Vondra
Reviewed-by: Dean Rasheed
Reported-By: Manuel Rigger
Discussion: https://postgr.es/m/CA+u7OA7H5rcE2=8f263w4NZD6ipO_XOrYB816nuLXbmSTH9pQQ@mail.gmail.com
Back-through: 12

5 years agoRemove useless "return;" lines
Alvaro Herrera [Thu, 28 Nov 2019 19:48:37 +0000 (16:48 -0300)]
Remove useless "return;" lines

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

5 years agoAdd tests for '-f' option in dropdb utility.
Amit Kapila [Thu, 28 Nov 2019 06:16:57 +0000 (11:46 +0530)]
Add tests for '-f' option in dropdb utility.

This will test that the force option works when there is an active backend
connected to the database being dropped.

Author: Pavel Stehule and Vignesh C
Reviewed-by: Amit Kapila and Vignesh C
Discussion: https://postgr.es/m/CAP_rwwmLJJbn70vLOZFpxGw3XD7nLB_7+NKz46H5EOO2k5H7OQ@mail.gmail.com

5 years agoMove pump_until to TestLib.pm.
Amit Kapila [Thu, 28 Nov 2019 02:58:17 +0000 (08:28 +0530)]
Move pump_until to TestLib.pm.

The subroutine pump_until provides the functionality to poll until the
given string is matched, or a timeout occurs.  This can be used from other
places as well, so moving it to TestLib.pm.  The immediate need is for an
upcoming regression test  for dropdb utility.

Author: Vignesh C
Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/CAP_rwwmLJJbn70vLOZFpxGw3XD7nLB_7+NKz46H5EOO2k5H7OQ@mail.gmail.com

5 years agopg_upgrade: adjust error paragraph width to be consistent
Bruce Momjian [Thu, 28 Nov 2019 01:36:33 +0000 (20:36 -0500)]
pg_upgrade:  adjust error paragraph width to be consistent

Previously these error paragraphs were too wide.

Back-through: 13

5 years agopg_upgrade: improve instructions for fixing incompatible isn use
Bruce Momjian [Thu, 28 Nov 2019 01:24:57 +0000 (20:24 -0500)]
pg_upgrade: improve instructions for fixing incompatible isn use

This clarifies instructions on how to dump/reload databases that use
incompatible isn versions.

Reported-by: Alvaro Herrera
Discussion: https://postgr.es/m/20191114190652[email protected]

Reviewed-by: Daniel Gustafsson <[email protected]>
Back-through: 13

5 years agoDon't use native methods in TestLib::slurp_file on Msys
Andrew Dunstan [Wed, 27 Nov 2019 20:45:44 +0000 (15:45 -0500)]
Don't use native methods in TestLib::slurp_file on Msys

Commit 114541d58e has upset some buildfarm members running Msys, that
weren't previously having problems, so the use of native Windows methods
to open files is restricted by this  to only MSVC builds.

5 years agoRevert "Close stdin where it's not needed in TestLib.pm procedures"
Andrew Dunstan [Wed, 27 Nov 2019 12:19:22 +0000 (07:19 -0500)]
Revert "Close stdin where it's not needed in TestLib.pm procedures"

This reverts commits 9af34f3c6b and 792dba73c8.

The code has been found not to be portable.

Discussion: https://postgr.es/m/2658c496-f885-02db-13bb-228423782524@2ndQuadrant.com

5 years agoMove configure --disable-float8-byval to pg_config_manual.h
Peter Eisentraut [Wed, 27 Nov 2019 10:21:02 +0000 (11:21 +0100)]
Move configure --disable-float8-byval to pg_config_manual.h

This build option was once useful to maintain compatibility with
version-0 functions, but those are no longer supported, so this option
is no longer useful for end users.  We keep the option available to
developers in pg_config_manual.h so that it is easy to test the
pass-by-reference code paths without having to fire up a 32-bit
machine.

Discussion: https://www.postgresql.org/message-id/flat/f3e1e576-2749-bbd7-2d57-3f9dcf75255a@2ndquadrant.com

5 years agoFix typo in comment.
Etsuro Fujita [Wed, 27 Nov 2019 07:00:45 +0000 (16:00 +0900)]
Fix typo in comment.

5 years agoFix closing stdin in TestLib.pm
Andrew Dunstan [Tue, 26 Nov 2019 21:23:00 +0000 (16:23 -0500)]
Fix closing stdin in TestLib.pm

Commit 9af34f3c6b naively assumed that all non-windows platforms would
have pseudoterminals and that perl would have IO::Pty. Such is not the
case. Instead of assumung anything, test for the presence of IO::Pty and
only use code that might depend on it if it's present. The test result is
exposed in $TestLib::have_io_pty so that it can be conveniently used in
SKIP tests.

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

5 years agoAllow access to child table statistics if user can read parent table.
Tom Lane [Tue, 26 Nov 2019 19:41:48 +0000 (14:41 -0500)]
Allow access to child table statistics if user can read parent table.

The fix for CVE-2017-7484 disallowed use of pg_statistic data for
planning purposes if the user would not be able to select the associated
column and a non-proof function is to be applied to the statistics
values.  That turns out to disable use of pg_statistic data in some
common cases involving inheritance/partitioning, where the user does
have permission to select from the parent table that was actually named
in the query, but not from a child table whose stats are needed.  Since,
in non-corner cases, the user *can* select the child table's data via
the parent, this restriction is not actually useful from a security
standpoint.  Improve the logic so that we also check the permissions of
the originally-named table, and allow access if select permission exists
for that.

When checking access to stats for a simple child column, we can map
the child column number back to the parent, and perform this test
exactly (including not allowing access if the child column isn't
exposed by the parent).  For expression indexes, the current logic
just insists on whole-table select access, and this  allows
access if the user can select the whole parent table.  In principle,
if the child table has extra columns, this might allow access to
stats on columns the user can't read.  In practice, it's unlikely
that the planner is going to do any stats calculations involving
expressions that are not visible to the query, so we'll ignore that
fine point for now.  Perhaps someday we'll improve that logic to
detect exactly which columns are used by an expression index ...
but today is not that day.

Back- to v11.  The issue was created in 9.2 and up by the
CVE-2017-7484 fix, but this  depends on the append_rel_array[]
planner data structure which only exists in v11 and up.  In
practice the issue is most urgent with partitioned tables, so
fixing v11 and later should satisfy much of the practical need.

Dilip Kumar and Amit Langote, with some kibitzing by me

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

5 years agoAdd safeguards for pg_fsync() called with incorrectly-opened fds
Michael Paquier [Tue, 26 Nov 2019 04:32:52 +0000 (13:32 +0900)]
Add safeguards for pg_fsync() called with incorrectly-opened fds

On some platforms, fsync() returns EBADFD when opening a file descriptor
with O_RDONLY (read-only), leading ultimately now to a PANIC to prevent
data corruption.

This commit adds a new sanity check in pg_fsync() based on fcntl() to
make sure that we don't repeat again mistakes with incorrectly-set file
descriptors so as problems are detected at an early stage.  Without
that, such errors could only be detected after running Postgres on a
specific supported platform for the culprit code path, which could take
some time before being found.  b8e19b93 was a fix for such a problem,
which got undetected for more than 5 years, and a586cc4b fixed another
similar issue.

Note that the new check added works as well when fsync=off is
configured, so as all regression tests would detect problems as long as
assertions are enabled.  fcntl() being not available on Windows, the
new checks do not happen there.

Author: Michael Paquier
Reviewed-by: Mark Dilger
Discussion: https://postgr.es/m/20191009062640[email protected]

5 years agoDon't shut down Gather[Merge] early under Limit.
Amit Kapila [Mon, 18 Nov 2019 08:47:41 +0000 (14:17 +0530)]
Don't shut down Gather[Merge] early under Limit.

Revert part of commit 19df1702f5.

Early shutdown was added by that commit so that we could collect
statistics from workers, but unfortunately, it interacted badly with
rescans.  The problem is that we ended up destroying the parallel context
which is required for rescans.  This leads to rescans of a Limit node over
a Gather node to produce unpredictable results as it tries to access
destroyed parallel context.  By reverting the early shutdown code, we
might lose statistics in some cases of Limit over Gather [Merge], but that
will require further study to fix.

Reported-by: Jerry Sievers
Diagnosed-by: Thomas Munro
Author: Amit Kapila, testcase by Vignesh C
Back-through: 9.6
Discussion: https://postgr.es/m/[email protected]

5 years agoUse procsignal_sigusr1_handler for auxiliary processes.
Robert Haas [Mon, 25 Nov 2019 21:08:53 +0000 (16:08 -0500)]
Use procsignal_sigusr1_handler for auxiliary processes.

AuxiliaryProcessMain does ProcSignalInit, so one might expect that
auxiliary processes would need to respond to SendProcSignal, but none
of the auxiliary processes do that. Change them to use
procsignal_sigusr1_handler instead of their own private handlers so
that they do. Besides seeming more correct, this is also less code. It
shouldn't make any functional difference right now because, as far as
we know, there are no current cases where SendProcSignal targets an
auxiliary process, but there are plans to change that in the future.

Andres Freund

Discussion: http://postgr.es/m/20181030051643[email protected]

5 years agoClose stdin where it's not needed in TestLib.pm procedures
Andrew Dunstan [Mon, 25 Nov 2019 20:51:51 +0000 (15:51 -0500)]
Close stdin where it's not needed in TestLib.pm procedures

Where possible, do this using a pseudoterminal, so that things like
openssl that want to open /dev/tty if stdin isn't a tty won't.
Elsewhere, i.e. Windows, just close by providing an empty string using
the standard IPC::Run pipe mechanism.

 by Andrew Dunstan, based on an idea from Craig Ringer.

Reviewed by Mark Dilger.

Discussion: https://postgr.es/m/873ebb57-fc98-340d-949d-691b1810bf66@2ndQuadrant.com

5 years agoRefactor WAL file-reading code into WALRead()
Alvaro Herrera [Mon, 25 Nov 2019 18:04:54 +0000 (15:04 -0300)]
Refactor WAL file-reading code into WALRead()

XLogReader, walsender and pg_waldump all had their own routines to read
data from WAL files to memory, with slightly different approaches
according to the particular conditions of each environment.  There's a
lot of commonality, so we can refactor that into a single routine
WALRead in XLogReader, and move the differences to a separate (simpler)
callback that just opens the next WAL-segment.  This results in a
clearer (ahem) code flow.

The error reporting needs are covered by filling in a new error-info
struct, WALReadError, and it's the caller's responsibility to act on it.
The backend has WALReadRaiseError() to do so.

We no longer ever need to seek in this interface; switch to using
pg_pread().

Author: Antonin Houska, with contributions from Álvaro Herrera
Reviewed-by: Michaël Paquier, Kyotaro Horiguchi
Discussion: https://postgr.es/m/14984.1554998742@spoje.net

5 years agoFix unportable printf format introduced in commit 9290ad198.
Tom Lane [Mon, 25 Nov 2019 15:48:36 +0000 (10:48 -0500)]
Fix unportable printf format introduced in commit 9290ad198.

"%ld" is not an acceptable format spec for int64 variables, though
it accidentally works on most non-Windows 64-bit platforms.  Follow
the lead of commit 6a1cd8b92, and use "%lld" with an explicit cast
to long long.  Per buildfarm.

5 years agoMake the order of the header file includes consistent.
Amit Kapila [Mon, 25 Nov 2019 02:38:57 +0000 (08:08 +0530)]
Make the order of the header file includes consistent.

Similar to commits 14aec035027e735035f2 and dddf4cdc33, this commit
makes the order of header file inclusion consistent in more places.

Author: Vignesh C
Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/CALDaNm2Sznv8RR6Ex-iJO6xAdsxgWhCoETkaYX=+9DW3q0QCfA@mail.gmail.com

5 years agoFix inconsistent variable name in static function of mac8.c
Michael Paquier [Mon, 25 Nov 2019 00:57:35 +0000 (09:57 +0900)]
Fix inconsistent variable name in static function of mac8.c

Both argument names were reversed in the declaration of the function.

Author: Ranier Vilela
Discussion: https://postgr.es/m/MN2PR18MB292755AEFF9A9144B220ABEEE34B0@MN2PR18MB2927.namprd18.prod.outlook.com

5 years agoRefactor reloption handling for index AMs in-core
Michael Paquier [Mon, 25 Nov 2019 00:40:53 +0000 (09:40 +0900)]
Refactor reloption handling for index AMs in-core

This reworks the reloption parsing and build of a couple of index AMs by
creating new structures for each index AM's options.  This split was
already done for BRIN, GIN and GiST (which actually has a fillfactor
parameter), but not for hash, B-tree and SPGiST which relied on
StdRdOptions due to an overlap with the default option set.

This saves a couple of bytes for rd_options in each relcache entry with
indexes making use of relation options, and brings more consistency
between all index AMs.  While on it, add a couple of AssertMacro() calls
to make sure that utility macros to grab values of reloptions are used
with the expected index AM.

Author: Nikolay Shaplov
Reviewed-by: Amit Langote, Michael Paquier, Álvaro Herrera, Dent John
Discussion: https://postgr.es/m/4127670.gFlpRb6XCm@x200m

5 years agoUse native methods to open input in TestLib::slurp_file on Windows.
Andrew Dunstan [Sun, 24 Nov 2019 23:25:22 +0000 (18:25 -0500)]
Use native methods to open input in TestLib::slurp_file on Windows.

It is hoped that this will avoid some errors that we have seen before,
but lately with greater frequency, in buildfarm animals.

For now apply only to master. If this proves effective it can be
backed.

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

Author: Juan José Santamaría Flecha

5 years agoDoc: improve discussion of race conditions involved in LISTEN.
Tom Lane [Sun, 24 Nov 2019 23:03:39 +0000 (18:03 -0500)]
Doc: improve discussion of race conditions involved in LISTEN.

The user docs didn't really explain how to use LISTEN safely,
so clarify that.  Also clean up some fuzzy-headed explanations
in comments.  No code changes.

Discussion: https://postgr.es/m/3ac7f397-4d5f-be8e-f354-440020675694@gmail.com

5 years agoAvoid assertion failure with LISTEN in a serializable transaction.
Tom Lane [Sun, 24 Nov 2019 20:57:31 +0000 (15:57 -0500)]
Avoid assertion failure with LISTEN in a serializable transaction.

If LISTEN is the only action in a serializable-mode transaction,
and the session was not previously listening, and the notify queue
is not empty, predicate.c reported an assertion failure.  That
happened because we'd acquire the transaction's initial snapshot
during PreCommit_Notify, which was called *after* predicate.c
expects any such snapshot to have been established.

To fix, just swap the order of the PreCommit_Notify and
PreCommit_CheckForSerializationFailure calls during CommitTransaction.
This will imply holding the notify-insertion lock slightly longer,
but the difference could only be meaningful in serializable mode,
which is an expensive option anyway.

It appears that this is just an assertion failure, with no
consequences in non-assert builds.  A snapshot used only to scan
the notify queue could not have been involved in any serialization
conflicts, so there would be nothing for
PreCommit_CheckForSerializationFailure to do except assign it a
prepareSeqNo and set the SXACT_FLAG_PREPARED flag.  And given no
conflicts, neither of those omissions affect the behavior of
ReleasePredicateLocks.  This admittedly once-over-lightly analysis
is backed up by the lack of field reports of trouble.

Per report from Mark Dilger.  The bug is old, so back- to all
supported branches; but the new test case only goes back to 9.6,
for lack of adequate isolationtester infrastructure before that.

Discussion: https://postgr.es/m/3ac7f397-4d5f-be8e-f354-440020675694@gmail.com
Discussion: https://postgr.es/m/13881.1574557302@sss.pgh.pa.us

5 years agodoc: Fix whitespace in syntax.
Thomas Munro [Sun, 24 Nov 2019 20:20:28 +0000 (09:20 +1300)]
doc: Fix whitespace in syntax.

Back- to 10.

Author: Andreas Karlsson
Discussion: https://postgr.es/m/043acae2-a369-b7fa-be48-1933aa2e82d1%40proxel.se

5 years agoStabilize NOTIFY behavior by transmitting notifies before ReadyForQuery.
Tom Lane [Sun, 24 Nov 2019 19:42:59 +0000 (14:42 -0500)]
Stabilize NOTIFY behavior by transmitting notifies before ReadyForQuery.

This  ensures that, if any notify messages were received during
a just-finished transaction, they get sent to the frontend just before
not just after the ReadyForQuery message.  With libpq and other client
libraries that act similarly, this guarantees that the client will see
the notify messages as available as soon as it thinks the transaction
is done.

This probably makes no difference in practice, since in realistic
use-cases the application would have to cope with asynchronous
arrival of notify events anyhow.  However, it makes it a lot easier
to build cross-session-notify test cases with stable behavior.
I'm a bit surprised now that we've not seen any buildfarm instability
with the test cases added by commit b10f40bf0.  Tests that I intend
to add in an upcoming bug fix are definitely unstable without this.

Back- to 9.6, which is as far back as we can do NOTIFY testing
with the isolationtester infrastructure.

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

5 years agoStabilize the results of pg_notification_queue_usage().
Tom Lane [Sun, 24 Nov 2019 19:09:33 +0000 (14:09 -0500)]
Stabilize the results of pg_notification_queue_usage().

This function wasn't touched in commit 51004c717, but that turns out
to be a bad idea, because its results now include any dead space
that exists in the NOTIFY queue on account of our being lazy about
advancing the queue tail.  Notably, the isolation tests now fail
if run twice without a server restart between, because async-notify's
first test of the function will already show a positive value.
It seems likely that end users would be equally unhappy about the
result's instability.  To fix, just make the function call
asyncQueueAdvanceTail before computing its result.  That should end
in producing the same value as before, and it's hard to believe that
there's any practical use-case where pg_notification_queue_usage()
is called so often as to create a performance degradation, especially
compared to what we did before.

Out of paranoia, also mark this function parallel-restricted (it
was volatile, but parallel-safe by default, before).  Although the
code seems to work fine when run in a parallel worker, that's outside
the design scope of async.c, and it's a bit scary to have intentional
side-effects happening in a parallel worker.  There seems no plausible
use-case where it'd be important to try to parallelize this, so let's
not take any risk of introducing new bugs.

In passing, re-pgindent async.c and run reformat-dat-files on
pg_proc.dat, just because I'm a neatnik.

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

5 years agoRemove a couple of unnecessary if-tests.
Tom Lane [Sun, 24 Nov 2019 17:03:16 +0000 (12:03 -0500)]
Remove a couple of unnecessary if-tests.

Commit abd9ca377 replaced a couple of while-loops in fmtfloat()
with calls to dopr_outchmulti, but I (tgl) failed to notice that
the new if-tests guarding those calls were really unnecessary,
because they're inside a larger if-block checking the same thing.

Ranier Vilela

Discussion: https://postgr.es/m/MN2PR18MB2927850AB00CF39CC370D107E34B0@MN2PR18MB2927.namprd18.prod.outlook.com

5 years agoRemove debugging aid
Alvaro Herrera [Sat, 23 Nov 2019 16:19:20 +0000 (13:19 -0300)]
Remove debugging aid

This Assert(false) was not supposed to be in the committed copy.

Reported by: Tom Lane
Discussion: https://postgr.es/m/26476.1574525468@sss.pgh.pa.us

5 years agoUpdate sepgsql to add mandatory access control for TRUNCATE
Joe Conway [Sat, 23 Nov 2019 15:41:52 +0000 (10:41 -0500)]
Update sepgsql to add mandatory access control for TRUNCATE

Use SELinux "db_table: { truncate }" to check if permission is granted to
TRUNCATE. Update example SELinux policy to grant needed permission for
TRUNCATE. Add new regression test to demonstrate a positive and negative
cases. Test will only be run if the loaded SELinux policy has the
"db_table: { truncate }" permission. Makes use of recent commit which added
object TRUNCATE hook.  by Yuli Khodorkovskiy with minor
editorialization by me. Not back-ed because the object TRUNCATE hook
was not.

Author: Yuli Khodorkovskiy
Reviewed-by: Joe Conway
Discussion: https://postgr.es/m/CAFL5wJcomybj1Xdw7qWmPJRpGuFukKgNrDb6uVBaCMgYS9dkaA%40mail.gmail.com

5 years agoAdd object TRUNCATE hook
Joe Conway [Sat, 23 Nov 2019 15:39:20 +0000 (10:39 -0500)]
Add object TRUNCATE hook

All operations with acl permissions checks should have a corresponding hook
so that, for example, mandatory access control (MAC) may be enforced by an
extension. The command TRUNCATE is missing this hook, so add it.  by
Yuli Khodorkovskiy with some editorialization by me. Based on the discussion
not back-ed. A separate  will exercise the hook in the sepgsql
extension.

Author: Yuli Khodorkovskiy
Reviewed-by: Joe Conway
Discussion: https://postgr.es/m/CAFL5wJcomybj1Xdw7qWmPJRpGuFukKgNrDb6uVBaCMgYS9dkaA%40mail.gmail.com

5 years agoMake psql redisplay the query buffer after \e.
Tom Lane [Fri, 22 Nov 2019 22:07:54 +0000 (17:07 -0500)]
Make psql redisplay the query buffer after \e.

Up to now, whatever you'd edited was put back into the query buffer
but not redisplayed, which is less than user-friendly.  But we can
improve that just by printing the text along with a prompt, if we
enforce that the editing result ends with a newline (which it
typically would anyway).  You then continue typing more lines if
you want, or you can type ";" or do \g or \r or another \e.

This is intentionally divorced from readline's processing,
for simplicity and so that it works the same with or without
readline enabled.  We discussed possibly integrating things
more closely with readline; but that seems difficult, uncertainly
portable across different readline and libedit versions, and
of limited real benefit anyway.  Let's try the simple way and
see if it's good enough.

 by me, thanks to Fabien Coelho and Laurenz Albe for review

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

5 years agoAvoid taking a new snapshot for an immutable simple expression in plpgsql.
Tom Lane [Fri, 22 Nov 2019 20:02:18 +0000 (15:02 -0500)]
Avoid taking a new snapshot for an immutable simple expression in plpgsql.

We already used this optimization if the plpgsql function is read-only.
But it seems okay to do it even in a read-write function, if the
expression contains only immutable functions/operators.  There would
only be a change of behavior if an "immutable" called function depends
on seeing database updates made during the current plpgsql function.
That's enough of a violation of the promise of immutability that anyone
who complains won't have much of a case.

The benefits are significant --- for simple cases like

  while i < 10000000
  loop
    i := i + 1;
  end loop;

I see net performance improvements around 45%.  Of course, real-world
cases won't get that much faster, but it ought to be noticeable.
At the very least, this removes much of the performance penalty that
used to exist for forgetting to mark a plpgsql function non-volatile.

Konstantin Knizhnik, reviewed by Pavel Stehule, cosmetic changes by me

Discussion: https://postgr.es/m/ed9da20e-01aa-d04b-d085-e6c16b14b9d7@postgrespro.ru

5 years agoAdd test coverage for "unchanged toast column" replication code path.
Tom Lane [Fri, 22 Nov 2019 17:52:26 +0000 (12:52 -0500)]
Add test coverage for "unchanged toast column" replication code path.

It seems pretty unacceptable to have no regression test coverage
for this aspect of the logical replication protocol, especially
given the bugs we've found in related code.

Discussion: https://postgr.es/m/16129-a0c0f48e71741e5f@postgresql.org

5 years agoFix bogus tuple-slot management in logical replication UPDATE handling.
Tom Lane [Fri, 22 Nov 2019 16:31:19 +0000 (11:31 -0500)]
Fix bogus tuple-slot management in logical replication UPDATE handling.

slot_modify_cstrings seriously abused the TupleTableSlot API by relying
on a slot's underlying data to stay valid across ExecClearTuple.  Since
this abuse was also quite undocumented, it's little surprise that the
case got broken during the v12 slot rewrites.  As reported in bug #16129
from Ondřej Jirman, this could lead to crashes or data corruption when
a logical replication subscriber processes a row update.  Problems would
only arise if the subscriber's table contained columns of pass-by-ref
types that were not being copied from the publisher.

Fix by explicitly copying the datum/isnull arrays from the source slot
that the old row was in already.  This ends up being about the same
thing that happened pre-v12, but hopefully in a less opaque and
fragile way.

We might've caught the problem sooner if there were any test cases
dealing with updates involving non-replicated or dropped columns.
Now there are.

Back- to v10 where this code came in.  Even though the failure
does not manifest before v12, IMO this code is too fragile to leave
as-is.  In any case we certainly want the additional test coverage.

 by me; thanks to Tomas Vondra for initial investigation.

Discussion: https://postgr.es/m/16129-a0c0f48e71741e5f@postgresql.org

5 years agoAdd .gitignore to src/tutorial/
Michael Paquier [Fri, 22 Nov 2019 12:14:54 +0000 (21:14 +0900)]
Add .gitignore to src/tutorial/

A set of SQL files are generated for the tutorial when compiling the
code, so let's avoid any risk to have them added in the tree in the
future.

5 years agoRemove traces of version-0 calling convention in src/tutorial/
Michael Paquier [Fri, 22 Nov 2019 12:08:49 +0000 (21:08 +0900)]
Remove traces of version-0 calling convention in src/tutorial/

Support has been removed as of 5ded4bd, but code related to the tutorial
still used it.  Functions using version-1 are already present for some
time in the tutorial, and the documentation mentions them, so just
replace the old version with the new one.

Reported-by: Pavel Stehule
Analyzed-by: Euler Taveira
Author: Michael Paquier
Reviewed-by: Tom Lane, Pavel Stehule
Discussion: https://postgr.es/m/CAFj8pRCgC2uDzrw-vvanXu6Z3ofyviEOQPEpH6_aL4OCe7JRag@mail.gmail.com

5 years agoDefend against self-referential views in relation_is_updatable().
Tom Lane [Thu, 21 Nov 2019 21:21:43 +0000 (16:21 -0500)]
Defend against self-referential views in relation_is_updatable().

While a self-referential view doesn't actually work, it's possible
to create one, and it turns out that this breaks some of the
information_schema views.  Those views call relation_is_updatable(),
which neglected to consider the hazards of being recursive.  In
older PG versions you get a "stack depth limit exceeded" error,
but since v10 it'd recurse to the point of stack overrun and crash,
because commit a4c35ea1c took out the expression_returns_set() call
that was incidentally checking the stack depth.

Since this function is only used by information_schema views, it
seems like it'd be better to return "not updatable" than suffer
an error.  Hence, add tracking of what views we're examining,
in just the same way that the nearby fireRIRrules() code detects
self-referential views.  I added a check_stack_depth() call too,
just to be defensive.

Per private report from Manuel Rigger.  Back- to all
supported versions.

5 years agoRemove configure --disable-float4-byval
Peter Eisentraut [Thu, 21 Nov 2019 17:00:07 +0000 (18:00 +0100)]
Remove configure --disable-float4-byval

This build option was only useful to maintain compatibility for
version-0 functions, but those are no longer supported, so this option
can be removed.

float4 is now always pass-by-value; the pass-by-reference code path is
completely removed.

Discussion: https://www.postgresql.org/message-id/flat/f3e1e576-2749-bbd7-2d57-3f9dcf75255a@2ndquadrant.com

5 years agoBump WAL version.
Fujii Masao [Thu, 21 Nov 2019 13:17:28 +0000 (22:17 +0900)]
Bump WAL version.

Oversight in commit e6d8069522. Since that commit changed the format of
XLOG_DBASE_DROP WAL record, XLOG_PAGE_MAGIC needs to be bumped.

Spotted by Michael Paquier

5 years agoMake DROP DATABASE command generate less WAL records.
Fujii Masao [Thu, 21 Nov 2019 12:10:37 +0000 (21:10 +0900)]
Make DROP DATABASE command generate less WAL records.

Previously DROP DATABASE generated as many XLOG_DBASE_DROP WAL records
as the number of tablespaces that the database to drop uses. This caused
the scans of shared_buffers as many times as the number of the tablespaces
during recovery because WAL replay of one XLOG_DBASE_DROP record needs
that full scan. This could make the recovery time longer especially
when shared_buffers is large.

This commit changes DROP DATABASE so that it generates only one
XLOG_DBASE_DROP record, and registers the information of all the tablespaces
into it. Then, WAL replay of XLOG_DBASE_DROP record needs full scan of
shared_buffers only once, and which may improve the recovery performance.

Author: Fujii Masao
Reviewed-by: Kirk Jamison, Simon Riggs
Discussion: https://postgr.es/m/CAHGQGwF8YwNH0ZaL+2wjZPkj+ji9UhC+Z4ScnG97WKtVY5L9iw@mail.gmail.com

5 years agoAllow ALTER VIEW command to rename the column in the view.
Fujii Masao [Thu, 21 Nov 2019 10:55:13 +0000 (19:55 +0900)]
Allow ALTER VIEW command to rename the column in the view.

ALTER TABLE RENAME COLUMN command always can be used to rename the column
in the view, but it's reasonable to add that syntax to ALTER VIEW too.

Author: Fujii Masao
Reviewed-by: Ibrar Ahmed, Yu Kimura
Discussion: https://postgr.es/m/CAHGQGwHoQMD3b-MqTLcp1MgdhCpOKU7QNRwjFooT4_d+ti5v6g@mail.gmail.com

5 years agoImprove tab-completion for ALTER MATERIALIZED VIEW.
Fujii Masao [Thu, 21 Nov 2019 10:22:37 +0000 (19:22 +0900)]
Improve tab-completion for ALTER MATERIALIZED VIEW.

Author: Takao Fujii
Reviewed-by: Fujii Masao
Discussion: https://postgr.es/m/f9dcdef78c124517edc9e5e5880f651e@oss.nttdata.com

5 years agoTrack statistics for spilling of changes from ReorderBuffer.
Amit Kapila [Sat, 16 Nov 2019 12:54:00 +0000 (18:24 +0530)]
Track statistics for spilling of changes from ReorderBuffer.

This adds the statistics about transactions spilled to disk from
ReorderBuffer.  Users can query the pg_stat_replication view to check
these stats.

Author: Tomas Vondra, with bug-fixes and minor changes by Dilip Kumar
Reviewed-by: Amit Kapila
Discussion: https://postgr.es/m/688b0b7f-2f6c-d827-c27b-216a8e3ea700@2ndquadrant.com

5 years agoProvide statistics for hypothetical BRIN indexes
Michael Paquier [Thu, 21 Nov 2019 01:23:28 +0000 (10:23 +0900)]
Provide statistics for hypothetical BRIN indexes

Trying to use hypothetical indexes with BRIN currently fails when trying
to access a relation that does not exist when looking for the
statistics.  With the current API, it is not possible to easily pass
a value for pages_per_range down to the hypothetical index, so this
makes use of the default value of BRIN_DEFAULT_PAGES_PER_RANGE, which
should be fine enough in most cases.

Being able to refine or enforce the hypothetical costs in more
optimistic ways would require more refactoring by filling in the
statistics when building IndexOptInfo in plancat.c.  This would involve
ABI breakages around the costing routines, something not fit for stable
branches.

This is broken since 7e534ad, so back down to v10.

Author: Julien Rouhaud, Heikki Linnakangas
Reviewed-by: Álvaro Herrera, Tom Lane, Michael Paquier
Discussion: https://postgr.es/m/CAOBaU_ZH0LKEA8VFCocr6Lpte1ab0b6FpvgS0y4way+RPSXfYg@mail.gmail.com
Back-through: 10

5 years agoSync patternsel_common's operator selection logic with pattern_prefix's.
Tom Lane [Wed, 20 Nov 2019 20:00:11 +0000 (15:00 -0500)]
Sync patternsel_common's operator selection logic with pattern_prefix's.

Make patternsel_common() select the comparison operators to use with
hardwired logic that matches pattern_prefix()'s new logic, eliminating
its dependencies on particular index opfamilies.

This shouldn't change any behavior, as it's just replacing runtime
operator lookups with the same values hard-wired.  But it makes these
closely-related functions look more alike, and saving some runtime
syscache lookups is worth something.

Actually, it's not quite true that this is zero behavioral change:
when estimating for a column of type "name", the comparison constant
will be kept as "text" not coerced to "name".  But that's more correct
anyway, and it allows additional simplification of the coercion logic,
again syncing this more closely with pattern_prefix().

Per consideration of a report from Manuel Rigger.

Discussion: https://postgr.es/m/CA+u7OA7nnGYy8rY0vdTe811NuA+Frr9nbcBO9u2Z+JxqNaud+g@mail.gmail.com

5 years agoFix HeapTupleSatisfiesNonVacuumable() comment.
Peter Geoghegan [Wed, 20 Nov 2019 19:36:54 +0000 (11:36 -0800)]
Fix HeapTupleSatisfiesNonVacuumable() comment.

Oversight in commit 63746189b23.