C++ port of Postgres

Started by Joy Arulrajover 9 years ago76 messages
#1Joy Arulraj
jarulraj@cs.cmu.edu

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its standard
library to simplify coding, improve code reuse, and avoid bugs. Peter's
article titled `Moving to C++
<https://petereisentraut.blogspot.com/2013/05/moving-to-c.html&gt;` was a
source of inspiration for us.

Regards.

#2John R Pierce
pierce@hogranch.com
In reply to: Joy Arulraj (#1)
Re: C++ port of Postgres

On 8/14/2016 2:05 PM, Joy Arulraj wrote:

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its
standard library to simplify coding, improve code reuse, and avoid
bugs. Peter's article titled `Moving to C++
<https://petereisentraut.blogspot.com/2013/05/moving-to-c.html&gt;` was a
source of inspiration for us.

does this compile with the non-GCC compilers that postgres gets built
with, for instance, IBM XLC++ on AIX, Oracle Studio C++ on Solaris,
Microsoft Visual C++ on MS Windows, CLang on BSD ? what about popular
platforms like RHEL 6, where gcc is 4.4.7 ?

--
john r pierce, recycling bits in santa cruz

#3Dmitry Igrishin
dmitigr@gmail.com
In reply to: Joy Arulraj (#1)
Re: C++ port of Postgres

Hi Joy,

2016-08-15 0:05 GMT+03:00 Joy Arulraj <jarulraj@cs.cmu.edu>:

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its standard
library to simplify coding, improve code reuse, and avoid bugs. Peter's
article titled `Moving to C++` was a source of inspiration for us.

What about the exceptions? Are you using them?

--
// Dmitry.

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

#4Joy Arulraj
jarulraj@cs.cmu.edu
In reply to: Joy Arulraj (#1)
Re: C++ port of Postgres

Hi Dmitry -- We currently don't use exceptions, but we can certainly use
them in the port. We can also use STL and smart pointers to simplify
development and minimize memory bugs.

On Aug 14, 2016 5:41 PM, "Dmitry Igrishin" <dmitigr@gmail.com> wrote:

Show quoted text

Hi Joy,

2016-08-15 0:05 GMT+03:00 Joy Arulraj <jarulraj@cs.cmu.edu>:

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its standard
library to simplify coding, improve code reuse, and avoid bugs. Peter's
article titled `Moving to C++` was a source of inspiration for us.

What about the exceptions? Are you using them?

--
// Dmitry.

#5kang joni
kangjoni76@gmail.com
In reply to: Joy Arulraj (#4)
Re: C++ port of Postgres

I agree with this project, I dont like any setjmp/longjmp and the
like. It just fighting against the nature of c++ language. Building
either from scratch gcc48 or clang381 were easy nowdays on either old
linux debian squeeze or centos 5. PS: I had this requirement
circumtances.

On 8/15/16, Joy Arulraj <jarulraj@cs.cmu.edu> wrote:

Hi Dmitry -- We currently don't use exceptions, but we can certainly use
them in the port. We can also use STL and smart pointers to simplify
development and minimize memory bugs.

On Aug 14, 2016 5:41 PM, "Dmitry Igrishin" <dmitigr@gmail.com> wrote:

Hi Joy,

2016-08-15 0:05 GMT+03:00 Joy Arulraj <jarulraj@cs.cmu.edu>:

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its
standard
library to simplify coding, improve code reuse, and avoid bugs. Peter's
article titled `Moving to C++` was a source of inspiration for us.

What about the exceptions? Are you using them?

--
// Dmitry.

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

#6Joy Arulraj
jarulraj@cs.cmu.edu
In reply to: kang joni (#5)
Re: C++ port of Postgres

Kang -- Yes, this is one of the reasons why we chose to do this.

John -- We have not compiled it with non-GCC compilers. But, I presume that
the changes required to support compilation with other compilers should be
minimal as we don't rely on any compiler-specific features.

On Sun, Aug 14, 2016 at 6:30 PM, kang joni <kangjoni76@gmail.com> wrote:

Show quoted text

I agree with this project, I dont like any setjmp/longjmp and the
like. It just fighting against the nature of c++ language. Building
either from scratch gcc48 or clang381 were easy nowdays on either old
linux debian squeeze or centos 5. PS: I had this requirement
circumtances.

On 8/15/16, Joy Arulraj <jarulraj@cs.cmu.edu> wrote:

Hi Dmitry -- We currently don't use exceptions, but we can certainly use
them in the port. We can also use STL and smart pointers to simplify
development and minimize memory bugs.

On Aug 14, 2016 5:41 PM, "Dmitry Igrishin" <dmitigr@gmail.com> wrote:

Hi Joy,

2016-08-15 0:05 GMT+03:00 Joy Arulraj <jarulraj@cs.cmu.edu>:

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its
standard
library to simplify coding, improve code reuse, and avoid bugs.

Peter's

article titled `Moving to C++` was a source of inspiration for us.

What about the exceptions? Are you using them?

--
// Dmitry.

#7Adam Brusselback
adambrusselback@gmail.com
In reply to: Joy Arulraj (#6)
Re: C++ port of Postgres

Just wondering what the end goal is for this project... Is it to just
maintain an up to date Postgres fork that will compile with a C++ compiler?
Is it to get a conversation going for a direction for Postgres itself to
move? The former I don't see gaining much traction or doing all that much
for the state of the project. The latter possibly could if the community
gets on board.

Thanks,
-Adam

#8dandl
david@andl.org
In reply to: Adam Brusselback (#7)
Re: C++ port of Postgres

Just wondering what the end goal is for this project... Is it to just maintain an up to date Postgres fork that will compile with a C++ compiler? Is it to get a conversation going for a direction for Postgres itself to move? The former I don't see gaining much traction or doing all that much for the state of the project. The latter possibly could if the community gets on board.

I would certainly hope the latter. Having done some work on extension functions and an extension language for Postgres, the current situation can be quite limiting.

* Parts of my code could only be written in C++, so I finished up with a mixed build, which is not ideal.

* My other issue was dealing with the Datum macros. Type-safe inline C++ functions would help reduce dumb errors.

Not compelling reasons perhaps, but just a vote for a move in that direction, some time.

Regards

David M Bennett FACS

_____

Andl - A New Database Language - andl.org

#9Gavin Flower
GavinFlower@archidevsys.co.nz
In reply to: dandl (#8)
Re: C++ port of Postgres

On 16/08/16 18:24, dandl wrote:

Just wondering what the end goal is for this project... Is it to just
maintain an up to date Postgres fork that will compile with a C++
compiler? Is it to get a conversation going for a direction for
Postgres itself to move? The former I don't see gaining much traction
or doing all that much for the state of the project. The latter
possibly could if the community gets on board.

I would certainly hope the latter. Having done some work on extension
functions and an extension language for Postgres, the current
situation can be quite limiting.

·Parts of my code could only be written in C++, so I finished up with
a mixed build, which is not ideal.

·My other issue was dealing with the Datum macros. Type-safe inline
C++ functions would help reduce dumb errors.

Not compelling reasons perhaps, but just a vote for a move in that
direction, some time.

Regards

David M Bennett FACS

/
------------------------------------------------------------------------
/

/Andl - A New Database Language - andl.org/

I note that gcc itself is now written in C++, and so is squid (web
proxy)...

In both cases, part of the motivation to change from C was to appeal to
new developers - from what I remember of the discussions.

Cheers,
Gavin

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

#10FarjadFarid(ChkNet)
farjad.farid@checknetworks.com
In reply to: Joy Arulraj (#1)
Re: C++ port of Postgres

Well done. This is a much needed conversion. As Peter’s article says, it does open up more opportunities.

From: pgsql-general-owner@postgresql.org [mailto:pgsql-general-owner@postgresql.org] On Behalf Of Joy Arulraj
Sent: 14 August 2016 22:06
To: pgsql-general@postgresql.org
Subject: [GENERAL] C++ port of Postgres

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its standard library to simplify coding, improve code reuse, and avoid bugs. Peter's article titled `Moving to C++ <https://petereisentraut.blogspot.com/2013/05/moving-to-c.html&gt; ` was a source of inspiration for us.

Regards.

#11Jim Nasby
Jim.Nasby@BlueTreble.com
In reply to: Gavin Flower (#9)
Re: [GENERAL] C++ port of Postgres

On 8/16/16 2:52 AM, Gavin Flower wrote:

In both cases, part of the motivation to change from C was to appeal to
new developers - from what I remember of the discussions.

Moving this to -hackers. Original thread at [1].

tl;dr: A C++ port of Postgres has been created, and several folks on
general have commented that this makes it easier to work with the
Postgres codebase. This potentially attracts more developers to the
project. I hope we can find a way to pull these folks into the fold.

People in core have complained that we don't have enough hackers coming
in (which I agree with). Part of that is lack of familiarity with C.

I think we can all agree that a C++ fork of Postgres would be a huge
waste of time, so the question becomes should core postgres start
supporting C++.

Peter wrote a blog about this in 2013 that makes some good arguments
[2]: ; in particular "easing into" this by first officially supporting C++ compilation. I also like the idea of investigating Rust.
compilation. I also like the idea of investigating Rust.

I realize there's little technical reason why we *need* C++ support. The
level if discipline applied to our codebase negates some of the benefits
of C++. But maintaining the discipline takes a lot of time and effort,
and makes it more difficult to attract new contributors. My hope is that
existing hackers can agree on a reasonable way forward and guide/assist
new folks that are interested in walking that path.

1:
/messages/by-id/CABgyVxDBd3EvRdo-Rd6eo8QPEqV8=ShaU2SJfo16wfE0R-hXTA@mail.gmail.com
2: https://petereisentraut.blogspot.com/2013/05/moving-to-c.html
--
Jim Nasby, Data Architect, Blue Treble Consulting, Austin TX
Experts in Analytics, Data Architecture and PostgreSQL
Data in Trouble? Get it in Treble! http://BlueTreble.com
855-TREBLE2 (855-873-2532) mobile: 512-569-9461

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#12Yury Zhuravlev
u.zhuravlev@postgrespro.ru
In reply to: Jim Nasby (#11)
Re: [GENERAL] C++ port of Postgres

Jim Nasby wrote:

My hope is that existing hackers can agree on a reasonable way
forward and guide/assist new folks that are interested in
walking that path.

I tried this path. https://github.com/stalkerg/postgres_cpp
And I fully support this desire. But I'm in the minority.

I also like the idea of investigating Rust.

I am working on it last few weeks. But it's like seek blocks for new DB. I
don't know how we can insert Rust code into Postgres spaghetti.

--
Yury Zhuravlev
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#13Aleksander Alekseev
a.alekseev@postgrespro.ru
In reply to: Jim Nasby (#11)
Re: [GENERAL] C++ port of Postgres

Well, well, well. Another C vs C++ holly war, really?

In both cases, part of the motivation to change from C was to
appeal to new developers - from what I remember of the
discussions.

Moving this to -hackers. Original thread at [1].

tl;dr: A C++ port of Postgres has been created, and several folks on
general have commented that this makes it easier to work with the
Postgres codebase. This potentially attracts more developers to the
project. I hope we can find a way to pull these folks into the fold.

Who are these "folks"? How many more developers it would attract
_exactly_, not potentially?

People in core have complained that we don't have enough hackers
coming in (which I agree with). Part of that is lack of familiarity
with C.

One again, which "people"? I've seen people complained that there is
not enough code reviewers and testers. I doubt very much its something
C++ will help with.

I think we can all agree that a C++ fork of Postgres would be a huge
waste of time, so the question becomes should core postgres start
supporting C++.

Peter wrote a blog about this in 2013 that makes some good arguments
[2]; in particular "easing into" this by first officially supporting
C++ compilation. I also like the idea of investigating Rust.

And I wrote a blog post (in Russian) [1]http://eax.me/c-vs-cpp/ in 2016 why nobody should (if
they can) write a new code in C++. In my opinion Rust looks way more
promising. However I personally prefer to wait like 5 years before
using a new and shiny technology. This is also something I blogged
about (in Russian [2]http://eax.me/cpp-will-never-die/, translation [3]http://www.viva64.com/en/b/0324/).

I realize there's little technical reason why we *need* C++ support.

You are right, there is none.

The level if discipline applied to our codebase negates some of the
benefits of C++. But maintaining the discipline takes a lot of time
and effort, and makes it more difficult to attract new contributors.

There are companies. They hire developers who write code. Doesn't
really matters in which language.

Long story short - I strongly believe you are trying to solve a problem
that doesn't exist. And probably create a few new ones.

[1]: http://eax.me/c-vs-cpp/
[2]: http://eax.me/cpp-will-never-die/
[3]: http://www.viva64.com/en/b/0324/

--
Best regards,
Aleksander Alekseev

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#14Joy Arulraj
jarulraj@cs.cmu.edu
In reply to: Gavin Flower (#9)
Re: C++ port of Postgres

On Tue, Aug 16, 2016 at 3:52 AM, Gavin Flower <GavinFlower@archidevsys.co.nz

wrote:

On 16/08/16 18:24, dandl wrote:

Just wondering what the end goal is for this project... Is it to just
maintain an up to date Postgres fork that will compile with a C++ compiler?
Is it to get a conversation going for a direction for Postgres itself to
move? The former I don't see gaining much traction or doing all that much
for the state of the project. The latter possibly could if the community
gets on board.

I was kind of hoping that this might start off a coversation on getting
postgres to support C++.

I would certainly hope the latter. Having done some work on extension

functions and an extension language for Postgres, the current situation can
be quite limiting.

·Parts of my code could only be written in C++, so I finished up with a
mixed build, which is not ideal.

·My other issue was dealing with the Datum macros. Type-safe inline C++
functions would help reduce dumb errors.

Not compelling reasons perhaps, but just a vote for a move in that
direction, some time.

I concur.

Show quoted text

Regards

David M Bennett FACS

/
------------------------------------------------------------------------
/

/Andl - A New Database Language - andl.org/

I note that gcc itself is now written in C++, and so is squid (web

proxy)...

In both cases, part of the motivation to change from C was to appeal to
new developers - from what I remember of the discussions.

Cheers,
Gavin

#15Joy Arulraj
jarulraj@cs.cmu.edu
In reply to: FarjadFarid(ChkNet) (#10)
Re: C++ port of Postgres

Thanks, I do hope so.

On Tue, Aug 16, 2016 at 7:00 AM, FarjadFarid(ChkNet) <
farjad.farid@checknetworks.com> wrote:

Show quoted text

Well done. This is a much needed conversion. As Peter’s article says, it
does open up more opportunities.

*From:* pgsql-general-owner@postgresql.org [mailto:pgsql-general-owner@
postgresql.org] *On Behalf Of *Joy Arulraj
*Sent:* 14 August 2016 22:06
*To:* pgsql-general@postgresql.org
*Subject:* [GENERAL] C++ port of Postgres

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its standard
library to simplify coding, improve code reuse, and avoid bugs. Peter's
article titled `Moving to C++
<https://petereisentraut.blogspot.com/2013/05/moving-to-c.html&gt;` was a
source of inspiration for us.

Regards.

#16Heikki Linnakangas
hlinnaka@iki.fi
In reply to: Jim Nasby (#11)
Re: [GENERAL] C++ port of Postgres

On 08/16/2016 05:47 PM, Jim Nasby wrote:

I realize there's little technical reason why we *need* C++ support. The
level if discipline applied to our codebase negates some of the benefits
of C++. But maintaining the discipline takes a lot of time and effort,
and makes it more difficult to attract new contributors.

I suspect that it would take as much discipline to keep a C++ codebase
readable, as the current C codebase. If not more.

- Heikki

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#17Yury Zhuravlev
u.zhuravlev@postgrespro.ru
In reply to: Aleksander Alekseev (#13)
Re: [GENERAL] C++ port of Postgres

Aleksander Alekseev wrote:

You are right, there is none.

First: trees in parser, planer and etc.
Second: normal exception.

Two big projects lately move to C++ from C:
GCC, Mesa

You can read their reasons.
Only C++ we can use without full rewrite currently. (or ObjectC maybe)
If we wish fix C limitations.

--
Yury Zhuravlev
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#18Robert Haas
robertmhaas@gmail.com
In reply to: Jim Nasby (#11)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 10:47 AM, Jim Nasby <Jim.Nasby@bluetreble.com> wrote:

On 8/16/16 2:52 AM, Gavin Flower wrote:

In both cases, part of the motivation to change from C was to appeal to
new developers - from what I remember of the discussions.

Moving this to -hackers. Original thread at [1].

tl;dr: A C++ port of Postgres has been created, and several folks on general
have commented that this makes it easier to work with the Postgres codebase.
This potentially attracts more developers to the project. I hope we can find
a way to pull these folks into the fold.

People in core have complained that we don't have enough hackers coming in
(which I agree with). Part of that is lack of familiarity with C.

I think we can all agree that a C++ fork of Postgres would be a huge waste
of time, so the question becomes should core postgres start supporting C++.

Peter wrote a blog about this in 2013 that makes some good arguments [2]; in
particular "easing into" this by first officially supporting C++
compilation. I also like the idea of investigating Rust.

I'm not really interested in supporting PostgreSQL code written in
other languages entirely, such as Rust, but I do think it would make
sense to write our code so that it can be compiled using either a C
compiler or a C++ compiler. Even if we don't ever use any C++ code in
core, this would let people who create forks or extensions use it if
they wished. It wouldn't be that much work to maintain, either: we'd
just set up some buildfarm members that compiled using C++ and when
they turned red, we'd go fix it.

I agree with your statement that one of our biggest problems is
getting more developers interested in working on PostgreSQL. Even if
there's only a 10% chance that something like this will help, why not?
We're not talking about moving the earth.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#19Joshua D. Drake
jd@commandprompt.com
In reply to: Robert Haas (#18)
Re: [GENERAL] C++ port of Postgres

On 08/16/2016 09:33 AM, Robert Haas wrote:

On Tue, Aug 16, 2016 at 10:47 AM, Jim Nasby <Jim.Nasby@bluetreble.com> wrote:

On 8/16/16 2:52 AM, Gavin Flower wrote:

I agree with your statement that one of our biggest problems is
getting more developers interested in working on PostgreSQL. Even if
there's only a 10% chance that something like this will help, why not?
We're not talking about moving the earth.

Right. It is just reality that less people are learning C which means
less people will be interested in joining a project that is focused or
(required) to be C.

Sincerely,

JD

--
Command Prompt, Inc. http://the.postgres.company/
+1-503-667-4564
PostgreSQL Centered full stack support, consulting and development.
Everyone appreciates your honesty, until you are honest with them.
Unless otherwise stated, opinions are my own.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#20Tom Lane
tgl@sss.pgh.pa.us
In reply to: Robert Haas (#18)
Re: [GENERAL] C++ port of Postgres

Robert Haas <robertmhaas@gmail.com> writes:

I'm not really interested in supporting PostgreSQL code written in
other languages entirely, such as Rust, but I do think it would make
sense to write our code so that it can be compiled using either a C
compiler or a C++ compiler. Even if we don't ever use any C++ code in
core, this would let people who create forks or extensions use it if
they wished. It wouldn't be that much work to maintain, either: we'd
just set up some buildfarm members that compiled using C++ and when
they turned red, we'd go fix it.

I think this might have advantages purely from the standpoint of new
compilers possibly offering useful warnings we don't get now. But
if we only go this far, I'm pretty dubious that it really helps people
to develop extensions in C++. Almost invariably, if you ask *why* they
want to do that, you'll get an answer involving C++ libraries that are
not going to play very nice with our error handling or memory management
conventions. I do not see how we could C++-ify the error handling without
making a complete break with C compilers ... which is a step I don't
really want to take.

The whole thing would make a lot more sense given a credible design
for error handling that keeps both languages happy.

A lot of the other things people have muttered about, such as heavier
use of inline functions instead of macros, don't particularly need C++
at all.

regards, tom lane

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#21Robert Haas
robertmhaas@gmail.com
In reply to: Tom Lane (#20)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 12:59 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:

Robert Haas <robertmhaas@gmail.com> writes:

I'm not really interested in supporting PostgreSQL code written in
other languages entirely, such as Rust, but I do think it would make
sense to write our code so that it can be compiled using either a C
compiler or a C++ compiler. Even if we don't ever use any C++ code in
core, this would let people who create forks or extensions use it if
they wished. It wouldn't be that much work to maintain, either: we'd
just set up some buildfarm members that compiled using C++ and when
they turned red, we'd go fix it.

I think this might have advantages purely from the standpoint of new
compilers possibly offering useful warnings we don't get now.

Yeah, that could be nice.

But
if we only go this far, I'm pretty dubious that it really helps people
to develop extensions in C++. Almost invariably, if you ask *why* they
want to do that, you'll get an answer involving C++ libraries that are
not going to play very nice with our error handling or memory management
conventions. I do not see how we could C++-ify the error handling without
making a complete break with C compilers ... which is a step I don't
really want to take.

I agree, but we don't have to agree to change everything before we
agree to change anything. If we got an agreement to try to make
everything compile in both languages, that'd be more agreement than
we've ever had before, and I'd rather take that agreement and run than
look a gift horse in the mouth.

The whole thing would make a lot more sense given a credible design
for error handling that keeps both languages happy.

Well, getting so that we can at least compile in both systems would
certainly increase the chances of somebody being willing to work on
such a design. And if nobody ever does, then at least people who want
to fork and do research projects based on PostgreSQL will have
slightly less work to do when they want to hack it up. PostgreSQL
seems to be a very popular starting point for research work, but a
paper I read recently complained about the antiquity of our code base.
I prefer to call that backward-compatibility, but at some point people
stop thinking of you as backward-compatible and instead think of you
as simply backward.

A lot of the other things people have muttered about, such as heavier
use of inline functions instead of macros, don't particularly need C++
at all.

True.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#22Joy Arulraj
jarulraj@cs.cmu.edu
In reply to: Robert Haas (#21)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 1:13 PM, Robert Haas <robertmhaas@gmail.com> wrote:

On Tue, Aug 16, 2016 at 12:59 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:

Robert Haas <robertmhaas@gmail.com> writes:

I'm not really interested in supporting PostgreSQL code written in
other languages entirely, such as Rust, but I do think it would make
sense to write our code so that it can be compiled using either a C
compiler or a C++ compiler. Even if we don't ever use any C++ code in
core, this would let people who create forks or extensions use it if
they wished. It wouldn't be that much work to maintain, either: we'd
just set up some buildfarm members that compiled using C++ and when
they turned red, we'd go fix it.

I think this might have advantages purely from the standpoint of new
compilers possibly offering useful warnings we don't get now.

Yeah, that could be nice.

But
if we only go this far, I'm pretty dubious that it really helps people
to develop extensions in C++. Almost invariably, if you ask *why* they
want to do that, you'll get an answer involving C++ libraries that are
not going to play very nice with our error handling or memory management
conventions. I do not see how we could C++-ify the error handling

without

making a complete break with C compilers ... which is a step I don't
really want to take.

I agree, but we don't have to agree to change everything before we
agree to change anything. If we got an agreement to try to make
everything compile in both languages, that'd be more agreement than
we've ever had before, and I'd rather take that agreement and run than
look a gift horse in the mouth.

The whole thing would make a lot more sense given a credible design
for error handling that keeps both languages happy.

Well, getting so that we can at least compile in both systems would
certainly increase the chances of somebody being willing to work on
such a design. And if nobody ever does, then at least people who want
to fork and do research projects based on PostgreSQL will have
slightly less work to do when they want to hack it up. PostgreSQL
seems to be a very popular starting point for research work, but a
paper I read recently complained about the antiquity of our code base.
I prefer to call that backward-compatibility, but at some point people
stop thinking of you as backward-compatible and instead think of you
as simply backward.

I agree, this was the main reason why we wanted to add support for C++.

Show quoted text

A lot of the other things people have muttered about, such as heavier
use of inline functions instead of macros, don't particularly need C++
at all.

True.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

#23Dmitry Igrishin
dmitigr@gmail.com
In reply to: Heikki Linnakangas (#16)
Re: [GENERAL] C++ port of Postgres

2016-08-16 18:52 GMT+03:00 Heikki Linnakangas <hlinnaka@iki.fi>:

On 08/16/2016 05:47 PM, Jim Nasby wrote:

I realize there's little technical reason why we *need* C++ support. The
level if discipline applied to our codebase negates some of the benefits
of C++. But maintaining the discipline takes a lot of time and effort,
and makes it more difficult to attract new contributors.

I suspect that it would take as much discipline to keep a C++ codebase
readable, as the current C codebase. If not more.

For example, its easier and less error prone to define structures with
virtual functions in C++ than write vtables manually in C. So, the adequate
subset of the C++ features can be useful to write more readable and
maintainable C-style code. These features are:

- abstract classes (well, structures with virtual functions);
- RTTI;
- lambda functions;
- constexpr functions;
- destructors;
- templates (very reservedly).

But these features should be avoided (as least for now):

- exceptions;
- the parts of the standard library which generates exceptions
(in particular, regex and thread).

--
// Dmitry.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#24Jim Nasby
Jim.Nasby@BlueTreble.com
In reply to: Gavin Flower (#9)
Re: C++ port of Postgres

On 8/16/16 2:52 AM, Gavin Flower wrote:

In both cases, part of the motivation to change from C was to appeal to
new developers - from what I remember of the discussions.

I have moved this discussion over to -hackers.
(/messages/by-id/f7682c24-4271-1ff5-d963-053ecb0fce40@BlueTreble.com)
--
Jim Nasby, Data Architect, Blue Treble Consulting, Austin TX
Experts in Analytics, Data Architecture and PostgreSQL
Data in Trouble? Get it in Treble! http://BlueTreble.com
855-TREBLE2 (855-873-2532) mobile: 512-569-9461

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

#25Jim Nasby
Jim.Nasby@BlueTreble.com
In reply to: Joy Arulraj (#22)
Re: [GENERAL] C++ port of Postgres

On 8/16/16 12:53 PM, Joy Arulraj wrote:

The whole thing would make a lot more sense given a credible design
for error handling that keeps both languages happy.

Well, getting so that we can at least compile in both systems would
certainly increase the chances of somebody being willing to work on
such a design. And if nobody ever does, then at least people who want
to fork and do research projects based on PostgreSQL will have
slightly less work to do when they want to hack it up. PostgreSQL
seems to be a very popular starting point for research work, but a
paper I read recently complained about the antiquity of our code base.
I prefer to call that backward-compatibility, but at some point people
stop thinking of you as backward-compatible and instead think of you
as simply backward.

I agree, this was the main reason why we wanted to add support for C++.

Joy, do you have an idea what a *minimally invasive* patch for C++
support would look like? That's certainly the first step here.
--
Jim Nasby, Data Architect, Blue Treble Consulting, Austin TX
Experts in Analytics, Data Architecture and PostgreSQL
Data in Trouble? Get it in Treble! http://BlueTreble.com
855-TREBLE2 (855-873-2532) mobile: 512-569-9461

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#26Andres Freund
andres@anarazel.de
In reply to: Heikki Linnakangas (#16)
Re: [GENERAL] C++ port of Postgres

On 2016-08-16 18:52:39 +0300, Heikki Linnakangas wrote:

On 08/16/2016 05:47 PM, Jim Nasby wrote:

I realize there's little technical reason why we *need* C++ support. The
level if discipline applied to our codebase negates some of the benefits
of C++. But maintaining the discipline takes a lot of time and effort,
and makes it more difficult to attract new contributors.

I suspect that it would take as much
discipline to keep a C++ codebase
readable, as the current C codebase. If
not more.

Well, having typed pg_list.h style lists, ilist.h linked lists,
hash-tables, and proper typechecks for pg_nodes.h instead of the NodeTag
stuff, would surely make life easier.

But given the small subset of C++ available on all our supported
platforms... I think we'd first need to make the decision to cut support
for some platforms, before using C++. Which imo is a distinct task from
*allowing* to compile with a C++ compiler.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#27Peter Geoghegan
pg@heroku.com
In reply to: Tom Lane (#20)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 9:59 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:

I think this might have advantages purely from the standpoint of new
compilers possibly offering useful warnings we don't get now. But
if we only go this far, I'm pretty dubious that it really helps people
to develop extensions in C++. Almost invariably, if you ask *why* they
want to do that, you'll get an answer involving C++ libraries that are
not going to play very nice with our error handling or memory management
conventions.

FWIW, it's not uncommon to opt-out of C++ exceptions entirely, for
various reasons. For example, the Google C++ style guide forbids it
(if only for historical reasons), as does the GCC style guide (since
GCC was a C program until several years ago [1]https://lwn.net/Articles/542457/ -- Peter Geoghegan). Sometimes, these
third party libraries that mandate the use of exceptions do indeed
create significant headaches for Postgres, compatibility-wise, but
that isn't a given.

IMV, it would be useful to use C++ classes (and even template classes)
for a small number of data structures, while still largely adhering to
earlier practices (this is what GCC did). Specifically, a few modules
such as StringInfo, could be made to follow the RAII/scope bound
resource management usefully, which doesn't seem incompatible with
memory contexts. However, this doesn't seem terribly exciting to me.

[1]: https://lwn.net/Articles/542457/ -- Peter Geoghegan
--
Peter Geoghegan

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#28Jim Nasby
Jim.Nasby@BlueTreble.com
In reply to: Aleksander Alekseev (#13)
Re: [GENERAL] C++ port of Postgres

I'm sure this wasn't your intent, but the tone of your response is part
of why people don't get involved with Postgres development...

On 8/16/16 10:39 AM, Aleksander Alekseev wrote:

Well, well, well. Another C vs C++ holly war, really?

Please note that you're the only person in the entire thread that's said
anything to the effect of a holy war...

Who are these "folks"? How many more developers it would attract
_exactly_, not potentially?

As someone else (Robert?) said, there's a decent chance of it attracting
some, and it should be rather non-invasive, so why not try?

One again, which "people"? I've seen people complained that there is
not enough code reviewers and testers. I doubt very much its something
C++ will help with.

Will it suddenly draw 20 people? Probably not. But if the community
actually welcomes the effort Joy put forth and encourages him then we've
very likely gained at least one more; maybe several.

OTOH, if the community takes the stance of "WTF WHY DO WE NEED THIS?!",
we've just driven Joy and anyone else that's a C++ fan away.

When it comes specifically to reviewing and testing, you need to provide
some kind of reason for people to do that grunt work. A big form of that
is supporting people who want to change something about Postgres. (It's
certainly possible to get non-hackers to help with this stuff, but
that's a different discussion entirely.)

And I wrote a blog post (in Russian) [1] in 2016 why nobody should (if
they can) write a new code in C++. In my opinion Rust looks way more
promising. However I personally prefer to wait like 5 years before
using a new and shiny technology. This is also something I blogged
about (in Russian [2], translation [3]).

I agree that Rust is more interesting than C++. I think it'd be great if
we supported it as well, but I don't know how practical that would
actually be. Note I said support, not use... it's going to be far more
challenging to make Rust (or even C++) a requirement to build Postgres.
Maybe we'll eventually go that route, after demonstrating the
significant benefits that would need to exist to make that work
worthwhile. It's going to be FAR easier to demonstrate that if the
native project at least supports using it, vs needing a complete fork.
--
Jim Nasby, Data Architect, Blue Treble Consulting, Austin TX
Experts in Analytics, Data Architecture and PostgreSQL
Data in Trouble? Get it in Treble! http://BlueTreble.com
855-TREBLE2 (855-873-2532) mobile: 512-569-9461

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#29Andres Freund
andres@anarazel.de
In reply to: Tom Lane (#20)
Re: [GENERAL] C++ port of Postgres

On 2016-08-16 12:59:24 -0400, Tom Lane wrote:

I'm pretty dubious that it really helps people
to develop extensions in C++. Almost invariably, if you ask *why* they
want to do that, you'll get an answer involving C++ libraries that are
not going to play very nice with our error handling or memory management
conventions. I do not see how we could C++-ify the error handling without
making a complete break with C compilers ... which is a step I don't
really want to take.

I don't think it's *that* hard to make our and C++ error handling play
well together, at least when compiled with a C++ compiler.

The whole thing would make a lot more sense given a credible design
for error handling that keeps both languages happy.

Using C++ exceptions instead of sigsetjmp()/siglongjmp, when compiled
with a C++ compiler, seems not that hard, and could easily be hidden
behind PG_TRY/CATCH/RE_THROW/END_TRY. We'd have to hide the "bottom of
the exception stack" cases like PostgresMain() behind another macro, but
to me that doesn't sound like a bad idea anyway.

I do think it makes sense to work towards being able to compile postgres
with both C++ and C compilers. Most of the work towards that is pretty
boring...

A lot of the other things people have muttered about, such as heavier
use of inline functions instead of macros, don't particularly need C++
at all.

I think the more exciting bit is type safe lists, hash tables, ...,
without having to use huge amounts of macro magic. Using actual
inheritance for Node* stuff would also surely make some code better
checked (checked casts) and easier to write (less pointless
downcasting/upcasting from Node).

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#30Peter Geoghegan
pg@heroku.com
In reply to: Peter Geoghegan (#27)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 1:29 PM, Peter Geoghegan <pg@heroku.com> wrote:

IMV, it would be useful to use C++ classes (and even template classes)
for a small number of data structures, while still largely adhering to
earlier practices (this is what GCC did). Specifically, a few modules
such as StringInfo, could be made to follow the RAII/scope bound
resource management usefully, which doesn't seem incompatible with
memory contexts. However, this doesn't seem terribly exciting to me.

Actually, come to think of it, I guess this is wrong. The problem with
what I say here is that longjmp() and setjmp() are incompatible with
the stack unwinding used by C++ destructors in general (exceptions are
another issue). I think that the practical implication of that is that
we can never use any C++ feature that hides the complexity of resource
management, unless and until elog() is reimplemented to not use
longjmp() and setjmp().

--
Peter Geoghegan

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#31Jim Nasby
Jim.Nasby@BlueTreble.com
In reply to: Andres Freund (#26)
Re: [GENERAL] C++ port of Postgres

On 8/16/16 3:29 PM, Andres Freund wrote:

Well, having typed pg_list.h style lists, ilist.h linked lists,
hash-tables, and proper typechecks for pg_nodes.h instead of the NodeTag
stuff, would surely make life easier.

I certainly wish parts of the system brought code and "data" together in
a better way. Nodes are an example; all the Walker stuff in the
planner/executor is another. (I'm not saying C++ would make that better,
just saying those are parts of the code I find it much harder to grok.)

But given the small subset of C++ available on all our supported
platforms... I think we'd first need to make the decision to cut support
for some platforms, before using C++. Which imo is a distinct task from
*allowing* to compile with a C++ compiler.

Exactly. If we at least maintain support for compiling that means people
can experiment with other enhancements in a way that's much more
compatible with normal community contribution practices, which makes it
far more likely for that stuff to be accepted.

As for the backwards compatibility... the stance I've seen the community
take is cost vs benefit. Right now the benefits are completely
hypothetical, because no one could realistically propose a patch to use
C++ (or maybe even Rust) features.
--
Jim Nasby, Data Architect, Blue Treble Consulting, Austin TX
Experts in Analytics, Data Architecture and PostgreSQL
Data in Trouble? Get it in Treble! http://BlueTreble.com
855-TREBLE2 (855-873-2532) mobile: 512-569-9461

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#32Andres Freund
andres@anarazel.de
In reply to: Peter Geoghegan (#30)
Re: [GENERAL] C++ port of Postgres

On 2016-08-16 13:40:06 -0700, Peter Geoghegan wrote:

On Tue, Aug 16, 2016 at 1:29 PM, Peter Geoghegan <pg@heroku.com> wrote:

IMV, it would be useful to use C++ classes (and even template classes)
for a small number of data structures, while still largely adhering to
earlier practices (this is what GCC did). Specifically, a few modules
such as StringInfo, could be made to follow the RAII/scope bound
resource management usefully, which doesn't seem incompatible with
memory contexts. However, this doesn't seem terribly exciting to me.

Actually, come to think of it, I guess this is wrong. The problem with
what I say here is that longjmp() and setjmp() are incompatible with
the stack unwinding used by C++ destructors in general (exceptions are
another issue). I think that the practical implication of that is that
we can never use any C++ feature that hides the complexity of resource
management, unless and until elog() is reimplemented to not use
longjmp() and setjmp().

FWIW, IIRC that's not true for gcc/glibc, because they IIRC use common
codepaths. But obviously that's not all-encompassing enough to rely on that.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#33Tom Lane
tgl@sss.pgh.pa.us
In reply to: Andres Freund (#32)
Re: [GENERAL] C++ port of Postgres

Andres Freund <andres@anarazel.de> writes:

On 2016-08-16 13:40:06 -0700, Peter Geoghegan wrote:

Actually, come to think of it, I guess this is wrong. The problem with
what I say here is that longjmp() and setjmp() are incompatible with
the stack unwinding used by C++ destructors in general (exceptions are
another issue). I think that the practical implication of that is that
we can never use any C++ feature that hides the complexity of resource
management, unless and until elog() is reimplemented to not use
longjmp() and setjmp().

FWIW, IIRC that's not true for gcc/glibc, because they IIRC use common
codepaths. But obviously that's not all-encompassing enough to rely on that.

I wonder whether it'd be possible to implement the PG_TRY/CATCH macros
to use C++ exceptions when building in C++. This would probably mean
that C and C++ builds would be incompatible as far as loadable extensions
are concerned, because it'd amount to an ABI difference. But maybe
that's OK. We could certainly have the PG_MODULE_MAGIC macro guard
against the case.

regards, tom lane

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#34Piotr Stefaniak
postgres@piotr-stefaniak.me
In reply to: Robert Haas (#18)
Re: [GENERAL] C++ port of Postgres

On 2016-08-16 18:33, Robert Haas wrote:

It wouldn't be that much work to maintain, either: we'd
just set up some buildfarm members that compiled using C++ and when
they turned red, we'd go fix it.

I think that there exist subtle differences between C and C++ that
without compile-time diagnostic could potentially lead to different
run-time behavior. As an artificial example:

$ cat ./test.c
#include <stdio.h>

int main(void) {
FILE *f = fopen("test.bin", "w");
if (f == NULL)
return 1;
fwrite("1", sizeof '1', 1, f);
fclose(f);
return 0;
}
$ clang ./test.c -o test
$ ./test
$ hexdump test.bin
0000000 0031 0000
0000004
$ clang++ ./test.c -o test
clang-3.9: warning: treating 'c' input as 'c++' when in C++ mode, this
behavior is deprecated
$ ./test
$ hexdump test.bin
0000000 0031
0000001

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#35Peter Geoghegan
pg@heroku.com
In reply to: Tom Lane (#33)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 1:59 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:

FWIW, IIRC that's not true for gcc/glibc, because they IIRC use common
codepaths. But obviously that's not all-encompassing enough to rely on that.

I wonder whether it'd be possible to implement the PG_TRY/CATCH macros
to use C++ exceptions when building in C++. This would probably mean
that C and C++ builds would be incompatible as far as loadable extensions
are concerned, because it'd amount to an ABI difference. But maybe
that's OK. We could certainly have the PG_MODULE_MAGIC macro guard
against the case.

Maybe.

I think that the best thing about C++ is the ability to encapsulate
and simplify some aspects of resource management quite well, which
necessitates reimplementing PG_TRY/CATCH. The worst thing about C++ is
that ABI compatibility is far messier. This makes a C++ port seem less
compelling to me than the idea first appears.

Note, for example, that ICU is implemented in C++, but still has C
stub functions, not necessarily for the exclusive benefit of C client
code.

--
Peter Geoghegan

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#36Andres Freund
andres@anarazel.de
In reply to: Tom Lane (#33)
Re: [GENERAL] C++ port of Postgres

On 2016-08-16 16:59:56 -0400, Tom Lane wrote:

Andres Freund <andres@anarazel.de> writes:

On 2016-08-16 13:40:06 -0700, Peter Geoghegan wrote:

Actually, come to think of it, I guess this is wrong. The problem with
what I say here is that longjmp() and setjmp() are incompatible with
the stack unwinding used by C++ destructors in general (exceptions are
another issue). I think that the practical implication of that is that
we can never use any C++ feature that hides the complexity of resource
management, unless and until elog() is reimplemented to not use
longjmp() and setjmp().

FWIW, IIRC that's not true for gcc/glibc, because they IIRC use common
codepaths. But obviously that's not all-encompassing enough to rely on that.

I wonder whether it'd be possible to implement the PG_TRY/CATCH macros
to use C++ exceptions when building in C++.

Yea, I suggested that somewhere nearby. I think that'd be fairly easy -
to me the hard part is making it possible to compile postgres with C++, not
changing the exception handling itself.

This would probably mean that C and C++ builds would be incompatible
as far as loadable extensions are concerned, because it'd amount to an
ABI difference. But maybe that's OK. We could certainly have the
PG_MODULE_MAGIC macro guard against the case.

Right.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#37Christopher Browne
cbbrowne@gmail.com
In reply to: Piotr Stefaniak (#34)
Re: [GENERAL] C++ port of Postgres

On 16 August 2016 at 17:08, Piotr Stefaniak <postgres@piotr-stefaniak.me> wrote:

On 2016-08-16 18:33, Robert Haas wrote:

It wouldn't be that much work to maintain, either: we'd
just set up some buildfarm members that compiled using C++ and when
they turned red, we'd go fix it.

I think that there exist subtle differences between C and C++ that
without compile-time diagnostic could potentially lead to different
run-time behavior.

It seems to me that if we were really keen on attaching in another
"totally compiled" language, that C++ wouldn't seem like the best
choice.

As you say, it's subtly different, which seems a bit dangerous to me.

Further, it's not as if C++ is particularly newer than C. C is about 45
years old; C++, at 33, hardly seems like a "spry young whippersnapper"
whose inclusion ought to lead to vast excitement.

The would-be "spry young things" that head to my mind are Rust and
Go. I'm not sure it's terribly plausible to have parts of Postgres
written in both C and (Rust|Go); they're different enough that
I'm not sure what functionality would mix sensibly. But I think
that would be more interesting, all the same. Perhaps it would
work out well to be able to create background workers in Rust,
or to implement a stored procedure language in Go.
--
When confronted by a difficult problem, solve it by reducing it to the
question, "How would the Lone Ranger handle this?"

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#38Joy Arulraj
jarulraj@cs.cmu.edu
In reply to: Jim Nasby (#25)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 4:22 PM, Jim Nasby <Jim.Nasby@bluetreble.com> wrote:

On 8/16/16 12:53 PM, Joy Arulraj wrote:

The whole thing would make a lot more sense given a credible design
for error handling that keeps both languages happy.

Well, getting so that we can at least compile in both systems would
certainly increase the chances of somebody being willing to work on
such a design. And if nobody ever does, then at least people who want
to fork and do research projects based on PostgreSQL will have
slightly less work to do when they want to hack it up. PostgreSQL
seems to be a very popular starting point for research work, but a
paper I read recently complained about the antiquity of our code base.
I prefer to call that backward-compatibility, but at some point people
stop thinking of you as backward-compatible and instead think of you
as simply backward.

I agree, this was the main reason why we wanted to add support for C++.

Joy, do you have an idea what a *minimally invasive* patch for C++ support
would look like? That's certainly the first step here.

Jim -- I believe that the patch will be roughly 6K lines long. The majority
of the changes correspond to handling language keyword conflicts.

https://github.com/jarulraj/postgresql-cpp/compare/182656bf32b99c96e5cd9dc59ece4c20149787fb...7ef6f472b53a83a4cedd0222b41345c0f74fae1e

I must mention that some of the changes I have made preclude the
possibility of supporting compilation with both C and C++ compilers.
However, I am certain that this limitation can be circumvented with some
clever hacking.

Show quoted text

--
Jim Nasby, Data Architect, Blue Treble Consulting, Austin TX
Experts in Analytics, Data Architecture and PostgreSQL
Data in Trouble? Get it in Treble! http://BlueTreble.com
855-TREBLE2 (855-873-2532) mobile: 512-569-9461

#39dandl
david@andl.org
In reply to: Robert Haas (#21)
Re: [GENERAL] C++ port of Postgres

Well, getting so that we can at least compile in both systems would
certainly increase the chances of somebody being willing to work on
such a design.

From my particular perspective it would be enough if all the internal headers (that one needs to use in writing server-side extensions) were completely usable in C++. It's not so much hacking on the internals, it's more about being to build an extension DLL in C++ that makes extensive use of calls to internals without having to write shim layers. That looks like a lot less work than a full C++ port.

And if nobody ever does, then at least people who want

to fork and do research projects based on PostgreSQL will have
slightly less work to do when they want to hack it up. PostgreSQL
seems to be a very popular starting point for research work, but a
paper I read recently complained about the antiquity of our code base.
I prefer to call that backward-compatibility, but at some point people
stop thinking of you as backward-compatible and instead think of you
as simply backward.

Certainly the positive arguments for sticking with pure C are diminishing over time, perhaps faster in perception than in fact.

A lot of the other things people have muttered about, such as

heavier

use of inline functions instead of macros, don't particularly need

C++

at all.

My point is only that C++ can be used to provide better type safety, with little of any effect on performance.

Regards
David M Bennett FACS

Andl - A New Database Language - andl.org

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#40Andres Freund
andres@anarazel.de
In reply to: dandl (#39)
Re: [GENERAL] C++ port of Postgres

On 2016-08-17 10:45:25 +1000, dandl wrote:

From my particular perspective it would be enough if all the internal
headers (that one needs to use in writing server-side extensions) were
completely usable in C++.

That should already be the case. There's even a dirty hack^WWscript
that checks that that remains the case (src/tools/pginclude/cpluspluscheck).

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#41Tsunakawa, Takayuki
tsunakawa.takay@jp.fujitsu.com
In reply to: Christopher Browne (#37)
Re: [GENERAL] C++ port of Postgres

From: pgsql-hackers-owner@postgresql.org

[mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Peter Geoghegan
I think that the best thing about C++ is the ability to encapsulate and
simplify some aspects of resource management quite well, which necessitates
reimplementing PG_TRY/CATCH. The worst thing about C++ is that ABI
compatibility is far messier. This makes a C++ port seem less compelling
to me than the idea first appears.

From: pgsql-hackers-owner@postgresql.org

[mailto:pgsql-hackers-owner@postgresql.org] On Behalf Of Christopher
Further, it's not as if C++ is particularly newer than C. C is about 45
years old; C++, at 33, hardly seems like a "spry young whippersnapper"
whose inclusion ought to lead to vast excitement.

The would-be "spry young things" that head to my mind are Rust and Go. I'm
not sure it's terribly plausible to have parts of Postgres written in both
C and (Rust|Go); they're different enough that I'm not sure what
functionality would mix sensibly. But I think that would be more
interesting, all the same. Perhaps it would work out well to be able to
create background workers in Rust, or to implement a stored procedure
language in Go.

First, I'm neither for nor against rewriting PostgreSQL in C++. But I wonder whether it would really pay for the cost. I'm worried about these, for example:

* Wouldn't it increase the coding and testing burdon? Coding and testing in C, and coding and testing in C++. PostgreSQL seem to have many features to develop, and I'm not sure C++ will help to speed up the development of them.

* Would it really attract more developers of PostgreSQL itself, not extensions? FYI, Tiobe Index says C is nearly twice as popular as C++.

http://www.tiobe.com/tiobe-index/

* Wouldn't it distance some developers if they don't want to learn C++? As Christopher said, C++ is old and there are many newer languages that attract developers -- C#, Swift, Go, Java, JavaScript, etc. I wonder whether recent developers want to spend time in learning complex C++ now. I learned C++ because it is still the most popular language in game development, but maybe I would not want to learn C++ anymore if I didn't know C++.

Regards
Takayuki Tsunakawa

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#42'Andres Freund'
andres@anarazel.de
In reply to: Adam Brusselback (#7)
Re: [GENERAL] C++ port of Postgres

On 2016-08-17 11:51:04 +1000, dandl wrote:

From my particular perspective it would be enough if all the

internal

headers (that one needs to use in writing server-side extensions)

were

completely usable in C++.

That should already be the case. There's even a dirty hack^WWscript
that checks that that remains the case
(src/tools/pginclude/cpluspluscheck).

The source code for my project is here:
https://github.com/davidandl/Andl/tree/master/plandl
https://github.com/davidandl/Andl/blob/master/plandl/plandl.c

I was not able to get this file to compile correctly in C++, and my
recollection is that at the time I asked on this list and that was the
advice.

You need to include the files surrounded by extern "C" { }.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#43dandl
david@andl.org
In reply to: Andres Freund (#40)
Re: [GENERAL] C++ port of Postgres

From my particular perspective it would be enough if all the

internal

headers (that one needs to use in writing server-side extensions)

were

completely usable in C++.

That should already be the case. There's even a dirty hack^WWscript
that checks that that remains the case
(src/tools/pginclude/cpluspluscheck).

The source code for my project is here:
https://github.com/davidandl/Andl/tree/master/plandl
https://github.com/davidandl/Andl/blob/master/plandl/plandl.c

I was not able to get this file to compile correctly in C++, and my
recollection is that at the time I asked on this list and that was the
advice.

Sorry, I don't remember the error but it seemed to be too deeply embedded to
worry about. I just wrote the C code and moved on.

Since the Windows COM in the other part is C++ only, I finished up with a
mixed build. It works fine, but is not the ideal outcome.

Regards
David M Bennett FACS

Andl - A New Database Language - andl.org

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#44Craig Ringer
craig@2ndquadrant.com
In reply to: 'Andres Freund' (#42)
Re: [GENERAL] C++ port of Postgres

On 17 August 2016 at 09:49, Andres Freund <andres@anarazel.de> wrote:

You need to include the files surrounded by extern "C" { }.

I'd really like to adopt the convention used by many libraries etc of doing
this automatically - detecting a c++ compiler in the preprocessor and
wrapping in "extern "C"" .

Having the codebase c++-clean enough to compile with a c++ compiler seems
to be the easiest way to maintain that, but means more "extern "C""
droppings in the .c files, not just the headers. Still, pretty ignoreable.

--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

#45Aleksander Alekseev
a.alekseev@postgrespro.ru
In reply to: Yury Zhuravlev (#17)
Re: [GENERAL] C++ port of Postgres

Two big projects lately move to C++ from C:
GCC, Mesa

You can read their reasons.
Only C++ we can use without full rewrite currently. (or ObjectC maybe)
If we wish fix C limitations.

I would like just to leave this link here:

https://en.wikipedia.org/wiki/List_of_fallacies

Long story short - no one cares who did what in other projects.
Recently I rewrote my OpenGL demo [1]https://github.com/afiskon/c-opengl-text/ from C++ to C. Uber recently
moved from PostgreSQL to MySQL. It proves literally nothing.

[1]: https://github.com/afiskon/c-opengl-text/

--
Best regards,
Aleksander Alekseev

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#46Aleksander Alekseev
a.alekseev@postgrespro.ru
In reply to: Jim Nasby (#28)
Re: [GENERAL] C++ port of Postgres

I'm sure this wasn't your intent, but the tone of your response is
part of why people don't get involved with Postgres development...

Please note that you're the only person in the entire thread that's
said anything to the effect of a holy war...

OTOH, if the community takes the stance of "WTF WHY DO WE NEED
THIS?!", we've just driven Joy and anyone else that's a C++ fan away.

I'm sorry for being maybe to emotional. It's was not (and never is!) my
intent to offend anyone. Also I would like to note that I don't speak
for community, I speak for myself.

What I saw was: "hey, lets rewrite PostgreSQL in C++ without any good
reason except (see [1]https://en.wikipedia.org/wiki/List_of_fallacies list)". Naturally I though (and still think) that
you people are just trolls. Or maybe "everything should be written in
C++ because it's the only right language and anyone who thinks
otherwise is wrong" type of fanatics. Thus I don't think you are here to
help.

Give a concrete reason. Like "hey, we rewrote this part of code in C++
and look, its much more readable, twice as fast as code in C (how to do
benchmarks right is a separate good topic!) and it still compiles fast
even on Raspberry Pi, works on all platforms you are supporting, etc".
Or "hey, we solved xid wraparound problem once and for all, but solution
is in C++, so its for you to decide whether to merge it or not".

If you really want to help, just solve _real_ problems using instruments
you prefer instead of reposting obviously holly war topic from general@
mailing list.

[1]: https://en.wikipedia.org/wiki/List_of_fallacies

--
Best regards,
Aleksander Alekseev

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#47Serge Rielau
srielau@gmail.com
In reply to: Craig Ringer (#44)
Re: [GENERAL] C++ port of Postgres

On Aug 16, 2016, at 10:16 PM, Craig Ringer <craig@2ndquadrant.com> wrote:

On 17 August 2016 at 09:49, Andres Freund <andres@anarazel.de <mailto:andres@anarazel.de>> wrote:

You need to include the files surrounded by extern "C" { }.

I'd really like to adopt the convention used by many libraries etc of doing this automatically - detecting a c++ compiler in the preprocessor and wrapping in "extern "C"" .

Having the codebase c++-clean enough to compile with a c++ compiler seems to be the easiest way to maintain that, but means more "extern "C"" droppings in the .c files, not just the headers. Still, pretty ignoreable.

Big +1 here,
Just having community code compilable with a C++ compiler out of the box would go a long way.

Beyond that, on my end I have been working with PG now for a year and a half and here is a quick list of what I sorely miss from my C++ days:
* Overloading of functions (same as in SQL) keeps naming clean
* Named parameters (same as SQL) keeps code readable
* Adding new function parameters with defaults so I don’t need to pass in NULL, 0, … at 20 places (again supported in SQL)
* Member functions greatly help organize code
* simple inheritance (as emulated today in node types)

At my old employer we used C++ for the DBMS in various degrees in different components.
That degree was agreed upon in coding standards, so we could pick what we like about C++ and blacklist what we didn’t.
E.g. C style exception handling was prohibited
Default memory management (new) was prohibited.
Instead new() was overloaded and hooked into the DBMS memory manager.
I see no reason why this couldn’t be done in PG.

I can’t comment of compiling on a Rasperry PI, but know that my former DBMS code compiled and ran on Windows, Linux, AIX, Sun, HP, and Mac.

But again, just having the community code compile so proprietary (for now) enhancements could be written in C++ would be huge.

Cheers
Serge

#48Dmitry Igrishin
dmitigr@gmail.com
In reply to: Aleksander Alekseev (#46)
Re: [GENERAL] C++ port of Postgres

2016-08-17 14:40 GMT+03:00 Aleksander Alekseev <a.alekseev@postgrespro.ru>:

I'm sure this wasn't your intent, but the tone of your response is
part of why people don't get involved with Postgres development...

Please note that you're the only person in the entire thread that's
said anything to the effect of a holy war...

OTOH, if the community takes the stance of "WTF WHY DO WE NEED
THIS?!", we've just driven Joy and anyone else that's a C++ fan away.

I'm sorry for being maybe to emotional. It's was not (and never is!) my
intent to offend anyone. Also I would like to note that I don't speak
for community, I speak for myself.

What I saw was: "hey, lets rewrite PostgreSQL in C++ without any good
reason except (see [1] list)". Naturally I though (and still think) that
you people are just trolls. Or maybe "everything should be written in
C++ because it's the only right language and anyone who thinks
otherwise is wrong" type of fanatics. Thus I don't think you are here to
help.

Give a concrete reason. Like "hey, we rewrote this part of code in C++
and look, its much more readable, twice as fast as code in C (how to do
benchmarks right is a separate good topic!) and it still compiles fast
even on Raspberry Pi, works on all platforms you are supporting, etc".
Or "hey, we solved xid wraparound problem once and for all, but solution
is in C++, so its for you to decide whether to merge it or not".

I doubt that someone will rush to rewrite PostgreSQL in C++. At now, the
reason to consider the refactoring of current codebase to make the C++
compilers happy, is to make the code more qualitative. I think, that only after
that step it is reasonable to consider the use some of C++ features.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#49Robert Haas
robertmhaas@gmail.com
In reply to: Piotr Stefaniak (#34)
Re: [GENERAL] C++ port of Postgres

On Tue, Aug 16, 2016 at 5:08 PM, Piotr Stefaniak
<postgres@piotr-stefaniak.me> wrote:

On 2016-08-16 18:33, Robert Haas wrote:

It wouldn't be that much work to maintain, either: we'd
just set up some buildfarm members that compiled using C++ and when
they turned red, we'd go fix it.

I think that there exist subtle differences between C and C++ that
without compile-time diagnostic could potentially lead to different
run-time behavior. As an artificial example:

$ cat ./test.c
#include <stdio.h>

int main(void) {
FILE *f = fopen("test.bin", "w");
if (f == NULL)
return 1;
fwrite("1", sizeof '1', 1, f);
fclose(f);
return 0;
}
$ clang ./test.c -o test
$ ./test
$ hexdump test.bin
0000000 0031 0000
0000004
$ clang++ ./test.c -o test
clang-3.9: warning: treating 'c' input as 'c++' when in C++ mode, this
behavior is deprecated
$ ./test
$ hexdump test.bin
0000000 0031
0000001

Hmm, so sizeof() has different semantics in C vs. C++?

While that's a little alarming, I'm wondering whether this sort of
thing is likely to actually be a problem in practice. We have such a
long laundry list of coding conventions already that I am inclined to
believe we could add a few more without breaking our ability to do
development.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#50Andrew Gierth
andrew@tao11.riddles.org.uk
In reply to: Robert Haas (#49)
Re: [GENERAL] C++ port of Postgres

"Robert" == Robert Haas <robertmhaas@gmail.com> writes:

Robert> Hmm, so sizeof() has different semantics in C vs. C++?

No. '1' has different semantics in C vs C++. (In C, '1' is an int,
whereas in C++ it's a char. It so happens that (sizeof '1') is the only
case which is valid in both C and C++ where this makes a difference.)

--
Andrew (irc:RhodiumToad)

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#51Robert Haas
robertmhaas@gmail.com
In reply to: Andrew Gierth (#50)
Re: [GENERAL] C++ port of Postgres

On Wed, Aug 17, 2016 at 11:36 AM, Andrew Gierth
<andrew@tao11.riddles.org.uk> wrote:

"Robert" == Robert Haas <robertmhaas@gmail.com> writes:

Robert> Hmm, so sizeof() has different semantics in C vs. C++?

No. '1' has different semantics in C vs C++. (In C, '1' is an int,
whereas in C++ it's a char. It so happens that (sizeof '1') is the only
case which is valid in both C and C++ where this makes a difference.)

OK. Doesn't seem like a big problem.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#52Gavin Flower
GavinFlower@archidevsys.co.nz
In reply to: Aleksander Alekseev (#46)
Re: [GENERAL] C++ port of Postgres

On 17/08/16 23:40, Aleksander Alekseev wrote:

I'm sure this wasn't your intent, but the tone of your response is
part of why people don't get involved with Postgres development...

Please note that you're the only person in the entire thread that's
said anything to the effect of a holy war...

OTOH, if the community takes the stance of "WTF WHY DO WE NEED
THIS?!", we've just driven Joy and anyone else that's a C++ fan away.

I'm sorry for being maybe to emotional. It's was not (and never is!) my
intent to offend anyone. Also I would like to note that I don't speak
for community, I speak for myself.

What I saw was: "hey, lets rewrite PostgreSQL in C++ without any good
reason except (see [1] list)". Naturally I though (and still think) that
you people are just trolls. Or maybe "everything should be written in
C++ because it's the only right language and anyone who thinks
otherwise is wrong" type of fanatics. Thus I don't think you are here to
help.

Give a concrete reason. Like "hey, we rewrote this part of code in C++
and look, its much more readable, twice as fast as code in C (how to do
benchmarks right is a separate good topic!) and it still compiles fast
even on Raspberry Pi, works on all platforms you are supporting, etc".
Or "hey, we solved xid wraparound problem once and for all, but solution
is in C++, so its for you to decide whether to merge it or not".

If you really want to help, just solve _real_ problems using instruments
you prefer instead of reposting obviously holly war topic from general@
mailing list.

[1] https://en.wikipedia.org/wiki/List_of_fallacies

My main language is Java, and there are a lot of very good reasons for
rewriting Postgres in Java, but I'd never push that - as there are also
many good reasons for NOT rewriting Postgres in Java!

I am not an expert in C++, but I'm interested in its development and
growing usage. I've read enough about C++ to think it worthwhile to
consider rewriting Postgres in C++. If I had time, I would get deeper
into C++, but for now pressures push me towards getting deeper into
JavaScript - despite having an intense dislike for JavaScript!

The first 2 languages I used commercially were FORTRAN & COBOL back in
the 70's, and I've been paid to teacht C to experienced programmers.

As far as I am concerned, there is no one language that is perfect. I
have written programs i over 20 different languages.

So I did not suggest C++, because I'm a C++ Fanatic!!!

Cheers,
Gavin

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#53Craig Ringer
craig@2ndquadrant.com
In reply to: Gavin Flower (#52)
Re: [GENERAL] C++ port of Postgres

On 18 August 2016 at 02:14, Gavin Flower <GavinFlower@archidevsys.co.nz>
wrote:

My main language is Java, and there are a lot of very good reasons for
rewriting Postgres in Java, but I'd never push that - as there are also
many good reasons for NOT rewriting Postgres in Java!

I don't know why folks are jumping on the idea of a "rewrite". The original
post mentioned a C++ port, adding C++ compatibility and adopting some C++
features. Hardly a rewrite.

I'm not convinced that's a good idea either, unless it shows compelling
advantages in code clarity, performance, static checking, etc. But it's
hardly a "rewrite", that's just hyperbolic.

I think that to get anywhere with this you'll need to show a more concrete
plan for:

* What happens with libpq
* How this affects existing extensions and what changes they'll need
* How this affects PGXS
* What benefits this change offers. Concrete benefits with examples -
performance numbers, code snippets, etc
* Compatibility impact on platform and compiler support

Since there's approximately zero chance of a "one big commit" switchover,
you'll also need to present a transition plan, probably something like:

* Make all headers "extern "C"" conditionally if compiled as C++
* Add "extern "C"" to all C files conditionally if compiled as C++
* add a 'configure' option to compile as C++
* Progressively resolve C++-incompatibilities in C files and headers until
the whole database compiles as c++
* Resolve any runtime issues
* Add buildfarm client support for optionally building with c++
* Switch one or more buildfarm members to build with c++ or add new ones
* Identify and fix compatibility issues on other platforms

Then down the track we'd:
* Switch to C++ builds by default
* Define a C++ coding standard/policy that strictly identifies what C++
features are permissible
* Shut down the C-only buildfarm members and start permitting some C++
feature use where appropriate

--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

#54Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Jim Nasby (#25)
27 attachment(s)
Re: [GENERAL] C++ port of Postgres

[trimmed cc list because of big attachments]

On 8/16/16 4:22 PM, Jim Nasby wrote:

Joy, do you have an idea what a *minimally invasive* patch for C++
support would look like? That's certainly the first step here.

I developed a minimally invasive patch for C++ support a few years ago
shortly after I wrote that blog post. Since there appears to have been
some interest here now, I have updated that and split it up into logical
chunks.

So here you go.

To build this, you need to configure with g++ <= version 5. (4.x works,
too.) g++ version 6 does not work yet because of the issues described
in patch 0013.

Then you also need to edit src/Makefile.custom and set

COPT = -fpermissive -Wno-sign-compare -Wno-write-strings

The -W options are optional just to reduce some noise. Cleaning up
those warnings can be a separate project that might also have some
benefit under C.

The -fpermissive option is a g++ specific option that reduces some
errors to warnings. (So this won't work with clang or other compilers
at all at this point.) In particular, C++ does not allow casting from
or to void pointers without a cast, but -fpermissive allows that. The
step from this to "real" C++ would be adding a bunch of casts around
things like malloc and palloc and other places. That would be mostly
busy work, so I have excluded that here.

The patches are numbered approximately in increasing order of dubiosity.
So 0001 is probably a straight bug fix, 0002 and 0003 are arguably
minor bug fixes as well. The patches through 0012 can probably be
considered for committing in some form. After that it gets a bit hackish.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

Attachments:

0001-Fix-use-of-offsetof.patchtext/x-patch; name=0001-Fix-use-of-offsetof.patchDownload
From 86dbd4a5a0ab3212cd340e1fa56f03e864aa8e1a Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 01/27] Fix use of offsetof()

Using offsetof() with a run-time computed argument is not allowed in
either C or C++.  Apparently, gcc allows it, but g++ doesn't.
---
 contrib/bloom/blutils.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/contrib/bloom/blutils.c b/contrib/bloom/blutils.c
index debf4f4..b68a0d1 100644
--- a/contrib/bloom/blutils.c
+++ b/contrib/bloom/blutils.c
@@ -75,7 +75,7 @@ _PG_init(void)
 		bl_relopt_tab[i + 1].optname = MemoryContextStrdup(TopMemoryContext,
 														   buf);
 		bl_relopt_tab[i + 1].opttype = RELOPT_TYPE_INT;
-		bl_relopt_tab[i + 1].offset = offsetof(BloomOptions, bitSize[i]);
+		bl_relopt_tab[i + 1].offset = offsetof(BloomOptions, bitSize[0]) + sizeof(int) * i;
 	}
 }
 
-- 
2.9.3

0002-Use-return-instead-of-exit-in-configure.patchtext/x-patch; name=0002-Use-return-instead-of-exit-in-configure.patchDownload
From d3c7c1fbb346fd5c040a7a379d971db7b5129581 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 02/27] Use return instead of exit() in configure

Using exit() requires stdlib.h, which is not included.  Use return
instead.  Also add return type for main().
---
 config/c-compiler.m4 |  4 +++-
 config/c-library.m4  |  4 +++-
 configure            | 12 +++++++++---
 3 files changed, 15 insertions(+), 5 deletions(-)

diff --git a/config/c-compiler.m4 b/config/c-compiler.m4
index a7f6773..7d901e1 100644
--- a/config/c-compiler.m4
+++ b/config/c-compiler.m4
@@ -71,8 +71,10 @@ int does_int64_work()
     return 0;
   return 1;
 }
+
+int
 main() {
-  exit(! does_int64_work());
+  return (! does_int64_work());
 }])],
 [Ac_cachevar=yes],
 [Ac_cachevar=no],
diff --git a/config/c-library.m4 b/config/c-library.m4
index 50d068d..56658b5 100644
--- a/config/c-library.m4
+++ b/config/c-library.m4
@@ -204,8 +204,10 @@ int does_int64_snprintf_work()
     return 0;			/* either multiply or snprintf is busted */
   return 1;
 }
+
+int
 main() {
-  exit(! does_int64_snprintf_work());
+  return (! does_int64_snprintf_work());
 }]])],
 [pgac_cv_snprintf_long_long_int_modifier=$pgac_modifier; break],
 [],
diff --git a/configure b/configure
index 45c8eef..36d9a54 100755
--- a/configure
+++ b/configure
@@ -13563,8 +13563,10 @@ int does_int64_work()
     return 0;
   return 1;
 }
+
+int
 main() {
-  exit(! does_int64_work());
+  return (! does_int64_work());
 }
 _ACEOF
 if ac_fn_c_try_run "$LINENO"; then :
@@ -13645,8 +13647,10 @@ int does_int64_work()
     return 0;
   return 1;
 }
+
+int
 main() {
-  exit(! does_int64_work());
+  return (! does_int64_work());
 }
 _ACEOF
 if ac_fn_c_try_run "$LINENO"; then :
@@ -13739,8 +13743,10 @@ int does_int64_snprintf_work()
     return 0;			/* either multiply or snprintf is busted */
   return 1;
 }
+
+int
 main() {
-  exit(! does_int64_snprintf_work());
+  return (! does_int64_snprintf_work());
 }
 _ACEOF
 if ac_fn_c_try_run "$LINENO"; then :
-- 
2.9.3

0003-Add-missing-include-files-to-configure-tests.patchtext/x-patch; name=0003-Add-missing-include-files-to-configure-tests.patchDownload
From 54ed07be5a29d4955a9485316e68da5c6896797b Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 03/27] Add missing include files to configure tests

atoi() needs stdlib.h
strcmp() needs string.h
---
 config/c-library.m4 | 4 +++-
 configure           | 2 ++
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/config/c-library.m4 b/config/c-library.m4
index 56658b5..8a9da36 100644
--- a/config/c-library.m4
+++ b/config/c-library.m4
@@ -42,7 +42,8 @@ if test "$ac_cv_member_struct_tm_tm_zone" = yes; then
 fi
 AC_CACHE_CHECK(for tzname, ac_cv_var_tzname,
 [AC_LINK_IFELSE([AC_LANG_PROGRAM(
-[[#include <time.h>
+[[#include <stdlib.h>
+#include <time.h>
 #ifndef tzname /* For SGI.  */
 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
 #endif
@@ -184,6 +185,7 @@ AC_DEFUN([PGAC_FUNC_SNPRINTF_LONG_LONG_INT_MODIFIER],
 AC_CACHE_VAL(pgac_cv_snprintf_long_long_int_modifier,
 [for pgac_modifier in 'll' 'q' 'I64'; do
 AC_RUN_IFELSE([AC_LANG_SOURCE([[#include <stdio.h>
+#include <string.h>
 typedef long long int ac_int64;
 #define INT64_FORMAT "%${pgac_modifier}d"
 
diff --git a/configure b/configure
index 36d9a54..2308c61 100755
--- a/configure
+++ b/configure
@@ -11538,6 +11538,7 @@ if ${ac_cv_var_tzname+:} false; then :
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
+#include <stdlib.h>
 #include <time.h>
 #ifndef tzname /* For SGI.  */
 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
@@ -13723,6 +13724,7 @@ else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
+#include <string.h>
 typedef long long int ac_int64;
 #define INT64_FORMAT "%${pgac_modifier}d"
 
-- 
2.9.3

0004-Fix-LDFLAGS-test-for-C.patchtext/x-patch; name=0004-Fix-LDFLAGS-test-for-C.patchDownload
From ee7e69813784e7cf120165ba222e93f91d0d8f42 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 04/27] Fix LDFLAGS test for C++

The test looks to link to particular function, so we need to make that
function have C linkage.
---
 config/c-compiler.m4 |  9 ++++++++-
 configure            | 27 ++++++++++++++++++++++++---
 2 files changed, 32 insertions(+), 4 deletions(-)

diff --git a/config/c-compiler.m4 b/config/c-compiler.m4
index 7d901e1..21fb464 100644
--- a/config/c-compiler.m4
+++ b/config/c-compiler.m4
@@ -353,7 +353,14 @@ AC_DEFUN([PGAC_PROG_CC_LDFLAGS_OPT],
 AC_CACHE_CHECK([whether $CC supports $1], [Ac_cachevar],
 [pgac_save_LDFLAGS=$LDFLAGS
 LDFLAGS="$pgac_save_LDFLAGS $1"
-AC_RUN_IFELSE([AC_LANG_PROGRAM([extern void $2 (); void (*fptr) () = $2;],[])],
+AC_RUN_IFELSE([AC_LANG_PROGRAM([#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $2 ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $2;],[])],
               [Ac_cachevar=yes],
               [Ac_cachevar=no],
               [Ac_cachevar="assuming no"])
diff --git a/configure b/configure
index 2308c61..d74b25f 100755
--- a/configure
+++ b/configure
@@ -15748,7 +15748,14 @@ if test "$cross_compiling" = yes; then :
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-extern void $link_test_func (); void (*fptr) () = $link_test_func;
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $link_test_func ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $link_test_func;
 int
 main ()
 {
@@ -15787,7 +15794,14 @@ if test "$cross_compiling" = yes; then :
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-extern void $link_test_func (); void (*fptr) () = $link_test_func;
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $link_test_func ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $link_test_func;
 int
 main ()
 {
@@ -15826,7 +15840,14 @@ if test "$cross_compiling" = yes; then :
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-extern void $link_test_func (); void (*fptr) () = $link_test_func;
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $link_test_func ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $link_test_func;
 int
 main ()
 {
-- 
2.9.3

0005-Add-test-for-Wmissing-prototypes.patchtext/x-patch; name=0005-Add-test-for-Wmissing-prototypes.patchDownload
From 98b10d21551df4d038e10287f9bb447922897342 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 05/27] Add test for -Wmissing-prototypes

This was part of the hard-coded default warnings set in C, but the
option is not valid for C++ (since prototypes are always required).
---
 configure    | 38 +++++++++++++++++++++++++++++++++++++-
 configure.in |  4 +++-
 2 files changed, 40 insertions(+), 2 deletions(-)

diff --git a/configure b/configure
index d74b25f..7821c2f 100755
--- a/configure
+++ b/configure
@@ -4418,7 +4418,43 @@ fi
 # but has its own.  Also check other compiler-specific flags here.
 
 if test "$GCC" = yes -a "$ICC" = no; then
-  CFLAGS="-Wall -Wmissing-prototypes -Wpointer-arith"
+  CFLAGS="-Wall -Wpointer-arith"
+  # not valid for C++
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wmissing-prototypes" >&5
+$as_echo_n "checking whether $CC supports -Wmissing-prototypes... " >&6; }
+if ${pgac_cv_prog_cc_cflags__Wmissing_prototypes+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  pgac_save_CFLAGS=$CFLAGS
+CFLAGS="$pgac_save_CFLAGS -Wmissing-prototypes"
+ac_save_c_werror_flag=$ac_c_werror_flag
+ac_c_werror_flag=yes
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  pgac_cv_prog_cc_cflags__Wmissing_prototypes=yes
+else
+  pgac_cv_prog_cc_cflags__Wmissing_prototypes=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_c_werror_flag=$ac_save_c_werror_flag
+CFLAGS="$pgac_save_CFLAGS"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $pgac_cv_prog_cc_cflags__Wmissing_prototypes" >&5
+$as_echo "$pgac_cv_prog_cc_cflags__Wmissing_prototypes" >&6; }
+if test x"$pgac_cv_prog_cc_cflags__Wmissing_prototypes" = x"yes"; then
+  CFLAGS="$CFLAGS -Wmissing-prototypes"
+fi
+
   # These work in some but not all gcc versions
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wdeclaration-after-statement" >&5
 $as_echo_n "checking whether $CC supports -Wdeclaration-after-statement... " >&6; }
diff --git a/configure.in b/configure.in
index c878b4e..011e4c4 100644
--- a/configure.in
+++ b/configure.in
@@ -440,7 +440,9 @@ fi
 # but has its own.  Also check other compiler-specific flags here.
 
 if test "$GCC" = yes -a "$ICC" = no; then
-  CFLAGS="-Wall -Wmissing-prototypes -Wpointer-arith"
+  CFLAGS="-Wall -Wpointer-arith"
+  # not valid for C++
+  PGAC_PROG_CC_CFLAGS_OPT([-Wmissing-prototypes])
   # These work in some but not all gcc versions
   PGAC_PROG_CC_CFLAGS_OPT([-Wdeclaration-after-statement])
   PGAC_PROG_CC_CFLAGS_OPT([-Wendif-labels])
-- 
2.9.3

0006-Remove-unnecessary-prototypes.patchtext/x-patch; name=0006-Remove-unnecessary-prototypes.patchDownload
From 69259fa4f5fb0f28cbceda63fb2f2f425bcab7d8 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 06/27] Remove unnecessary prototypes

Prototypes for functions implementing V1-callable functions are no
longer necessary.
---
 contrib/bloom/bloom.h           |  1 -
 contrib/btree_gist/btree_gist.h | 10 ----------
 contrib/dblink/dblink.h         | 24 ------------------------
 contrib/isn/isn.h               | 19 -------------------
 contrib/pgcrypto/pgcrypto.h     | 13 -------------
 contrib/tablefunc/tablefunc.h   |  9 ---------
 6 files changed, 76 deletions(-)

diff --git a/contrib/bloom/bloom.h b/contrib/bloom/bloom.h
index bc451a0..18f5127 100644
--- a/contrib/bloom/bloom.h
+++ b/contrib/bloom/bloom.h
@@ -174,7 +174,6 @@ typedef BloomScanOpaqueData *BloomScanOpaque;
 
 /* blutils.c */
 extern void _PG_init(void);
-extern Datum blhandler(PG_FUNCTION_ARGS);
 extern void initBloomState(BloomState *state, Relation index);
 extern void BloomFillMetapage(Relation index, Page metaPage);
 extern void BloomInitMetapage(Relation index);
diff --git a/contrib/btree_gist/btree_gist.h b/contrib/btree_gist/btree_gist.h
index dcffbb5..191202a 100644
--- a/contrib/btree_gist/btree_gist.h
+++ b/contrib/btree_gist/btree_gist.h
@@ -34,14 +34,4 @@ enum gbtree_type
 	gbt_t_inet
 };
 
-
-
-/*
- * Generic btree functions
- */
-
-Datum		gbtreekey_in(PG_FUNCTION_ARGS);
-
-Datum		gbtreekey_out(PG_FUNCTION_ARGS);
-
 #endif
diff --git a/contrib/dblink/dblink.h b/contrib/dblink/dblink.h
index 1b94912..1102236 100644
--- a/contrib/dblink/dblink.h
+++ b/contrib/dblink/dblink.h
@@ -36,28 +36,4 @@
 
 #include "fmgr.h"
 
-/*
- * External declarations
- */
-extern Datum dblink_connect(PG_FUNCTION_ARGS);
-extern Datum dblink_disconnect(PG_FUNCTION_ARGS);
-extern Datum dblink_open(PG_FUNCTION_ARGS);
-extern Datum dblink_close(PG_FUNCTION_ARGS);
-extern Datum dblink_fetch(PG_FUNCTION_ARGS);
-extern Datum dblink_record(PG_FUNCTION_ARGS);
-extern Datum dblink_send_query(PG_FUNCTION_ARGS);
-extern Datum dblink_get_result(PG_FUNCTION_ARGS);
-extern Datum dblink_get_connections(PG_FUNCTION_ARGS);
-extern Datum dblink_is_busy(PG_FUNCTION_ARGS);
-extern Datum dblink_cancel_query(PG_FUNCTION_ARGS);
-extern Datum dblink_error_message(PG_FUNCTION_ARGS);
-extern Datum dblink_exec(PG_FUNCTION_ARGS);
-extern Datum dblink_get_pkey(PG_FUNCTION_ARGS);
-extern Datum dblink_build_sql_insert(PG_FUNCTION_ARGS);
-extern Datum dblink_build_sql_delete(PG_FUNCTION_ARGS);
-extern Datum dblink_build_sql_update(PG_FUNCTION_ARGS);
-extern Datum dblink_current_query(PG_FUNCTION_ARGS);
-extern Datum dblink_get_notify(PG_FUNCTION_ARGS);
-extern Datum dblink_fdw_validator(PG_FUNCTION_ARGS);
-
 #endif   /* DBLINK_H */
diff --git a/contrib/isn/isn.h b/contrib/isn/isn.h
index d8291c2..e1a52b2 100644
--- a/contrib/isn/isn.h
+++ b/contrib/isn/isn.h
@@ -30,25 +30,6 @@ typedef uint64 ean13;
 #define PG_GETARG_EAN13(n) PG_GETARG_INT64(n)
 #define PG_RETURN_EAN13(x) PG_RETURN_INT64(x)
 
-extern Datum isn_out(PG_FUNCTION_ARGS);
-extern Datum ean13_out(PG_FUNCTION_ARGS);
-extern Datum ean13_in(PG_FUNCTION_ARGS);
-extern Datum isbn_in(PG_FUNCTION_ARGS);
-extern Datum ismn_in(PG_FUNCTION_ARGS);
-extern Datum issn_in(PG_FUNCTION_ARGS);
-extern Datum upc_in(PG_FUNCTION_ARGS);
-
-extern Datum isbn_cast_from_ean13(PG_FUNCTION_ARGS);
-extern Datum ismn_cast_from_ean13(PG_FUNCTION_ARGS);
-extern Datum issn_cast_from_ean13(PG_FUNCTION_ARGS);
-extern Datum upc_cast_from_ean13(PG_FUNCTION_ARGS);
-
-extern Datum is_valid(PG_FUNCTION_ARGS);
-extern Datum make_valid(PG_FUNCTION_ARGS);
-
-extern Datum accept_weak_input(PG_FUNCTION_ARGS);
-extern Datum weak_input_status(PG_FUNCTION_ARGS);
-
 extern void initialize(void);
 
 #endif   /* ISN_H */
diff --git a/contrib/pgcrypto/pgcrypto.h b/contrib/pgcrypto/pgcrypto.h
index dfc7a10..65a1ed3 100644
--- a/contrib/pgcrypto/pgcrypto.h
+++ b/contrib/pgcrypto/pgcrypto.h
@@ -34,17 +34,4 @@
 
 #include "fmgr.h"
 
-/* exported functions */
-Datum		pg_digest(PG_FUNCTION_ARGS);
-Datum		pg_hmac(PG_FUNCTION_ARGS);
-Datum		pg_gen_salt(PG_FUNCTION_ARGS);
-Datum		pg_gen_salt_rounds(PG_FUNCTION_ARGS);
-Datum		pg_crypt(PG_FUNCTION_ARGS);
-Datum		pg_encrypt(PG_FUNCTION_ARGS);
-Datum		pg_decrypt(PG_FUNCTION_ARGS);
-Datum		pg_encrypt_iv(PG_FUNCTION_ARGS);
-Datum		pg_decrypt_iv(PG_FUNCTION_ARGS);
-Datum		pg_random_bytes(PG_FUNCTION_ARGS);
-Datum		pg_random_uuid(PG_FUNCTION_ARGS);
-
 #endif
diff --git a/contrib/tablefunc/tablefunc.h b/contrib/tablefunc/tablefunc.h
index 3477ed8..34d44a8 100644
--- a/contrib/tablefunc/tablefunc.h
+++ b/contrib/tablefunc/tablefunc.h
@@ -36,13 +36,4 @@
 
 #include "fmgr.h"
 
-/*
- * External declarations
- */
-extern Datum normal_rand(PG_FUNCTION_ARGS);
-extern Datum crosstab(PG_FUNCTION_ARGS);
-extern Datum crosstab_hash(PG_FUNCTION_ARGS);
-extern Datum connectby_text(PG_FUNCTION_ARGS);
-extern Datum connectby_text_serial(PG_FUNCTION_ARGS);
-
 #endif   /* TABLEFUNC_H */
-- 
2.9.3

0007-Fix-incorrect-type-cast.patchtext/x-patch; name=0007-Fix-incorrect-type-cast.patchDownload
From be0494cefb5e4a34c57f491ff44829395374720d Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 07/27] Fix incorrect type cast

---
 src/backend/access/gin/ginscan.c | 2 +-
 src/include/access/gin_private.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/gin/ginscan.c b/src/backend/access/gin/ginscan.c
index bfa86b5..77ca097 100644
--- a/src/backend/access/gin/ginscan.c
+++ b/src/backend/access/gin/ginscan.c
@@ -147,7 +147,7 @@ ginFillScanKey(GinScanOpaque so, OffsetNumber attnum,
 	key->nuserentries = nUserQueryValues;
 
 	key->scanEntry = (GinScanEntry *) palloc(sizeof(GinScanEntry) * nQueryValues);
-	key->entryRes = (bool *) palloc0(sizeof(bool) * nQueryValues);
+	key->entryRes = (GinTernaryValue *) palloc0(sizeof(GinTernaryValue) * nQueryValues);
 
 	key->query = query;
 	key->queryValues = queryValues;
diff --git a/src/include/access/gin_private.h b/src/include/access/gin_private.h
index 68cfe0c..fa6ddad 100644
--- a/src/include/access/gin_private.h
+++ b/src/include/access/gin_private.h
@@ -788,7 +788,7 @@ typedef struct GinScanKeyData
 	int			nadditional;
 
 	/* array of check flags, reported to consistentFn */
-	bool	   *entryRes;
+	GinTernaryValue *entryRes;
 	bool		(*boolConsistentFn) (GinScanKey key);
 	GinTernaryValue (*triConsistentFn) (GinScanKey key);
 	FmgrInfo   *consistentFmgrInfo;
-- 
2.9.3

0008-Add-necessary-type-cast.patchtext/x-patch; name=0008-Add-necessary-type-cast.patchDownload
From fc1fc82238496f527e870df489694f2c8e7844bb Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 08/27] Add necessary type cast

---
 src/backend/utils/adt/tsginidx.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/tsginidx.c b/src/backend/utils/adt/tsginidx.c
index c953f53..d4945b0 100644
--- a/src/backend/utils/adt/tsginidx.c
+++ b/src/backend/utils/adt/tsginidx.c
@@ -302,7 +302,7 @@ gin_tsquery_consistent(PG_FUNCTION_ARGS)
 		 * query.
 		 */
 		gcv.first_item = item = GETQUERY(query);
-		gcv.check = check;
+		gcv.check = (GinTernaryValue *) check;
 		gcv.map_item_operand = (int *) (extra_data[0]);
 		gcv.need_recheck = recheck;
 
-- 
2.9.3

0009-Rename-some-typedefs-to-avoid-name-conflicts.patchtext/x-patch; name=0009-Rename-some-typedefs-to-avoid-name-conflicts.patchDownload
From 34a45d8172fb36790523b90a6d7ee238d4adbf8b Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 09/27] Rename some typedefs to avoid name conflicts

C++ does not like that in struct _archiveHandle some of the fields have
the same name as a typedef.  This changes the meaning of the typedef in
the scope of the struct, causing warnings and possibly other problems.

Rename the types so they have names distinct from the struct fields.
---
 src/bin/pg_dump/pg_backup.h          |   4 +-
 src/bin/pg_dump/pg_backup_archiver.c |  10 +--
 src/bin/pg_dump/pg_backup_archiver.h | 114 +++++++++++++++++------------------
 3 files changed, 64 insertions(+), 64 deletions(-)

diff --git a/src/bin/pg_dump/pg_backup.h b/src/bin/pg_dump/pg_backup.h
index 4afa92f..dac8383 100644
--- a/src/bin/pg_dump/pg_backup.h
+++ b/src/bin/pg_dump/pg_backup.h
@@ -221,7 +221,7 @@ typedef int DumpId;
 
 typedef int (*DataDumperPtr) (Archive *AH, void *userArg);
 
-typedef void (*SetupWorkerPtr) (Archive *AH);
+typedef void (*SetupWorkerPtrType) (Archive *AH);
 
 /*
  * Main archiver interface.
@@ -268,7 +268,7 @@ extern Archive *OpenArchive(const char *FileSpec, const ArchiveFormat fmt);
 /* Create a new archive */
 extern Archive *CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
 			  const int compression, ArchiveMode mode,
-			  SetupWorkerPtr setupDumpWorker);
+			  SetupWorkerPtrType setupDumpWorker);
 
 /* The --list option */
 extern void PrintTOCSummary(Archive *AH);
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index 05bdbdb..5a0c1fb 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -56,7 +56,7 @@ static const char *modulename = gettext_noop("archiver");
 
 
 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
-	 const int compression, ArchiveMode mode, SetupWorkerPtr setupWorkerPtr);
+	 const int compression, ArchiveMode mode, SetupWorkerPtrType setupWorkerPtr);
 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
 					  ArchiveHandle *AH);
 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData, bool acl_pass);
@@ -197,7 +197,7 @@ setupRestoreWorker(Archive *AHX)
 /* Public */
 Archive *
 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
-	 const int compression, ArchiveMode mode, SetupWorkerPtr setupDumpWorker)
+	 const int compression, ArchiveMode mode, SetupWorkerPtrType setupDumpWorker)
 
 {
 	ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, mode, setupDumpWorker);
@@ -2217,7 +2217,7 @@ _discoverArchiveFormat(ArchiveHandle *AH)
  */
 static ArchiveHandle *
 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
-	  const int compression, ArchiveMode mode, SetupWorkerPtr setupWorkerPtr)
+	  const int compression, ArchiveMode mode, SetupWorkerPtrType setupWorkerPtr)
 {
 	ArchiveHandle *AH;
 
@@ -2371,8 +2371,8 @@ WriteDataChunks(ArchiveHandle *AH, ParallelState *pstate)
 void
 WriteDataChunksForTocEntry(ArchiveHandle *AH, TocEntry *te)
 {
-	StartDataPtr startPtr;
-	EndDataPtr	endPtr;
+	StartDataPtrType startPtr;
+	EndDataPtrType	endPtr;
 
 	AH->currToc = te;
 
diff --git a/src/bin/pg_dump/pg_backup_archiver.h b/src/bin/pg_dump/pg_backup_archiver.h
index 0376f2b..b33793f 100644
--- a/src/bin/pg_dump/pg_backup_archiver.h
+++ b/src/bin/pg_dump/pg_backup_archiver.h
@@ -136,40 +136,40 @@ typedef enum T_Action
 	ACT_RESTORE
 } T_Action;
 
-typedef void (*ClosePtr) (ArchiveHandle *AH);
-typedef void (*ReopenPtr) (ArchiveHandle *AH);
-typedef void (*ArchiveEntryPtr) (ArchiveHandle *AH, TocEntry *te);
-
-typedef void (*StartDataPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*WriteDataPtr) (ArchiveHandle *AH, const void *data, size_t dLen);
-typedef void (*EndDataPtr) (ArchiveHandle *AH, TocEntry *te);
-
-typedef void (*StartBlobsPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*StartBlobPtr) (ArchiveHandle *AH, TocEntry *te, Oid oid);
-typedef void (*EndBlobPtr) (ArchiveHandle *AH, TocEntry *te, Oid oid);
-typedef void (*EndBlobsPtr) (ArchiveHandle *AH, TocEntry *te);
-
-typedef int (*WriteBytePtr) (ArchiveHandle *AH, const int i);
-typedef int (*ReadBytePtr) (ArchiveHandle *AH);
-typedef void (*WriteBufPtr) (ArchiveHandle *AH, const void *c, size_t len);
-typedef void (*ReadBufPtr) (ArchiveHandle *AH, void *buf, size_t len);
-typedef void (*SaveArchivePtr) (ArchiveHandle *AH);
-typedef void (*WriteExtraTocPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*ReadExtraTocPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*PrintExtraTocPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*PrintTocDataPtr) (ArchiveHandle *AH, TocEntry *te);
-
-typedef void (*ClonePtr) (ArchiveHandle *AH);
-typedef void (*DeClonePtr) (ArchiveHandle *AH);
-
-typedef char *(*WorkerJobRestorePtr) (ArchiveHandle *AH, TocEntry *te);
-typedef char *(*WorkerJobDumpPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef char *(*MasterStartParallelItemPtr) (ArchiveHandle *AH, TocEntry *te,
+typedef void (*ClosePtrType) (ArchiveHandle *AH);
+typedef void (*ReopenPtrType) (ArchiveHandle *AH);
+typedef void (*ArchiveEntryPtrType) (ArchiveHandle *AH, TocEntry *te);
+
+typedef void (*StartDataPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*WriteDataPtrType) (ArchiveHandle *AH, const void *data, size_t dLen);
+typedef void (*EndDataPtrType) (ArchiveHandle *AH, TocEntry *te);
+
+typedef void (*StartBlobsPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*StartBlobPtrType) (ArchiveHandle *AH, TocEntry *te, Oid oid);
+typedef void (*EndBlobPtrType) (ArchiveHandle *AH, TocEntry *te, Oid oid);
+typedef void (*EndBlobsPtrType) (ArchiveHandle *AH, TocEntry *te);
+
+typedef int (*WriteBytePtrType) (ArchiveHandle *AH, const int i);
+typedef int (*ReadBytePtrType) (ArchiveHandle *AH);
+typedef void (*WriteBufPtrType) (ArchiveHandle *AH, const void *c, size_t len);
+typedef void (*ReadBufPtrType) (ArchiveHandle *AH, void *buf, size_t len);
+typedef void (*SaveArchivePtrType) (ArchiveHandle *AH);
+typedef void (*WriteExtraTocPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*ReadExtraTocPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*PrintExtraTocPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*PrintTocDataPtrType) (ArchiveHandle *AH, TocEntry *te);
+
+typedef void (*ClonePtrType) (ArchiveHandle *AH);
+typedef void (*DeClonePtrType) (ArchiveHandle *AH);
+
+typedef char *(*WorkerJobRestorePtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef char *(*WorkerJobDumpPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef char *(*MasterStartParallelItemPtrType) (ArchiveHandle *AH, TocEntry *te,
 														 T_Action act);
-typedef int (*MasterEndParallelItemPtr) (ArchiveHandle *AH, TocEntry *te,
+typedef int (*MasterEndParallelItemPtrType) (ArchiveHandle *AH, TocEntry *te,
 											  const char *str, T_Action act);
 
-typedef size_t (*CustomOutPtr) (ArchiveHandle *AH, const void *buf, size_t len);
+typedef size_t (*CustomOutPtrType) (ArchiveHandle *AH, const void *buf, size_t len);
 
 typedef enum
 {
@@ -242,42 +242,42 @@ struct _archiveHandle
 	size_t		lookaheadLen;	/* Length of data in lookahead */
 	pgoff_t		lookaheadPos;	/* Current read position in lookahead buffer */
 
-	ArchiveEntryPtr ArchiveEntryPtr;	/* Called for each metadata object */
-	StartDataPtr StartDataPtr;	/* Called when table data is about to be
+	ArchiveEntryPtrType ArchiveEntryPtr;	/* Called for each metadata object */
+	StartDataPtrType StartDataPtr;	/* Called when table data is about to be
 								 * dumped */
-	WriteDataPtr WriteDataPtr;	/* Called to send some table data to the
+	WriteDataPtrType WriteDataPtr;	/* Called to send some table data to the
 								 * archive */
-	EndDataPtr EndDataPtr;		/* Called when table data dump is finished */
-	WriteBytePtr WriteBytePtr;	/* Write a byte to output */
-	ReadBytePtr ReadBytePtr;	/* Read a byte from an archive */
-	WriteBufPtr WriteBufPtr;	/* Write a buffer of output to the archive */
-	ReadBufPtr ReadBufPtr;		/* Read a buffer of input from the archive */
-	ClosePtr ClosePtr;			/* Close the archive */
-	ReopenPtr ReopenPtr;		/* Reopen the archive */
-	WriteExtraTocPtr WriteExtraTocPtr;	/* Write extra TOC entry data
+	EndDataPtrType EndDataPtr;		/* Called when table data dump is finished */
+	WriteBytePtrType WriteBytePtr;	/* Write a byte to output */
+	ReadBytePtrType ReadBytePtr;	/* Read a byte from an archive */
+	WriteBufPtrType WriteBufPtr;	/* Write a buffer of output to the archive */
+	ReadBufPtrType ReadBufPtr;		/* Read a buffer of input from the archive */
+	ClosePtrType ClosePtr;			/* Close the archive */
+	ReopenPtrType ReopenPtr;		/* Reopen the archive */
+	WriteExtraTocPtrType WriteExtraTocPtr;	/* Write extra TOC entry data
 										 * associated with the current archive
 										 * format */
-	ReadExtraTocPtr ReadExtraTocPtr;	/* Read extr info associated with
+	ReadExtraTocPtrType ReadExtraTocPtr;	/* Read extr info associated with
 										 * archie format */
-	PrintExtraTocPtr PrintExtraTocPtr;	/* Extra TOC info for format */
-	PrintTocDataPtr PrintTocDataPtr;
+	PrintExtraTocPtrType PrintExtraTocPtr;	/* Extra TOC info for format */
+	PrintTocDataPtrType PrintTocDataPtr;
 
-	StartBlobsPtr StartBlobsPtr;
-	EndBlobsPtr EndBlobsPtr;
-	StartBlobPtr StartBlobPtr;
-	EndBlobPtr EndBlobPtr;
+	StartBlobsPtrType StartBlobsPtr;
+	EndBlobsPtrType EndBlobsPtr;
+	StartBlobPtrType StartBlobPtr;
+	EndBlobPtrType EndBlobPtr;
 
-	MasterStartParallelItemPtr MasterStartParallelItemPtr;
-	MasterEndParallelItemPtr MasterEndParallelItemPtr;
+	MasterStartParallelItemPtrType MasterStartParallelItemPtr;
+	MasterEndParallelItemPtrType MasterEndParallelItemPtr;
 
-	SetupWorkerPtr SetupWorkerPtr;
-	WorkerJobDumpPtr WorkerJobDumpPtr;
-	WorkerJobRestorePtr WorkerJobRestorePtr;
+	SetupWorkerPtrType SetupWorkerPtr;
+	WorkerJobDumpPtrType WorkerJobDumpPtr;
+	WorkerJobRestorePtrType WorkerJobRestorePtr;
 
-	ClonePtr ClonePtr;			/* Clone format-specific fields */
-	DeClonePtr DeClonePtr;		/* Clean up cloned fields */
+	ClonePtrType ClonePtr;			/* Clone format-specific fields */
+	DeClonePtrType DeClonePtr;		/* Clean up cloned fields */
 
-	CustomOutPtr CustomOutPtr;	/* Alternative script output routine */
+	CustomOutPtrType CustomOutPtr;	/* Alternative script output routine */
 
 	/* Stuff for direct DB connection */
 	char	   *archdbname;		/* DB name *read* from archive */
-- 
2.9.3

0010-Reorder-some-things.patchtext/x-patch; name=0010-Reorder-some-things.patchDownload
From c8363af9978e978cb860e0410fe31a39d49a7366 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 10/27] Reorder some things

Forward declarations of static variables are not possible in C++, so
move the full definition before its use.
---
 src/port/pg_crc32c_sb8.c | 136 +++++++++++++++++++++++------------------------
 1 file changed, 67 insertions(+), 69 deletions(-)

diff --git a/src/port/pg_crc32c_sb8.c b/src/port/pg_crc32c_sb8.c
index 2680e36..c7e03e9 100644
--- a/src/port/pg_crc32c_sb8.c
+++ b/src/port/pg_crc32c_sb8.c
@@ -22,8 +22,6 @@
 
 #include "port/pg_crc32c.h"
 
-static const uint32 pg_crc32c_table[8][256];
-
 /* Accumulate one input byte */
 #ifdef WORDS_BIGENDIAN
 #define CRC8(x) pg_crc32c_table[0][((crc >> 24) ^ (x)) & 0xFF] ^ (crc << 8)
@@ -31,73 +29,6 @@ static const uint32 pg_crc32c_table[8][256];
 #define CRC8(x) pg_crc32c_table[0][(crc ^ (x)) & 0xFF] ^ (crc >> 8)
 #endif
 
-pg_crc32c
-pg_comp_crc32c_sb8(pg_crc32c crc, const void *data, size_t len)
-{
-	const unsigned char *p = data;
-	const uint32 *p4;
-
-	/*
-	 * Handle 0-3 initial bytes one at a time, so that the loop below starts
-	 * with a pointer aligned to four bytes.
-	 */
-	while (len > 0 && ((uintptr_t) p & 3))
-	{
-		crc = CRC8(*p++);
-		len--;
-	}
-
-	/*
-	 * Process eight bytes of data at a time.
-	 */
-	p4 = (const uint32 *) p;
-	while (len >= 8)
-	{
-		uint32		a = *p4++ ^ crc;
-		uint32		b = *p4++;
-
-#ifdef WORDS_BIGENDIAN
-		const uint8 c0 = b;
-		const uint8 c1 = b >> 8;
-		const uint8 c2 = b >> 16;
-		const uint8 c3 = b >> 24;
-		const uint8 c4 = a;
-		const uint8 c5 = a >> 8;
-		const uint8 c6 = a >> 16;
-		const uint8 c7 = a >> 24;
-#else
-		const uint8 c0 = b >> 24;
-		const uint8 c1 = b >> 16;
-		const uint8 c2 = b >> 8;
-		const uint8 c3 = b;
-		const uint8 c4 = a >> 24;
-		const uint8 c5 = a >> 16;
-		const uint8 c6 = a >> 8;
-		const uint8 c7 = a;
-#endif
-
-		crc =
-			pg_crc32c_table[0][c0] ^ pg_crc32c_table[1][c1] ^
-			pg_crc32c_table[2][c2] ^ pg_crc32c_table[3][c3] ^
-			pg_crc32c_table[4][c4] ^ pg_crc32c_table[5][c5] ^
-			pg_crc32c_table[6][c6] ^ pg_crc32c_table[7][c7];
-
-		len -= 8;
-	}
-
-	/*
-	 * Handle any remaining bytes one at a time.
-	 */
-	p = (const unsigned char *) p4;
-	while (len > 0)
-	{
-		crc = CRC8(*p++);
-		len--;
-	}
-
-	return crc;
-}
-
 /*
  * Lookup tables for the slicing-by-8 algorithm, for the so-called Castagnoli
  * polynomial (the same that is used e.g. in iSCSI), 0x1EDC6F41. Using
@@ -1167,3 +1098,70 @@ static const uint32 pg_crc32c_table[8][256] = {
 	}
 #endif   /* WORDS_BIGENDIAN */
 };
+
+pg_crc32c
+pg_comp_crc32c_sb8(pg_crc32c crc, const void *data, size_t len)
+{
+	const unsigned char *p = data;
+	const uint32 *p4;
+
+	/*
+	 * Handle 0-3 initial bytes one at a time, so that the loop below starts
+	 * with a pointer aligned to four bytes.
+	 */
+	while (len > 0 && ((uintptr_t) p & 3))
+	{
+		crc = CRC8(*p++);
+		len--;
+	}
+
+	/*
+	 * Process eight bytes of data at a time.
+	 */
+	p4 = (const uint32 *) p;
+	while (len >= 8)
+	{
+		uint32		a = *p4++ ^ crc;
+		uint32		b = *p4++;
+
+#ifdef WORDS_BIGENDIAN
+		const uint8 c0 = b;
+		const uint8 c1 = b >> 8;
+		const uint8 c2 = b >> 16;
+		const uint8 c3 = b >> 24;
+		const uint8 c4 = a;
+		const uint8 c5 = a >> 8;
+		const uint8 c6 = a >> 16;
+		const uint8 c7 = a >> 24;
+#else
+		const uint8 c0 = b >> 24;
+		const uint8 c1 = b >> 16;
+		const uint8 c2 = b >> 8;
+		const uint8 c3 = b;
+		const uint8 c4 = a >> 24;
+		const uint8 c5 = a >> 16;
+		const uint8 c6 = a >> 8;
+		const uint8 c7 = a;
+#endif
+
+		crc =
+			pg_crc32c_table[0][c0] ^ pg_crc32c_table[1][c1] ^
+			pg_crc32c_table[2][c2] ^ pg_crc32c_table[3][c3] ^
+			pg_crc32c_table[4][c4] ^ pg_crc32c_table[5][c5] ^
+			pg_crc32c_table[6][c6] ^ pg_crc32c_table[7][c7];
+
+		len -= 8;
+	}
+
+	/*
+	 * Handle any remaining bytes one at a time.
+	 */
+	p = (const unsigned char *) p4;
+	while (len > 0)
+	{
+		crc = CRC8(*p++);
+		len--;
+	}
+
+	return crc;
+}
-- 
2.9.3

0011-Add-missing-fields-in-struct-initializations.patchtext/x-patch; name=0011-Add-missing-fields-in-struct-initializations.patchDownload
From d37cbfa16ce3676fc0dc5436a135953b963a4caa Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 11/27] Add missing fields in struct initializations

---
 src/bin/psql/tab-complete.c | 64 ++++++++++++++++++++++-----------------------
 1 file changed, 32 insertions(+), 32 deletions(-)

diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index 1345e4e..c5e5dbc 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -884,54 +884,54 @@ typedef struct
 #define THING_NO_SHOW		(THING_NO_CREATE | THING_NO_DROP)
 
 static const pgsql_thing_t words_after_create[] = {
-	{"ACCESS METHOD", NULL, NULL},
-	{"AGGREGATE", NULL, &Query_for_list_of_aggregates},
-	{"CAST", NULL, NULL},		/* Casts have complex structures for names, so
+	{"ACCESS METHOD", NULL, NULL, 0},
+	{"AGGREGATE", NULL, &Query_for_list_of_aggregates, 0},
+	{"CAST", NULL, NULL, 0},	/* Casts have complex structures for names, so
 								 * skip it */
-	{"COLLATION", "SELECT pg_catalog.quote_ident(collname) FROM pg_catalog.pg_collation WHERE collencoding IN (-1, pg_catalog.pg_char_to_encoding(pg_catalog.getdatabaseencoding())) AND substring(pg_catalog.quote_ident(collname),1,%d)='%s'"},
+	{"COLLATION", "SELECT pg_catalog.quote_ident(collname) FROM pg_catalog.pg_collation WHERE collencoding IN (-1, pg_catalog.pg_char_to_encoding(pg_catalog.getdatabaseencoding())) AND substring(pg_catalog.quote_ident(collname),1,%d)='%s'", NULL, 0},
 
 	/*
 	 * CREATE CONSTRAINT TRIGGER is not supported here because it is designed
 	 * to be used only by pg_dump.
 	 */
 	{"CONFIGURATION", Query_for_list_of_ts_configurations, NULL, THING_NO_SHOW},
-	{"CONVERSION", "SELECT pg_catalog.quote_ident(conname) FROM pg_catalog.pg_conversion WHERE substring(pg_catalog.quote_ident(conname),1,%d)='%s'"},
-	{"DATABASE", Query_for_list_of_databases},
+	{"CONVERSION", "SELECT pg_catalog.quote_ident(conname) FROM pg_catalog.pg_conversion WHERE substring(pg_catalog.quote_ident(conname),1,%d)='%s'", NULL, 0},
+	{"DATABASE", Query_for_list_of_databases, NULL, 0},
 	{"DICTIONARY", Query_for_list_of_ts_dictionaries, NULL, THING_NO_SHOW},
-	{"DOMAIN", NULL, &Query_for_list_of_domains},
-	{"EVENT TRIGGER", NULL, NULL},
-	{"EXTENSION", Query_for_list_of_extensions},
-	{"FOREIGN DATA WRAPPER", NULL, NULL},
-	{"FOREIGN TABLE", NULL, NULL},
-	{"FUNCTION", NULL, &Query_for_list_of_functions},
-	{"GROUP", Query_for_list_of_roles},
-	{"LANGUAGE", Query_for_list_of_languages},
-	{"INDEX", NULL, &Query_for_list_of_indexes},
-	{"MATERIALIZED VIEW", NULL, &Query_for_list_of_matviews},
-	{"OPERATOR", NULL, NULL},	/* Querying for this is probably not such a
+	{"DOMAIN", NULL, &Query_for_list_of_domains, 0},
+	{"EVENT TRIGGER", NULL, NULL, 0},
+	{"EXTENSION", Query_for_list_of_extensions, NULL, 0},
+	{"FOREIGN DATA WRAPPER", NULL, NULL, 0},
+	{"FOREIGN TABLE", NULL, NULL, 0},
+	{"FUNCTION", NULL, &Query_for_list_of_functions, 0},
+	{"GROUP", Query_for_list_of_roles, NULL, 0},
+	{"LANGUAGE", Query_for_list_of_languages, NULL, 0},
+	{"INDEX", NULL, &Query_for_list_of_indexes, 0},
+	{"MATERIALIZED VIEW", NULL, &Query_for_list_of_matviews, 0},
+	{"OPERATOR", NULL, NULL, 0},/* Querying for this is probably not such a
 								 * good idea. */
 	{"OWNED", NULL, NULL, THING_NO_CREATE},		/* for DROP OWNED BY ... */
 	{"PARSER", Query_for_list_of_ts_parsers, NULL, THING_NO_SHOW},
-	{"POLICY", NULL, NULL},
-	{"ROLE", Query_for_list_of_roles},
-	{"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'"},
-	{"SCHEMA", Query_for_list_of_schemas},
-	{"SEQUENCE", NULL, &Query_for_list_of_sequences},
-	{"SERVER", Query_for_list_of_servers},
-	{"TABLE", NULL, &Query_for_list_of_tables},
-	{"TABLESPACE", Query_for_list_of_tablespaces},
+	{"POLICY", NULL, NULL, 0},
+	{"ROLE", Query_for_list_of_roles, NULL, 0},
+	{"RULE", "SELECT pg_catalog.quote_ident(rulename) FROM pg_catalog.pg_rules WHERE substring(pg_catalog.quote_ident(rulename),1,%d)='%s'", NULL, 0},
+	{"SCHEMA", Query_for_list_of_schemas, NULL, 0},
+	{"SEQUENCE", NULL, &Query_for_list_of_sequences, 0},
+	{"SERVER", Query_for_list_of_servers, NULL, 0},
+	{"TABLE", NULL, &Query_for_list_of_tables, 0},
+	{"TABLESPACE", Query_for_list_of_tablespaces, NULL, 0},
 	{"TEMP", NULL, NULL, THING_NO_DROP},		/* for CREATE TEMP TABLE ... */
 	{"TEMPLATE", Query_for_list_of_ts_templates, NULL, THING_NO_SHOW},
-	{"TEXT SEARCH", NULL, NULL},
-	{"TRIGGER", "SELECT pg_catalog.quote_ident(tgname) FROM pg_catalog.pg_trigger WHERE substring(pg_catalog.quote_ident(tgname),1,%d)='%s' AND NOT tgisinternal"},
-	{"TYPE", NULL, &Query_for_list_of_datatypes},
+	{"TEXT SEARCH", NULL, NULL, 0},
+	{"TRIGGER", "SELECT pg_catalog.quote_ident(tgname) FROM pg_catalog.pg_trigger WHERE substring(pg_catalog.quote_ident(tgname),1,%d)='%s' AND NOT tgisinternal", NULL, 0},
+	{"TYPE", NULL, &Query_for_list_of_datatypes, 0},
 	{"UNIQUE", NULL, NULL, THING_NO_DROP},		/* for CREATE UNIQUE INDEX ... */
 	{"UNLOGGED", NULL, NULL, THING_NO_DROP},	/* for CREATE UNLOGGED TABLE
 												 * ... */
-	{"USER", Query_for_list_of_roles},
-	{"USER MAPPING FOR", NULL, NULL},
-	{"VIEW", NULL, &Query_for_list_of_views},
-	{NULL}						/* end of list */
+	{"USER", Query_for_list_of_roles, NULL, 0},
+	{"USER MAPPING FOR", NULL, NULL, 0},
+	{"VIEW", NULL, &Query_for_list_of_views, 0},
+	{NULL, NULL, NULL, 0}						/* end of list */
 };
 
 
-- 
2.9.3

0012-Separate-enum-from-struct.patchtext/x-patch; name=0012-Separate-enum-from-struct.patchDownload
From 9dfb2949af5c764bcf553ded32c827dbb9b5eba6 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 12/27] Separate enum from struct

Otherwise the enum symbols are not visible outside the struct in C++.
---
 src/include/utils/jsonb.h | 28 +++++++++++++++-------------
 1 file changed, 15 insertions(+), 13 deletions(-)

diff --git a/src/include/utils/jsonb.h b/src/include/utils/jsonb.h
index fa52afc..48ca9dc 100644
--- a/src/include/utils/jsonb.h
+++ b/src/include/utils/jsonb.h
@@ -219,6 +219,20 @@ typedef struct
 #define JB_ROOT_IS_ARRAY(jbp_)	( *(uint32*) VARDATA(jbp_) & JB_FARRAY)
 
 
+enum jbvType
+{
+	/* Scalar types */
+	jbvNull = 0x0,
+	jbvString,
+	jbvNumeric,
+	jbvBool,
+	/* Composite types */
+	jbvArray = 0x10,
+	jbvObject,
+	/* Binary (i.e. struct Jsonb) jbvArray/jbvObject */
+	jbvBinary
+};
+
 /*
  * JsonbValue:	In-memory representation of Jsonb.  This is a convenient
  * deserialized representation, that can easily support using the "val"
@@ -227,19 +241,7 @@ typedef struct
  */
 struct JsonbValue
 {
-	enum
-	{
-		/* Scalar types */
-		jbvNull = 0x0,
-		jbvString,
-		jbvNumeric,
-		jbvBool,
-		/* Composite types */
-		jbvArray = 0x10,
-		jbvObject,
-		/* Binary (i.e. struct Jsonb) jbvArray/jbvObject */
-		jbvBinary
-	}			type;			/* Influences sort order */
+	jbvType		type;			/* Influences sort order */
 
 	union
 	{
-- 
2.9.3

0013-Avoid-C-key-words.patchtext/x-patch; name=0013-Avoid-C-key-words.patchDownload
From 5f83d64832d71fe271b8f27898b33e83c8cee4b8 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 13/27] Avoid C++ key words

This is not a long-term solution, because C header files that are
included somewhere might have C++ awareness and will break if the key
word is defined away.  But this shows the list of words that would have
to be renamed around the code.
---
 src/include/c.h                                  | 16 ++++++++++++++++
 src/interfaces/ecpg/include/ecpg-pthread-win32.h |  2 ++
 src/interfaces/libpq/libpq-int.h                 |  2 ++
 src/pl/plperl/plperl.h                           |  2 ++
 4 files changed, 22 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index 4ab3f80..a9515d1 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -45,6 +45,22 @@
 #ifndef C_H
 #define C_H
 
+#ifdef __cplusplus
+#define class class_
+#define constexpr constexpr_
+#define delete delete_
+#define friend friend_
+#define namespace namespace_
+#define new new_
+#define operator operator_
+#define private private_
+#define public public_
+#define template template_
+#define this this_
+#define typeid typeid_
+#define typename typename_
+#endif
+
 #include "postgres_ext.h"
 
 /* Must undef pg_config_ext.h symbols before including pg_config.h */
diff --git a/src/interfaces/ecpg/include/ecpg-pthread-win32.h b/src/interfaces/ecpg/include/ecpg-pthread-win32.h
index 7e59357..505838f 100644
--- a/src/interfaces/ecpg/include/ecpg-pthread-win32.h
+++ b/src/interfaces/ecpg/include/ecpg-pthread-win32.h
@@ -9,6 +9,8 @@
 
 #ifndef WIN32
 
+#undef class
+#undef public
 #include <pthread.h>
 #else
 
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index a94ead0..b2f2d74 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -34,6 +34,8 @@
 #ifdef WIN32
 #include "pthread-win32.h"
 #else
+#undef class
+#undef public
 #include <pthread.h>
 #endif
 #include <signal.h>
diff --git a/src/pl/plperl/plperl.h b/src/pl/plperl/plperl.h
index 0146d60..1ed68a4 100644
--- a/src/pl/plperl/plperl.h
+++ b/src/pl/plperl/plperl.h
@@ -43,6 +43,8 @@
 #endif
 
 
+#undef class
+#undef public
 /* required for perl API */
 #include "EXTERN.h"
 #include "perl.h"
-- 
2.9.3

0014-Set-up-for-static-asserts-in-C.patchtext/x-patch; name=0014-Set-up-for-static-asserts-in-C.patchDownload
From dc0be2c9b096545d7f95bf44336a9e92715c629c Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 14/27] Set up for static asserts in C++

This doesn't appear to work yet.  It might need a really new compiler.
---
 src/include/c.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index a9515d1..cbefc47 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -756,14 +756,26 @@ typedef NameData *Name;
  * about a negative width for a struct bit-field.  This will not include a
  * helpful error message, but it beats not getting an error at all.
  */
+#ifdef __cplusplus
+#if __cpp_static_assert >= 201411
+#define _Static_assert(condition, errmessage) static_assert(condition, errmessage)
+#define HAVE__STATIC_ASSERT 1
+#endif
+#endif
+
 #ifdef HAVE__STATIC_ASSERT
 #define StaticAssertStmt(condition, errmessage) \
 	do { _Static_assert(condition, errmessage); } while(0)
 #define StaticAssertExpr(condition, errmessage) \
 	({ StaticAssertStmt(condition, errmessage); true; })
 #else							/* !HAVE__STATIC_ASSERT */
+#ifdef __cplusplus
+#define  StaticAssertStmt(condition, errmessage) \
+	((void) 0)
+#else
 #define StaticAssertStmt(condition, errmessage) \
 	((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
+#endif
 #define StaticAssertExpr(condition, errmessage) \
 	StaticAssertStmt(condition, errmessage)
 #endif   /* HAVE__STATIC_ASSERT */
-- 
2.9.3

0015-Fix-function-prototypes-for-C.patchtext/x-patch; name=0015-Fix-function-prototypes-for-C.patchDownload
From b8eb3e6c31d50f1e2d14e0f4996cc58debdc6aac Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 15/27] Fix function prototypes for C++

C++ needs to have the right number of arguments in function signatures.
---
 src/backend/nodes/nodeFuncs.c | 28 ++++++++++++++--------------
 src/include/nodes/nodeFuncs.h | 20 ++++++++++----------
 2 files changed, 24 insertions(+), 24 deletions(-)

diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 3997441..311b86d 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -28,10 +28,10 @@
 static bool expression_returns_set_walker(Node *node, void *context);
 static int	leftmostLoc(int loc1, int loc2);
 static bool fix_opfuncids_walker(Node *node, void *context);
-static bool planstate_walk_subplans(List *plans, bool (*walker) (),
+static bool planstate_walk_subplans(List *plans, bool (*walker) (void *, void *),
 												void *context);
 static bool planstate_walk_members(List *plans, PlanState **planstates,
-					   bool (*walker) (), void *context);
+								   bool (*walker) (void *, void *), void *context);
 
 
 /*
@@ -1849,7 +1849,7 @@ check_functions_in_node(Node *node, check_function_callback checker,
 
 bool
 expression_tree_walker(Node *node,
-					   bool (*walker) (),
+					   bool (*walker) (void *, void *),
 					   void *context)
 {
 	ListCell   *temp;
@@ -2236,7 +2236,7 @@ expression_tree_walker(Node *node,
  */
 bool
 query_tree_walker(Query *query,
-				  bool (*walker) (),
+				  bool (*walker) (void *, void *),
 				  void *context,
 				  int flags)
 {
@@ -2280,7 +2280,7 @@ query_tree_walker(Query *query,
  */
 bool
 range_table_walker(List *rtable,
-				   bool (*walker) (),
+				   bool (*walker) (void *, void *),
 				   void *context,
 				   int flags)
 {
@@ -2395,7 +2395,7 @@ range_table_walker(List *rtable,
 
 Node *
 expression_tree_mutator(Node *node,
-						Node *(*mutator) (),
+						Node *(*mutator) (void *, void *),
 						void *context)
 {
 	/*
@@ -3038,7 +3038,7 @@ expression_tree_mutator(Node *node,
  */
 Query *
 query_tree_mutator(Query *query,
-				   Node *(*mutator) (),
+				   Node *(*mutator) (void *, void *),
 				   void *context,
 				   int flags)
 {
@@ -3077,7 +3077,7 @@ query_tree_mutator(Query *query,
  */
 List *
 range_table_mutator(List *rtable,
-					Node *(*mutator) (),
+					Node *(*mutator) (void *, void *),
 					void *context,
 					int flags)
 {
@@ -3144,7 +3144,7 @@ range_table_mutator(List *rtable,
  */
 bool
 query_or_expression_tree_walker(Node *node,
-								bool (*walker) (),
+								bool (*walker) (void *, void *),
 								void *context,
 								int flags)
 {
@@ -3167,7 +3167,7 @@ query_or_expression_tree_walker(Node *node,
  */
 Node *
 query_or_expression_tree_mutator(Node *node,
-								 Node *(*mutator) (),
+								 Node *(*mutator) (void *, void *),
 								 void *context,
 								 int flags)
 {
@@ -3198,7 +3198,7 @@ query_or_expression_tree_mutator(Node *node,
  */
 bool
 raw_expression_tree_walker(Node *node,
-						   bool (*walker) (),
+						   bool (*walker) (void *, void *),
 						   void *context)
 {
 	ListCell   *temp;
@@ -3638,7 +3638,7 @@ raw_expression_tree_walker(Node *node,
  */
 bool
 planstate_tree_walker(PlanState *planstate,
-					  bool (*walker) (),
+					  bool (*walker) (void *, void *),
 					  void *context)
 {
 	Plan	   *plan = planstate->plan;
@@ -3722,7 +3722,7 @@ planstate_tree_walker(PlanState *planstate,
  */
 static bool
 planstate_walk_subplans(List *plans,
-						bool (*walker) (),
+						bool (*walker) (void *, void *),
 						void *context)
 {
 	ListCell   *lc;
@@ -3748,7 +3748,7 @@ planstate_walk_subplans(List *plans,
  */
 static bool
 planstate_walk_members(List *plans, PlanState **planstates,
-					   bool (*walker) (), void *context)
+					   bool (*walker) (void *, void *), void *context)
 {
 	int			nplans = list_length(plans);
 	int			j;
diff --git a/src/include/nodes/nodeFuncs.h b/src/include/nodes/nodeFuncs.h
index 97af142..82add17 100644
--- a/src/include/nodes/nodeFuncs.h
+++ b/src/include/nodes/nodeFuncs.h
@@ -50,31 +50,31 @@ extern void set_sa_opfuncid(ScalarArrayOpExpr *opexpr);
 extern bool check_functions_in_node(Node *node, check_function_callback checker,
 						void *context);
 
-extern bool expression_tree_walker(Node *node, bool (*walker) (),
+extern bool expression_tree_walker(Node *node, bool (*walker) (void *, void *),
 											   void *context);
-extern Node *expression_tree_mutator(Node *node, Node *(*mutator) (),
+extern Node *expression_tree_mutator(Node *node, Node *(*mutator) (void *, void *),
 												 void *context);
 
-extern bool query_tree_walker(Query *query, bool (*walker) (),
+extern bool query_tree_walker(Query *query, bool (*walker) (void *, void *),
 										  void *context, int flags);
-extern Query *query_tree_mutator(Query *query, Node *(*mutator) (),
+extern Query *query_tree_mutator(Query *query, Node *(*mutator) (void *, void *),
 											 void *context, int flags);
 
-extern bool range_table_walker(List *rtable, bool (*walker) (),
+extern bool range_table_walker(List *rtable, bool (*walker) (void *, void *),
 										   void *context, int flags);
-extern List *range_table_mutator(List *rtable, Node *(*mutator) (),
+extern List *range_table_mutator(List *rtable, Node *(*mutator) (void *, void *),
 											 void *context, int flags);
 
-extern bool query_or_expression_tree_walker(Node *node, bool (*walker) (),
+extern bool query_or_expression_tree_walker(Node *node, bool (*walker) (void *, void *),
 												   void *context, int flags);
-extern Node *query_or_expression_tree_mutator(Node *node, Node *(*mutator) (),
+extern Node *query_or_expression_tree_mutator(Node *node, Node *(*mutator) (void *, void *),
 												   void *context, int flags);
 
-extern bool raw_expression_tree_walker(Node *node, bool (*walker) (),
+extern bool raw_expression_tree_walker(Node *node, bool (*walker) (void *, void *),
 												   void *context);
 
 struct PlanState;
-extern bool planstate_tree_walker(struct PlanState *planstate, bool (*walker) (),
+extern bool planstate_tree_walker(struct PlanState *planstate, bool (*walker) (void *, void *),
 											  void *context);
 
 #endif   /* NODEFUNCS_H */
-- 
2.9.3

0016-Fix-fmgr_oldstyle-for-C.patchtext/x-patch; name=0016-Fix-fmgr_oldstyle-for-C.patchDownload
From 4cbdafcc7a7979b9eeea1ce0def9f528e6125d49 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 16/27] Fix fmgr_oldstyle for C++

C++ needs the function pointer to have the right number of arguments, so
some casts are needed here.
---
 src/backend/utils/fmgr/fmgr.c | 56 ++++++++++++++++++++++++++++---------------
 1 file changed, 37 insertions(+), 19 deletions(-)

diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c
index 7e6a60d..1da553b 100644
--- a/src/backend/utils/fmgr/fmgr.c
+++ b/src/backend/utils/fmgr/fmgr.c
@@ -53,11 +53,29 @@ PGDLLIMPORT fmgr_hook_type fmgr_hook = NULL;
  * with suitably ugly casts in fmgr_oldstyle().
  */
 #if (defined(__mc68000__) || (defined(__m68k__))) && defined(__ELF__)
-typedef int32 (*func_ptr) ();
+#define func_ptr_ret int32
 #else
-typedef char *(*func_ptr) ();
+#define func_ptr_ret char*
 #endif
 
+typedef func_ptr_ret (*func_ptr) ();
+typedef func_ptr_ret (*func1_ptr) (Datum, bool);
+typedef func_ptr_ret (*func2_ptr) (Datum, Datum);
+typedef func_ptr_ret (*func3_ptr) (Datum, Datum, Datum);
+typedef func_ptr_ret (*func4_ptr) (Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func5_ptr) (Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func6_ptr) (Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func7_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func8_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func9_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func10_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func11_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func12_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func13_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func14_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func15_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func16_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+
 /*
  * For an oldstyle function, fn_extra points to a record like this:
  */
@@ -658,7 +676,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 	switch (n_arguments)
 	{
 		case 0:
-			returnValue = (char *) (*user_fn) ();
+			returnValue = (char *) (user_fn) ();
 			break;
 		case 1:
 
@@ -667,33 +685,33 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 			 * there are other functions still out there that also rely on
 			 * this undocumented hack?
 			 */
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func1_ptr) user_fn) (fcinfo->arg[0],
 											   &fcinfo->isnull);
 			break;
 		case 2:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func2_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1]);
 			break;
 		case 3:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func3_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2]);
 			break;
 		case 4:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func4_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3]);
 			break;
 		case 5:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func5_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
 											   fcinfo->arg[4]);
 			break;
 		case 6:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func6_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -701,7 +719,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[5]);
 			break;
 		case 7:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func7_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -710,7 +728,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[6]);
 			break;
 		case 8:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func8_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -720,7 +738,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[7]);
 			break;
 		case 9:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func9_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -731,7 +749,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[8]);
 			break;
 		case 10:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func10_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -743,7 +761,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[9]);
 			break;
 		case 11:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func11_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -756,7 +774,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[10]);
 			break;
 		case 12:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func12_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -770,7 +788,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[11]);
 			break;
 		case 13:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func13_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -785,7 +803,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[12]);
 			break;
 		case 14:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func14_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -801,7 +819,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[13]);
 			break;
 		case 15:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func15_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -818,7 +836,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[14]);
 			break;
 		case 16:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func16_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
-- 
2.9.3

0017-Don-t-define-bool-in-C.patchtext/x-patch; name=0017-Don-t-define-bool-in-C.patchDownload
From f75db7835d76456a4152aa12a8878c8f5ba47662 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 17/27] Don't define bool in C++

---
 src/test/thread/thread_test.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/test/thread/thread_test.c b/src/test/thread/thread_test.c
index 26d1949..d7cf5ef 100644
--- a/src/test/thread/thread_test.c
+++ b/src/test/thread/thread_test.c
@@ -24,6 +24,8 @@
 #include "postgres.h"
 #else
 /* From src/include/c.h" */
+#ifndef __cplusplus
+
 #ifndef bool
 typedef char bool;
 #endif
@@ -37,6 +39,8 @@ typedef char bool;
 #endif
 #endif
 
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
-- 
2.9.3

0018-Change-TimeoutId-from-enum-to-integer.patchtext/x-patch; name=0018-Change-TimeoutId-from-enum-to-integer.patchDownload
From de2fa8c6ecd92449c893db07dc3458a713c2269d Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 18/27] Change TimeoutId from enum to integer

RegisterTimeout() treats it like an integer.  C++ doesn't like enums to
be treated that way.
---
 src/include/utils/timeout.h | 25 ++++++++++++-------------
 1 file changed, 12 insertions(+), 13 deletions(-)

diff --git a/src/include/utils/timeout.h b/src/include/utils/timeout.h
index 260c013..15a0f09 100644
--- a/src/include/utils/timeout.h
+++ b/src/include/utils/timeout.h
@@ -20,22 +20,21 @@
  * Identifiers for timeout reasons.  Note that in case multiple timeouts
  * trigger at the same time, they are serviced in the order of this enum.
  */
-typedef enum TimeoutId
-{
+typedef int TimeoutId;
+
 	/* Predefined timeout reasons */
-	STARTUP_PACKET_TIMEOUT,
-	DEADLOCK_TIMEOUT,
-	LOCK_TIMEOUT,
-	STATEMENT_TIMEOUT,
-	STANDBY_DEADLOCK_TIMEOUT,
-	STANDBY_TIMEOUT,
-	STANDBY_LOCK_TIMEOUT,
-	IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
+const int STARTUP_PACKET_TIMEOUT = 1;
+const int DEADLOCK_TIMEOUT = 2;
+const int LOCK_TIMEOUT = 3;
+const int STATEMENT_TIMEOUT = 4;
+const int STANDBY_DEADLOCK_TIMEOUT = 5;
+const int STANDBY_TIMEOUT = 6;
+const int STANDBY_LOCK_TIMEOUT = 7;
+const int IDLE_IN_TRANSACTION_SESSION_TIMEOUT = 8;
 	/* First user-definable timeout reason */
-	USER_TIMEOUT,
+const int USER_TIMEOUT = 9;
 	/* Maximum number of timeout reasons */
-	MAX_TIMEOUTS = 16
-} TimeoutId;
+const int MAX_TIMEOUTS = 16;
 
 /* callback function signature */
 typedef void (*timeout_handler_proc) (void);
-- 
2.9.3

0019-Add-explicit-cast-for-casting-away-volatile.patchtext/x-patch; name=0019-Add-explicit-cast-for-casting-away-volatile.patchDownload
From a8f8b2ea81f0364cc31d125800b705c701a9105f Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 19/27] Add explicit cast for casting away volatile

---
 contrib/pg_stat_statements/pg_stat_statements.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 8ce24e0..37aac98 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -1547,7 +1547,7 @@ pg_stat_statements_internal(FunctionCallInfo fcinfo,
 			volatile pgssEntry *e = (volatile pgssEntry *) entry;
 
 			SpinLockAcquire(&e->mutex);
-			tmp = e->counters;
+			tmp = const_cast<pgssEntry *>(e)->counters;
 			SpinLockRelease(&e->mutex);
 		}
 
-- 
2.9.3

0020-Add-more-extern-key-words.patchtext/x-patch; name=0020-Add-more-extern-key-words.patchDownload
From 42c4728e8cc0937485e4d3957d1768d6b6736e7d Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 20/27] Add more extern key words

C++ needs those to make the definitions visible externally.  This is not
compatible with C.
---
 src/backend/access/rmgrdesc/xlogdesc.c | 2 +-
 src/backend/access/transam/xlog.c      | 4 ++--
 src/backend/storage/ipc/dsm_impl.c     | 2 +-
 3 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index 62ed1dc..d3ea5e6 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -23,7 +23,7 @@
 /*
  * GUC support
  */
-const struct config_enum_entry wal_level_options[] = {
+extern const struct config_enum_entry wal_level_options[] = {
 	{"minimal", WAL_LEVEL_MINIMAL, false},
 	{"replica", WAL_LEVEL_REPLICA, false},
 	{"archive", WAL_LEVEL_REPLICA, true},		/* deprecated */
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index acd95aa..6732151 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -125,7 +125,7 @@ static double PrevCheckPointDistance = 0;
 /*
  * GUC support
  */
-const struct config_enum_entry sync_method_options[] = {
+extern const struct config_enum_entry sync_method_options[] = {
 	{"fsync", SYNC_METHOD_FSYNC, false},
 #ifdef HAVE_FSYNC_WRITETHROUGH
 	{"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
@@ -147,7 +147,7 @@ const struct config_enum_entry sync_method_options[] = {
  * Although only "on", "off", and "always" are documented,
  * we accept all the likely variants of "on" and "off".
  */
-const struct config_enum_entry archive_mode_options[] = {
+extern const struct config_enum_entry archive_mode_options[] = {
 	{"always", ARCHIVE_MODE_ALWAYS, false},
 	{"on", ARCHIVE_MODE_ON, false},
 	{"off", ARCHIVE_MODE_OFF, false},
diff --git a/src/backend/storage/ipc/dsm_impl.c b/src/backend/storage/ipc/dsm_impl.c
index c07a5c6..3b6a710 100644
--- a/src/backend/storage/ipc/dsm_impl.c
+++ b/src/backend/storage/ipc/dsm_impl.c
@@ -91,7 +91,7 @@ static bool dsm_impl_mmap(dsm_op op, dsm_handle handle, Size request_size,
 #endif
 static int	errcode_for_dynamic_shared_memory(void);
 
-const struct config_enum_entry dynamic_shared_memory_options[] = {
+extern const struct config_enum_entry dynamic_shared_memory_options[] = {
 #ifdef USE_DSM_POSIX
 	{"posix", DSM_IMPL_POSIX, false},
 #endif
-- 
2.9.3

0021-Workaround-for-using-typdef-ed-ints-in-loops.patchtext/x-patch; name=0021-Workaround-for-using-typdef-ed-ints-in-loops.patchDownload
From c420d60d7e54f3e7799a15210413f34eb133de95 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 21/27] Workaround for using typdef'ed ints in loops

Types made from int don't have a ++ operator in C++, so they can't be
used in for loops without further work.

Needs more research
---
 src/backend/access/transam/xact.c | 4 ++--
 src/backend/commands/tablecmds.c  | 2 +-
 src/backend/storage/smgr/md.c     | 8 ++++----
 src/backend/storage/smgr/smgr.c   | 6 +++---
 src/backend/utils/adt/dbsize.c    | 6 +++---
 src/bin/pgbench/pgbench.c         | 5 ++++-
 src/common/relpath.c              | 4 ++--
 7 files changed, 19 insertions(+), 16 deletions(-)

diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index e11b229..6fd16e7 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -5456,7 +5456,7 @@ xact_redo_commit(xl_xact_parsed_commit *parsed,
 		for (i = 0; i < parsed->nrels; i++)
 		{
 			SMgrRelation srel = smgropen(parsed->xnodes[i], InvalidBackendId);
-			ForkNumber	fork;
+			int			fork;
 
 			for (fork = 0; fork <= MAX_FORKNUM; fork++)
 				XLogDropRelation(parsed->xnodes[i], fork);
@@ -5566,7 +5566,7 @@ xact_redo_abort(xl_xact_parsed_abort *parsed, TransactionId xid)
 	for (i = 0; i < parsed->nrels; i++)
 	{
 		SMgrRelation srel = smgropen(parsed->xnodes[i], InvalidBackendId);
-		ForkNumber	fork;
+		int			fork;
 
 		for (fork = 0; fork <= MAX_FORKNUM; fork++)
 			XLogDropRelation(parsed->xnodes[i], fork);
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 86e9814..d10d8bc 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -9557,7 +9557,7 @@ ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
 	Relation	pg_class;
 	HeapTuple	tuple;
 	Form_pg_class rd_rel;
-	ForkNumber	forkNum;
+	int			forkNum;
 	List	   *reltoastidxids = NIL;
 	ListCell   *lc;
 
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 1287142..21bc909 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -400,7 +400,7 @@ mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
 	/* Now do the per-fork work */
 	if (forkNum == InvalidForkNumber)
 	{
-		for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
+		for (int forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
 			mdunlinkfork(rnode, forkNum, isRedo);
 	}
 	else
@@ -1127,7 +1127,7 @@ mdsync(void)
 	hash_seq_init(&hstat, pendingOpsTable);
 	while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
 	{
-		ForkNumber	forknum;
+		int		forknum;
 
 		/*
 		 * If the entry is new then don't process it this time; it might
@@ -1532,7 +1532,7 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
 			if (forknum == InvalidForkNumber)
 			{
 				/* remove requests for all forks */
-				for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
+				for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
 				{
 					bms_free(entry->requests[forknum]);
 					entry->requests[forknum] = NULL;
@@ -1564,7 +1564,7 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
 			if (entry->rnode.dbNode == rnode.dbNode)
 			{
 				/* remove requests for all forks */
-				for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
+				for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
 				{
 					bms_free(entry->requests[forknum]);
 					entry->requests[forknum] = NULL;
diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c
index 94aa952..73eb118 100644
--- a/src/backend/storage/smgr/smgr.c
+++ b/src/backend/storage/smgr/smgr.c
@@ -296,7 +296,7 @@ void
 smgrclose(SMgrRelation reln)
 {
 	SMgrRelation *owner;
-	ForkNumber	forknum;
+	int			forknum;
 
 	for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
 		(*(smgrsw[reln->smgr_which].smgr_close)) (reln, forknum);
@@ -415,7 +415,7 @@ smgrdounlink(SMgrRelation reln, bool isRedo)
 {
 	RelFileNodeBackend rnode = reln->smgr_rnode;
 	int			which = reln->smgr_which;
-	ForkNumber	forknum;
+	int			forknum;
 
 	/* Close the forks at smgr level */
 	for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
@@ -472,7 +472,7 @@ smgrdounlinkall(SMgrRelation *rels, int nrels, bool isRedo)
 {
 	int			i = 0;
 	RelFileNodeBackend *rnodes;
-	ForkNumber	forknum;
+	int			forknum;
 
 	if (nrels == 0)
 		return;
diff --git a/src/backend/utils/adt/dbsize.c b/src/backend/utils/adt/dbsize.c
index 3167bad..dd43033 100644
--- a/src/backend/utils/adt/dbsize.c
+++ b/src/backend/utils/adt/dbsize.c
@@ -342,7 +342,7 @@ calculate_toast_table_size(Oid toastrelid)
 {
 	int64		size = 0;
 	Relation	toastRel;
-	ForkNumber	forkNum;
+	int			forkNum;
 	ListCell   *lc;
 	List	   *indexlist;
 
@@ -387,7 +387,7 @@ static int64
 calculate_table_size(Relation rel)
 {
 	int64		size = 0;
-	ForkNumber	forkNum;
+	int			forkNum;
 
 	/*
 	 * heap size, including FSM and VM
@@ -427,7 +427,7 @@ calculate_indexes_size(Relation rel)
 		{
 			Oid			idxOid = lfirst_oid(cell);
 			Relation	idxRel;
-			ForkNumber	forkNum;
+			int			forkNum;
 
 			idxRel = relation_open(idxOid, AccessShareLock);
 
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 8027955..78c3872 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -3655,9 +3655,12 @@ main(int argc, char **argv)
 					fprintf(stderr, "query mode (-M) should be specified before any transaction scripts (-f or -b)\n");
 					exit(1);
 				}
-				for (querymode = 0; querymode < NUM_QUERYMODE; querymode++)
+				for (int qm = 0; qm < NUM_QUERYMODE; qm++)
 					if (strcmp(optarg, QUERYMODE[querymode]) == 0)
+					{
+						querymode = qm;
 						break;
+					}
 				if (querymode >= NUM_QUERYMODE)
 				{
 					fprintf(stderr, "invalid query mode (-M): \"%s\"\n",
diff --git a/src/common/relpath.c b/src/common/relpath.c
index 1aacb81..8bb918a 100644
--- a/src/common/relpath.c
+++ b/src/common/relpath.c
@@ -47,7 +47,7 @@ const char *const forkNames[] = {
 ForkNumber
 forkname_to_number(const char *forkName)
 {
-	ForkNumber	forkNum;
+	int		forkNum;
 
 	for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
 		if (strcmp(forkNames[forkNum], forkName) == 0)
@@ -78,7 +78,7 @@ forkname_to_number(const char *forkName)
 int
 forkname_chars(const char *str, ForkNumber *fork)
 {
-	ForkNumber	forkNum;
+	int			forkNum;
 
 	for (forkNum = 1; forkNum <= MAX_FORKNUM; forkNum++)
 	{
-- 
2.9.3

0022-Disable-conflicting-function.patchtext/x-patch; name=0022-Disable-conflicting-function.patchDownload
From 75495adef7bc6e3fe01e7b859a353efd5174cb4a Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 22/27] Disable conflicting function

This function conflicts with a function in the backend.  FIXME
---
 contrib/xml2/xpath.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/contrib/xml2/xpath.c b/contrib/xml2/xpath.c
index ac28996..d654884 100644
--- a/contrib/xml2/xpath.c
+++ b/contrib/xml2/xpath.c
@@ -90,6 +90,7 @@ pgxml_parser_init(PgXmlStrictness strictness)
  * definitions for the contrib module, this won't be called.
  */
 
+#ifdef BROKEN
 PG_FUNCTION_INFO_V1(xml_is_well_formed);
 
 Datum
@@ -124,6 +125,7 @@ xml_is_well_formed(PG_FUNCTION_ARGS)
 
 	PG_RETURN_BOOL(result);
 }
+#endif
 
 
 /* Encodes special characters (<, >, &, " and \r) as XML entities */
-- 
2.9.3

0023-Add-C-linkage-to-replacement-declaration-of-fdatasyn.patchtext/x-patch; name=0023-Add-C-linkage-to-replacement-declaration-of-fdatasyn.patchDownload
From e23bbc59fed34b155bcdbff5317eea776e06a72d Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 23/27] Add C linkage to replacement declaration of fdatasync

---
 src/include/c.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/include/c.h b/src/include/c.h
index cbefc47..18af261 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1099,7 +1099,7 @@ extern int	vsnprintf(char *str, size_t count, const char *fmt, va_list args);
 #endif
 
 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
-extern int	fdatasync(int fildes);
+extern "C" int	fdatasync(int fildes);
 #endif
 
 /* If strtoq() exists, rename it to the more standard strtoll() */
-- 
2.9.3

0024-Make-inet_net_-to-C-linkage.patchtext/x-patch; name=0024-Make-inet_net_-to-C-linkage.patchDownload
From 27910bcbea854f36ee993af79a63ad184933c98a Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 24/27] Make inet_net_?to? C linkage

These functions can also be declared by the operating system, so we need
to match the linkage.
---
 src/include/port.h           | 2 +-
 src/include/utils/builtins.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/include/port.h b/src/include/port.h
index 455f723..2607a3d 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -450,7 +450,7 @@ extern int	pg_codepage_to_encoding(UINT cp);
 #endif
 
 /* port/inet_net_ntop.c */
-extern char *inet_net_ntop(int af, const void *src, int bits,
+extern "C" char *inet_net_ntop(int af, const void *src, int bits,
 			  char *dst, size_t size);
 
 /* port/pgcheckdir.c */
diff --git a/src/include/utils/builtins.h b/src/include/utils/builtins.h
index 2ae212a..3f71457 100644
--- a/src/include/utils/builtins.h
+++ b/src/include/utils/builtins.h
@@ -947,7 +947,7 @@ extern char *inet_cidr_ntop(int af, const void *src, int bits,
 			   char *dst, size_t size);
 
 /* inet_net_pton.c */
-extern int inet_net_pton(int af, const char *src,
+extern "C" int inet_net_pton(int af, const char *src,
 			  void *dst, size_t size);
 
 /* network.c */
-- 
2.9.3

0025-Add-C-linkage-to-functions-exported-by-plugins.patchtext/x-patch; name=0025-Add-C-linkage-to-functions-exported-by-plugins.patchDownload
From a3124209270fde6c7cc1fd00244eb968326b7e1f Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 25/27] Add C linkage to functions exported by plugins

This is required so dlsym() can find them reliably.
---
 contrib/bloom/bloom.h                           | 2 +-
 contrib/earthdistance/earthdistance.c           | 2 +-
 contrib/hstore/hstore.h                         | 4 ++--
 contrib/ltree/ltree.h                           | 2 ++
 contrib/pg_stat_statements/pg_stat_statements.c | 2 ++
 contrib/seg/seg.c                               | 6 ++++++
 src/include/fmgr.h                              | 6 +++---
 src/pl/plperl/plperl.c                          | 2 ++
 src/pl/plpgsql/src/plpgsql.h                    | 2 +-
 src/pl/plpython/plpy_main.c                     | 2 ++
 src/pl/tcl/pltcl.c                              | 2 ++
 src/test/regress/regress.c                      | 8 +++++---
 12 files changed, 29 insertions(+), 11 deletions(-)

diff --git a/contrib/bloom/bloom.h b/contrib/bloom/bloom.h
index 18f5127..c80d9b0 100644
--- a/contrib/bloom/bloom.h
+++ b/contrib/bloom/bloom.h
@@ -173,7 +173,7 @@ typedef struct BloomScanOpaqueData
 typedef BloomScanOpaqueData *BloomScanOpaque;
 
 /* blutils.c */
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 extern void initBloomState(BloomState *state, Relation index);
 extern void BloomFillMetapage(Relation index, Page metaPage);
 extern void BloomInitMetapage(Relation index);
diff --git a/contrib/earthdistance/earthdistance.c b/contrib/earthdistance/earthdistance.c
index 861b166..305be5d 100644
--- a/contrib/earthdistance/earthdistance.c
+++ b/contrib/earthdistance/earthdistance.c
@@ -112,7 +112,7 @@ geo_distance(PG_FUNCTION_ARGS)
 }
 #else							/* !USE_FLOAT8_BYVAL */
 
-double	   *geo_distance(Point *pt1, Point *pt2);
+extern "C" double	   *geo_distance(Point *pt1, Point *pt2);
 
 double *
 geo_distance(Point *pt1, Point *pt2)
diff --git a/contrib/hstore/hstore.h b/contrib/hstore/hstore.h
index 6bab08b..373a5f1 100644
--- a/contrib/hstore/hstore.h
+++ b/contrib/hstore/hstore.h
@@ -194,8 +194,8 @@ extern Pairs *hstoreArrayToPairs(ArrayType *a, int *npairs);
 #if HSTORE_POLLUTE_NAMESPACE
 #define HSTORE_POLLUTE(newname_,oldname_) \
 	PG_FUNCTION_INFO_V1(oldname_);		  \
-	Datum newname_(PG_FUNCTION_ARGS);	  \
-	Datum oldname_(PG_FUNCTION_ARGS) { return newname_(fcinfo); } \
+	extern "C" Datum newname_(PG_FUNCTION_ARGS);	  \
+	extern "C" Datum oldname_(PG_FUNCTION_ARGS) { return newname_(fcinfo); } \
 	extern int no_such_variable
 #else
 #define HSTORE_POLLUTE(newname_,oldname_) \
diff --git a/contrib/ltree/ltree.h b/contrib/ltree/ltree.h
index c604357..277b9a4 100644
--- a/contrib/ltree/ltree.h
+++ b/contrib/ltree/ltree.h
@@ -130,6 +130,7 @@ typedef struct
 
 
 /* use in array iterator */
+extern "C" {
 Datum		ltree_isparent(PG_FUNCTION_ARGS);
 Datum		ltree_risparent(PG_FUNCTION_ARGS);
 Datum		ltq_regex(PG_FUNCTION_ARGS);
@@ -154,6 +155,7 @@ Datum		ltree_textadd(PG_FUNCTION_ARGS);
 
 /* Util function */
 Datum		ltree_in(PG_FUNCTION_ARGS);
+}
 
 bool ltree_execute(ITEM *curitem, void *checkval,
 			  bool calcnot, bool (*chkcond) (void *checkval, ITEM *val));
diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 37aac98..fb6bd82 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -275,8 +275,10 @@ static bool pgss_save;			/* whether to save stats across shutdown */
 
 /*---- Function declarations ----*/
 
+extern "C" {
 void		_PG_init(void);
 void		_PG_fini(void);
+}
 
 PG_FUNCTION_INFO_V1(pg_stat_statements_reset);
 PG_FUNCTION_INFO_V1(pg_stat_statements_1_2);
diff --git a/contrib/seg/seg.c b/contrib/seg/seg.c
index c6c082b..45d3503 100644
--- a/contrib/seg/seg.c
+++ b/contrib/seg/seg.c
@@ -47,6 +47,7 @@ PG_FUNCTION_INFO_V1(seg_center);
 /*
 ** GiST support methods
 */
+extern "C" {
 bool gseg_consistent(GISTENTRY *entry,
 				SEG *query,
 				StrategyNumber strategy,
@@ -61,11 +62,13 @@ bool		gseg_internal_consistent(SEG *key, SEG *query, StrategyNumber strategy);
 SEG		   *gseg_union(GistEntryVector *entryvec, int *sizep);
 SEG		   *gseg_binary_union(SEG *r1, SEG *r2, int *sizep);
 bool	   *gseg_same(SEG *b1, SEG *b2, bool *result);
+}
 
 
 /*
 ** R-tree support functions
 */
+extern "C" {
 bool		seg_same(SEG *a, SEG *b);
 bool		seg_contains_int(SEG *a, int *b);
 bool		seg_contains_float4(SEG *a, float4 *b);
@@ -80,16 +83,19 @@ bool		seg_over_right(SEG *a, SEG *b);
 SEG		   *seg_union(SEG *a, SEG *b);
 SEG		   *seg_inter(SEG *a, SEG *b);
 void		rt_seg_size(SEG *a, float *sz);
+}
 
 /*
 ** Various operators
 */
+extern "C" {
 int32		seg_cmp(SEG *a, SEG *b);
 bool		seg_lt(SEG *a, SEG *b);
 bool		seg_le(SEG *a, SEG *b);
 bool		seg_gt(SEG *a, SEG *b);
 bool		seg_ge(SEG *a, SEG *b);
 bool		seg_different(SEG *a, SEG *b);
+}
 
 /*
 ** Auxiliary funxtions
diff --git a/src/include/fmgr.h b/src/include/fmgr.h
index 0491e2e..191235f 100644
--- a/src/include/fmgr.h
+++ b/src/include/fmgr.h
@@ -348,8 +348,8 @@ typedef const Pg_finfo_record *(*PGFInfoFunction) (void);
  *	doesn't hurt to add PGDLLIMPORT in case they don't.
  */
 #define PG_FUNCTION_INFO_V1(funcname) \
-Datum funcname(PG_FUNCTION_ARGS); \
-extern PGDLLEXPORT const Pg_finfo_record * CppConcat(pg_finfo_,funcname)(void); \
+extern "C" Datum funcname(PG_FUNCTION_ARGS); \
+extern "C" PGDLLEXPORT const Pg_finfo_record * CppConcat(pg_finfo_,funcname)(void); \
 const Pg_finfo_record * \
 CppConcat(pg_finfo_,funcname) (void) \
 { \
@@ -418,7 +418,7 @@ typedef const Pg_magic_struct *(*PGModuleMagicFunction) (void);
 #define PG_MAGIC_FUNCTION_NAME_STRING "Pg_magic_func"
 
 #define PG_MODULE_MAGIC \
-extern PGDLLEXPORT const Pg_magic_struct *PG_MAGIC_FUNCTION_NAME(void); \
+extern "C" PGDLLEXPORT const Pg_magic_struct *PG_MAGIC_FUNCTION_NAME(void); \
 const Pg_magic_struct * \
 PG_MAGIC_FUNCTION_NAME(void) \
 { \
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index 2cd7614..c5c0617 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -244,7 +244,9 @@ static plperl_call_data *current_call_data = NULL;
 /**********************************************************************
  * Forward declarations
  **********************************************************************/
+extern "C" {
 void		_PG_init(void);
+}
 
 static PerlInterpreter *plperl_init_interp(void);
 static void plperl_destroy_interp(PerlInterpreter **);
diff --git a/src/pl/plpgsql/src/plpgsql.h b/src/pl/plpgsql/src/plpgsql.h
index b416e50..f2ddd94 100644
--- a/src/pl/plpgsql/src/plpgsql.h
+++ b/src/pl/plpgsql/src/plpgsql.h
@@ -1085,7 +1085,7 @@ extern void plpgsql_HashTableInit(void);
 /*
  * Functions in pl_handler.c
  */
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 
 /*
  * Functions in pl_exec.c
diff --git a/src/pl/plpython/plpy_main.c b/src/pl/plpython/plpy_main.c
index 860b804..efd3bf0 100644
--- a/src/pl/plpython/plpy_main.c
+++ b/src/pl/plpython/plpy_main.c
@@ -39,7 +39,9 @@
 #define plpython_inline_handler plpython3_inline_handler
 #endif
 
+extern "C" {
 extern void _PG_init(void);
+}
 
 PG_MODULE_MAGIC;
 
diff --git a/src/pl/tcl/pltcl.c b/src/pl/tcl/pltcl.c
index 2a335aa..20578ad 100644
--- a/src/pl/tcl/pltcl.c
+++ b/src/pl/tcl/pltcl.c
@@ -205,7 +205,9 @@ static const TclExceptionNameMap exception_name_map[] = {
 /**********************************************************************
  * Forward declarations
  **********************************************************************/
+extern "C" {
 void		_PG_init(void);
+}
 
 static void pltcl_init_interp(pltcl_interp_desc *interp_desc, bool pltrusted);
 static pltcl_interp_desc *pltcl_fetch_interp(bool pltrusted);
diff --git a/src/test/regress/regress.c b/src/test/regress/regress.c
index e7826a4..9621cc1 100644
--- a/src/test/regress/regress.c
+++ b/src/test/regress/regress.c
@@ -45,8 +45,8 @@
 
 extern PATH *poly2path(POLYGON *poly);
 extern void regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2);
-extern char *reverse_name(char *string);
-extern int	oldstyle_length(int n, text *t);
+extern "C" char *reverse_name(char *string);
+extern "C" int	oldstyle_length(int n, text *t);
 
 #ifdef PG_MODULE_MAGIC
 PG_MODULE_MAGIC;
@@ -240,8 +240,10 @@ typedef struct
 	double		radius;
 } WIDGET;
 
+extern "C" {
 WIDGET	   *widget_in(char *str);
-char	   *widget_out(WIDGET *widget);
+char	   *widget_out(WIDGET * widget);
+}
 
 #define NARGS	3
 
-- 
2.9.3

0026-Add-C-linkage-to-client-libraries-in-non-systematic-.patchtext/x-patch; name=0026-Add-C-linkage-to-client-libraries-in-non-systematic-.patchDownload
From 92ff0ab38c864c2edea49a83ec0e46c33bf71e64 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 26/27] Add C linkage to client libraries in non-systematic
 ways

---
 src/backend/utils/mb/encnames.c     |  3 +++
 src/include/mb/pg_wchar.h           | 12 ++++++++++++
 src/include/port.h                  |  6 ++++++
 src/interfaces/ecpg/pgtypeslib/dt.h |  2 +-
 src/interfaces/libpq/Makefile       |  2 +-
 src/interfaces/libpq/libpq-fe.h     |  1 +
 src/interfaces/libpq/pqexpbuffer.h  |  9 +++++++++
 7 files changed, 33 insertions(+), 2 deletions(-)

diff --git a/src/backend/utils/mb/encnames.c b/src/backend/utils/mb/encnames.c
index 11099b8..dc62e90 100644
--- a/src/backend/utils/mb/encnames.c
+++ b/src/backend/utils/mb/encnames.c
@@ -6,6 +6,9 @@
  */
 #ifdef FRONTEND
 #include "postgres_fe.h"
+#ifdef LIBPQ
+#include "libpq-fe.h"
+#endif
 #else
 #include "postgres.h"
 #include "utils/builtins.h"
diff --git a/src/include/mb/pg_wchar.h b/src/include/mb/pg_wchar.h
index 24e8d0d..f5dd098 100644
--- a/src/include/mb/pg_wchar.h
+++ b/src/include/mb/pg_wchar.h
@@ -491,11 +491,23 @@ extern int	pg_bind_textdomain_codeset(const char *domainname);
 #endif
 
 extern int	pg_valid_client_encoding(const char *name);
+#ifdef LIBPQ
+extern "C" {
+#endif
 extern int	pg_valid_server_encoding(const char *name);
+#ifdef LIBPQ
+}
+#endif
 
 extern unsigned char *unicode_to_utf8(pg_wchar c, unsigned char *utf8string);
 extern pg_wchar utf8_to_unicode(const unsigned char *c);
+#ifdef LIBPQ
+extern "C" {
+#endif
 extern int	pg_utf_mblen(const unsigned char *);
+#ifdef LIBPQ
+}
+#endif
 extern unsigned char *pg_do_encoding_conversion(unsigned char *src, int len,
 						  int src_encoding,
 						  int dest_encoding);
diff --git a/src/include/port.h b/src/include/port.h
index 2607a3d..831e9be 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -460,8 +460,14 @@ extern int	pg_check_dir(const char *dir);
 extern int	pg_mkdir_p(char *path, int omode);
 
 /* port/pqsignal.c */
+#ifdef LIBPQ
+extern "C" {
+#endif
 typedef void (*pqsigfunc) (int signo);
 extern pqsigfunc pqsignal(int signo, pqsigfunc func);
+#ifdef LIBPQ
+}
+#endif
 
 /* port/quotes.c */
 extern char *escape_single_quotes_ascii(const char *src);
diff --git a/src/interfaces/ecpg/pgtypeslib/dt.h b/src/interfaces/ecpg/pgtypeslib/dt.h
index c0c3ac1..ad77b05 100644
--- a/src/interfaces/ecpg/pgtypeslib/dt.h
+++ b/src/interfaces/ecpg/pgtypeslib/dt.h
@@ -365,7 +365,7 @@ void		GetCurrentDateTime(struct tm *);
 int			date2j(int, int, int);
 void		TrimTrailingZeros(char *);
 void		dt2time(double, int *, int *, int *, fsec_t *);
-int PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp * d,
+extern "C" int PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp * d,
 							int *year, int *month, int *day,
 							int *hour, int *minute, int *second,
 							int *tz);
diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile
index 0b4065e..d71b2c0 100644
--- a/src/interfaces/libpq/Makefile
+++ b/src/interfaces/libpq/Makefile
@@ -19,7 +19,7 @@ NAME= pq
 SO_MAJOR_VERSION= 5
 SO_MINOR_VERSION= $(MAJORVERSION)
 
-override CPPFLAGS :=  -DFRONTEND -DUNSAFE_STAT_OK -I$(srcdir) $(CPPFLAGS) -I$(top_builddir)/src/port -I$(top_srcdir)/src/port
+override CPPFLAGS :=  -DFRONTEND -DLIBPQ -DUNSAFE_STAT_OK -I$(srcdir) $(CPPFLAGS) -I$(top_builddir)/src/port -I$(top_srcdir)/src/port
 ifneq ($(PORTNAME), win32)
 override CFLAGS += $(PTHREAD_CFLAGS)
 endif
diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h
index 9ca0756..c8f5293 100644
--- a/src/interfaces/libpq/libpq-fe.h
+++ b/src/interfaces/libpq/libpq-fe.h
@@ -501,6 +501,7 @@ extern void PQclear(PGresult *res);
 extern void PQfreemem(void *ptr);
 
 /* Exists for backward compatibility.  bjm 2003-03-24 */
+extern void PQfreeNotify(PGnotify *notify);
 #define PQfreeNotify(ptr) PQfreemem(ptr)
 
 /* Error when no password was given. */
diff --git a/src/interfaces/libpq/pqexpbuffer.h b/src/interfaces/libpq/pqexpbuffer.h
index ce87cd5..ba4ac74 100644
--- a/src/interfaces/libpq/pqexpbuffer.h
+++ b/src/interfaces/libpq/pqexpbuffer.h
@@ -25,6 +25,11 @@
 #ifndef PQEXPBUFFER_H
 #define PQEXPBUFFER_H
 
+#ifdef __cplusplus
+extern      "C"
+{
+#endif
+
 /*-------------------------
  * PQExpBufferData holds information about an extensible string.
  *		data	is the current buffer for the string (allocated with malloc).
@@ -179,4 +184,8 @@ extern void appendPQExpBufferChar(PQExpBuffer str, char ch);
 extern void appendBinaryPQExpBuffer(PQExpBuffer str,
 						const char *data, size_t datalen);
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif   /* PQEXPBUFFER_H */
-- 
2.9.3

0027-Hack-Disable-volatile-that-causes-mysterious-compile.patchtext/x-patch; name=0027-Hack-Disable-volatile-that-causes-mysterious-compile.patchDownload
From 1af627d7881ebcb2a974eb0934a455cb9f806db2 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH 27/27] Hack: Disable volatile that causes mysterious compiler
 errors

---
 src/backend/commands/async.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c
index 716f1c3..c727788 100644
--- a/src/backend/commands/async.c
+++ b/src/backend/commands/async.c
@@ -385,7 +385,7 @@ static double asyncQueueUsage(void);
 static void asyncQueueFillWarning(void);
 static bool SignalBackends(void);
 static void asyncQueueReadAllNotifications(void);
-static bool asyncQueueProcessPageEntries(volatile QueuePosition *current,
+static bool asyncQueueProcessPageEntries(/*volatile*/ QueuePosition *current,
 							 QueuePosition stop,
 							 char *page_buffer);
 static void asyncQueueAdvanceTail(void);
@@ -1741,7 +1741,7 @@ ProcessNotifyInterrupt(void)
 static void
 asyncQueueReadAllNotifications(void)
 {
-	volatile QueuePosition pos;
+	/*volatile*/ QueuePosition pos;
 	QueuePosition oldpos;
 	QueuePosition head;
 	bool		advanceTail;
@@ -1901,7 +1901,7 @@ asyncQueueReadAllNotifications(void)
  * The QueuePosition *current is advanced past all processed messages.
  */
 static bool
-asyncQueueProcessPageEntries(volatile QueuePosition *current,
+asyncQueueProcessPageEntries(/*volatile*/ QueuePosition *current,
 							 QueuePosition stop,
 							 char *page_buffer)
 {
-- 
2.9.3

#55Christian Convey
christian.convey@gmail.com
In reply to: Peter Eisentraut (#54)
Re: [GENERAL] C++ port of Postgres

On Wed, Aug 31, 2016 at 9:41 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:

Joy, do you have an idea what a *minimally invasive* patch for C++
support would look like? That's certainly the first step here.

I developed a minimally invasive patch for C++ support a few years ago
shortly after I wrote that blog post. Since there appears to have been
some interest here now, I have updated that and split it up into logical
chunks.

So here you go.

Hi folks,

I'm ready for my first-ever PG code review, and I was considering
tackling this one. I.e., https://commitfest.postgresql.org/10/776/

Could someone help me with a few procedural questions?

(1) This page: https://wiki.postgresql.org/wiki/Reviewing_a_Patch
lists the current commitfest's manager as "(vacant)". But this page:
https://commitfest.postgresql.org/ seems to indicate that a commitfest
is currently in progress. Is there a commitfest manager at the
moment?

(2) It seems like there are still a few big questions about this commit:

- Is it wanted at the moment? It didn't seem like there's a
consensus about whether or not this enhancement should be
merged, even if the patch is pretty minimal.

- It seems like there are two competing patch
sets in play for this enhancement: Joy's and
Peter's. Presumably at most one of them would
be merged.

Are these signs that I should find a different commit to review
for now, so that this one can be further discussed?

Thanks very much,
Christian

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#56Heikki Linnakangas
hlinnaka@iki.fi
In reply to: Peter Eisentraut (#54)
Re: [GENERAL] C++ port of Postgres

On 08/31/2016 04:41 PM, Peter Eisentraut wrote:

I developed a minimally invasive patch for C++ support a few years ago
shortly after I wrote that blog post. Since there appears to have been
some interest here now, I have updated that and split it up into logical
chunks.

So here you go.

Looking at this with the POV of what would make sense, even if we don't
care about C++.

The patches are numbered approximately in increasing order of dubiosity.
So 0001 is probably a straight bug fix, 0002 and 0003 are arguably
minor bug fixes as well. The patches through 0012 can probably be
considered for committing in some form. After that it gets a bit hackish.

0001-0003 look clear to me as well. 0006 - 0009 also seem OK. The rest
really only make sense if we decided to make the switch to C++.

- Heikki

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#57Tom Lane
tgl@sss.pgh.pa.us
In reply to: Christian Convey (#55)
Re: [GENERAL] C++ port of Postgres

Christian Convey <christian.convey@gmail.com> writes:

Could someone help me with a few procedural questions?

(1) This page: https://wiki.postgresql.org/wiki/Reviewing_a_Patch
lists the current commitfest's manager as "(vacant)". But this page:
https://commitfest.postgresql.org/ seems to indicate that a commitfest
is currently in progress. Is there a commitfest manager at the
moment?

Fabrízio de Royes Mello is it. I guess he hasn't noticed that that
page ought to be updated.

(2) It seems like there are still a few big questions about this commit:
- Is it wanted at the moment? It didn't seem like there's a
consensus about whether or not this enhancement should be
merged, even if the patch is pretty minimal.
- It seems like there are two competing patch
sets in play for this enhancement: Joy's and
Peter's. Presumably at most one of them would
be merged.

These are things that reviews should be helping to decide. It's probably
a squishier topic than some patches, but if you're interested, feel free
to read code and weigh in.

regards, tom lane

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#58Christian Convey
christian.convey@gmail.com
In reply to: Tom Lane (#57)
Re: [GENERAL] C++ port of Postgres

On Tue, Sep 6, 2016 at 3:12 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:

(2) It seems like there are still a few big questions about this commit:
- Is it wanted at the moment? It didn't seem like there's a
consensus about whether or not this enhancement should be
merged, even if the patch is pretty minimal.
- It seems like there are two competing patch
sets in play for this enhancement: Joy's and
Peter's. Presumably at most one of them would
be merged.

These are things that reviews should be helping to decide. It's probably
a squishier topic than some patches, but if you're interested, feel free
to read code and weigh in.

Thanks. It sounds like worst-case scenario, I perform an unneeded
review. I'll give it a shot.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#59Christian Convey
christian.convey@gmail.com
In reply to: Christian Convey (#58)
Re: [GENERAL] C++ port of Postgres

Thanks. It sounds like worst-case scenario, I perform an unneeded
review. I'll give it a shot.

Hi guys,

Apologies for more boring process-related questions, but any pointers
would be greatly appreciated...

I'm a bit confused about how PG's code-review process is meant to
handle this C++ port. My confusion may stem from the combination of
my inexperience with the process, and there being two competing patch
sets.

Here's some background:

* My intention was to review Joy's patch.

* On "commitfest.postgresql.org" (for 2016-09), the only C++
-related patch I found was Peter's: [1]https://commitfest.postgresql.org/10/776/

* I wrongly assumed that the commitfest entry would be for
Joy's patch, not Peter's, so I signed up as its reviewer.
(That's fine - I don't mind reviewing both authors' patch
sets.)

But here are my questions:

Q1) My understanding of PG's code-review process is that it's a pipeline:
Step 1. The discussion starts on the pgsql-hackers mailing list, where
the author posts a patch. He/she may also post revised patches
based on the discussion.

Step 2. A subset of those discussions are modeled by new entries in
the commitfest website.

Step 3. A subset of those commitfest items get merged.

If that's correct, then it sounds like the only way Joy's commit has
a chance of acceptance is if Peter's commit is rejected.
Because Peter's commit might be merged as part of the 2016-09
commitfest, but Joy's can show up until 2016-11 at the earliest.

Is my understanding correct?

There seems to be a little ambiguity regarding the exact version of
the code to be reviewed. This is true for both Joy's and Peter's
submissions:
* Joy's email provides a link to a Github repo, but does not specify
a particular commit (or even branch) in that repo: [2]/messages/by-id/CABgyVxDBd3EvRdo-Rd6eo8QPEqV8=ShaU2SJfo16wfE0R-hXTA@mail.gmail.com

* In the email thread, Peter did provide a patch set: [3]/messages/by-id/bf9de63c-b669-4b8c-d33b-4a5ed11cd5d4@2ndquadrant.com
but the corresponding commitfest entry references a github branch: [4]https://github.com/petere/postgresql/tree/commitfest/c%2B%2B

So I have a few questions here:

Q2) Are authors expected to submit an unambiguous patch to frame the
discussion? (I.e,. a specific patch file, or a specific git commit
hash, as opposed to a github repo or a github branch.)

Q3) Are authors expected to submit a single patch/commit, or is it
acceptable / desirable for a large patch to be broken up as Peter has
done?

Q4) Do we require that any submitted patches appear as attachments on
the pgsql-hackers email list, or is a github URL good enough?

Q5) (This question is more generic.) I'm accustomed to using Github's
pull-request system, where I can engage in dialog regarding specifc
lines of a patch. I haven't noticed anything similar being used for
PG code reviews, but perhaps I'm just looking in the wrong places.
Are all PG code reviews basically just back-and-forth email
conversations on the pgsql-hackers list?

Thanks,
Christian

[1]: https://commitfest.postgresql.org/10/776/
[2]: /messages/by-id/CABgyVxDBd3EvRdo-Rd6eo8QPEqV8=ShaU2SJfo16wfE0R-hXTA@mail.gmail.com
[3]: /messages/by-id/bf9de63c-b669-4b8c-d33b-4a5ed11cd5d4@2ndquadrant.com
[4]: https://github.com/petere/postgresql/tree/commitfest/c%2B%2B

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#60Tom Lane
tgl@sss.pgh.pa.us
In reply to: Christian Convey (#59)
Re: [GENERAL] C++ port of Postgres

Christian Convey <christian.convey@gmail.com> writes:

If that's correct, then it sounds like the only way Joy's commit has
a chance of acceptance is if Peter's commit is rejected.
Because Peter's commit might be merged as part of the 2016-09
commitfest, but Joy's can show up until 2016-11 at the earliest.

No, we're not that rigid about it. The commitfest mechanism is really
mostly meant to ensure that every submission does get looked at within a
reasonable amount of time and doesn't get forgotten about. (We do tend
to be willing to tell new patches they've got to wait till the next fest,
but that's mainly when we're already feeling overloaded by what's in the
current queue.) In this case it would be nonsensical to consider only
Peter's submission and not Joy's, because part of the issue is whether
one's better than the other.

There seems to be a little ambiguity regarding the exact version of
the code to be reviewed. This is true for both Joy's and Peter's
submissions:
* Joy's email provides a link to a Github repo, but does not specify
a particular commit (or even branch) in that repo: [2]
* In the email thread, Peter did provide a patch set: [3]
but the corresponding commitfest entry references a github branch: [4]

Well, at the point we're at here, it's probably not that important exactly
which version of a patchset you're looking at; I'd take the latest.

Q4) Do we require that any submitted patches appear as attachments on
the pgsql-hackers email list, or is a github URL good enough?

Actually, we *do* require that, mainly as a formality to show that the
author intended to submit it for inclusion in Postgres. (We don't want
people coming back later and saying "hey, you ripped off this code from
my github repo without my permission".) If we were seriously considering
adopting Joy's version then that would have to happen before anything got
merged. But at this point it seems like we're in a very exploratory
phase and there's no need for legal niceties yet.

Q5) (This question is more generic.) I'm accustomed to using Github's
pull-request system, where I can engage in dialog regarding specifc
lines of a patch. I haven't noticed anything similar being used for
PG code reviews, but perhaps I'm just looking in the wrong places.
Are all PG code reviews basically just back-and-forth email
conversations on the pgsql-hackers list?

Yup, that's how we roll ... it's ancient habit from before there was
such a thing as git, let alone github, but we've not seen fit to change.
It does have the advantage that it's about equally amenable to high-
level discussions and line-by-line issues.

regards, tom lane

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#61Christian Convey
christian.convey@gmail.com
In reply to: Christian Convey (#58)
Re: [GENERAL] C++ port of Postgres

Hi Heikki,

Could I ask you a newbie-reviewer question about something I'm seeing
here? https://commitfest.postgresql.org/10/776/

From some reading I've done (e.g., Stephen Frost's PGCon 2011 slides),
I got the impression that a successful patch would always have this
sequence of states in commitfest:
1. patch-record created
...
2. Needs Review
...
3. Ready for Committer

But if I'm reading the patch's activity log correctly, it looks like
you marked the patch as "Ready for Committer" (2016-09-06 18:59:02)
without any record of it having been reviewed.

Was that intentional?

Thanks very much,
Christian

P.S. I'm asking because I was planning to review that patch. But I
can't tell if any more review by a non-committer is still required by
the commitfest workflow.

Kind regards,
Christian

On Tue, Sep 6, 2016 at 3:15 PM, Christian Convey
<christian.convey@gmail.com> wrote:

On Tue, Sep 6, 2016 at 3:12 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:

(2) It seems like there are still a few big questions about this commit:
- Is it wanted at the moment? It didn't seem like there's a
consensus about whether or not this enhancement should be
merged, even if the patch is pretty minimal.
- It seems like there are two competing patch
sets in play for this enhancement: Joy's and
Peter's. Presumably at most one of them would
be merged.

These are things that reviews should be helping to decide. It's probably
a squishier topic than some patches, but if you're interested, feel free
to read code and weigh in.

Thanks. It sounds like worst-case scenario, I perform an unneeded
review. I'll give it a shot.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#62Christian Convey
christian.convey@gmail.com
In reply to: Joy Arulraj (#1)
Re: C++ port of Postgres

On Sun, Aug 14, 2016 at 5:05 PM, Joy Arulraj <jarulraj@cs.cmu.edu> wrote:

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its standard
library to simplify coding, improve code reuse, and avoid bugs. Peter's
article titled `Moving to C++` was a source of inspiration for us.

Do you remember the particular commit of PG upon which you based this
work? Or even better, are you able to post a patch which applies
cleanly to PG's current HEAD?

I ask because I'd like to compare your approach to the one Peter has
posted, and I think that will be easier if I can use a common (or at
least similar) baseline for the comparison.

Kind regards,
Christian

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

#63Heikki Linnakangas
hlinnaka@iki.fi
In reply to: Christian Convey (#61)
Re: [GENERAL] C++ port of Postgres

On 09/11/2016 01:20 AM, Christian Convey wrote:

Hi Heikki,

Could I ask you a newbie-reviewer question about something I'm seeing
here? https://commitfest.postgresql.org/10/776/

From some reading I've done (e.g., Stephen Frost's PGCon 2011 slides),
I got the impression that a successful patch would always have this
sequence of states in commitfest:
1. patch-record created
...
2. Needs Review
...
3. Ready for Committer

But if I'm reading the patch's activity log correctly, it looks like
you marked the patch as "Ready for Committer" (2016-09-06 18:59:02)
without any record of it having been reviewed.

Was that intentional?

Yeah, I commented on the patches at
/messages/by-id/e8e7e5a7-0308-2c36-d32a-7aab16ba498c@iki.fi.
It was very cursory, but I figured that would be sufficient feedback for
now, for Peter to proceed with the first few straightforward patches in
the series. I don't think there's consensus that we want to do more than
that, to actually switch to C++.

P.S. I'm asking because I was planning to review that patch. But I
can't tell if any more review by a non-committer is still required by
the commitfest workflow.

I think this has gotten enough attention, for the commitfest workflow.
But of course, if you're interested, feel free to review and comment anyway!

- Heikki

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#64Heikki Linnakangas
hlinnaka@iki.fi
In reply to: Christian Convey (#61)
Re: [GENERAL] C++ port of Postgres

On 09/11/2016 01:20 AM, Christian Convey wrote:

Hi Heikki,

Could I ask you a newbie-reviewer question about something I'm seeing
here? https://commitfest.postgresql.org/10/776/

From some reading I've done (e.g., Stephen Frost's PGCon 2011 slides),
I got the impression that a successful patch would always have this
sequence of states in commitfest:
1. patch-record created
...
2. Needs Review
...
3. Ready for Committer

But if I'm reading the patch's activity log correctly, it looks like
you marked the patch as "Ready for Committer" (2016-09-06 18:59:02)
without any record of it having been reviewed.

Was that intentional?

Yeah, I commented on the patches at
/messages/by-id/e8e7e5a7-0308-2c36-d32a-7aab16ba498c@iki.fi.
It was very cursory, but I figured that would be sufficient feedback for
now, for Peter to proceed with the first few straightforward patches in
the series. I don't think there's consensus that we want to do more than
that, to actually switch to C++.

P.S. I'm asking because I was planning to review that patch. But I
can't tell if any more review by a non-committer is still required by
the commitfest workflow.

I think this has gotten enough attention, for the commitfest workflow.
The workflow is flexible, depending on the nature of patch. But of
course, if you're interested, feel free to review and comment anyway!

- Heikki

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#65Christian Convey
christian.convey@gmail.com
In reply to: Heikki Linnakangas (#64)
Re: [GENERAL] C++ port of Postgres

P.S. I'm asking because I was planning to review that patch. But I

can't tell if any more review by a non-committer is still required by
the commitfest workflow.

I think this has gotten enough attention, for the commitfest workflow. The
workflow is flexible, depending on the nature of patch. But of course, if
you're interested, feel free to review and comment anyway!

Hi Heikki,

Thanks for the help. If you think nothing more is needed for this
patch set w.r.t. the 2016-09 commitfest, I'll move on to other things.

- Christian

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#66Christian Convey
christian.convey@gmail.com
In reply to: Peter Eisentraut (#54)
Re: [GENERAL] C++ port of Postgres

Some of your patches look useful, but unrelated to C++: 7, 8, 15, 16(?), 20.

I applied that subset to 9.6 and got a clean "make check".

Would it make sense to add them to the next commitfest, regardless of
the C++ effort?

On Wed, Aug 31, 2016 at 9:41 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:

[trimmed cc list because of big attachments]

On 8/16/16 4:22 PM, Jim Nasby wrote:

Joy, do you have an idea what a *minimally invasive* patch for C++
support would look like? That's certainly the first step here.

I developed a minimally invasive patch for C++ support a few years ago
shortly after I wrote that blog post. Since there appears to have been
some interest here now, I have updated that and split it up into logical
chunks.

So here you go.

To build this, you need to configure with g++ <= version 5. (4.x works,
too.) g++ version 6 does not work yet because of the issues described
in patch 0013.

Then you also need to edit src/Makefile.custom and set

COPT = -fpermissive -Wno-sign-compare -Wno-write-strings

The -W options are optional just to reduce some noise. Cleaning up
those warnings can be a separate project that might also have some
benefit under C.

The -fpermissive option is a g++ specific option that reduces some
errors to warnings. (So this won't work with clang or other compilers
at all at this point.) In particular, C++ does not allow casting from
or to void pointers without a cast, but -fpermissive allows that. The
step from this to "real" C++ would be adding a bunch of casts around
things like malloc and palloc and other places. That would be mostly
busy work, so I have excluded that here.

The patches are numbered approximately in increasing order of dubiosity.
So 0001 is probably a straight bug fix, 0002 and 0003 are arguably
minor bug fixes as well. The patches through 0012 can probably be
considered for committing in some form. After that it gets a bit hackish.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#67Joy Arulraj
jarulraj@cs.cmu.edu
In reply to: Christian Convey (#62)
Re: C++ port of Postgres

Hi Christian -- Sorry about the delay. The patch is based on PG version
9.5.3.
The commit history of the repo should give a high-level idea of the changes
required in PG to support compilation by a C++ compiler. I presume that
Peter's patch would be easier to integrate into PG. In any case, I would be
very glad to see PostgreSQL support C++.

Regards.

On Sun, Sep 11, 2016 at 6:47 AM, Christian Convey <
christian.convey@gmail.com> wrote:

Show quoted text

On Sun, Aug 14, 2016 at 5:05 PM, Joy Arulraj <jarulraj@cs.cmu.edu> wrote:

Hi folks --

We have ported Postgres over to the C++ language (C++11 standard).

https://github.com/jarulraj/postgresql-cpp

Our goal is to use certain features of the C++ language and its standard
library to simplify coding, improve code reuse, and avoid bugs. Peter's
article titled `Moving to C++` was a source of inspiration for us.

Do you remember the particular commit of PG upon which you based this
work? Or even better, are you able to post a patch which applies
cleanly to PG's current HEAD?

I ask because I'd like to compare your approach to the one Peter has
posted, and I think that will be easier if I can use a common (or at
least similar) baseline for the comparison.

Kind regards,
Christian

#68Thomas Munro
thomas.munro@enterprisedb.com
In reply to: Peter Eisentraut (#54)
Re: [GENERAL] C++ port of Postgres

On Thu, Sep 1, 2016 at 1:41 AM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:

[trimmed cc list because of big attachments]

On 8/16/16 4:22 PM, Jim Nasby wrote:

Joy, do you have an idea what a *minimally invasive* patch for C++
support would look like? That's certainly the first step here.

I developed a minimally invasive patch for C++ support a few years ago
shortly after I wrote that blog post. Since there appears to have been
some interest here now, I have updated that and split it up into logical
chunks.

So here you go.

I looked at a random selection of these patches this morning.

0001-Fix-use-of-offsetof.patch

I agree that this is already invalid C because it's not constant. It is
accepted by GCC's C front end no matter what switches you give it and
clearly many other compilers too, but not clang's C front end with
"-pedantic".

0002-Use-return-instead-of-exit-in-configure.patch

Makes sense. Any reason not to #include <stdlib.h> instead like you did
for the 0003 patch?

0003-Add-missing-include-files-to-configure-tests.patch

Makes sense.

0014-Set-up-for-static-asserts-in-C.patch

+#if __cpp_static_assert >= 201411
+#define _Static_assert(condition, errmessage) static_assert(condition,
errmessage)

Don't you mean 201103L? C++11 introduced two-argument static_assert, not
C++14.

0021-Workaround-for-using-typdef-ed-ints-in-loops.patch

Types made from int don't have a ++ operator in C++, so they can't be
used in for loops without further work.

ForkNumber is not a typedef'd int: it's an enum. Since it's called a "fork
*number*" and clearly treated as a number in various places including loops
that want to increment it, perhaps it really should be a typedef of an int,
instead of an enum. Then either macros or an enum ForkNumberEnum could
define the names (you can assign enums to ints, and compare enums and ints,
you just can't assign ints to enums so it'd be no problem to have typedef
ForkNumber int and then enum ForkNumberEnum { ... } to define the friendly
names, but never actually use the type ForkNumberEnum).

0023-Add-C-linkage-to-replacement-declaration-of-fdatasyn.patch

-extern int fdatasync(int fildes);
+extern "C" int fdatasync(int fildes);

Doesn't this need to be made conditional on __cplusplus?

0024-Make-inet_net_-to-C-linkage.patch

Same.

0025-Add-C-linkage-to-functions-exported-by-plugins.patch

-extern void _PG_init(void);
+extern "C" void _PG_init(void);

Why this way in some places...

+extern "C" {
 extern void _PG_init(void);
+}

... and this way in single-function declaration cases in other places?

-char   *widget_out(WIDGET *widget);
+char   *widget_out(WIDGET * widget);

Noise.

0027-Hack-Disable-volatile-that-causes-mysterious-compile.patch

Subject: [PATCH 27/27] Hack: Disable volatile that causes mysterious

compiler errors
I don't grok the reason for the volatile qualifier in this code the first
place but if it actually does something useful, here's one way to fix it.
The specific reason for the error reported by GCC is that QueuePosition (a
struct) is copied by assignment:

pos = oldpos = QUEUE_BACKEND_POS(MyBackendId);

That means that it invokes the default assignment operator, and you can't
do that with a volatile and a non-volatile object either way around
according to C++ (though clang seems less fussy than GCC in this case).
You could try to untangle that by supplying a suitably qualified explicit
member operator:

#ifdef __cplusplus

QueuePosition& operator=(const volatile QueuePosition& other)

{

page = other.page;

offset = other.offset;

return *this;

}

#endif

But that doesn't help with assignments going the other way.... How about
just defining a macro in the style of the existing macros and then using
that in place of all those incompatible assignment operations:

iff --git a/src/backend/commands/async.c b/src/backend/commands/async.c
index 716f1c3..469018f 100644
--- a/src/backend/commands/async.c
+++ b/src/backend/commands/async.c
@@ -194,6 +194,12 @@ typedef struct QueuePosition
                (x).offset = (z); \
        } while (0)
+#define COPY_QUEUE_POS(x, y) \
+       do { \
+               (x).page = (y).page; \
+               (x).offset = (y).offset; \
+       } while (0)
+
 #define QUEUE_POS_EQUAL(x,y) \
         ((x).page == (y).page && (x).offset == (y).offset)
@@ -1757,7 +1763,8 @@ asyncQueueReadAllNotifications(void)
        LWLockAcquire(AsyncQueueLock, LW_SHARED);
        /* Assert checks that we have a valid state entry */
        Assert(MyProcPid == QUEUE_BACKEND_PID(MyBackendId));
-       pos = oldpos = QUEUE_BACKEND_POS(MyBackendId);
+       COPY_QUEUE_POS(pos, QUEUE_BACKEND_POS(MyBackendId));
+       COPY_QUEUE_POS(oldpos, pos);
        head = QUEUE_HEAD;
        LWLockRelease(AsyncQueueLock);
@@ -1861,7 +1868,7 @@ asyncQueueReadAllNotifications(void)
        {
                /* Update shared state */
                LWLockAcquire(AsyncQueueLock, LW_SHARED);
-               QUEUE_BACKEND_POS(MyBackendId) = pos;
+               COPY_QUEUE_POS(QUEUE_BACKEND_POS(MyBackendId), pos);
                advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
                LWLockRelease(AsyncQueueLock);

@@ -1875,7 +1882,7 @@ asyncQueueReadAllNotifications(void)

        /* Update shared state */
        LWLockAcquire(AsyncQueueLock, LW_SHARED);
-       QUEUE_BACKEND_POS(MyBackendId) = pos;
+       COPY_QUEUE_POS(QUEUE_BACKEND_POS(MyBackendId), pos);
        advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
        LWLockRelease(AsyncQueueLock);

@@ -1911,7 +1918,9 @@ asyncQueueProcessPageEntries(volatile QueuePosition
*current,

        do
        {
-               QueuePosition thisentry = *current;
+               QueuePosition thisentry;
+
+               COPY_QUEUE_POS(thisentry, *current);
                if (QUEUE_POS_EQUAL(thisentry, stop))
                        break;
@@ -1944,7 +1953,7 @@ asyncQueueProcessPageEntries(volatile QueuePosition
*current,
                                 * from a transaction that is not yet
visible to snapshots;
                                 * compare the comments at the head of
tqual.c.
                                 */
-                               *current = thisentry;
+                               COPY_QUEUE_POS(*current, thisentry);
                                reachedStop = true;
                                break;
                        }

--
Thomas Munro
http://www.enterprisedb.com

#69Thomas Munro
thomas.munro@enterprisedb.com
In reply to: Thomas Munro (#68)
Re: [GENERAL] C++ port of Postgres

On Mon, Sep 26, 2016 at 10:57 AM, Thomas Munro
<thomas.munro@enterprisedb.com> wrote:

On Thu, Sep 1, 2016 at 1:41 AM, Peter Eisentraut
<peter.eisentraut@2ndquadrant.com> wrote:

[trimmed cc list because of big attachments]

On 8/16/16 4:22 PM, Jim Nasby wrote:

Joy, do you have an idea what a *minimally invasive* patch for C++
support would look like? That's certainly the first step here.

I developed a minimally invasive patch for C++ support a few years ago
shortly after I wrote that blog post. Since there appears to have been
some interest here now, I have updated that and split it up into logical
chunks.

So here you go.

I looked at a random selection of these patches this morning.

And this morning I looked at the rest of them.

0004-Fix-LDFLAGS-test-for-C.patch

Makes sense.

0005-Add-test-for-Wmissing-prototypes.patch

This does seem to follow the example of how we test for support for
other warning flags.

0006-Remove-unnecessary-prototypes.patch

Looks OK.

0007-Fix-incorrect-type-cast.patch

  /* array of check flags, reported to consistentFn */
- bool   *entryRes;
+ GinTernaryValue *entryRes;

Right. That would be pretty dodgy even in C if we ever use stdbool.h,
because sizeof(_Bool) is implementation defined. The
interchangeability relies on bool and GinTernaryValue both being
typedefs for 'char'. (Not to mention the dangerous contradictions
possible with bools obtained that way: 'b == false || b == true' can
be false, which I guess has been thought about already and is off
topic here.)

I wonder if the following bit of gin.h should be more nuanced: maybe
it's OK to convert between bool and GinTernaryValue, but it's
definitely not OK to cast between pointers types? Or maybe we should
have a function/macro to convert between the types explicitly and not
encourage people to consider them convertible.

/*
* A ternary value used by tri-consistent functions.
*
* For convenience, this is compatible with booleans. A boolean can be
* safely cast to a GinTernaryValue.
*/
typedef char GinTernaryValue;

0008-Add-necessary-type-cast.patch

Maybe instead of this:

- gcv.check = check;
+ gcv.check = (GinTernaryValue *) check;

... it would be better to do this?

-        bool       *check = (bool *) PG_GETARG_POINTER(0);
+        GinTernaryValue *check = (GinTernaryValue *) PG_GETARG_POINTER(0);

0009-Rename-some-typedefs-to-avoid-name-conflicts.patch

I don't know if it's a relevant precedent or not, but I noticed that
fdwapi.h, amapi.h and tsmapi.h used the convention that function
pointer types are named XXX_function, and then the members of a struct
behaving as a kind of vtable are named XXX.

0010-Reorder-some-things.patch

Forward declarations of static variables are not possible in C++, so
move the full definition before its use.

Right.

0011-Add-missing-fields-in-struct-initializations.patch

I don't undestand why this is necessary, unless you're explicitly
choosing to enable a warning like missing-field-initializers for C++
but not for C. Implicit zero-initialisation of trailing missing
initialisers is a feature, not a bug. Also I noticed that 0013 (or a
proper solution to the keyword collision problem) is needed before
this one.

0012-Separate-enum-from-struct.patch

Right.

0013-Avoid-C-key-words.patch

This is not a long-term solution, because C header files that are
included somewhere might have C++ awareness and will break if the key
word is defined away. But this shows the list of words that would have
to be renamed around the code.

Right, let's rename them all directly.

0015-Fix-function-prototypes-for-C.patch

I wonder if (perhaps in some later later patch) walkers should take
const pointers and mutators non-const. That may require propagating
constness around some more places.

0017-Don-t-define-bool-in-C.patch

Check.

0018-Change-TimeoutId-from-enum-to-integer.patch

This works, but I feel like we're losing something valuable if we
convert all our enums to ints just because some tiny bit of code
somewhere wants to loop over them. Maybe we should we keep enums like
this, and do the necessary casting in the small number of places that
do int-like-stuff with them? Like so:

diff --git a/src/backend/utils/misc/timeout.c b/src/backend/utils/misc/timeout.c
index 7171a7c..cc5b2c4 100644
--- a/src/backend/utils/misc/timeout.c
+++ b/src/backend/utils/misc/timeout.c
@@ -348,7 +348,7 @@ InitializeTimeouts(void)
        for (i = 0; i < MAX_TIMEOUTS; i++)
        {
-               all_timeouts[i].index = i;
+               all_timeouts[i].index = (TimeoutId) i;
                all_timeouts[i].indicator = false;
                all_timeouts[i].timeout_handler = NULL;
                all_timeouts[i].start_time = 0;
@@ -379,7 +379,8 @@ RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
        if (id >= USER_TIMEOUT)
        {
                /* Allocate a user-defined timeout reason */
-               for (id = USER_TIMEOUT; id < MAX_TIMEOUTS; id++)
+               for (id = USER_TIMEOUT; id < MAX_TIMEOUTS;
+                        id = (TimeoutId) ((int) id + 1))
                        if (all_timeouts[id].timeout_handler == NULL)
                                break;
                if (id >= MAX_TIMEOUTS)

0019-Add-explicit-cast-for-casting-away-volatile.patch

- tmp = e->counters;
+ tmp = const_cast<pgssEntry *>(e)->counters;

Obviously we can't just drop C++ casts in here like that. Casting
away volatile might in theory produce the wrong result in some cases,
but we can see that there is a compiler barrier right there already
(included in the preceding SpinLockAcquire) so I guess we could do a
C-style cast to lose volatile so it remains a valid C program:

-                       tmp = e->counters;
+                       tmp = ((pgssEntry *) e)->counters;

0020-Add-more-extern-key-words.patch

Don't we just need to put declarations in a header included by guc.c
and the defining transation unit, or explicitly duplicate the
declarations in both (including the one that defines it immediately
after)? Then we would have valid C and C++ with the right linkage.
That is, instead of this:

-const struct config_enum_entry wal_level_options[] = {
+extern const struct config_enum_entry wal_level_options[] = {
  {"minimal", WAL_LEVEL_MINIMAL, false},
  {"replica", WAL_LEVEL_REPLICA, false},
  {"archive", WAL_LEVEL_REPLICA, true}, /* deprecated */

... we would do this:

+extern const struct config_enum_entry wal_level_options[];

const struct config_enum_entry wal_level_options[] = {
{"minimal", WAL_LEVEL_MINIMAL, false},
{"replica", WAL_LEVEL_REPLICA, false},
{"archive", WAL_LEVEL_REPLICA, true}, /* deprecated */

0022-Disable-conflicting-function.patch

This function conflicts with a function in the backend. FIXME

Indeed:

$ git grep ^xml_is_well_formed\(
contrib/xml2/xpath.c:xml_is_well_formed(PG_FUNCTION_ARGS)
src/backend/utils/adt/xml.c:xml_is_well_formed(PG_FUNCTION_ARGS)

The contrib one says:

/*
* Returns true if document is well-formed
*
* Note: this has been superseded by a core function. We still have to
* have it in the contrib module so that existing SQL-level references
* to the function won't fail; but in normal usage with up-to-date SQL
* definitions for the contrib module, this won't be called.
*/

It's been in core since 9.1, ie in every supported version. I'm not
sure what the comment means exactly but I wonder: can we just delete
the contrib version now?

As for the commitfest entry: this thread discusses two different
people's efforts to compile PostgreSQL as C++. Joy Arulraj's github
branch derives in some way from Peter Eisentraut's work, but I have
provided feedback on Peter's patches, because (1) they were posted
here in patch format and (2) there is a commitfest entry listening
Peter as the author. I think several of these patches are
committable, and many obviously are not. Heikki already set the CF
item to 'Ready for Committer' based on an inspection of a few of the
patches, but invited others to continue looking, so I did.

--
Thomas Munro
http://www.enterprisedb.com

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#70Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Heikki Linnakangas (#56)
Re: [GENERAL] C++ port of Postgres

On 9/6/16 2:58 PM, Heikki Linnakangas wrote:

0001-0003 look clear to me as well. 0006 - 0009 also seem OK. The rest
really only make sense if we decided to make the switch to C++.

I have committed 0001, 0002, 0003, 0006, as well as 0012. Thomas Munro
had some interesting comments on 0007-0009 that are worth considering
further.

The rest of the patches will be kept around for future amusement.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#71Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Thomas Munro (#69)
Re: [GENERAL] C++ port of Postgres

On 9/28/16 10:48 PM, Thomas Munro wrote:

I wonder if the following bit of gin.h should be more nuanced: maybe
it's OK to convert between bool and GinTernaryValue, but it's
definitely not OK to cast between pointers types? Or maybe we should
have a function/macro to convert between the types explicitly and not
encourage people to consider them convertible.

The more I look into the this, the more this looks like a web of lies.
:-) The GIN consistent and triconsistent functions randomly change
around between bool and GinTernaryValue, share some of the same data
structures, and there is little guarantee that they each get the right
kind of value all the time. This could perhaps use some deeper cleaning
at some point. I've left that alone for now.

0009-Rename-some-typedefs-to-avoid-name-conflicts.patch

I don't know if it's a relevant precedent or not, but I noticed that
fdwapi.h, amapi.h and tsmapi.h used the convention that function
pointer types are named XXX_function, and then the members of a struct
behaving as a kind of vtable are named XXX.

Good idea, and that also overlaps with some other stuff I have wanted to
tidy up in pg_dump, so I might get back to that later.

0011-Add-missing-fields-in-struct-initializations.patch

I don't undestand why this is necessary, unless you're explicitly
choosing to enable a warning like missing-field-initializers for C++
but not for C.

I can't reproduce this anymore, so never mind.

As for the commitfest entry: this thread discusses two different
people's efforts to compile PostgreSQL as C++. Joy Arulraj's github
branch derives in some way from Peter Eisentraut's work, but I have
provided feedback on Peter's patches, because (1) they were posted
here in patch format and (2) there is a commitfest entry listening
Peter as the author. I think several of these patches are
committable, and many obviously are not. Heikki already set the CF
item to 'Ready for Committer' based on an inspection of a few of the
patches, but invited others to continue looking, so I did.

Yeah, I have committed a few of the patches now and I'll close the CF
entry now. Thanks for your research.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#72Andres Freund
andres@anarazel.de
In reply to: Peter Eisentraut (#71)
Re: [GENERAL] C++ port of Postgres

Hi Peter,

On 2016-09-30 15:24:09 -0400, Peter Eisentraut wrote:

Yeah, I have committed a few of the patches now and I'll close the CF
entry now. Thanks for your research.

Are you planning to push more of these at some point?

- Andres

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#73Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Andres Freund (#72)
23 attachment(s)
Re: [GENERAL] C++ port of Postgres

On 1/26/17 22:46, Andres Freund wrote:

On 2016-09-30 15:24:09 -0400, Peter Eisentraut wrote:

Yeah, I have committed a few of the patches now and I'll close the CF
entry now. Thanks for your research.

Are you planning to push more of these at some point?

Sure, let's take a look.

Here are rebased patches. It now contains a patch that removes all C++
keywords, instead of just defining them away. With that, this now
builds with g++-6 (formerly only g++-5), and with that, the
static_assert support works as well.

Interesting patches to review would be:

v2-0001-Fix-mixup-of-bool-and-ternary-value.patch
v2-0004-Add-necessary-type-cast.patch
v2-0005-Rename-some-typedefs-to-avoid-name-conflicts.patch
v2-0007-Eliminate-C-keywords.patch
v2-0023-Fix-issue-with-enums-and-va_arg.patch

The rest are mostly for amusement.

Getting rid of the C++ keywords would open up the possibility of using
-Wc++-compat, which you have expressed interest in, I think. I think it
also increases clarity in some cases in its own right, so it's worth
taking a look. (Then again, there are some rush jobs in there, as well.)

(This semi-bug was found while preparing these patches:
https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=eb75f4fced77e108393f18425ec3f7aba2e70a9d)

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

Attachments:

v2-0001-Fix-mixup-of-bool-and-ternary-value.patchtext/x-patch; name=v2-0001-Fix-mixup-of-bool-and-ternary-value.patchDownload
From 041c259a35d37c097191dbdfef3e7268b01dac26 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 01/23] Fix mixup of bool and ternary value

---
 src/backend/access/gin/ginscan.c | 2 +-
 src/include/access/gin_private.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/gin/ginscan.c b/src/backend/access/gin/ginscan.c
index c3ce0479c5..c83375d6b4 100644
--- a/src/backend/access/gin/ginscan.c
+++ b/src/backend/access/gin/ginscan.c
@@ -147,7 +147,7 @@ ginFillScanKey(GinScanOpaque so, OffsetNumber attnum,
 	key->nuserentries = nUserQueryValues;
 
 	key->scanEntry = (GinScanEntry *) palloc(sizeof(GinScanEntry) * nQueryValues);
-	key->entryRes = (bool *) palloc0(sizeof(bool) * nQueryValues);
+	key->entryRes = (GinTernaryValue *) palloc0(sizeof(GinTernaryValue) * nQueryValues);
 
 	key->query = query;
 	key->queryValues = queryValues;
diff --git a/src/include/access/gin_private.h b/src/include/access/gin_private.h
index 34e7339f05..f1f395ac85 100644
--- a/src/include/access/gin_private.h
+++ b/src/include/access/gin_private.h
@@ -281,7 +281,7 @@ typedef struct GinScanKeyData
 	int			nadditional;
 
 	/* array of check flags, reported to consistentFn */
-	bool	   *entryRes;
+	GinTernaryValue *entryRes;
 	bool		(*boolConsistentFn) (GinScanKey key);
 	GinTernaryValue (*triConsistentFn) (GinScanKey key);
 	FmgrInfo   *consistentFmgrInfo;
-- 
2.12.0

v2-0002-Fix-LDFLAGS-test-for-C.patchtext/x-patch; name=v2-0002-Fix-LDFLAGS-test-for-C.patchDownload
From 7c2f4f31df0eec816d6bb17aa6df2e7f3c6da03e Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 02/23] Fix LDFLAGS test for C++

The test looks to link to particular function, so we need to make that
function have C linkage.
---
 config/c-compiler.m4 |  9 ++++++++-
 configure            | 27 ++++++++++++++++++++++++---
 2 files changed, 32 insertions(+), 4 deletions(-)

diff --git a/config/c-compiler.m4 b/config/c-compiler.m4
index 7d901e1f1a..21fb4645c4 100644
--- a/config/c-compiler.m4
+++ b/config/c-compiler.m4
@@ -353,7 +353,14 @@ AC_DEFUN([PGAC_PROG_CC_LDFLAGS_OPT],
 AC_CACHE_CHECK([whether $CC supports $1], [Ac_cachevar],
 [pgac_save_LDFLAGS=$LDFLAGS
 LDFLAGS="$pgac_save_LDFLAGS $1"
-AC_RUN_IFELSE([AC_LANG_PROGRAM([extern void $2 (); void (*fptr) () = $2;],[])],
+AC_RUN_IFELSE([AC_LANG_PROGRAM([#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $2 ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $2;],[])],
               [Ac_cachevar=yes],
               [Ac_cachevar=no],
               [Ac_cachevar="assuming no"])
diff --git a/configure b/configure
index b5cdebb510..b1ad1ce838 100755
--- a/configure
+++ b/configure
@@ -16025,7 +16025,14 @@ if test "$cross_compiling" = yes; then :
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-extern void $link_test_func (); void (*fptr) () = $link_test_func;
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $link_test_func ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $link_test_func;
 int
 main ()
 {
@@ -16064,7 +16071,14 @@ if test "$cross_compiling" = yes; then :
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-extern void $link_test_func (); void (*fptr) () = $link_test_func;
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $link_test_func ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $link_test_func;
 int
 main ()
 {
@@ -16103,7 +16117,14 @@ if test "$cross_compiling" = yes; then :
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-extern void $link_test_func (); void (*fptr) () = $link_test_func;
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $link_test_func ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $link_test_func;
 int
 main ()
 {
-- 
2.12.0

v2-0003-Add-test-for-Wmissing-prototypes.patchtext/x-patch; name=v2-0003-Add-test-for-Wmissing-prototypes.patchDownload
From fd5248ca63ce3cf35f22cebd2088c4dfd3d994a4 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 03/23] Add test for -Wmissing-prototypes

This was part of the hard-coded default warnings set in C, but the
option is not valid for C++ (since prototypes are always required).
---
 configure    | 38 +++++++++++++++++++++++++++++++++++++-
 configure.in |  4 +++-
 2 files changed, 40 insertions(+), 2 deletions(-)

diff --git a/configure b/configure
index b1ad1ce838..f0c5356e1f 100755
--- a/configure
+++ b/configure
@@ -4440,7 +4440,43 @@ fi
 # but has its own.  Also check other compiler-specific flags here.
 
 if test "$GCC" = yes -a "$ICC" = no; then
-  CFLAGS="-Wall -Wmissing-prototypes -Wpointer-arith"
+  CFLAGS="-Wall -Wpointer-arith"
+  # not valid for C++
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wmissing-prototypes" >&5
+$as_echo_n "checking whether $CC supports -Wmissing-prototypes... " >&6; }
+if ${pgac_cv_prog_cc_cflags__Wmissing_prototypes+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  pgac_save_CFLAGS=$CFLAGS
+CFLAGS="$pgac_save_CFLAGS -Wmissing-prototypes"
+ac_save_c_werror_flag=$ac_c_werror_flag
+ac_c_werror_flag=yes
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  pgac_cv_prog_cc_cflags__Wmissing_prototypes=yes
+else
+  pgac_cv_prog_cc_cflags__Wmissing_prototypes=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_c_werror_flag=$ac_save_c_werror_flag
+CFLAGS="$pgac_save_CFLAGS"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $pgac_cv_prog_cc_cflags__Wmissing_prototypes" >&5
+$as_echo "$pgac_cv_prog_cc_cflags__Wmissing_prototypes" >&6; }
+if test x"$pgac_cv_prog_cc_cflags__Wmissing_prototypes" = x"yes"; then
+  CFLAGS="$CFLAGS -Wmissing-prototypes"
+fi
+
   # These work in some but not all gcc versions
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wdeclaration-after-statement" >&5
 $as_echo_n "checking whether $CC supports -Wdeclaration-after-statement... " >&6; }
diff --git a/configure.in b/configure.in
index 1d99cda1d8..8099e5c59f 100644
--- a/configure.in
+++ b/configure.in
@@ -445,7 +445,9 @@ fi
 # but has its own.  Also check other compiler-specific flags here.
 
 if test "$GCC" = yes -a "$ICC" = no; then
-  CFLAGS="-Wall -Wmissing-prototypes -Wpointer-arith"
+  CFLAGS="-Wall -Wpointer-arith"
+  # not valid for C++
+  PGAC_PROG_CC_CFLAGS_OPT([-Wmissing-prototypes])
   # These work in some but not all gcc versions
   PGAC_PROG_CC_CFLAGS_OPT([-Wdeclaration-after-statement])
   PGAC_PROG_CC_CFLAGS_OPT([-Wendif-labels])
-- 
2.12.0

v2-0004-Add-necessary-type-cast.patchtext/x-patch; name=v2-0004-Add-necessary-type-cast.patchDownload
From 3447e7cc85c1f2836d882e19952e6db1950a2607 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 04/23] Add necessary type cast

---
 src/backend/utils/adt/tsginidx.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/tsginidx.c b/src/backend/utils/adt/tsginidx.c
index 83a939dfd5..8f38972676 100644
--- a/src/backend/utils/adt/tsginidx.c
+++ b/src/backend/utils/adt/tsginidx.c
@@ -309,7 +309,7 @@ gin_tsquery_consistent(PG_FUNCTION_ARGS)
 		 * query.
 		 */
 		gcv.first_item = GETQUERY(query);
-		gcv.check = check;
+		gcv.check = (GinTernaryValue *) check;
 		gcv.map_item_operand = (int *) (extra_data[0]);
 		gcv.need_recheck = recheck;
 
-- 
2.12.0

v2-0005-Rename-some-typedefs-to-avoid-name-conflicts.patchtext/x-patch; name=v2-0005-Rename-some-typedefs-to-avoid-name-conflicts.patchDownload
From db1807e62dd6ccf358132a7c56ede2531d33336f Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 05/23] Rename some typedefs to avoid name conflicts

C++ does not like that in struct _archiveHandle some of the fields have
the same name as a typedef.  This changes the meaning of the typedef in
the scope of the struct, causing warnings and possibly other problems.

Rename the types so they have names distinct from the struct fields.
---
 src/bin/pg_dump/pg_backup.h          |  4 +-
 src/bin/pg_dump/pg_backup_archiver.c | 10 ++--
 src/bin/pg_dump/pg_backup_archiver.h | 96 ++++++++++++++++++------------------
 3 files changed, 55 insertions(+), 55 deletions(-)

diff --git a/src/bin/pg_dump/pg_backup.h b/src/bin/pg_dump/pg_backup.h
index 6480fb8e74..a6e84efc38 100644
--- a/src/bin/pg_dump/pg_backup.h
+++ b/src/bin/pg_dump/pg_backup.h
@@ -229,7 +229,7 @@ typedef int DumpId;
 
 typedef int (*DataDumperPtr) (Archive *AH, void *userArg);
 
-typedef void (*SetupWorkerPtr) (Archive *AH);
+typedef void (*SetupWorkerPtrType) (Archive *AH);
 
 /*
  * Main archiver interface.
@@ -276,7 +276,7 @@ extern Archive *OpenArchive(const char *FileSpec, const ArchiveFormat fmt);
 /* Create a new archive */
 extern Archive *CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
 			  const int compression, ArchiveMode mode,
-			  SetupWorkerPtr setupDumpWorker);
+			  SetupWorkerPtrType setupDumpWorker);
 
 /* The --list option */
 extern void PrintTOCSummary(Archive *AH);
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index 7e2bed38b3..e387293664 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -54,7 +54,7 @@ static const char *modulename = gettext_noop("archiver");
 
 
 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
-	 const int compression, ArchiveMode mode, SetupWorkerPtr setupWorkerPtr);
+	 const int compression, ArchiveMode mode, SetupWorkerPtrType setupWorkerPtr);
 static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
 					  ArchiveHandle *AH);
 static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData, bool acl_pass);
@@ -202,7 +202,7 @@ setupRestoreWorker(Archive *AHX)
 /* Public */
 Archive *
 CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
-	 const int compression, ArchiveMode mode, SetupWorkerPtr setupDumpWorker)
+	 const int compression, ArchiveMode mode, SetupWorkerPtrType setupDumpWorker)
 
 {
 	ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, mode, setupDumpWorker);
@@ -2241,7 +2241,7 @@ _discoverArchiveFormat(ArchiveHandle *AH)
  */
 static ArchiveHandle *
 _allocAH(const char *FileSpec, const ArchiveFormat fmt,
-	  const int compression, ArchiveMode mode, SetupWorkerPtr setupWorkerPtr)
+	  const int compression, ArchiveMode mode, SetupWorkerPtrType setupWorkerPtr)
 {
 	ArchiveHandle *AH;
 
@@ -2413,8 +2413,8 @@ mark_dump_job_done(ArchiveHandle *AH,
 void
 WriteDataChunksForTocEntry(ArchiveHandle *AH, TocEntry *te)
 {
-	StartDataPtr startPtr;
-	EndDataPtr	endPtr;
+	StartDataPtrType startPtr;
+	EndDataPtrType	endPtr;
 
 	AH->currToc = te;
 
diff --git a/src/bin/pg_dump/pg_backup_archiver.h b/src/bin/pg_dump/pg_backup_archiver.h
index a44e16ee45..81f0db8d3c 100644
--- a/src/bin/pg_dump/pg_backup_archiver.h
+++ b/src/bin/pg_dump/pg_backup_archiver.h
@@ -143,36 +143,36 @@ typedef enum T_Action
 	ACT_RESTORE
 } T_Action;
 
-typedef void (*ClosePtr) (ArchiveHandle *AH);
-typedef void (*ReopenPtr) (ArchiveHandle *AH);
-typedef void (*ArchiveEntryPtr) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*ClosePtrType) (ArchiveHandle *AH);
+typedef void (*ReopenPtrType) (ArchiveHandle *AH);
+typedef void (*ArchiveEntryPtrType) (ArchiveHandle *AH, TocEntry *te);
 
-typedef void (*StartDataPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*WriteDataPtr) (ArchiveHandle *AH, const void *data, size_t dLen);
-typedef void (*EndDataPtr) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*StartDataPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*WriteDataPtrType) (ArchiveHandle *AH, const void *data, size_t dLen);
+typedef void (*EndDataPtrType) (ArchiveHandle *AH, TocEntry *te);
 
-typedef void (*StartBlobsPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*StartBlobPtr) (ArchiveHandle *AH, TocEntry *te, Oid oid);
-typedef void (*EndBlobPtr) (ArchiveHandle *AH, TocEntry *te, Oid oid);
-typedef void (*EndBlobsPtr) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*StartBlobsPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*StartBlobPtrType) (ArchiveHandle *AH, TocEntry *te, Oid oid);
+typedef void (*EndBlobPtrType) (ArchiveHandle *AH, TocEntry *te, Oid oid);
+typedef void (*EndBlobsPtrType) (ArchiveHandle *AH, TocEntry *te);
 
-typedef int (*WriteBytePtr) (ArchiveHandle *AH, const int i);
-typedef int (*ReadBytePtr) (ArchiveHandle *AH);
-typedef void (*WriteBufPtr) (ArchiveHandle *AH, const void *c, size_t len);
-typedef void (*ReadBufPtr) (ArchiveHandle *AH, void *buf, size_t len);
-typedef void (*SaveArchivePtr) (ArchiveHandle *AH);
-typedef void (*WriteExtraTocPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*ReadExtraTocPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*PrintExtraTocPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef void (*PrintTocDataPtr) (ArchiveHandle *AH, TocEntry *te);
+typedef int (*WriteBytePtrType) (ArchiveHandle *AH, const int i);
+typedef int (*ReadBytePtrType) (ArchiveHandle *AH);
+typedef void (*WriteBufPtrType) (ArchiveHandle *AH, const void *c, size_t len);
+typedef void (*ReadBufPtrType) (ArchiveHandle *AH, void *buf, size_t len);
+typedef void (*SaveArchivePtrType) (ArchiveHandle *AH);
+typedef void (*WriteExtraTocPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*ReadExtraTocPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*PrintExtraTocPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef void (*PrintTocDataPtrType) (ArchiveHandle *AH, TocEntry *te);
 
-typedef void (*ClonePtr) (ArchiveHandle *AH);
-typedef void (*DeClonePtr) (ArchiveHandle *AH);
+typedef void (*ClonePtrType) (ArchiveHandle *AH);
+typedef void (*DeClonePtrType) (ArchiveHandle *AH);
 
-typedef int (*WorkerJobDumpPtr) (ArchiveHandle *AH, TocEntry *te);
-typedef int (*WorkerJobRestorePtr) (ArchiveHandle *AH, TocEntry *te);
+typedef int (*WorkerJobDumpPtrType) (ArchiveHandle *AH, TocEntry *te);
+typedef int (*WorkerJobRestorePtrType) (ArchiveHandle *AH, TocEntry *te);
 
-typedef size_t (*CustomOutPtr) (ArchiveHandle *AH, const void *buf, size_t len);
+typedef size_t (*CustomOutPtrType) (ArchiveHandle *AH, const void *buf, size_t len);
 
 typedef enum
 {
@@ -242,39 +242,39 @@ struct _archiveHandle
 	size_t		lookaheadLen;	/* Length of data in lookahead */
 	pgoff_t		lookaheadPos;	/* Current read position in lookahead buffer */
 
-	ArchiveEntryPtr ArchiveEntryPtr;	/* Called for each metadata object */
-	StartDataPtr StartDataPtr;	/* Called when table data is about to be
+	ArchiveEntryPtrType ArchiveEntryPtr;	/* Called for each metadata object */
+	StartDataPtrType StartDataPtr;	/* Called when table data is about to be
 								 * dumped */
-	WriteDataPtr WriteDataPtr;	/* Called to send some table data to the
+	WriteDataPtrType WriteDataPtr;	/* Called to send some table data to the
 								 * archive */
-	EndDataPtr EndDataPtr;		/* Called when table data dump is finished */
-	WriteBytePtr WriteBytePtr;	/* Write a byte to output */
-	ReadBytePtr ReadBytePtr;	/* Read a byte from an archive */
-	WriteBufPtr WriteBufPtr;	/* Write a buffer of output to the archive */
-	ReadBufPtr ReadBufPtr;		/* Read a buffer of input from the archive */
-	ClosePtr ClosePtr;			/* Close the archive */
-	ReopenPtr ReopenPtr;		/* Reopen the archive */
-	WriteExtraTocPtr WriteExtraTocPtr;	/* Write extra TOC entry data
+	EndDataPtrType EndDataPtr;		/* Called when table data dump is finished */
+	WriteBytePtrType WriteBytePtr;	/* Write a byte to output */
+	ReadBytePtrType ReadBytePtr;	/* Read a byte from an archive */
+	WriteBufPtrType WriteBufPtr;	/* Write a buffer of output to the archive */
+	ReadBufPtrType ReadBufPtr;		/* Read a buffer of input from the archive */
+	ClosePtrType ClosePtr;			/* Close the archive */
+	ReopenPtrType ReopenPtr;		/* Reopen the archive */
+	WriteExtraTocPtrType WriteExtraTocPtr;	/* Write extra TOC entry data
 										 * associated with the current archive
 										 * format */
-	ReadExtraTocPtr ReadExtraTocPtr;	/* Read extr info associated with
+	ReadExtraTocPtrType ReadExtraTocPtr;	/* Read extr info associated with
 										 * archie format */
-	PrintExtraTocPtr PrintExtraTocPtr;	/* Extra TOC info for format */
-	PrintTocDataPtr PrintTocDataPtr;
+	PrintExtraTocPtrType PrintExtraTocPtr;	/* Extra TOC info for format */
+	PrintTocDataPtrType PrintTocDataPtr;
 
-	StartBlobsPtr StartBlobsPtr;
-	EndBlobsPtr EndBlobsPtr;
-	StartBlobPtr StartBlobPtr;
-	EndBlobPtr EndBlobPtr;
+	StartBlobsPtrType StartBlobsPtr;
+	EndBlobsPtrType EndBlobsPtr;
+	StartBlobPtrType StartBlobPtr;
+	EndBlobPtrType EndBlobPtr;
 
-	SetupWorkerPtr SetupWorkerPtr;
-	WorkerJobDumpPtr WorkerJobDumpPtr;
-	WorkerJobRestorePtr WorkerJobRestorePtr;
+	SetupWorkerPtrType SetupWorkerPtr;
+	WorkerJobDumpPtrType WorkerJobDumpPtr;
+	WorkerJobRestorePtrType WorkerJobRestorePtr;
 
-	ClonePtr ClonePtr;			/* Clone format-specific fields */
-	DeClonePtr DeClonePtr;		/* Clean up cloned fields */
+	ClonePtrType ClonePtr;			/* Clone format-specific fields */
+	DeClonePtrType DeClonePtr;		/* Clean up cloned fields */
 
-	CustomOutPtr CustomOutPtr;	/* Alternative script output routine */
+	CustomOutPtrType CustomOutPtr;	/* Alternative script output routine */
 
 	/* Stuff for direct DB connection */
 	char	   *archdbname;		/* DB name *read* from archive */
-- 
2.12.0

v2-0006-Reorder-some-things.patchtext/x-patch; name=v2-0006-Reorder-some-things.patchDownload
From 997b09fca65a139af8e73d7e6356739383bd8df1 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 06/23] Reorder some things

Forward declarations of static variables are not possible in C++, so
move the full definition before its use.
---
 src/port/pg_crc32c_sb8.c | 136 +++++++++++++++++++++++------------------------
 1 file changed, 67 insertions(+), 69 deletions(-)

diff --git a/src/port/pg_crc32c_sb8.c b/src/port/pg_crc32c_sb8.c
index eff7043202..92458a3062 100644
--- a/src/port/pg_crc32c_sb8.c
+++ b/src/port/pg_crc32c_sb8.c
@@ -22,8 +22,6 @@
 
 #include "port/pg_crc32c.h"
 
-static const uint32 pg_crc32c_table[8][256];
-
 /* Accumulate one input byte */
 #ifdef WORDS_BIGENDIAN
 #define CRC8(x) pg_crc32c_table[0][((crc >> 24) ^ (x)) & 0xFF] ^ (crc << 8)
@@ -31,73 +29,6 @@ static const uint32 pg_crc32c_table[8][256];
 #define CRC8(x) pg_crc32c_table[0][(crc ^ (x)) & 0xFF] ^ (crc >> 8)
 #endif
 
-pg_crc32c
-pg_comp_crc32c_sb8(pg_crc32c crc, const void *data, size_t len)
-{
-	const unsigned char *p = data;
-	const uint32 *p4;
-
-	/*
-	 * Handle 0-3 initial bytes one at a time, so that the loop below starts
-	 * with a pointer aligned to four bytes.
-	 */
-	while (len > 0 && ((uintptr_t) p & 3))
-	{
-		crc = CRC8(*p++);
-		len--;
-	}
-
-	/*
-	 * Process eight bytes of data at a time.
-	 */
-	p4 = (const uint32 *) p;
-	while (len >= 8)
-	{
-		uint32		a = *p4++ ^ crc;
-		uint32		b = *p4++;
-
-#ifdef WORDS_BIGENDIAN
-		const uint8 c0 = b;
-		const uint8 c1 = b >> 8;
-		const uint8 c2 = b >> 16;
-		const uint8 c3 = b >> 24;
-		const uint8 c4 = a;
-		const uint8 c5 = a >> 8;
-		const uint8 c6 = a >> 16;
-		const uint8 c7 = a >> 24;
-#else
-		const uint8 c0 = b >> 24;
-		const uint8 c1 = b >> 16;
-		const uint8 c2 = b >> 8;
-		const uint8 c3 = b;
-		const uint8 c4 = a >> 24;
-		const uint8 c5 = a >> 16;
-		const uint8 c6 = a >> 8;
-		const uint8 c7 = a;
-#endif
-
-		crc =
-			pg_crc32c_table[0][c0] ^ pg_crc32c_table[1][c1] ^
-			pg_crc32c_table[2][c2] ^ pg_crc32c_table[3][c3] ^
-			pg_crc32c_table[4][c4] ^ pg_crc32c_table[5][c5] ^
-			pg_crc32c_table[6][c6] ^ pg_crc32c_table[7][c7];
-
-		len -= 8;
-	}
-
-	/*
-	 * Handle any remaining bytes one at a time.
-	 */
-	p = (const unsigned char *) p4;
-	while (len > 0)
-	{
-		crc = CRC8(*p++);
-		len--;
-	}
-
-	return crc;
-}
-
 /*
  * Lookup tables for the slicing-by-8 algorithm, for the so-called Castagnoli
  * polynomial (the same that is used e.g. in iSCSI), 0x1EDC6F41. Using
@@ -1167,3 +1098,70 @@ static const uint32 pg_crc32c_table[8][256] = {
 	}
 #endif   /* WORDS_BIGENDIAN */
 };
+
+pg_crc32c
+pg_comp_crc32c_sb8(pg_crc32c crc, const void *data, size_t len)
+{
+	const unsigned char *p = data;
+	const uint32 *p4;
+
+	/*
+	 * Handle 0-3 initial bytes one at a time, so that the loop below starts
+	 * with a pointer aligned to four bytes.
+	 */
+	while (len > 0 && ((uintptr_t) p & 3))
+	{
+		crc = CRC8(*p++);
+		len--;
+	}
+
+	/*
+	 * Process eight bytes of data at a time.
+	 */
+	p4 = (const uint32 *) p;
+	while (len >= 8)
+	{
+		uint32		a = *p4++ ^ crc;
+		uint32		b = *p4++;
+
+#ifdef WORDS_BIGENDIAN
+		const uint8 c0 = b;
+		const uint8 c1 = b >> 8;
+		const uint8 c2 = b >> 16;
+		const uint8 c3 = b >> 24;
+		const uint8 c4 = a;
+		const uint8 c5 = a >> 8;
+		const uint8 c6 = a >> 16;
+		const uint8 c7 = a >> 24;
+#else
+		const uint8 c0 = b >> 24;
+		const uint8 c1 = b >> 16;
+		const uint8 c2 = b >> 8;
+		const uint8 c3 = b;
+		const uint8 c4 = a >> 24;
+		const uint8 c5 = a >> 16;
+		const uint8 c6 = a >> 8;
+		const uint8 c7 = a;
+#endif
+
+		crc =
+			pg_crc32c_table[0][c0] ^ pg_crc32c_table[1][c1] ^
+			pg_crc32c_table[2][c2] ^ pg_crc32c_table[3][c3] ^
+			pg_crc32c_table[4][c4] ^ pg_crc32c_table[5][c5] ^
+			pg_crc32c_table[6][c6] ^ pg_crc32c_table[7][c7];
+
+		len -= 8;
+	}
+
+	/*
+	 * Handle any remaining bytes one at a time.
+	 */
+	p = (const unsigned char *) p4;
+	while (len > 0)
+	{
+		crc = CRC8(*p++);
+		len--;
+	}
+
+	return crc;
+}
-- 
2.12.0

v2-0007-Eliminate-C-keywords.patchtext/x-patch; name=v2-0007-Eliminate-C-keywords.patchDownload
From e3393f8f5718b31c4ffe0346edabd8b08a2c7a3f Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 07/23] Eliminate C++ keywords

Remove use of these keywords: class constexpr delete friend namespace
new operator private public template this typeid typename
---
 contrib/hstore/hstore.h                     |   2 +-
 contrib/ltree/ltree_op.c                    |   4 +-
 contrib/postgres_fdw/postgres_fdw.c         |  12 +-
 src/backend/access/brin/brin_inclusion.c    |   6 +-
 src/backend/access/gist/gistproc.c          |   6 +-
 src/backend/access/transam/xlog.c           |  22 +-
 src/backend/catalog/namespace.c             |  40 +-
 src/backend/catalog/objectaddress.c         |  22 +-
 src/backend/catalog/partition.c             |   6 +-
 src/backend/catalog/pg_db_role_setting.c    |   8 +-
 src/backend/commands/alter.c                |   6 +-
 src/backend/commands/collationcmds.c        |   6 +-
 src/backend/commands/explain.c              |  14 +-
 src/backend/commands/functioncmds.c         |  34 +-
 src/backend/commands/tablecmds.c            |  10 +-
 src/backend/commands/typecmds.c             |  70 ++--
 src/backend/executor/execReplication.c      |   8 +-
 src/backend/nodes/copyfuncs.c               |  14 +-
 src/backend/optimizer/geqo/geqo_erx.c       |  20 +-
 src/backend/optimizer/geqo/geqo_eval.c      |   4 +-
 src/backend/optimizer/geqo/geqo_main.c      |   6 +-
 src/backend/optimizer/geqo/geqo_random.c    |  12 +-
 src/backend/optimizer/util/predtest.c       |  20 +-
 src/backend/parser/gram.y                   |  12 +-
 src/backend/parser/parse_clause.c           |  44 +-
 src/backend/parser/parse_node.c             |  48 +--
 src/backend/parser/scan.l                   |  20 +-
 src/backend/tcop/fastpath.c                 |  10 +-
 src/backend/tsearch/spell.c                 |  10 +-
 src/backend/utils/adt/acl.c                 |  18 +-
 src/backend/utils/adt/array_selfuncs.c      |  64 +--
 src/backend/utils/adt/format_type.c         |   6 +-
 src/backend/utils/adt/misc.c                |  10 +-
 src/backend/utils/adt/network_gist.c        |  14 +-
 src/backend/utils/adt/network_selfuncs.c    |  56 +--
 src/backend/utils/adt/numeric.c             |  22 +-
 src/backend/utils/adt/rangetypes_gist.c     |  24 +-
 src/backend/utils/adt/rangetypes_selfuncs.c |  52 +--
 src/backend/utils/adt/regproc.c             |  16 +-
 src/backend/utils/adt/ri_triggers.c         |  22 +-
 src/backend/utils/adt/ruleutils.c           |  24 +-
 src/backend/utils/adt/selfuncs.c            | 120 +++---
 src/backend/utils/adt/tsquery.c             |  18 +-
 src/backend/utils/adt/tsquery_op.c          |   6 +-
 src/backend/utils/adt/varbit.c              |   6 +-
 src/backend/utils/adt/varchar.c             |   6 +-
 src/backend/utils/adt/xml.c                 |   4 +-
 src/backend/utils/cache/ts_cache.c          |  14 +-
 src/backend/utils/fmgr/dfmgr.c              |  38 +-
 src/backend/utils/init/miscinit.c           |   6 +-
 src/bin/pg_dump/common.c                    |   4 +-
 src/bin/pg_dump/parallel.c                  |  16 +-
 src/bin/pg_dump/pg_backup.h                 |   2 +-
 src/bin/pg_dump/pg_backup_archiver.c        | 136 +++----
 src/bin/pg_dump/pg_backup_archiver.h        |   8 +-
 src/bin/pg_dump/pg_backup_custom.c          |   4 +-
 src/bin/pg_dump/pg_backup_db.c              |  16 +-
 src/bin/pg_dump/pg_backup_directory.c       |   4 +-
 src/bin/pg_dump/pg_backup_null.c            |   2 +-
 src/bin/pg_dump/pg_backup_tar.c             |  16 +-
 src/bin/pg_dump/pg_dump.c                   | 454 ++++++++++-----------
 src/bin/pg_dump/pg_dump.h                   |   4 +-
 src/bin/pg_dump/pg_dump_sort.c              |  12 +-
 src/bin/pg_rewind/parsexlog.c               |  44 +-
 src/bin/pg_waldump/pg_waldump.c             | 100 ++---
 src/bin/pgbench/exprparse.y                 |   6 +-
 src/bin/psql/tab-complete.c                 |  40 +-
 src/bin/scripts/createdb.c                  |   8 +-
 src/interfaces/ecpg/compatlib/informix.c    |  10 +-
 src/interfaces/ecpg/ecpglib/connect.c       |  36 +-
 src/interfaces/ecpg/ecpglib/descriptor.c    |  30 +-
 src/interfaces/ecpg/ecpglib/memory.c        |  20 +-
 src/interfaces/ecpg/ecpglib/prepare.c       |  88 ++--
 src/interfaces/ecpg/pgtypeslib/common.c     |  12 +-
 src/interfaces/ecpg/preproc/descriptor.c    |  30 +-
 src/interfaces/ecpg/preproc/ecpg.addons     |  32 +-
 src/interfaces/ecpg/preproc/ecpg.c          |  44 +-
 src/interfaces/ecpg/preproc/ecpg.header     |  28 +-
 src/interfaces/ecpg/preproc/ecpg.trailer    |  98 ++---
 src/interfaces/ecpg/preproc/pgc.l           |  44 +-
 src/interfaces/ecpg/preproc/type.c          |  12 +-
 src/interfaces/ecpg/preproc/type.h          |   4 +-
 src/interfaces/ecpg/preproc/variable.c      |  20 +-
 src/pl/plpgsql/src/pl_comp.c                |  86 ++--
 src/pl/plpgsql/src/pl_exec.c                |  68 ++--
 src/pl/plpgsql/src/pl_gram.y                | 600 ++++++++++++++--------------
 src/pl/plpgsql/src/plpgsql.h                |   4 +-
 src/port/path.c                             |  16 +-
 src/test/isolation/isolationtester.c        |   6 +-
 src/test/regress/pg_regress.c               |   6 +-
 90 files changed, 1606 insertions(+), 1606 deletions(-)

diff --git a/contrib/hstore/hstore.h b/contrib/hstore/hstore.h
index 6bab08b7de..fbedc971c0 100644
--- a/contrib/hstore/hstore.h
+++ b/contrib/hstore/hstore.h
@@ -188,7 +188,7 @@ extern Pairs *hstoreArrayToPairs(ArrayType *a, int *npairs);
  * for now, we default to on for the benefit of people restoring old dumps
  */
 #ifndef HSTORE_POLLUTE_NAMESPACE
-#define HSTORE_POLLUTE_NAMESPACE 1
+#define HSTORE_POLLUTE_NAMESPACE 0
 #endif
 
 #if HSTORE_POLLUTE_NAMESPACE
diff --git a/contrib/ltree/ltree_op.c b/contrib/ltree/ltree_op.c
index aa1e9918be..b51cde715e 100644
--- a/contrib/ltree/ltree_op.c
+++ b/contrib/ltree/ltree_op.c
@@ -545,7 +545,7 @@ Datum
 ltreeparentsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	VariableStatData vardata;
@@ -582,7 +582,7 @@ ltreeparentsel(PG_FUNCTION_ARGS)
 		double		nullfrac;
 		int			hist_size;
 
-		fmgr_info(get_opcode(operator), &contproc);
+		fmgr_info(get_opcode(opid), &contproc);
 
 		/*
 		 * Is the constant "<@" to any of the column's most common values?
diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 5d270b948a..3b58944d69 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -486,7 +486,7 @@ postgresGetForeignRelSize(PlannerInfo *root,
 	PgFdwRelationInfo *fpinfo;
 	ListCell   *lc;
 	RangeTblEntry *rte = planner_rt_fetch(baserel->relid, root);
-	const char *namespace;
+	const char *nspname;
 	const char *relname;
 	const char *refname;
 
@@ -659,11 +659,11 @@ postgresGetForeignRelSize(PlannerInfo *root,
 	 * not, so always schema-qualify the foreign table name.
 	 */
 	fpinfo->relation_name = makeStringInfo();
-	namespace = get_namespace_name(get_rel_namespace(foreigntableid));
+	nspname = get_namespace_name(get_rel_namespace(foreigntableid));
 	relname = get_rel_name(foreigntableid);
 	refname = rte->eref->aliasname;
 	appendStringInfo(fpinfo->relation_name, "%s.%s",
-					 quote_identifier(namespace),
+					 quote_identifier(nspname),
 					 quote_identifier(relname));
 	if (*refname && strcmp(refname, relname) != 0)
 		appendStringInfo(fpinfo->relation_name, " %s",
@@ -3938,7 +3938,7 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid)
 			do
 			{
 				char	   *attname;
-				char	   *typename;
+				char	   *typname;
 				char	   *attnotnull;
 				char	   *attdefault;
 				char	   *collname;
@@ -3949,7 +3949,7 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid)
 					continue;
 
 				attname = PQgetvalue(res, i, 1);
-				typename = PQgetvalue(res, i, 2);
+				typname = PQgetvalue(res, i, 2);
 				attnotnull = PQgetvalue(res, i, 3);
 				attdefault = PQgetisnull(res, i, 4) ? (char *) NULL :
 					PQgetvalue(res, i, 4);
@@ -3966,7 +3966,7 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid)
 				/* Print column name and type */
 				appendStringInfo(&buf, "  %s %s",
 								 quote_identifier(attname),
-								 typename);
+								 typname);
 
 				/*
 				 * Add column_name option so that renaming the foreign table's
diff --git a/src/backend/access/brin/brin_inclusion.c b/src/backend/access/brin/brin_inclusion.c
index bc16dd7981..b1a277eca3 100644
--- a/src/backend/access/brin/brin_inclusion.c
+++ b/src/backend/access/brin/brin_inclusion.c
@@ -139,7 +139,7 @@ brin_inclusion_add_value(PG_FUNCTION_ARGS)
 	Oid			colloid = PG_GET_COLLATION();
 	FmgrInfo   *finfo;
 	Datum		result;
-	bool		new = false;
+	bool		isnew = false;
 	AttrNumber	attno;
 	Form_pg_attribute attr;
 
@@ -170,7 +170,7 @@ brin_inclusion_add_value(PG_FUNCTION_ARGS)
 		column->bv_values[INCLUSION_UNMERGEABLE] = BoolGetDatum(false);
 		column->bv_values[INCLUSION_CONTAINS_EMPTY] = BoolGetDatum(false);
 		column->bv_allnulls = false;
-		new = true;
+		isnew = true;
 	}
 
 	/*
@@ -197,7 +197,7 @@ brin_inclusion_add_value(PG_FUNCTION_ARGS)
 		PG_RETURN_BOOL(false);
 	}
 
-	if (new)
+	if (isnew)
 		PG_RETURN_BOOL(true);
 
 	/* Check if the new value is already contained. */
diff --git a/src/backend/access/gist/gistproc.c b/src/backend/access/gist/gistproc.c
index ffb1d772ad..4394dd88f7 100644
--- a/src/backend/access/gist/gistproc.c
+++ b/src/backend/access/gist/gistproc.c
@@ -92,12 +92,12 @@ size_box(const BOX *box)
  * the original BOX's area.  The result can be +Infinity, but not NaN.
  */
 static double
-box_penalty(const BOX *original, const BOX *new)
+box_penalty(const BOX *originalbox, const BOX *newbox)
 {
 	BOX			unionbox;
 
-	rt_box_union(&unionbox, original, new);
-	return size_box(&unionbox) - size_box(original);
+	rt_box_union(&unionbox, originalbox, newbox);
+	return size_box(&unionbox) - size_box(originalbox);
 }
 
 /*
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 897358342d..038b8472ae 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -4128,12 +4128,12 @@ ReadRecord(XLogReaderState *xlogreader, XLogRecPtr RecPtr, int emode,
 		   bool fetching_ckpt)
 {
 	XLogRecord *record;
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogPageReadPrivate *private_data = (XLogPageReadPrivate *) xlogreader->private_data;
 
 	/* Pass through parameters to XLogPageRead */
-	private->fetching_ckpt = fetching_ckpt;
-	private->emode = emode;
-	private->randAccess = (RecPtr != InvalidXLogRecPtr);
+	private_data->fetching_ckpt = fetching_ckpt;
+	private_data->emode = emode;
+	private_data->randAccess = (RecPtr != InvalidXLogRecPtr);
 
 	/* This is the first attempt to read this page. */
 	lastSourceFailed = false;
@@ -6148,7 +6148,7 @@ StartupXLOG(void)
 	bool		backupFromStandby = false;
 	DBState		dbstate_at_startup;
 	XLogReaderState *xlogreader;
-	XLogPageReadPrivate private;
+	XLogPageReadPrivate private_data;
 	bool		fast_promoted = false;
 	struct stat st;
 
@@ -6285,8 +6285,8 @@ StartupXLOG(void)
 		OwnLatch(&XLogCtl->recoveryWakeupLatch);
 
 	/* Set up XLOG reader facility */
-	MemSet(&private, 0, sizeof(XLogPageReadPrivate));
-	xlogreader = XLogReaderAllocate(&XLogPageRead, &private);
+	MemSet(&private_data, 0, sizeof(XLogPageReadPrivate));
+	xlogreader = XLogReaderAllocate(&XLogPageRead, &private_data);
 	if (!xlogreader)
 		ereport(ERROR,
 				(errcode(ERRCODE_OUT_OF_MEMORY),
@@ -11339,9 +11339,9 @@ static int
 XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
 			 XLogRecPtr targetRecPtr, char *readBuf, TimeLineID *readTLI)
 {
-	XLogPageReadPrivate *private =
+	XLogPageReadPrivate *private_data =
 	(XLogPageReadPrivate *) xlogreader->private_data;
-	int			emode = private->emode;
+	int			emode = private_data->emode;
 	uint32		targetPageOff;
 	XLogSegNo targetSegNo PG_USED_FOR_ASSERTS_ONLY;
 
@@ -11382,8 +11382,8 @@ XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
 		 receivedUpto < targetPagePtr + reqLen))
 	{
 		if (!WaitForWALToBecomeAvailable(targetPagePtr + reqLen,
-										 private->randAccess,
-										 private->fetching_ckpt,
+										 private_data->randAccess,
+										 private_data->fetching_ckpt,
 										 targetRecPtr))
 		{
 			if (readFile >= 0)
diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c
index a38da3047f..302a55a0bf 100644
--- a/src/backend/catalog/namespace.c
+++ b/src/backend/catalog/namespace.c
@@ -2153,7 +2153,7 @@ TSParserIsVisible(Oid prsId)
 {
 	HeapTuple	tup;
 	Form_pg_ts_parser form;
-	Oid			namespace;
+	Oid			prsnamespace;
 	bool		visible;
 
 	tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
@@ -2168,9 +2168,9 @@ TSParserIsVisible(Oid prsId)
 	 * the system namespace are surely in the path and so we needn't even do
 	 * list_member_oid() for them.
 	 */
-	namespace = form->prsnamespace;
-	if (namespace != PG_CATALOG_NAMESPACE &&
-		!list_member_oid(activeSearchPath, namespace))
+	prsnamespace = form->prsnamespace;
+	if (prsnamespace != PG_CATALOG_NAMESPACE &&
+		!list_member_oid(activeSearchPath, prsnamespace))
 		visible = false;
 	else
 	{
@@ -2190,7 +2190,7 @@ TSParserIsVisible(Oid prsId)
 			if (namespaceId == myTempNamespace)
 				continue;		/* do not look in temp namespace */
 
-			if (namespaceId == namespace)
+			if (namespaceId == prsnamespace)
 			{
 				/* Found it first in path */
 				visible = true;
@@ -2279,7 +2279,7 @@ TSDictionaryIsVisible(Oid dictId)
 {
 	HeapTuple	tup;
 	Form_pg_ts_dict form;
-	Oid			namespace;
+	Oid			dictnamespace;
 	bool		visible;
 
 	tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
@@ -2295,9 +2295,9 @@ TSDictionaryIsVisible(Oid dictId)
 	 * the system namespace are surely in the path and so we needn't even do
 	 * list_member_oid() for them.
 	 */
-	namespace = form->dictnamespace;
-	if (namespace != PG_CATALOG_NAMESPACE &&
-		!list_member_oid(activeSearchPath, namespace))
+	dictnamespace = form->dictnamespace;
+	if (dictnamespace != PG_CATALOG_NAMESPACE &&
+		!list_member_oid(activeSearchPath, dictnamespace))
 		visible = false;
 	else
 	{
@@ -2317,7 +2317,7 @@ TSDictionaryIsVisible(Oid dictId)
 			if (namespaceId == myTempNamespace)
 				continue;		/* do not look in temp namespace */
 
-			if (namespaceId == namespace)
+			if (namespaceId == dictnamespace)
 			{
 				/* Found it first in path */
 				visible = true;
@@ -2406,7 +2406,7 @@ TSTemplateIsVisible(Oid tmplId)
 {
 	HeapTuple	tup;
 	Form_pg_ts_template form;
-	Oid			namespace;
+	Oid			tmplnamespace;
 	bool		visible;
 
 	tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
@@ -2421,9 +2421,9 @@ TSTemplateIsVisible(Oid tmplId)
 	 * the system namespace are surely in the path and so we needn't even do
 	 * list_member_oid() for them.
 	 */
-	namespace = form->tmplnamespace;
-	if (namespace != PG_CATALOG_NAMESPACE &&
-		!list_member_oid(activeSearchPath, namespace))
+	tmplnamespace = form->tmplnamespace;
+	if (tmplnamespace != PG_CATALOG_NAMESPACE &&
+		!list_member_oid(activeSearchPath, tmplnamespace))
 		visible = false;
 	else
 	{
@@ -2443,7 +2443,7 @@ TSTemplateIsVisible(Oid tmplId)
 			if (namespaceId == myTempNamespace)
 				continue;		/* do not look in temp namespace */
 
-			if (namespaceId == namespace)
+			if (namespaceId == tmplnamespace)
 			{
 				/* Found it first in path */
 				visible = true;
@@ -2532,7 +2532,7 @@ TSConfigIsVisible(Oid cfgid)
 {
 	HeapTuple	tup;
 	Form_pg_ts_config form;
-	Oid			namespace;
+	Oid			cfgnamespace;
 	bool		visible;
 
 	tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
@@ -2548,9 +2548,9 @@ TSConfigIsVisible(Oid cfgid)
 	 * the system namespace are surely in the path and so we needn't even do
 	 * list_member_oid() for them.
 	 */
-	namespace = form->cfgnamespace;
-	if (namespace != PG_CATALOG_NAMESPACE &&
-		!list_member_oid(activeSearchPath, namespace))
+	cfgnamespace = form->cfgnamespace;
+	if (cfgnamespace != PG_CATALOG_NAMESPACE &&
+		!list_member_oid(activeSearchPath, cfgnamespace))
 		visible = false;
 	else
 	{
@@ -2570,7 +2570,7 @@ TSConfigIsVisible(Oid cfgid)
 			if (namespaceId == myTempNamespace)
 				continue;		/* do not look in temp namespace */
 
-			if (namespaceId == namespace)
+			if (namespaceId == cfgnamespace)
 			{
 				/* Found it first in path */
 				visible = true;
diff --git a/src/backend/catalog/objectaddress.c b/src/backend/catalog/objectaddress.c
index cc636e2e3e..fa3aa241cb 100644
--- a/src/backend/catalog/objectaddress.c
+++ b/src/backend/catalog/objectaddress.c
@@ -936,9 +936,9 @@ get_object_address(ObjectType objtype, List *objname, List *objargs,
 				break;
 			case OBJECT_TRANSFORM:
 				{
-					TypeName   *typename = (TypeName *) linitial(objname);
+					TypeName   *typname = (TypeName *) linitial(objname);
 					char	   *langname = strVal(linitial(objargs));
-					Oid			type_id = LookupTypeNameOid(NULL, typename, missing_ok);
+					Oid			type_id = LookupTypeNameOid(NULL, typname, missing_ok);
 					Oid			lang_id = get_language_oid(langname, missing_ok);
 
 					address.classId = TransformRelationId;
@@ -1533,23 +1533,23 @@ static ObjectAddress
 get_object_address_type(ObjectType objtype, ListCell *typecell, bool missing_ok)
 {
 	ObjectAddress address;
-	TypeName   *typename;
+	TypeName   *typname;
 	Type		tup;
 
-	typename = (TypeName *) lfirst(typecell);
+	typname = (TypeName *) lfirst(typecell);
 
 	address.classId = TypeRelationId;
 	address.objectId = InvalidOid;
 	address.objectSubId = 0;
 
-	tup = LookupTypeName(NULL, typename, NULL, missing_ok);
+	tup = LookupTypeName(NULL, typname, NULL, missing_ok);
 	if (!HeapTupleIsValid(tup))
 	{
 		if (!missing_ok)
 			ereport(ERROR,
 					(errcode(ERRCODE_UNDEFINED_OBJECT),
 					 errmsg("type \"%s\" does not exist",
-							TypeNameToString(typename))));
+							TypeNameToString(typname))));
 		return address;
 	}
 	address.objectId = typeTypeId(tup);
@@ -1560,7 +1560,7 @@ get_object_address_type(ObjectType objtype, ListCell *typecell, bool missing_ok)
 			ereport(ERROR,
 					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
 					 errmsg("\"%s\" is not a domain",
-							TypeNameToString(typename))));
+							TypeNameToString(typname))));
 	}
 
 	ReleaseSysCache(tup);
@@ -2285,11 +2285,11 @@ check_object_ownership(Oid roleid, ObjectType objtype, ObjectAddress address,
 			break;
 		case OBJECT_TRANSFORM:
 			{
-				TypeName   *typename = (TypeName *) linitial(objname);
-				Oid			typeid = typenameTypeId(NULL, typename);
+				TypeName   *typname = (TypeName *) linitial(objname);
+				Oid			typid = typenameTypeId(NULL, typname);
 
-				if (!pg_type_ownercheck(typeid, roleid))
-					aclcheck_error_type(ACLCHECK_NOT_OWNER, typeid);
+				if (!pg_type_ownercheck(typid, roleid))
+					aclcheck_error_type(ACLCHECK_NOT_OWNER, typid);
 			}
 			break;
 		case OBJECT_TABLESPACE:
diff --git a/src/backend/catalog/partition.c b/src/backend/catalog/partition.c
index 4bcef58763..2cf5d7828f 100644
--- a/src/backend/catalog/partition.c
+++ b/src/backend/catalog/partition.c
@@ -1259,10 +1259,10 @@ get_qual_for_list(PartitionKey key, PartitionBoundSpec *spec)
 		result = list_make2(nulltest1, opexpr);
 	else if (nulltest2)
 	{
-		Expr	   *or;
+		Expr	   *or_expr;
 
-		or = makeBoolExpr(OR_EXPR, list_make2(nulltest2, opexpr), -1);
-		result = list_make1(or);
+		or_expr = makeBoolExpr(OR_EXPR, list_make2(nulltest2, opexpr), -1);
+		result = list_make1(or_expr);
 	}
 	else
 		result = list_make1(opexpr);
diff --git a/src/backend/catalog/pg_db_role_setting.c b/src/backend/catalog/pg_db_role_setting.c
index 323471bc83..56b9de29df 100644
--- a/src/backend/catalog/pg_db_role_setting.c
+++ b/src/backend/catalog/pg_db_role_setting.c
@@ -62,7 +62,7 @@ AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
 	{
 		if (HeapTupleIsValid(tuple))
 		{
-			ArrayType  *new = NULL;
+			ArrayType  *newarray = NULL;
 			Datum		datum;
 			bool		isnull;
 
@@ -70,9 +70,9 @@ AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
 								 RelationGetDescr(rel), &isnull);
 
 			if (!isnull)
-				new = GUCArrayReset(DatumGetArrayTypeP(datum));
+				newarray = GUCArrayReset(DatumGetArrayTypeP(datum));
 
-			if (new)
+			if (newarray)
 			{
 				Datum		repl_val[Natts_pg_db_role_setting];
 				bool		repl_null[Natts_pg_db_role_setting];
@@ -82,7 +82,7 @@ AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
 				memset(repl_repl, false, sizeof(repl_repl));
 
 				repl_val[Anum_pg_db_role_setting_setconfig - 1] =
-					PointerGetDatum(new);
+					PointerGetDatum(newarray);
 				repl_repl[Anum_pg_db_role_setting_setconfig - 1] = true;
 				repl_null[Anum_pg_db_role_setting_setconfig - 1] = false;
 
diff --git a/src/backend/commands/alter.c b/src/backend/commands/alter.c
index d6195e49f5..aab5021774 100644
--- a/src/backend/commands/alter.c
+++ b/src/backend/commands/alter.c
@@ -609,7 +609,7 @@ AlterObjectNamespace_internal(Relation rel, Oid objid, Oid nspOid)
 	AclObjectKind acl_kind = get_object_aclkind(classId);
 	Oid			oldNspOid;
 	Datum		name,
-				namespace;
+				nsp;
 	bool		isnull;
 	HeapTuple	tup,
 				newtup;
@@ -624,10 +624,10 @@ AlterObjectNamespace_internal(Relation rel, Oid objid, Oid nspOid)
 
 	name = heap_getattr(tup, Anum_name, RelationGetDescr(rel), &isnull);
 	Assert(!isnull);
-	namespace = heap_getattr(tup, Anum_namespace, RelationGetDescr(rel),
+	nsp = heap_getattr(tup, Anum_namespace, RelationGetDescr(rel),
 							 &isnull);
 	Assert(!isnull);
-	oldNspOid = DatumGetObjectId(namespace);
+	oldNspOid = DatumGetObjectId(nsp);
 
 	/*
 	 * If the object is already in the correct namespace, we don't need to do
diff --git a/src/backend/commands/collationcmds.c b/src/backend/commands/collationcmds.c
index 919cfc6a06..48c2704cd1 100644
--- a/src/backend/commands/collationcmds.c
+++ b/src/backend/commands/collationcmds.c
@@ -191,10 +191,10 @@ IsThereCollationInNamespace(const char *collname, Oid nspOid)
  */
 pg_attribute_unused()
 static bool
-normalize_locale_name(char *new, const char *old)
+normalize_locale_name(char *newname, const char *oldname)
 {
-	char	   *n = new;
-	const char *o = old;
+	char	   *n = newname;
+	const char *o = oldname;
 	bool		changed = false;
 
 	while (*o)
diff --git a/src/backend/commands/explain.c b/src/backend/commands/explain.c
index c9e0a3e42d..dfdfb75a23 100644
--- a/src/backend/commands/explain.c
+++ b/src/backend/commands/explain.c
@@ -2534,7 +2534,7 @@ static void
 ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
 {
 	char	   *objectname = NULL;
-	char	   *namespace = NULL;
+	char	   *namespacename = NULL;
 	const char *objecttag = NULL;
 	RangeTblEntry *rte;
 	char	   *refname;
@@ -2559,7 +2559,7 @@ ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
 			Assert(rte->rtekind == RTE_RELATION);
 			objectname = get_rel_name(rte->relid);
 			if (es->verbose)
-				namespace = get_namespace_name(get_rel_namespace(rte->relid));
+				namespacename = get_namespace_name(get_rel_namespace(rte->relid));
 			objecttag = "Relation Name";
 			break;
 		case T_FunctionScan:
@@ -2586,7 +2586,7 @@ ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
 
 						objectname = get_func_name(funcid);
 						if (es->verbose)
-							namespace =
+							namespacename =
 								get_namespace_name(get_func_namespace(funcid));
 					}
 				}
@@ -2617,8 +2617,8 @@ ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
 	if (es->format == EXPLAIN_FORMAT_TEXT)
 	{
 		appendStringInfoString(es->str, " on");
-		if (namespace != NULL)
-			appendStringInfo(es->str, " %s.%s", quote_identifier(namespace),
+		if (namespacename != NULL)
+			appendStringInfo(es->str, " %s.%s", quote_identifier(namespacename),
 							 quote_identifier(objectname));
 		else if (objectname != NULL)
 			appendStringInfo(es->str, " %s", quote_identifier(objectname));
@@ -2629,8 +2629,8 @@ ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
 	{
 		if (objecttag != NULL && objectname != NULL)
 			ExplainPropertyText(objecttag, objectname, es);
-		if (namespace != NULL)
-			ExplainPropertyText("Schema", namespace, es);
+		if (namespacename != NULL)
+			ExplainPropertyText("Schema", namespacename, es);
 		ExplainPropertyText("Alias", refname, es);
 	}
 }
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 8b1285a542..1494e2a26f 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -972,13 +972,13 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
 
 		foreach(lc, castNode(List, transformDefElem))
 		{
-			Oid			typeid = typenameTypeId(NULL, lfirst(lc));
-			Oid			elt = get_base_element_type(typeid);
+			Oid			typid = typenameTypeId(NULL, lfirst(lc));
+			Oid			elt = get_base_element_type(typid);
 
-			typeid = elt ? elt : typeid;
+			typid = elt ? elt : typid;
 
-			get_transform_oid(typeid, languageOid, false);
-			trftypes_list = lappend_oid(trftypes_list, typeid);
+			get_transform_oid(typid, languageOid, false);
+			trftypes_list = lappend_oid(trftypes_list, typid);
 		}
 	}
 
@@ -1779,7 +1779,7 @@ check_transform_function(Form_pg_proc procstruct)
 ObjectAddress
 CreateTransform(CreateTransformStmt *stmt)
 {
-	Oid			typeid;
+	Oid			typid;
 	char		typtype;
 	Oid			langid;
 	Oid			fromsqlfuncid;
@@ -1800,8 +1800,8 @@ CreateTransform(CreateTransformStmt *stmt)
 	/*
 	 * Get the type
 	 */
-	typeid = typenameTypeId(NULL, stmt->type_name);
-	typtype = get_typtype(typeid);
+	typid = typenameTypeId(NULL, stmt->type_name);
+	typtype = get_typtype(typid);
 
 	if (typtype == TYPTYPE_PSEUDO)
 		ereport(ERROR,
@@ -1815,12 +1815,12 @@ CreateTransform(CreateTransformStmt *stmt)
 				 errmsg("data type %s is a domain",
 						TypeNameToString(stmt->type_name))));
 
-	if (!pg_type_ownercheck(typeid, GetUserId()))
-		aclcheck_error_type(ACLCHECK_NOT_OWNER, typeid);
+	if (!pg_type_ownercheck(typid, GetUserId()))
+		aclcheck_error_type(ACLCHECK_NOT_OWNER, typid);
 
-	aclresult = pg_type_aclcheck(typeid, GetUserId(), ACL_USAGE);
+	aclresult = pg_type_aclcheck(typid, GetUserId(), ACL_USAGE);
 	if (aclresult != ACLCHECK_OK)
-		aclcheck_error_type(aclresult, typeid);
+		aclcheck_error_type(aclresult, typid);
 
 	/*
 	 * Get the language
@@ -1875,7 +1875,7 @@ CreateTransform(CreateTransformStmt *stmt)
 		if (!HeapTupleIsValid(tuple))
 			elog(ERROR, "cache lookup failed for function %u", tosqlfuncid);
 		procstruct = (Form_pg_proc) GETSTRUCT(tuple);
-		if (procstruct->prorettype != typeid)
+		if (procstruct->prorettype != typid)
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
 					 errmsg("return data type of TO SQL function must be the transform data type")));
@@ -1888,7 +1888,7 @@ CreateTransform(CreateTransformStmt *stmt)
 	/*
 	 * Ready to go
 	 */
-	values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typeid);
+	values[Anum_pg_transform_trftype - 1] = ObjectIdGetDatum(typid);
 	values[Anum_pg_transform_trflang - 1] = ObjectIdGetDatum(langid);
 	values[Anum_pg_transform_trffromsql - 1] = ObjectIdGetDatum(fromsqlfuncid);
 	values[Anum_pg_transform_trftosql - 1] = ObjectIdGetDatum(tosqlfuncid);
@@ -1898,7 +1898,7 @@ CreateTransform(CreateTransformStmt *stmt)
 	relation = heap_open(TransformRelationId, RowExclusiveLock);
 
 	tuple = SearchSysCache2(TRFTYPELANG,
-							ObjectIdGetDatum(typeid),
+							ObjectIdGetDatum(typid),
 							ObjectIdGetDatum(langid));
 	if (HeapTupleIsValid(tuple))
 	{
@@ -1906,7 +1906,7 @@ CreateTransform(CreateTransformStmt *stmt)
 			ereport(ERROR,
 					(errcode(ERRCODE_DUPLICATE_OBJECT),
 			   errmsg("transform for type %s language \"%s\" already exists",
-					  format_type_be(typeid),
+					  format_type_be(typid),
 					  stmt->lang)));
 
 		MemSet(replaces, false, sizeof(replaces));
@@ -1943,7 +1943,7 @@ CreateTransform(CreateTransformStmt *stmt)
 
 	/* dependency on type */
 	referenced.classId = TypeRelationId;
-	referenced.objectId = typeid;
+	referenced.objectId = typid;
 	referenced.objectSubId = 0;
 	recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 3cea220421..56906d603c 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -11391,7 +11391,7 @@ ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 {
 	Oid			relid = RelationGetRelid(rel);
 	Type		typetuple;
-	Oid			typeid;
+	Oid			typid;
 	Relation	inheritsRelation,
 				relationRelation;
 	SysScanDesc scan;
@@ -11407,7 +11407,7 @@ ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 	/* Validate the type. */
 	typetuple = typenameType(NULL, ofTypename, NULL);
 	check_of_type(typetuple);
-	typeid = HeapTupleGetOid(typetuple);
+	typid = HeapTupleGetOid(typetuple);
 
 	/* Fail if the table has any inheritance parents. */
 	inheritsRelation = heap_open(InheritsRelationId, AccessShareLock);
@@ -11429,7 +11429,7 @@ ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 	 * require that the order also match.  However, attnotnull need not match.
 	 * Also unlike inheritance, we do not require matching relhasoids.
 	 */
-	typeTupleDesc = lookup_rowtype_tupdesc(typeid, -1);
+	typeTupleDesc = lookup_rowtype_tupdesc(typid, -1);
 	tableTupleDesc = RelationGetDescr(rel);
 	table_attno = 1;
 	for (type_attno = 1; type_attno <= typeTupleDesc->natts; type_attno++)
@@ -11496,7 +11496,7 @@ ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 	tableobj.objectId = relid;
 	tableobj.objectSubId = 0;
 	typeobj.classId = TypeRelationId;
-	typeobj.objectId = typeid;
+	typeobj.objectId = typid;
 	typeobj.objectSubId = 0;
 	recordDependencyOn(&tableobj, &typeobj, DEPENDENCY_NORMAL);
 
@@ -11505,7 +11505,7 @@ ATExecAddOf(Relation rel, const TypeName *ofTypename, LOCKMODE lockmode)
 	classtuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
 	if (!HeapTupleIsValid(classtuple))
 		elog(ERROR, "cache lookup failed for relation %u", relid);
-	((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typeid;
+	((Form_pg_class) GETSTRUCT(classtuple))->reloftype = typid;
 	CatalogTupleUpdate(relationRelation, &classtuple->t_self, classtuple);
 
 	InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c
index d8bd8a50dd..a1a091fe2c 100644
--- a/src/backend/commands/typecmds.c
+++ b/src/backend/commands/typecmds.c
@@ -85,7 +85,7 @@ typedef struct
 /* Potentially set by pg_upgrade_support functions */
 Oid			binary_upgrade_next_array_pg_type_oid = InvalidOid;
 
-static void makeRangeConstructors(const char *name, Oid namespace,
+static void makeRangeConstructors(const char *name, Oid namespaceOid,
 					  Oid rangeOid, Oid subtype);
 static Oid	findTypeInputFunction(List *procname, Oid typeOid);
 static Oid	findTypeOutputFunction(List *procname, Oid typeOid);
@@ -1228,13 +1228,13 @@ ObjectAddress
 AlterEnum(AlterEnumStmt *stmt)
 {
 	Oid			enum_type_oid;
-	TypeName   *typename;
+	TypeName   *typeName;
 	HeapTuple	tup;
 	ObjectAddress address;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(stmt->typeName);
-	enum_type_oid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(stmt->typeName);
+	enum_type_oid = typenameTypeId(NULL, typeName);
 
 	tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(enum_type_oid));
 	if (!HeapTupleIsValid(tup))
@@ -1563,7 +1563,7 @@ DefineRange(CreateRangeStmt *stmt)
  * to offer more convenience for the user.
  */
 static void
-makeRangeConstructors(const char *name, Oid namespace,
+makeRangeConstructors(const char *name, Oid namespaceOid,
 					  Oid rangeOid, Oid subtype)
 {
 	static const char *const prosrc[2] = {"range_constructor2",
@@ -1591,7 +1591,7 @@ makeRangeConstructors(const char *name, Oid namespace,
 												   pronargs[i]);
 
 		myself = ProcedureCreate(name,	/* name: same as range type */
-								 namespace,		/* namespace */
+								 namespaceOid,		/* namespace */
 								 false, /* replace */
 								 false, /* returns set */
 								 rangeOid,		/* return type */
@@ -2125,7 +2125,7 @@ DefineCompositeType(RangeVar *typevar, List *coldeflist)
 ObjectAddress
 AlterDomainDefault(List *names, Node *defaultRaw)
 {
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			domainoid;
 	HeapTuple	tup;
 	ParseState *pstate;
@@ -2140,8 +2140,8 @@ AlterDomainDefault(List *names, Node *defaultRaw)
 	ObjectAddress address;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
-	domainoid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(names);
+	domainoid = typenameTypeId(NULL, typeName);
 
 	/* Look up the domain in the type table */
 	rel = heap_open(TypeRelationId, RowExclusiveLock);
@@ -2264,7 +2264,7 @@ AlterDomainDefault(List *names, Node *defaultRaw)
 ObjectAddress
 AlterDomainNotNull(List *names, bool notNull)
 {
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			domainoid;
 	Relation	typrel;
 	HeapTuple	tup;
@@ -2272,8 +2272,8 @@ AlterDomainNotNull(List *names, bool notNull)
 	ObjectAddress address = InvalidObjectAddress;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
-	domainoid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(names);
+	domainoid = typenameTypeId(NULL, typeName);
 
 	/* Look up the domain in the type table */
 	typrel = heap_open(TypeRelationId, RowExclusiveLock);
@@ -2380,7 +2380,7 @@ ObjectAddress
 AlterDomainDropConstraint(List *names, const char *constrName,
 						  DropBehavior behavior, bool missing_ok)
 {
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			domainoid;
 	HeapTuple	tup;
 	Relation	rel;
@@ -2392,8 +2392,8 @@ AlterDomainDropConstraint(List *names, const char *constrName,
 	ObjectAddress address = InvalidObjectAddress;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
-	domainoid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(names);
+	domainoid = typenameTypeId(NULL, typeName);
 
 	/* Look up the domain in the type table */
 	rel = heap_open(TypeRelationId, RowExclusiveLock);
@@ -2451,11 +2451,11 @@ AlterDomainDropConstraint(List *names, const char *constrName,
 			ereport(ERROR,
 					(errcode(ERRCODE_UNDEFINED_OBJECT),
 				  errmsg("constraint \"%s\" of domain \"%s\" does not exist",
-						 constrName, TypeNameToString(typename))));
+						 constrName, TypeNameToString(typeName))));
 		else
 			ereport(NOTICE,
 					(errmsg("constraint \"%s\" of domain \"%s\" does not exist, skipping",
-							constrName, TypeNameToString(typename))));
+							constrName, TypeNameToString(typeName))));
 	}
 
 	return address;
@@ -2470,7 +2470,7 @@ ObjectAddress
 AlterDomainAddConstraint(List *names, Node *newConstraint,
 						 ObjectAddress *constrAddr)
 {
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			domainoid;
 	Relation	typrel;
 	HeapTuple	tup;
@@ -2480,8 +2480,8 @@ AlterDomainAddConstraint(List *names, Node *newConstraint,
 	ObjectAddress address;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
-	domainoid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(names);
+	domainoid = typenameTypeId(NULL, typeName);
 
 	/* Look up the domain in the type table */
 	typrel = heap_open(TypeRelationId, RowExclusiveLock);
@@ -2578,7 +2578,7 @@ AlterDomainAddConstraint(List *names, Node *newConstraint,
 ObjectAddress
 AlterDomainValidateConstraint(List *names, char *constrName)
 {
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			domainoid;
 	Relation	typrel;
 	Relation	conrel;
@@ -2596,8 +2596,8 @@ AlterDomainValidateConstraint(List *names, char *constrName)
 	ObjectAddress address;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
-	domainoid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(names);
+	domainoid = typenameTypeId(NULL, typeName);
 
 	/* Look up the domain in the type table */
 	typrel = heap_open(TypeRelationId, AccessShareLock);
@@ -2634,13 +2634,13 @@ AlterDomainValidateConstraint(List *names, char *constrName)
 		ereport(ERROR,
 				(errcode(ERRCODE_UNDEFINED_OBJECT),
 				 errmsg("constraint \"%s\" of domain \"%s\" does not exist",
-						constrName, TypeNameToString(typename))));
+						constrName, TypeNameToString(typeName))));
 
 	if (con->contype != CONSTRAINT_CHECK)
 		ereport(ERROR,
 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
 		errmsg("constraint \"%s\" of domain \"%s\" is not a check constraint",
-			   constrName, TypeNameToString(typename))));
+			   constrName, TypeNameToString(typeName))));
 
 	val = SysCacheGetAttr(CONSTROID, tuple,
 						  Anum_pg_constraint_conbin,
@@ -3135,7 +3135,7 @@ RenameType(RenameStmt *stmt)
 {
 	List	   *names = stmt->object;
 	const char *newTypeName = stmt->newname;
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			typeOid;
 	Relation	rel;
 	HeapTuple	tup;
@@ -3143,8 +3143,8 @@ RenameType(RenameStmt *stmt)
 	ObjectAddress address;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
-	typeOid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(names);
+	typeOid = typenameTypeId(NULL, typeName);
 
 	/* Look up the type in the type table */
 	rel = heap_open(TypeRelationId, RowExclusiveLock);
@@ -3211,7 +3211,7 @@ RenameType(RenameStmt *stmt)
 ObjectAddress
 AlterTypeOwner(List *names, Oid newOwnerId, ObjectType objecttype)
 {
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			typeOid;
 	Relation	rel;
 	HeapTuple	tup;
@@ -3223,15 +3223,15 @@ AlterTypeOwner(List *names, Oid newOwnerId, ObjectType objecttype)
 	rel = heap_open(TypeRelationId, RowExclusiveLock);
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
+	typeName = makeTypeNameFromNameList(names);
 
 	/* Use LookupTypeName here so that shell types can be processed */
-	tup = LookupTypeName(NULL, typename, NULL, false);
+	tup = LookupTypeName(NULL, typeName, NULL, false);
 	if (tup == NULL)
 		ereport(ERROR,
 				(errcode(ERRCODE_UNDEFINED_OBJECT),
 				 errmsg("type \"%s\" does not exist",
-						TypeNameToString(typename))));
+						TypeNameToString(typeName))));
 	typeOid = typeTypeId(tup);
 
 	/* Copy the syscache entry so we can scribble on it below */
@@ -3416,7 +3416,7 @@ ObjectAddress
 AlterTypeNamespace(List *names, const char *newschema, ObjectType objecttype,
 				   Oid *oldschema)
 {
-	TypeName   *typename;
+	TypeName   *typeName;
 	Oid			typeOid;
 	Oid			nspOid;
 	Oid			oldNspOid;
@@ -3424,8 +3424,8 @@ AlterTypeNamespace(List *names, const char *newschema, ObjectType objecttype,
 	ObjectAddress myself;
 
 	/* Make a TypeName so we can use standard type lookup machinery */
-	typename = makeTypeNameFromNameList(names);
-	typeOid = typenameTypeId(NULL, typename);
+	typeName = makeTypeNameFromNameList(names);
+	typeOid = typenameTypeId(NULL, typeName);
 
 	/* Don't allow ALTER DOMAIN on a type */
 	if (objecttype == OBJECT_DOMAIN && get_typtype(typeOid) != TYPTYPE_DOMAIN)
diff --git a/src/backend/executor/execReplication.c b/src/backend/executor/execReplication.c
index f20d728ad5..5570a2f011 100644
--- a/src/backend/executor/execReplication.c
+++ b/src/backend/executor/execReplication.c
@@ -63,7 +63,7 @@ build_replindex_scan_key(ScanKey skey, Relation rel, Relation idxrel,
 	/* Build scankey for every attribute in the index. */
 	for (attoff = 0; attoff < RelationGetNumberOfAttributes(idxrel); attoff++)
 	{
-		Oid			operator;
+		Oid			opid;
 		Oid			opfamily;
 		RegProcedure regop;
 		int			pkattno = attoff + 1;
@@ -76,15 +76,15 @@ build_replindex_scan_key(ScanKey skey, Relation rel, Relation idxrel,
 		 */
 		opfamily = get_opclass_family(opclass->values[attoff]);
 
-		operator = get_opfamily_member(opfamily, optype,
+		opid = get_opfamily_member(opfamily, optype,
 									   optype,
 									   BTEqualStrategyNumber);
 
-		if (!OidIsValid(operator))
+		if (!OidIsValid(opid))
 			elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
 				 BTEqualStrategyNumber, optype, optype, opfamily);
 
-		regop = get_opcode(operator);
+		regop = get_opcode(opid);
 
 		/* Initialize the scankey. */
 		ScanKeyInit(&skey[attoff],
diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c
index 05d8538717..c3348991cd 100644
--- a/src/backend/nodes/copyfuncs.c
+++ b/src/backend/nodes/copyfuncs.c
@@ -4368,17 +4368,17 @@ _copyDropSubscriptionStmt(const DropSubscriptionStmt *from)
 static List *
 _copyList(const List *from)
 {
-	List	   *new;
+	List	   *newnode;
 	ListCell   *curr_old;
 	ListCell   *prev_new;
 
 	Assert(list_length(from) >= 1);
 
-	new = makeNode(List);
-	new->length = from->length;
+	newnode = makeNode(List);
+	newnode->length = from->length;
 
-	COPY_NODE_CELL(new->head, from->head);
-	prev_new = new->head;
+	COPY_NODE_CELL(newnode->head, from->head);
+	prev_new = newnode->head;
 	curr_old = lnext(from->head);
 
 	while (curr_old)
@@ -4388,9 +4388,9 @@ _copyList(const List *from)
 		curr_old = curr_old->next;
 	}
 	prev_new->next = NULL;
-	new->tail = prev_new;
+	newnode->tail = prev_new;
 
-	return new;
+	return newnode;
 }
 
 /* ****************************************************************
diff --git a/src/backend/optimizer/geqo/geqo_erx.c b/src/backend/optimizer/geqo/geqo_erx.c
index 023abf70e2..9a765668b7 100644
--- a/src/backend/optimizer/geqo/geqo_erx.c
+++ b/src/backend/optimizer/geqo/geqo_erx.c
@@ -281,7 +281,7 @@ static Gene
 gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
 {
 	int			i;
-	Gene		friend;
+	Gene		friend_;
 	int			minimum_edges;
 	int			minimum_count = -1;
 	int			rand_decision;
@@ -297,7 +297,7 @@ gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
 
 	for (i = 0; i < edge.unused_edges; i++)
 	{
-		friend = (Gene) edge.edge_list[i];
+		friend_ = (Gene) edge.edge_list[i];
 
 		/*
 		 * give priority to shared edges that are negative; so return 'em
@@ -307,8 +307,8 @@ gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
 		 * negative values are caught here so we need not worry about
 		 * converting to absolute values
 		 */
-		if (friend < 0)
-			return (Gene) Abs(friend);
+		if (friend_ < 0)
+			return (Gene) Abs(friend_);
 
 
 		/*
@@ -327,14 +327,14 @@ gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
 		 */
 
 
-		if (edge_table[(int) friend].unused_edges < minimum_edges)
+		if (edge_table[(int) friend_].unused_edges < minimum_edges)
 		{
-			minimum_edges = edge_table[(int) friend].unused_edges;
+			minimum_edges = edge_table[(int) friend_].unused_edges;
 			minimum_count = 1;
 		}
 		else if (minimum_count == -1)
 			elog(ERROR, "minimum_count not set");
-		else if (edge_table[(int) friend].unused_edges == minimum_edges)
+		else if (edge_table[(int) friend_].unused_edges == minimum_edges)
 			minimum_count++;
 
 	}							/* for (i=0; i<edge.unused_edges; i++) */
@@ -346,15 +346,15 @@ gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
 
 	for (i = 0; i < edge.unused_edges; i++)
 	{
-		friend = (Gene) edge.edge_list[i];
+		friend_ = (Gene) edge.edge_list[i];
 
 		/* return the chosen candidate point */
-		if (edge_table[(int) friend].unused_edges == minimum_edges)
+		if (edge_table[(int) friend_].unused_edges == minimum_edges)
 		{
 			minimum_count--;
 
 			if (minimum_count == rand_decision)
-				return friend;
+				return friend_;
 		}
 	}
 
diff --git a/src/backend/optimizer/geqo/geqo_eval.c b/src/backend/optimizer/geqo/geqo_eval.c
index b5cab0c351..503a867251 100644
--- a/src/backend/optimizer/geqo/geqo_eval.c
+++ b/src/backend/optimizer/geqo/geqo_eval.c
@@ -162,7 +162,7 @@ geqo_eval(PlannerInfo *root, Gene *tour, int num_gene)
 RelOptInfo *
 gimme_tree(PlannerInfo *root, Gene *tour, int num_gene)
 {
-	GeqoPrivateData *private = (GeqoPrivateData *) root->join_search_private;
+	GeqoPrivateData *private_data = (GeqoPrivateData *) root->join_search_private;
 	List	   *clumps;
 	int			rel_count;
 
@@ -187,7 +187,7 @@ gimme_tree(PlannerInfo *root, Gene *tour, int num_gene)
 
 		/* Get the next input relation */
 		cur_rel_index = (int) tour[rel_count];
-		cur_rel = (RelOptInfo *) list_nth(private->initial_rels,
+		cur_rel = (RelOptInfo *) list_nth(private_data->initial_rels,
 										  cur_rel_index - 1);
 
 		/* Make it into a single-rel clump */
diff --git a/src/backend/optimizer/geqo/geqo_main.c b/src/backend/optimizer/geqo/geqo_main.c
index 52bd428187..c5d6b7c0c0 100644
--- a/src/backend/optimizer/geqo/geqo_main.c
+++ b/src/backend/optimizer/geqo/geqo_main.c
@@ -66,7 +66,7 @@ static int	gimme_number_generations(int pool_size);
 RelOptInfo *
 geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
 {
-	GeqoPrivateData private;
+	GeqoPrivateData private_data;
 	int			generation;
 	Chromosome *momma;
 	Chromosome *daddy;
@@ -94,8 +94,8 @@ geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
 #endif
 
 /* set up private information */
-	root->join_search_private = (void *) &private;
-	private.initial_rels = initial_rels;
+	root->join_search_private = (void *) &private_data;
+	private_data.initial_rels = initial_rels;
 
 /* initialize private number generator */
 	geqo_set_seed(root, Geqo_seed);
diff --git a/src/backend/optimizer/geqo/geqo_random.c b/src/backend/optimizer/geqo/geqo_random.c
index 6f3500649c..1e4ec0e545 100644
--- a/src/backend/optimizer/geqo/geqo_random.c
+++ b/src/backend/optimizer/geqo/geqo_random.c
@@ -19,22 +19,22 @@
 void
 geqo_set_seed(PlannerInfo *root, double seed)
 {
-	GeqoPrivateData *private = (GeqoPrivateData *) root->join_search_private;
+	GeqoPrivateData *private_data = (GeqoPrivateData *) root->join_search_private;
 
 	/*
 	 * XXX. This seeding algorithm could certainly be improved - but it is not
 	 * critical to do so.
 	 */
-	memset(private->random_state, 0, sizeof(private->random_state));
-	memcpy(private->random_state,
+	memset(private_data->random_state, 0, sizeof(private_data->random_state));
+	memcpy(private_data->random_state,
 		   &seed,
-		   Min(sizeof(private->random_state), sizeof(seed)));
+		   Min(sizeof(private_data->random_state), sizeof(seed)));
 }
 
 double
 geqo_rand(PlannerInfo *root)
 {
-	GeqoPrivateData *private = (GeqoPrivateData *) root->join_search_private;
+	GeqoPrivateData *private_data = (GeqoPrivateData *) root->join_search_private;
 
-	return pg_erand48(private->random_state);
+	return pg_erand48(private_data->random_state);
 }
diff --git a/src/backend/optimizer/util/predtest.c b/src/backend/optimizer/util/predtest.c
index c4a04cfa95..da05429b9b 100644
--- a/src/backend/optimizer/util/predtest.c
+++ b/src/backend/optimizer/util/predtest.c
@@ -869,7 +869,7 @@ boolexpr_startup_fn(Node *clause, PredIterInfo info)
 typedef struct
 {
 	OpExpr		opexpr;
-	Const		constexpr;
+	Const		const_expr;
 	int			next_elem;
 	int			num_elems;
 	Datum	   *elem_values;
@@ -913,13 +913,13 @@ arrayconst_startup_fn(Node *clause, PredIterInfo info)
 	state->opexpr.args = list_copy(saop->args);
 
 	/* Set up a dummy Const node to hold the per-element values */
-	state->constexpr.xpr.type = T_Const;
-	state->constexpr.consttype = ARR_ELEMTYPE(arrayval);
-	state->constexpr.consttypmod = -1;
-	state->constexpr.constcollid = arrayconst->constcollid;
-	state->constexpr.constlen = elmlen;
-	state->constexpr.constbyval = elmbyval;
-	lsecond(state->opexpr.args) = &state->constexpr;
+	state->const_expr.xpr.type = T_Const;
+	state->const_expr.consttype = ARR_ELEMTYPE(arrayval);
+	state->const_expr.consttypmod = -1;
+	state->const_expr.constcollid = arrayconst->constcollid;
+	state->const_expr.constlen = elmlen;
+	state->const_expr.constbyval = elmbyval;
+	lsecond(state->opexpr.args) = &state->const_expr;
 
 	/* Initialize iteration state */
 	state->next_elem = 0;
@@ -932,8 +932,8 @@ arrayconst_next_fn(PredIterInfo info)
 
 	if (state->next_elem >= state->num_elems)
 		return NULL;
-	state->constexpr.constvalue = state->elem_values[state->next_elem];
-	state->constexpr.constisnull = state->elem_nulls[state->next_elem];
+	state->const_expr.constvalue = state->elem_values[state->next_elem];
+	state->const_expr.constisnull = state->elem_nulls[state->next_elem];
 	state->next_elem++;
 	return (Node *) &(state->opexpr);
 }
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index e833b2eba5..2e5ce3a5e8 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -144,9 +144,9 @@ static RawStmt *makeRawStmt(Node *stmt, int stmt_location);
 static void updateRawStmtEnd(RawStmt *rs, int end_location);
 static Node *makeColumnRef(char *colname, List *indirection,
 						   int location, core_yyscan_t yyscanner);
-static Node *makeTypeCast(Node *arg, TypeName *typename, int location);
+static Node *makeTypeCast(Node *arg, TypeName *typname, int location);
 static Node *makeStringConst(char *str, int location);
-static Node *makeStringConstCast(char *str, int location, TypeName *typename);
+static Node *makeStringConstCast(char *str, int location, TypeName *typname);
 static Node *makeIntConst(int val, int location);
 static Node *makeFloatConst(char *str, int location);
 static Node *makeBitStringConst(char *str, int location);
@@ -14840,11 +14840,11 @@ makeColumnRef(char *colname, List *indirection,
 }
 
 static Node *
-makeTypeCast(Node *arg, TypeName *typename, int location)
+makeTypeCast(Node *arg, TypeName *typname, int location)
 {
 	TypeCast *n = makeNode(TypeCast);
 	n->arg = arg;
-	n->typeName = typename;
+	n->typeName = typname;
 	n->location = location;
 	return (Node *) n;
 }
@@ -14862,11 +14862,11 @@ makeStringConst(char *str, int location)
 }
 
 static Node *
-makeStringConstCast(char *str, int location, TypeName *typename)
+makeStringConstCast(char *str, int location, TypeName *typname)
 {
 	Node *s = makeStringConst(str, location);
 
-	return makeTypeCast(s, typename, -1);
+	return makeTypeCast(s, typname, -1);
 }
 
 static Node *
diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c
index b5eae56006..0c404a0fef 100644
--- a/src/backend/parser/parse_clause.c
+++ b/src/backend/parser/parse_clause.c
@@ -57,7 +57,7 @@ static Node *transformJoinUsingClause(ParseState *pstate,
 						 RangeTblEntry *leftRTE, RangeTblEntry *rightRTE,
 						 List *leftVars, List *rightVars);
 static Node *transformJoinOnClause(ParseState *pstate, JoinExpr *j,
-					  List *namespace);
+					  List *namespaces);
 static RangeTblEntry *transformTableEntry(ParseState *pstate, RangeVar *r);
 static RangeTblEntry *transformCTEReference(ParseState *pstate, RangeVar *r,
 					  CommonTableExpr *cte, Index levelsup);
@@ -69,14 +69,14 @@ static TableSampleClause *transformRangeTableSample(ParseState *pstate,
 						  RangeTableSample *rts);
 static Node *transformFromClauseItem(ParseState *pstate, Node *n,
 						RangeTblEntry **top_rte, int *top_rti,
-						List **namespace);
+						List **namespaces);
 static Node *buildMergedJoinVar(ParseState *pstate, JoinType jointype,
 				   Var *l_colvar, Var *r_colvar);
 static ParseNamespaceItem *makeNamespaceItem(RangeTblEntry *rte,
 				  bool rel_visible, bool cols_visible,
 				  bool lateral_only, bool lateral_ok);
-static void setNamespaceColumnVisibility(List *namespace, bool cols_visible);
-static void setNamespaceLateralState(List *namespace,
+static void setNamespaceColumnVisibility(List *namespaces, bool cols_visible);
+static void setNamespaceLateralState(List *namespaces,
 						 bool lateral_only, bool lateral_ok);
 static void checkExprIsVarFree(ParseState *pstate, Node *n,
 				   const char *constructName);
@@ -124,20 +124,20 @@ transformFromClause(ParseState *pstate, List *frmList)
 		Node	   *n = lfirst(fl);
 		RangeTblEntry *rte;
 		int			rtindex;
-		List	   *namespace;
+		List	   *namespaces;
 
 		n = transformFromClauseItem(pstate, n,
 									&rte,
 									&rtindex,
-									&namespace);
+									&namespaces);
 
-		checkNameSpaceConflicts(pstate, pstate->p_namespace, namespace);
+		checkNameSpaceConflicts(pstate, pstate->p_namespace, namespaces);
 
 		/* Mark the new namespace items as visible only to LATERAL */
-		setNamespaceLateralState(namespace, true, true);
+		setNamespaceLateralState(namespaces, true, true);
 
 		pstate->p_joinlist = lappend(pstate->p_joinlist, n);
-		pstate->p_namespace = list_concat(pstate->p_namespace, namespace);
+		pstate->p_namespace = list_concat(pstate->p_namespace, namespaces);
 	}
 
 	/*
@@ -376,7 +376,7 @@ transformJoinUsingClause(ParseState *pstate,
  *	  Result is a transformed qualification expression.
  */
 static Node *
-transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
+transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespaces)
 {
 	Node	   *result;
 	List	   *save_namespace;
@@ -389,10 +389,10 @@ transformJoinOnClause(ParseState *pstate, JoinExpr *j, List *namespace)
 	 * already did.)  All namespace items are marked visible regardless of
 	 * LATERAL state.
 	 */
-	setNamespaceLateralState(namespace, false, true);
+	setNamespaceLateralState(namespaces, false, true);
 
 	save_namespace = pstate->p_namespace;
-	pstate->p_namespace = namespace;
+	pstate->p_namespace = namespaces;
 
 	result = transformWhereClause(pstate, j->quals,
 								  EXPR_KIND_JOIN_ON, "JOIN/ON");
@@ -820,7 +820,7 @@ transformRangeTableSample(ParseState *pstate, RangeTableSample *rts)
 static Node *
 transformFromClauseItem(ParseState *pstate, Node *n,
 						RangeTblEntry **top_rte, int *top_rti,
-						List **namespace)
+						List **namespaces)
 {
 	if (IsA(n, RangeVar))
 	{
@@ -850,7 +850,7 @@ transformFromClauseItem(ParseState *pstate, Node *n,
 		Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
 		*top_rte = rte;
 		*top_rti = rtindex;
-		*namespace = list_make1(makeDefaultNSItem(rte));
+		*namespaces = list_make1(makeDefaultNSItem(rte));
 		rtr = makeNode(RangeTblRef);
 		rtr->rtindex = rtindex;
 		return (Node *) rtr;
@@ -868,7 +868,7 @@ transformFromClauseItem(ParseState *pstate, Node *n,
 		Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
 		*top_rte = rte;
 		*top_rti = rtindex;
-		*namespace = list_make1(makeDefaultNSItem(rte));
+		*namespaces = list_make1(makeDefaultNSItem(rte));
 		rtr = makeNode(RangeTblRef);
 		rtr->rtindex = rtindex;
 		return (Node *) rtr;
@@ -886,7 +886,7 @@ transformFromClauseItem(ParseState *pstate, Node *n,
 		Assert(rte == rt_fetch(rtindex, pstate->p_rtable));
 		*top_rte = rte;
 		*top_rti = rtindex;
-		*namespace = list_make1(makeDefaultNSItem(rte));
+		*namespaces = list_make1(makeDefaultNSItem(rte));
 		rtr = makeNode(RangeTblRef);
 		rtr->rtindex = rtindex;
 		return (Node *) rtr;
@@ -901,7 +901,7 @@ transformFromClauseItem(ParseState *pstate, Node *n,
 
 		/* Recursively transform the contained relation */
 		rel = transformFromClauseItem(pstate, rts->relation,
-									  top_rte, top_rti, namespace);
+									  top_rte, top_rti, namespaces);
 		/* Currently, grammar could only return a RangeVar as contained rel */
 		rtr = castNode(RangeTblRef, rel);
 		rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
@@ -1230,7 +1230,7 @@ transformFromClauseItem(ParseState *pstate, Node *n,
 		 * The join RTE itself is always made visible for unqualified column
 		 * names.  It's visible as a relation name only if it has an alias.
 		 */
-		*namespace = lappend(my_namespace,
+		*namespaces = lappend(my_namespace,
 							 makeNamespaceItem(rte,
 											   (j->alias != NULL),
 											   true,
@@ -1387,11 +1387,11 @@ makeNamespaceItem(RangeTblEntry *rte, bool rel_visible, bool cols_visible,
  *	  Convenience subroutine to update cols_visible flags in a namespace list.
  */
 static void
-setNamespaceColumnVisibility(List *namespace, bool cols_visible)
+setNamespaceColumnVisibility(List *namespaces, bool cols_visible)
 {
 	ListCell   *lc;
 
-	foreach(lc, namespace)
+	foreach(lc, namespaces)
 	{
 		ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
 
@@ -1404,11 +1404,11 @@ setNamespaceColumnVisibility(List *namespace, bool cols_visible)
  *	  Convenience subroutine to update LATERAL flags in a namespace list.
  */
 static void
-setNamespaceLateralState(List *namespace, bool lateral_only, bool lateral_ok)
+setNamespaceLateralState(List *namespaces, bool lateral_only, bool lateral_ok)
 {
 	ListCell   *lc;
 
-	foreach(lc, namespace)
+	foreach(lc, namespaces)
 	{
 		ParseNamespaceItem *nsitem = (ParseNamespaceItem *) lfirst(lc);
 
diff --git a/src/backend/parser/parse_node.c b/src/backend/parser/parse_node.c
index 30cc7dadca..5a87e08d82 100644
--- a/src/backend/parser/parse_node.c
+++ b/src/backend/parser/parse_node.c
@@ -470,9 +470,9 @@ make_const(ParseState *pstate, Value *value, int location)
 	Const	   *con;
 	Datum		val;
 	int64		val64;
-	Oid			typeid;
-	int			typelen;
-	bool		typebyval;
+	Oid			typid;
+	int			typlen;
+	bool		typbyval;
 	ParseCallbackState pcbstate;
 
 	switch (nodeTag(value))
@@ -480,9 +480,9 @@ make_const(ParseState *pstate, Value *value, int location)
 		case T_Integer:
 			val = Int32GetDatum(intVal(value));
 
-			typeid = INT4OID;
-			typelen = sizeof(int32);
-			typebyval = true;
+			typid = INT4OID;
+			typlen = sizeof(int32);
+			typbyval = true;
 			break;
 
 		case T_Float:
@@ -499,17 +499,17 @@ make_const(ParseState *pstate, Value *value, int location)
 				{
 					val = Int32GetDatum(val32);
 
-					typeid = INT4OID;
-					typelen = sizeof(int32);
-					typebyval = true;
+					typid = INT4OID;
+					typlen = sizeof(int32);
+					typbyval = true;
 				}
 				else
 				{
 					val = Int64GetDatum(val64);
 
-					typeid = INT8OID;
-					typelen = sizeof(int64);
-					typebyval = FLOAT8PASSBYVAL;		/* int8 and float8 alike */
+					typid = INT8OID;
+					typlen = sizeof(int64);
+					typbyval = FLOAT8PASSBYVAL;		/* int8 and float8 alike */
 				}
 			}
 			else
@@ -522,9 +522,9 @@ make_const(ParseState *pstate, Value *value, int location)
 										  Int32GetDatum(-1));
 				cancel_parser_errposition_callback(&pcbstate);
 
-				typeid = NUMERICOID;
-				typelen = -1;	/* variable len */
-				typebyval = false;
+				typid = NUMERICOID;
+				typlen = -1;	/* variable len */
+				typbyval = false;
 			}
 			break;
 
@@ -536,9 +536,9 @@ make_const(ParseState *pstate, Value *value, int location)
 			 */
 			val = CStringGetDatum(strVal(value));
 
-			typeid = UNKNOWNOID;	/* will be coerced later */
-			typelen = -2;		/* cstring-style varwidth type */
-			typebyval = false;
+			typid = UNKNOWNOID;	/* will be coerced later */
+			typlen = -2;		/* cstring-style varwidth type */
+			typbyval = false;
 			break;
 
 		case T_BitString:
@@ -549,9 +549,9 @@ make_const(ParseState *pstate, Value *value, int location)
 									  ObjectIdGetDatum(InvalidOid),
 									  Int32GetDatum(-1));
 			cancel_parser_errposition_callback(&pcbstate);
-			typeid = BITOID;
-			typelen = -1;
-			typebyval = false;
+			typid = BITOID;
+			typlen = -1;
+			typbyval = false;
 			break;
 
 		case T_Null:
@@ -571,13 +571,13 @@ make_const(ParseState *pstate, Value *value, int location)
 			return NULL;		/* keep compiler quiet */
 	}
 
-	con = makeConst(typeid,
+	con = makeConst(typid,
 					-1,			/* typmod -1 is OK for all cases */
 					InvalidOid, /* all cases are uncollatable types */
-					typelen,
+					typlen,
 					val,
 					false,
-					typebyval);
+					typbyval);
 	con->location = location;
 
 	return con;
diff --git a/src/backend/parser/scan.l b/src/backend/parser/scan.l
index 634bfa512f..ef53cc4a67 100644
--- a/src/backend/parser/scan.l
+++ b/src/backend/parser/scan.l
@@ -1195,12 +1195,12 @@ static char *
 litbufdup(core_yyscan_t yyscanner)
 {
 	int			llen = yyextra->literallen;
-	char	   *new;
+	char	   *newbuf;
 
-	new = palloc(llen + 1);
-	memcpy(new, yyextra->literalbuf, llen);
-	new[llen] = '\0';
-	return new;
+	newbuf = palloc(llen + 1);
+	memcpy(newbuf, yyextra->literalbuf, llen);
+	newbuf[llen] = '\0';
+	return newbuf;
 }
 
 static int
@@ -1307,7 +1307,7 @@ check_uescapechar(unsigned char escape)
 static char *
 litbuf_udeescape(unsigned char escape, core_yyscan_t yyscanner)
 {
-	char	   *new;
+	char	   *newbuf;
 	char	   *litbuf,
 			   *in,
 			   *out;
@@ -1321,10 +1321,10 @@ litbuf_udeescape(unsigned char escape, core_yyscan_t yyscanner)
 	 * This relies on the subtle assumption that a UTF-8 expansion cannot be
 	 * longer than its escaped representation.
 	 */
-	new = palloc(yyextra->literallen + 1);
+	newbuf = palloc(yyextra->literallen + 1);
 
 	in = litbuf;
-	out = new;
+	out = newbuf;
 	while (*in)
 	{
 		if (in[0] == escape)
@@ -1449,8 +1449,8 @@ litbuf_udeescape(unsigned char escape, core_yyscan_t yyscanner)
 	 * codes; but it's probably not worth the trouble, since this isn't likely
 	 * to be a performance-critical path.
 	 */
-	pg_verifymbstr(new, out - new, false);
-	return new;
+	pg_verifymbstr(newbuf, out - newbuf, false);
+	return newbuf;
 }
 
 static unsigned char
diff --git a/src/backend/tcop/fastpath.c b/src/backend/tcop/fastpath.c
index 2efed95132..124267f72d 100644
--- a/src/backend/tcop/fastpath.c
+++ b/src/backend/tcop/fastpath.c
@@ -51,7 +51,7 @@ struct fp_info
 {
 	Oid			funcid;
 	FmgrInfo	flinfo;			/* function lookup info for funcid */
-	Oid			namespace;		/* other stuff from pg_proc */
+	Oid			namespaceid;	/* other stuff from pg_proc */
 	Oid			rettype;
 	Oid			argtypes[FUNC_MAX_ARGS];
 	char		fname[NAMEDATALEN];		/* function name for logging */
@@ -228,7 +228,7 @@ fetch_fp_info(Oid func_id, struct fp_info * fip)
 		elog(ERROR, "function %s has more than %d arguments",
 			 NameStr(pp->proname), FUNC_MAX_ARGS);
 
-	fip->namespace = pp->pronamespace;
+	fip->namespaceid = pp->pronamespace;
 	fip->rettype = pp->prorettype;
 	memcpy(fip->argtypes, pp->proargtypes.values, pp->pronargs * sizeof(Oid));
 	strlcpy(fip->fname, NameStr(pp->proname), NAMEDATALEN);
@@ -325,11 +325,11 @@ HandleFunctionRequest(StringInfo msgBuf)
 	 * Check permission to access and call function.  Since we didn't go
 	 * through a normal name lookup, we need to check schema usage too.
 	 */
-	aclresult = pg_namespace_aclcheck(fip->namespace, GetUserId(), ACL_USAGE);
+	aclresult = pg_namespace_aclcheck(fip->namespaceid, GetUserId(), ACL_USAGE);
 	if (aclresult != ACLCHECK_OK)
 		aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
-					   get_namespace_name(fip->namespace));
-	InvokeNamespaceSearchHook(fip->namespace, true);
+					   get_namespace_name(fip->namespaceid));
+	InvokeNamespaceSearchHook(fip->namespaceid, true);
 
 	aclresult = pg_proc_aclcheck(fid, GetUserId(), ACL_EXECUTE);
 	if (aclresult != ACLCHECK_OK)
diff --git a/src/backend/tsearch/spell.c b/src/backend/tsearch/spell.c
index c1e194a8f5..c397033352 100644
--- a/src/backend/tsearch/spell.c
+++ b/src/backend/tsearch/spell.c
@@ -2388,7 +2388,7 @@ SplitToVariants(IspellDict *Conf, SPNode *snode, SplitVar *orig, char *word, int
 			if (subres)
 			{
 				/* Yes, it was a word from dictionary */
-				SplitVar   *new = CopyVar(var, 0);
+				SplitVar   *newvar = CopyVar(var, 0);
 				SplitVar   *ptr = var;
 				char	  **sptr = subres;
 
@@ -2396,17 +2396,17 @@ SplitToVariants(IspellDict *Conf, SPNode *snode, SplitVar *orig, char *word, int
 
 				while (*sptr)
 				{
-					AddStem(new, *sptr);
+					AddStem(newvar, *sptr);
 					sptr++;
 				}
 				pfree(subres);
 
 				while (ptr->next)
 					ptr = ptr->next;
-				ptr->next = SplitToVariants(Conf, NULL, new, word, wordlen, startpos + lenaff, startpos + lenaff);
+				ptr->next = SplitToVariants(Conf, NULL, newvar, word, wordlen, startpos + lenaff, startpos + lenaff);
 
-				pfree(new->stem);
-				pfree(new);
+				pfree(newvar->stem);
+				pfree(newvar);
 			}
 		}
 
diff --git a/src/backend/utils/adt/acl.c b/src/backend/utils/adt/acl.c
index 96ac1dfefd..d74b5c2e66 100644
--- a/src/backend/utils/adt/acl.c
+++ b/src/backend/utils/adt/acl.c
@@ -113,7 +113,7 @@ static Oid	convert_server_name(text *servername);
 static AclMode convert_server_priv_string(text *priv_type_text);
 static Oid	convert_tablespace_name(text *tablespacename);
 static AclMode convert_tablespace_priv_string(text *priv_type_text);
-static Oid	convert_type_name(text *typename);
+static Oid	convert_type_name(text *typeName);
 static AclMode convert_type_priv_string(text *priv_type_text);
 static AclMode convert_role_priv_string(text *priv_type_text);
 static AclResult pg_role_aclcheck(Oid role_oid, Oid roleid, AclMode mode);
@@ -4213,7 +4213,7 @@ Datum
 has_type_privilege_name_name(PG_FUNCTION_ARGS)
 {
 	Name		username = PG_GETARG_NAME(0);
-	text	   *typename = PG_GETARG_TEXT_P(1);
+	text	   *typname = PG_GETARG_TEXT_P(1);
 	text	   *priv_type_text = PG_GETARG_TEXT_P(2);
 	Oid			roleid;
 	Oid			typeoid;
@@ -4221,7 +4221,7 @@ has_type_privilege_name_name(PG_FUNCTION_ARGS)
 	AclResult	aclresult;
 
 	roleid = get_role_oid_or_public(NameStr(*username));
-	typeoid = convert_type_name(typename);
+	typeoid = convert_type_name(typname);
 	mode = convert_type_priv_string(priv_type_text);
 
 	aclresult = pg_type_aclcheck(typeoid, roleid, mode);
@@ -4238,7 +4238,7 @@ has_type_privilege_name_name(PG_FUNCTION_ARGS)
 Datum
 has_type_privilege_name(PG_FUNCTION_ARGS)
 {
-	text	   *typename = PG_GETARG_TEXT_P(0);
+	text	   *typname = PG_GETARG_TEXT_P(0);
 	text	   *priv_type_text = PG_GETARG_TEXT_P(1);
 	Oid			roleid;
 	Oid			typeoid;
@@ -4246,7 +4246,7 @@ has_type_privilege_name(PG_FUNCTION_ARGS)
 	AclResult	aclresult;
 
 	roleid = GetUserId();
-	typeoid = convert_type_name(typename);
+	typeoid = convert_type_name(typname);
 	mode = convert_type_priv_string(priv_type_text);
 
 	aclresult = pg_type_aclcheck(typeoid, roleid, mode);
@@ -4315,13 +4315,13 @@ Datum
 has_type_privilege_id_name(PG_FUNCTION_ARGS)
 {
 	Oid			roleid = PG_GETARG_OID(0);
-	text	   *typename = PG_GETARG_TEXT_P(1);
+	text	   *typname = PG_GETARG_TEXT_P(1);
 	text	   *priv_type_text = PG_GETARG_TEXT_P(2);
 	Oid			typeoid;
 	AclMode		mode;
 	AclResult	aclresult;
 
-	typeoid = convert_type_name(typename);
+	typeoid = convert_type_name(typname);
 	mode = convert_type_priv_string(priv_type_text);
 
 	aclresult = pg_type_aclcheck(typeoid, roleid, mode);
@@ -4361,9 +4361,9 @@ has_type_privilege_id_id(PG_FUNCTION_ARGS)
  * Given a type name expressed as a string, look it up and return Oid
  */
 static Oid
-convert_type_name(text *typename)
+convert_type_name(text *typeName)
 {
-	char	   *typname = text_to_cstring(typename);
+	char	   *typname = text_to_cstring(typeName);
 	Oid			oid;
 
 	oid = DatumGetObjectId(DirectFunctionCall1(regtypein,
diff --git a/src/backend/utils/adt/array_selfuncs.c b/src/backend/utils/adt/array_selfuncs.c
index 50e8145241..39ab45a839 100644
--- a/src/backend/utils/adt/array_selfuncs.c
+++ b/src/backend/utils/adt/array_selfuncs.c
@@ -40,22 +40,22 @@
 		DEFAULT_OVERLAP_SEL : DEFAULT_CONTAIN_SEL)
 
 static Selectivity calc_arraycontsel(VariableStatData *vardata, Datum constval,
-				  Oid elemtype, Oid operator);
+				  Oid elemtype, Oid opid);
 static Selectivity mcelem_array_selec(ArrayType *array,
 				   TypeCacheEntry *typentry,
 				   Datum *mcelem, int nmcelem,
 				   float4 *numbers, int nnumbers,
 				   float4 *hist, int nhist,
-				   Oid operator, FmgrInfo *cmpfunc);
+				   Oid opid, FmgrInfo *cmpfunc);
 static Selectivity mcelem_array_contain_overlap_selec(Datum *mcelem, int nmcelem,
 								   float4 *numbers, int nnumbers,
 								   Datum *array_data, int nitems,
-								   Oid operator, FmgrInfo *cmpfunc);
+								   Oid opid, FmgrInfo *cmpfunc);
 static Selectivity mcelem_array_contained_selec(Datum *mcelem, int nmcelem,
 							 float4 *numbers, int nnumbers,
 							 Datum *array_data, int nitems,
 							 float4 *hist, int nhist,
-							 Oid operator, FmgrInfo *cmpfunc);
+							 Oid opid, FmgrInfo *cmpfunc);
 static float *calc_hist(const float4 *hist, int nhist, int n);
 static float *calc_distr(const float *p, int n, int m, float rest);
 static int	floor_log2(uint32 n);
@@ -251,7 +251,7 @@ Datum
 arraycontsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	VariableStatData vardata;
@@ -266,7 +266,7 @@ arraycontsel(PG_FUNCTION_ARGS)
 	 */
 	if (!get_restriction_variable(root, args, varRelid,
 								  &vardata, &other, &varonleft))
-		PG_RETURN_FLOAT8(DEFAULT_SEL(operator));
+		PG_RETURN_FLOAT8(DEFAULT_SEL(opid));
 
 	/*
 	 * Can't do anything useful if the something is not a constant, either.
@@ -274,7 +274,7 @@ arraycontsel(PG_FUNCTION_ARGS)
 	if (!IsA(other, Const))
 	{
 		ReleaseVariableStats(vardata);
-		PG_RETURN_FLOAT8(DEFAULT_SEL(operator));
+		PG_RETURN_FLOAT8(DEFAULT_SEL(opid));
 	}
 
 	/*
@@ -293,10 +293,10 @@ arraycontsel(PG_FUNCTION_ARGS)
 	 */
 	if (!varonleft)
 	{
-		if (operator == OID_ARRAY_CONTAINS_OP)
-			operator = OID_ARRAY_CONTAINED_OP;
-		else if (operator == OID_ARRAY_CONTAINED_OP)
-			operator = OID_ARRAY_CONTAINS_OP;
+		if (opid == OID_ARRAY_CONTAINS_OP)
+			opid = OID_ARRAY_CONTAINED_OP;
+		else if (opid == OID_ARRAY_CONTAINED_OP)
+			opid = OID_ARRAY_CONTAINS_OP;
 	}
 
 	/*
@@ -310,11 +310,11 @@ arraycontsel(PG_FUNCTION_ARGS)
 		element_typeid == get_base_element_type(vardata.vartype))
 	{
 		selec = calc_arraycontsel(&vardata, ((Const *) other)->constvalue,
-								  element_typeid, operator);
+								  element_typeid, opid);
 	}
 	else
 	{
-		selec = DEFAULT_SEL(operator);
+		selec = DEFAULT_SEL(opid);
 	}
 
 	ReleaseVariableStats(vardata);
@@ -331,9 +331,9 @@ Datum
 arraycontjoinsel(PG_FUNCTION_ARGS)
 {
 	/* For the moment this is just a stub */
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 
-	PG_RETURN_FLOAT8(DEFAULT_SEL(operator));
+	PG_RETURN_FLOAT8(DEFAULT_SEL(opid));
 }
 
 /*
@@ -345,7 +345,7 @@ arraycontjoinsel(PG_FUNCTION_ARGS)
  */
 static Selectivity
 calc_arraycontsel(VariableStatData *vardata, Datum constval,
-				  Oid elemtype, Oid operator)
+				  Oid elemtype, Oid opid)
 {
 	Selectivity selec;
 	TypeCacheEntry *typentry;
@@ -355,7 +355,7 @@ calc_arraycontsel(VariableStatData *vardata, Datum constval,
 	/* Get element type's default comparison function */
 	typentry = lookup_type_cache(elemtype, TYPECACHE_CMP_PROC_FINFO);
 	if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
-		return DEFAULT_SEL(operator);
+		return DEFAULT_SEL(opid);
 	cmpfunc = &typentry->cmp_proc_finfo;
 
 	/*
@@ -388,7 +388,7 @@ calc_arraycontsel(VariableStatData *vardata, Datum constval,
 			 * For "array <@ const" case we also need histogram of distinct
 			 * element counts.
 			 */
-			if (operator != OID_ARRAY_CONTAINED_OP ||
+			if (opid != OID_ARRAY_CONTAINED_OP ||
 				!get_attstatsslot(vardata->statsTuple,
 								  elemtype, vardata->atttypmod,
 								  STATISTIC_KIND_DECHIST, InvalidOid,
@@ -405,7 +405,7 @@ calc_arraycontsel(VariableStatData *vardata, Datum constval,
 									   values, nvalues,
 									   numbers, nnumbers,
 									   hist, nhist,
-									   operator, cmpfunc);
+									   opid, cmpfunc);
 
 			if (hist)
 				free_attstatsslot(elemtype, NULL, 0, hist, nhist);
@@ -416,7 +416,7 @@ calc_arraycontsel(VariableStatData *vardata, Datum constval,
 			/* No most-common-elements info, so do without */
 			selec = mcelem_array_selec(array, typentry,
 									   NULL, 0, NULL, 0, NULL, 0,
-									   operator, cmpfunc);
+									   opid, cmpfunc);
 		}
 
 		/*
@@ -429,7 +429,7 @@ calc_arraycontsel(VariableStatData *vardata, Datum constval,
 		/* No stats at all, so do without */
 		selec = mcelem_array_selec(array, typentry,
 								   NULL, 0, NULL, 0, NULL, 0,
-								   operator, cmpfunc);
+								   opid, cmpfunc);
 		/* we assume no nulls here, so no stanullfrac correction */
 	}
 
@@ -452,7 +452,7 @@ mcelem_array_selec(ArrayType *array, TypeCacheEntry *typentry,
 				   Datum *mcelem, int nmcelem,
 				   float4 *numbers, int nnumbers,
 				   float4 *hist, int nhist,
-				   Oid operator, FmgrInfo *cmpfunc)
+				   Oid opid, FmgrInfo *cmpfunc)
 {
 	Selectivity selec;
 	int			num_elems;
@@ -488,7 +488,7 @@ mcelem_array_selec(ArrayType *array, TypeCacheEntry *typentry,
 	 * Query "column @> '{anything, null}'" matches nothing.  For the other
 	 * two operators, presence of a null in the constant can be ignored.
 	 */
-	if (null_present && operator == OID_ARRAY_CONTAINS_OP)
+	if (null_present && opid == OID_ARRAY_CONTAINS_OP)
 	{
 		pfree(elem_values);
 		pfree(elem_nulls);
@@ -500,21 +500,21 @@ mcelem_array_selec(ArrayType *array, TypeCacheEntry *typentry,
 			  element_compare, cmpfunc);
 
 	/* Separate cases according to operator */
-	if (operator == OID_ARRAY_CONTAINS_OP || operator == OID_ARRAY_OVERLAP_OP)
+	if (opid == OID_ARRAY_CONTAINS_OP || opid == OID_ARRAY_OVERLAP_OP)
 		selec = mcelem_array_contain_overlap_selec(mcelem, nmcelem,
 												   numbers, nnumbers,
 												 elem_values, nonnull_nitems,
-												   operator, cmpfunc);
-	else if (operator == OID_ARRAY_CONTAINED_OP)
+												   opid, cmpfunc);
+	else if (opid == OID_ARRAY_CONTAINED_OP)
 		selec = mcelem_array_contained_selec(mcelem, nmcelem,
 											 numbers, nnumbers,
 											 elem_values, nonnull_nitems,
 											 hist, nhist,
-											 operator, cmpfunc);
+											 opid, cmpfunc);
 	else
 	{
 		elog(ERROR, "arraycontsel called for unrecognized operator %u",
-			 operator);
+			 opid);
 		selec = 0.0;			/* keep compiler quiet */
 	}
 
@@ -544,7 +544,7 @@ static Selectivity
 mcelem_array_contain_overlap_selec(Datum *mcelem, int nmcelem,
 								   float4 *numbers, int nnumbers,
 								   Datum *array_data, int nitems,
-								   Oid operator, FmgrInfo *cmpfunc)
+								   Oid opid, FmgrInfo *cmpfunc)
 {
 	Selectivity selec,
 				elem_selec;
@@ -582,7 +582,7 @@ mcelem_array_contain_overlap_selec(Datum *mcelem, int nmcelem,
 	else
 		use_bsearch = false;
 
-	if (operator == OID_ARRAY_CONTAINS_OP)
+	if (opid == OID_ARRAY_CONTAINS_OP)
 	{
 		/*
 		 * Initial selectivity for "column @> const" query is 1.0, and it will
@@ -654,7 +654,7 @@ mcelem_array_contain_overlap_selec(Datum *mcelem, int nmcelem,
 		 * Update overall selectivity using the current element's selectivity
 		 * and an assumption of element occurrence independence.
 		 */
-		if (operator == OID_ARRAY_CONTAINS_OP)
+		if (opid == OID_ARRAY_CONTAINS_OP)
 			selec *= elem_selec;
 		else
 			selec = selec + elem_selec - selec * elem_selec;
@@ -720,7 +720,7 @@ mcelem_array_contained_selec(Datum *mcelem, int nmcelem,
 							 float4 *numbers, int nnumbers,
 							 Datum *array_data, int nitems,
 							 float4 *hist, int nhist,
-							 Oid operator, FmgrInfo *cmpfunc)
+							 Oid opid, FmgrInfo *cmpfunc)
 {
 	int			mcelem_index,
 				i,
diff --git a/src/backend/utils/adt/format_type.c b/src/backend/utils/adt/format_type.c
index 00bfaca59e..fccd1d4f18 100644
--- a/src/backend/utils/adt/format_type.c
+++ b/src/backend/utils/adt/format_type.c
@@ -437,9 +437,9 @@ oidvectortypes(PG_FUNCTION_ARGS)
 
 	for (num = 0; num < numargs; num++)
 	{
-		char	   *typename = format_type_internal(oidArray->values[num], -1,
+		char	   *typname = format_type_internal(oidArray->values[num], -1,
 													false, true, false);
-		size_t		slen = strlen(typename);
+		size_t		slen = strlen(typname);
 
 		if (left < (slen + 2))
 		{
@@ -453,7 +453,7 @@ oidvectortypes(PG_FUNCTION_ARGS)
 			strcat(result, ", ");
 			left -= 2;
 		}
-		strcat(result, typename);
+		strcat(result, typname);
 		left -= slen;
 	}
 
diff --git a/src/backend/utils/adt/misc.c b/src/backend/utils/adt/misc.c
index 0116fa08a6..54e6d768ff 100644
--- a/src/backend/utils/adt/misc.c
+++ b/src/backend/utils/adt/misc.c
@@ -651,17 +651,17 @@ pg_typeof(PG_FUNCTION_ARGS)
 Datum
 pg_collation_for(PG_FUNCTION_ARGS)
 {
-	Oid			typeid;
+	Oid			typid;
 	Oid			collid;
 
-	typeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
-	if (!typeid)
+	typid = get_fn_expr_argtype(fcinfo->flinfo, 0);
+	if (!typid)
 		PG_RETURN_NULL();
-	if (!type_is_collatable(typeid) && typeid != UNKNOWNOID)
+	if (!type_is_collatable(typid) && typid != UNKNOWNOID)
 		ereport(ERROR,
 				(errcode(ERRCODE_DATATYPE_MISMATCH),
 				 errmsg("collations are not supported by type %s",
-						format_type_be(typeid))));
+						format_type_be(typid))));
 
 	collid = PG_GET_COLLATION();
 	if (!collid)
diff --git a/src/backend/utils/adt/network_gist.c b/src/backend/utils/adt/network_gist.c
index a0097dae9c..4c6a6b2d81 100644
--- a/src/backend/utils/adt/network_gist.c
+++ b/src/backend/utils/adt/network_gist.c
@@ -629,17 +629,17 @@ inet_gist_penalty(PG_FUNCTION_ARGS)
 	GISTENTRY  *origent = (GISTENTRY *) PG_GETARG_POINTER(0);
 	GISTENTRY  *newent = (GISTENTRY *) PG_GETARG_POINTER(1);
 	float	   *penalty = (float *) PG_GETARG_POINTER(2);
-	GistInetKey *orig = DatumGetInetKeyP(origent->key),
-			   *new = DatumGetInetKeyP(newent->key);
+	GistInetKey *origkey = DatumGetInetKeyP(origent->key),
+			   *newkey = DatumGetInetKeyP(newent->key);
 	int			commonbits;
 
-	if (gk_ip_family(orig) == gk_ip_family(new))
+	if (gk_ip_family(origkey) == gk_ip_family(newkey))
 	{
-		if (gk_ip_minbits(orig) <= gk_ip_minbits(new))
+		if (gk_ip_minbits(origkey) <= gk_ip_minbits(newkey))
 		{
-			commonbits = bitncommon(gk_ip_addr(orig), gk_ip_addr(new),
-									Min(gk_ip_commonbits(orig),
-										gk_ip_commonbits(new)));
+			commonbits = bitncommon(gk_ip_addr(origkey), gk_ip_addr(newkey),
+									Min(gk_ip_commonbits(origkey),
+										gk_ip_commonbits(newkey)));
 			if (commonbits > 0)
 				*penalty = 1.0f / commonbits;
 			else
diff --git a/src/backend/utils/adt/network_selfuncs.c b/src/backend/utils/adt/network_selfuncs.c
index bcdd902ee8..2bcd16f356 100644
--- a/src/backend/utils/adt/network_selfuncs.c
+++ b/src/backend/utils/adt/network_selfuncs.c
@@ -43,16 +43,16 @@
 /* Maximum number of items to consider in join selectivity calculations */
 #define MAX_CONSIDERED_ELEMS 1024
 
-static Selectivity networkjoinsel_inner(Oid operator,
+static Selectivity networkjoinsel_inner(Oid opid,
 					 VariableStatData *vardata1, VariableStatData *vardata2);
-static Selectivity networkjoinsel_semi(Oid operator,
+static Selectivity networkjoinsel_semi(Oid opid,
 					VariableStatData *vardata1, VariableStatData *vardata2);
 static Selectivity mcv_population(float4 *mcv_numbers, int mcv_nvalues);
 static Selectivity inet_hist_value_sel(Datum *values, int nvalues,
 					Datum constvalue, int opr_codenum);
 static Selectivity inet_mcv_join_sel(Datum *mcv1_values,
 				  float4 *mcv1_numbers, int mcv1_nvalues, Datum *mcv2_values,
-				  float4 *mcv2_numbers, int mcv2_nvalues, Oid operator);
+				  float4 *mcv2_numbers, int mcv2_nvalues, Oid opid);
 static Selectivity inet_mcv_hist_sel(Datum *mcv_values, float4 *mcv_numbers,
 				  int mcv_nvalues, Datum *hist_values, int hist_nvalues,
 				  int opr_codenum);
@@ -65,7 +65,7 @@ static Selectivity inet_semi_join_sel(Datum lhs_value,
 				   bool hist_exists, Datum *hist_values, int hist_nvalues,
 				   double hist_weight,
 				   FmgrInfo *proc, int opr_codenum);
-static int	inet_opr_codenum(Oid operator);
+static int	inet_opr_codenum(Oid opid);
 static int	inet_inclusion_cmp(inet *left, inet *right, int opr_codenum);
 static int inet_masklen_inclusion_cmp(inet *left, inet *right,
 						   int opr_codenum);
@@ -79,7 +79,7 @@ Datum
 networksel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	VariableStatData vardata;
@@ -102,7 +102,7 @@ networksel(PG_FUNCTION_ARGS)
 	 */
 	if (!get_restriction_variable(root, args, varRelid,
 								  &vardata, &other, &varonleft))
-		PG_RETURN_FLOAT8(DEFAULT_SEL(operator));
+		PG_RETURN_FLOAT8(DEFAULT_SEL(opid));
 
 	/*
 	 * Can't do anything useful if the something is not a constant, either.
@@ -110,7 +110,7 @@ networksel(PG_FUNCTION_ARGS)
 	if (!IsA(other, Const))
 	{
 		ReleaseVariableStats(vardata);
-		PG_RETURN_FLOAT8(DEFAULT_SEL(operator));
+		PG_RETURN_FLOAT8(DEFAULT_SEL(opid));
 	}
 
 	/* All of the operators handled here are strict. */
@@ -125,7 +125,7 @@ networksel(PG_FUNCTION_ARGS)
 	if (!HeapTupleIsValid(vardata.statsTuple))
 	{
 		ReleaseVariableStats(vardata);
-		PG_RETURN_FLOAT8(DEFAULT_SEL(operator));
+		PG_RETURN_FLOAT8(DEFAULT_SEL(opid));
 	}
 
 	stats = (Form_pg_statistic) GETSTRUCT(vardata.statsTuple);
@@ -137,7 +137,7 @@ networksel(PG_FUNCTION_ARGS)
 	 * to the result selectivity.  Also add up the total fraction represented
 	 * by MCV entries.
 	 */
-	fmgr_info(get_opcode(operator), &proc);
+	fmgr_info(get_opcode(opid), &proc);
 	mcv_selec = mcv_selectivity(&vardata, &proc, constvalue, varonleft,
 								&sumcommon);
 
@@ -153,7 +153,7 @@ networksel(PG_FUNCTION_ARGS)
 						 &hist_values, &hist_nvalues,
 						 NULL, NULL))
 	{
-		int			opr_codenum = inet_opr_codenum(operator);
+		int			opr_codenum = inet_opr_codenum(opid);
 
 		/* Commute if needed, so we can consider histogram to be on the left */
 		if (!varonleft)
@@ -164,7 +164,7 @@ networksel(PG_FUNCTION_ARGS)
 		free_attstatsslot(vardata.atttype, hist_values, hist_nvalues, NULL, 0);
 	}
 	else
-		non_mcv_selec = DEFAULT_SEL(operator);
+		non_mcv_selec = DEFAULT_SEL(opid);
 
 	/* Combine selectivities for MCV and non-MCV populations */
 	selec = mcv_selec + (1.0 - nullfrac - sumcommon) * non_mcv_selec;
@@ -199,7 +199,7 @@ Datum
 networkjoinsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 #ifdef NOT_USED
 	JoinType	jointype = (JoinType) PG_GETARG_INT16(3);
@@ -223,15 +223,15 @@ networkjoinsel(PG_FUNCTION_ARGS)
 			 * Selectivity for left/full join is not exactly the same as inner
 			 * join, but we neglect the difference, as eqjoinsel does.
 			 */
-			selec = networkjoinsel_inner(operator, &vardata1, &vardata2);
+			selec = networkjoinsel_inner(opid, &vardata1, &vardata2);
 			break;
 		case JOIN_SEMI:
 		case JOIN_ANTI:
 			/* Here, it's important that we pass the outer var on the left. */
 			if (!join_is_reversed)
-				selec = networkjoinsel_semi(operator, &vardata1, &vardata2);
+				selec = networkjoinsel_semi(opid, &vardata1, &vardata2);
 			else
-				selec = networkjoinsel_semi(get_commutator(operator),
+				selec = networkjoinsel_semi(get_commutator(opid),
 											&vardata2, &vardata1);
 			break;
 		default:
@@ -263,7 +263,7 @@ networkjoinsel(PG_FUNCTION_ARGS)
  * Also, MCV vs histogram selectivity is not neglected as in eqjoinsel_inner().
  */
 static Selectivity
-networkjoinsel_inner(Oid operator,
+networkjoinsel_inner(Oid opid,
 					 VariableStatData *vardata1, VariableStatData *vardata2)
 {
 	Form_pg_statistic stats;
@@ -338,7 +338,7 @@ networkjoinsel_inner(Oid operator,
 			sumcommon2 = mcv_population(mcv2_numbers, mcv2_length);
 	}
 
-	opr_codenum = inet_opr_codenum(operator);
+	opr_codenum = inet_opr_codenum(opid);
 
 	/*
 	 * Calculate selectivity for MCV vs MCV matches.
@@ -346,7 +346,7 @@ networkjoinsel_inner(Oid operator,
 	if (mcv1_exists && mcv2_exists)
 		selec += inet_mcv_join_sel(mcv1_values, mcv1_numbers, mcv1_length,
 								   mcv2_values, mcv2_numbers, mcv2_length,
-								   operator);
+								   opid);
 
 	/*
 	 * Add in selectivities for MCV vs histogram matches, scaling according to
@@ -380,7 +380,7 @@ networkjoinsel_inner(Oid operator,
 	 * We can apply null fractions if known, though.
 	 */
 	if ((!mcv1_exists && !hist1_exists) || (!mcv2_exists && !hist2_exists))
-		selec = (1.0 - nullfrac1) * (1.0 - nullfrac2) * DEFAULT_SEL(operator);
+		selec = (1.0 - nullfrac1) * (1.0 - nullfrac2) * DEFAULT_SEL(opid);
 
 	/* Release stats. */
 	if (mcv1_exists)
@@ -406,7 +406,7 @@ networkjoinsel_inner(Oid operator,
  * histogram selectivity for semi/anti join cases.
  */
 static Selectivity
-networkjoinsel_semi(Oid operator,
+networkjoinsel_semi(Oid opid,
 					VariableStatData *vardata1, VariableStatData *vardata2)
 {
 	Form_pg_statistic stats;
@@ -484,8 +484,8 @@ networkjoinsel_semi(Oid operator,
 			sumcommon2 = mcv_population(mcv2_numbers, mcv2_length);
 	}
 
-	opr_codenum = inet_opr_codenum(operator);
-	fmgr_info(get_opcode(operator), &proc);
+	opr_codenum = inet_opr_codenum(opid);
+	fmgr_info(get_opcode(opid), &proc);
 
 	/* Estimate number of input rows represented by RHS histogram. */
 	if (hist2_exists && vardata2->rel)
@@ -547,7 +547,7 @@ networkjoinsel_semi(Oid operator,
 	 * We can apply null fractions if known, though.
 	 */
 	if ((!mcv1_exists && !hist1_exists) || (!mcv2_exists && !hist2_exists))
-		selec = (1.0 - nullfrac1) * (1.0 - nullfrac2) * DEFAULT_SEL(operator);
+		selec = (1.0 - nullfrac1) * (1.0 - nullfrac2) * DEFAULT_SEL(opid);
 
 	/* Release stats. */
 	if (mcv1_exists)
@@ -707,14 +707,14 @@ inet_hist_value_sel(Datum *values, int nvalues, Datum constvalue,
 static Selectivity
 inet_mcv_join_sel(Datum *mcv1_values, float4 *mcv1_numbers, int mcv1_nvalues,
 				  Datum *mcv2_values, float4 *mcv2_numbers, int mcv2_nvalues,
-				  Oid operator)
+				  Oid opid)
 {
 	Selectivity selec = 0.0;
 	FmgrInfo	proc;
 	int			i,
 				j;
 
-	fmgr_info(get_opcode(operator), &proc);
+	fmgr_info(get_opcode(opid), &proc);
 
 	for (i = 0; i < mcv1_nvalues; i++)
 	{
@@ -868,9 +868,9 @@ inet_semi_join_sel(Datum lhs_value,
  * operator.
  */
 static int
-inet_opr_codenum(Oid operator)
+inet_opr_codenum(Oid opid)
 {
-	switch (operator)
+	switch (opid)
 	{
 		case OID_INET_SUP_OP:
 			return -2;
@@ -884,7 +884,7 @@ inet_opr_codenum(Oid operator)
 			return 2;
 		default:
 			elog(ERROR, "unrecognized operator %u for inet selectivity",
-				 operator);
+				 opid);
 	}
 	return 0;					/* unreached, but keep compiler quiet */
 }
diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index 781c713f81..d0439d319b 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -934,7 +934,7 @@ numeric		(PG_FUNCTION_ARGS)
 {
 	Numeric		num = PG_GETARG_NUMERIC(0);
 	int32		typmod = PG_GETARG_INT32(1);
-	Numeric		new;
+	Numeric		newnum;
 	int32		tmp_typmod;
 	int			precision;
 	int			scale;
@@ -954,9 +954,9 @@ numeric		(PG_FUNCTION_ARGS)
 	 */
 	if (typmod < (int32) (VARHDRSZ))
 	{
-		new = (Numeric) palloc(VARSIZE(num));
-		memcpy(new, num, VARSIZE(num));
-		PG_RETURN_NUMERIC(new);
+		newnum = (Numeric) palloc(VARSIZE(num));
+		memcpy(newnum, num, VARSIZE(num));
+		PG_RETURN_NUMERIC(newnum);
 	}
 
 	/*
@@ -979,16 +979,16 @@ numeric		(PG_FUNCTION_ARGS)
 		&& (NUMERIC_CAN_BE_SHORT(scale, NUMERIC_WEIGHT(num))
 			|| !NUMERIC_IS_SHORT(num)))
 	{
-		new = (Numeric) palloc(VARSIZE(num));
-		memcpy(new, num, VARSIZE(num));
+		newnum = (Numeric) palloc(VARSIZE(num));
+		memcpy(newnum, num, VARSIZE(num));
 		if (NUMERIC_IS_SHORT(num))
-			new->choice.n_short.n_header =
+			newnum->choice.n_short.n_header =
 				(num->choice.n_short.n_header & ~NUMERIC_SHORT_DSCALE_MASK)
 				| (scale << NUMERIC_SHORT_DSCALE_SHIFT);
 		else
-			new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
+			newnum->choice.n_long.n_sign_dscale = NUMERIC_SIGN(newnum) |
 				((uint16) scale & NUMERIC_DSCALE_MASK);
-		PG_RETURN_NUMERIC(new);
+		PG_RETURN_NUMERIC(newnum);
 	}
 
 	/*
@@ -999,11 +999,11 @@ numeric		(PG_FUNCTION_ARGS)
 
 	set_var_from_num(num, &var);
 	apply_typmod(&var, typmod);
-	new = make_result(&var);
+	newnum = make_result(&var);
 
 	free_var(&var);
 
-	PG_RETURN_NUMERIC(new);
+	PG_RETURN_NUMERIC(newnum);
 }
 
 Datum
diff --git a/src/backend/utils/adt/rangetypes_gist.c b/src/backend/utils/adt/rangetypes_gist.c
index f81b16c236..9f5390f34b 100644
--- a/src/backend/utils/adt/rangetypes_gist.c
+++ b/src/backend/utils/adt/rangetypes_gist.c
@@ -257,8 +257,8 @@ range_gist_penalty(PG_FUNCTION_ARGS)
 	GISTENTRY  *origentry = (GISTENTRY *) PG_GETARG_POINTER(0);
 	GISTENTRY  *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
 	float	   *penalty = (float *) PG_GETARG_POINTER(2);
-	RangeType  *orig = DatumGetRangeType(origentry->key);
-	RangeType  *new = DatumGetRangeType(newentry->key);
+	RangeType  *origkey = DatumGetRangeType(origentry->key);
+	RangeType  *newkey = DatumGetRangeType(newentry->key);
 	TypeCacheEntry *typcache;
 	bool		has_subtype_diff;
 	RangeBound	orig_lower,
@@ -268,15 +268,15 @@ range_gist_penalty(PG_FUNCTION_ARGS)
 	bool		orig_empty,
 				new_empty;
 
-	if (RangeTypeGetOid(orig) != RangeTypeGetOid(new))
+	if (RangeTypeGetOid(origkey) != RangeTypeGetOid(newkey))
 		elog(ERROR, "range types do not match");
 
-	typcache = range_get_typcache(fcinfo, RangeTypeGetOid(orig));
+	typcache = range_get_typcache(fcinfo, RangeTypeGetOid(origkey));
 
 	has_subtype_diff = OidIsValid(typcache->rng_subdiff_finfo.fn_oid);
 
-	range_deserialize(typcache, orig, &orig_lower, &orig_upper, &orig_empty);
-	range_deserialize(typcache, new, &new_lower, &new_upper, &new_empty);
+	range_deserialize(typcache, origkey, &orig_lower, &orig_upper, &orig_empty);
+	range_deserialize(typcache, newkey, &new_lower, &new_upper, &new_empty);
 
 	/*
 	 * Distinct branches for handling distinct classes of ranges.  Note that
@@ -295,7 +295,7 @@ range_gist_penalty(PG_FUNCTION_ARGS)
 			 */
 			*penalty = 0.0;
 		}
-		else if (RangeIsOrContainsEmpty(orig))
+		else if (RangeIsOrContainsEmpty(origkey))
 		{
 			/*
 			 * The second case is to insert empty range into range which
@@ -356,7 +356,7 @@ range_gist_penalty(PG_FUNCTION_ARGS)
 			*penalty = 2 * INFINITE_BOUND_PENALTY;
 		}
 
-		if (RangeIsOrContainsEmpty(orig))
+		if (RangeIsOrContainsEmpty(origkey))
 		{
 			/*
 			 * Original range is narrower when it doesn't contain empty
@@ -952,17 +952,17 @@ range_gist_class_split(TypeCacheEntry *typcache,
 	for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
 	{
 		RangeType  *range = DatumGetRangeType(entryvec->vector[i].key);
-		int			class;
+		int			classNumber;
 
 		/* Get class of range */
-		class = get_gist_range_class(range);
+		classNumber = get_gist_range_class(range);
 
 		/* Place range to appropriate page */
-		if (classes_groups[class] == SPLIT_LEFT)
+		if (classes_groups[classNumber] == SPLIT_LEFT)
 			PLACE_LEFT(range, i);
 		else
 		{
-			Assert(classes_groups[class] == SPLIT_RIGHT);
+			Assert(classes_groups[classNumber] == SPLIT_RIGHT);
 			PLACE_RIGHT(range, i);
 		}
 	}
diff --git a/src/backend/utils/adt/rangetypes_selfuncs.c b/src/backend/utils/adt/rangetypes_selfuncs.c
index 2997edd672..0b05df1214 100644
--- a/src/backend/utils/adt/rangetypes_selfuncs.c
+++ b/src/backend/utils/adt/rangetypes_selfuncs.c
@@ -27,11 +27,11 @@
 #include "utils/typcache.h"
 
 static double calc_rangesel(TypeCacheEntry *typcache, VariableStatData *vardata,
-			  RangeType *constval, Oid operator);
-static double default_range_selectivity(Oid operator);
+			  RangeType *constval, Oid opid);
+static double default_range_selectivity(Oid opid);
 static double calc_hist_selectivity(TypeCacheEntry *typcache,
 					  VariableStatData *vardata, RangeType *constval,
-					  Oid operator);
+					  Oid opid);
 static double calc_hist_selectivity_scalar(TypeCacheEntry *typcache,
 							 RangeBound *constbound,
 							 RangeBound *hist, int hist_nvalues,
@@ -61,9 +61,9 @@ static double calc_hist_selectivity_contains(TypeCacheEntry *typcache,
  * have statistics or cannot use them for some reason.
  */
 static double
-default_range_selectivity(Oid operator)
+default_range_selectivity(Oid opid)
 {
-	switch (operator)
+	switch (opid)
 	{
 		case OID_RANGE_OVERLAP_OP:
 			return 0.01;
@@ -105,7 +105,7 @@ Datum
 rangesel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	VariableStatData vardata;
@@ -121,7 +121,7 @@ rangesel(PG_FUNCTION_ARGS)
 	 */
 	if (!get_restriction_variable(root, args, varRelid,
 								  &vardata, &other, &varonleft))
-		PG_RETURN_FLOAT8(default_range_selectivity(operator));
+		PG_RETURN_FLOAT8(default_range_selectivity(opid));
 
 	/*
 	 * Can't do anything useful if the something is not a constant, either.
@@ -129,7 +129,7 @@ rangesel(PG_FUNCTION_ARGS)
 	if (!IsA(other, Const))
 	{
 		ReleaseVariableStats(vardata);
-		PG_RETURN_FLOAT8(default_range_selectivity(operator));
+		PG_RETURN_FLOAT8(default_range_selectivity(opid));
 	}
 
 	/*
@@ -149,12 +149,12 @@ rangesel(PG_FUNCTION_ARGS)
 	if (!varonleft)
 	{
 		/* we have other Op var, commute to make var Op other */
-		operator = get_commutator(operator);
-		if (!operator)
+		opid = get_commutator(opid);
+		if (!opid)
 		{
 			/* Use default selectivity (should we raise an error instead?) */
 			ReleaseVariableStats(vardata);
-			PG_RETURN_FLOAT8(default_range_selectivity(operator));
+			PG_RETURN_FLOAT8(default_range_selectivity(opid));
 		}
 	}
 
@@ -169,7 +169,7 @@ rangesel(PG_FUNCTION_ARGS)
 	 * only that single point, so that we don't need special handling for that
 	 * in what follows.
 	 */
-	if (operator == OID_RANGE_CONTAINS_ELEM_OP)
+	if (opid == OID_RANGE_CONTAINS_ELEM_OP)
 	{
 		typcache = range_get_typcache(fcinfo, vardata.vartype);
 
@@ -189,7 +189,7 @@ rangesel(PG_FUNCTION_ARGS)
 			constrange = range_serialize(typcache, &lower, &upper, false);
 		}
 	}
-	else if (operator == OID_RANGE_ELEM_CONTAINED_OP)
+	else if (opid == OID_RANGE_ELEM_CONTAINED_OP)
 	{
 		/*
 		 * Here, the Var is the elem, not the range.  For now we just punt and
@@ -212,9 +212,9 @@ rangesel(PG_FUNCTION_ARGS)
 	 * OID_RANGE_ELEM_CONTAINED_OP.
 	 */
 	if (constrange)
-		selec = calc_rangesel(typcache, &vardata, constrange, operator);
+		selec = calc_rangesel(typcache, &vardata, constrange, opid);
 	else
-		selec = default_range_selectivity(operator);
+		selec = default_range_selectivity(opid);
 
 	ReleaseVariableStats(vardata);
 
@@ -225,7 +225,7 @@ rangesel(PG_FUNCTION_ARGS)
 
 static double
 calc_rangesel(TypeCacheEntry *typcache, VariableStatData *vardata,
-			  RangeType *constval, Oid operator)
+			  RangeType *constval, Oid opid)
 {
 	double		hist_selec;
 	double		selec;
@@ -280,7 +280,7 @@ calc_rangesel(TypeCacheEntry *typcache, VariableStatData *vardata,
 		 * An empty range matches all ranges, all empty ranges, or nothing,
 		 * depending on the operator
 		 */
-		switch (operator)
+		switch (opid)
 		{
 				/* these return false if either argument is empty */
 			case OID_RANGE_OVERLAP_OP:
@@ -315,7 +315,7 @@ calc_rangesel(TypeCacheEntry *typcache, VariableStatData *vardata,
 				/* an element cannot be empty */
 			case OID_RANGE_CONTAINS_ELEM_OP:
 			default:
-				elog(ERROR, "unexpected operator %u", operator);
+				elog(ERROR, "unexpected operator %u", opid);
 				selec = 0.0;	/* keep compiler quiet */
 				break;
 		}
@@ -331,16 +331,16 @@ calc_rangesel(TypeCacheEntry *typcache, VariableStatData *vardata,
 		 * NULL tuples, if we had statistics for them.
 		 */
 		hist_selec = calc_hist_selectivity(typcache, vardata, constval,
-										   operator);
+										   opid);
 		if (hist_selec < 0.0)
-			hist_selec = default_range_selectivity(operator);
+			hist_selec = default_range_selectivity(opid);
 
 		/*
 		 * Now merge the results for the empty ranges and histogram
 		 * calculations, realizing that the histogram covers only the
 		 * non-null, non-empty values.
 		 */
-		if (operator == OID_RANGE_CONTAINED_OP)
+		if (opid == OID_RANGE_CONTAINED_OP)
 		{
 			/* empty is contained by anything non-empty */
 			selec = (1.0 - empty_frac) * hist_selec + empty_frac;
@@ -369,7 +369,7 @@ calc_rangesel(TypeCacheEntry *typcache, VariableStatData *vardata,
  */
 static double
 calc_hist_selectivity(TypeCacheEntry *typcache, VariableStatData *vardata,
-					  RangeType *constval, Oid operator)
+					  RangeType *constval, Oid opid)
 {
 	Datum	   *hist_values;
 	int			nhist;
@@ -409,8 +409,8 @@ calc_hist_selectivity(TypeCacheEntry *typcache, VariableStatData *vardata,
 	}
 
 	/* @> and @< also need a histogram of range lengths */
-	if (operator == OID_RANGE_CONTAINS_OP ||
-		operator == OID_RANGE_CONTAINED_OP)
+	if (opid == OID_RANGE_CONTAINS_OP ||
+		opid == OID_RANGE_CONTAINED_OP)
 	{
 		if (!(HeapTupleIsValid(vardata->statsTuple) &&
 			  get_attstatsslot(vardata->statsTuple,
@@ -435,7 +435,7 @@ calc_hist_selectivity(TypeCacheEntry *typcache, VariableStatData *vardata,
 	 * Calculate selectivity comparing the lower or upper bound of the
 	 * constant with the histogram of lower or upper bounds.
 	 */
-	switch (operator)
+	switch (opid)
 	{
 		case OID_RANGE_LESS_OP:
 
@@ -555,7 +555,7 @@ calc_hist_selectivity(TypeCacheEntry *typcache, VariableStatData *vardata,
 			break;
 
 		default:
-			elog(ERROR, "unknown range operator %u", operator);
+			elog(ERROR, "unknown range operator %u", opid);
 			hist_selec = -1.0;	/* keep compiler quiet */
 			break;
 	}
diff --git a/src/backend/utils/adt/regproc.c b/src/backend/utils/adt/regproc.c
index fa920c0d8c..a75f054e9c 100644
--- a/src/backend/utils/adt/regproc.c
+++ b/src/backend/utils/adt/regproc.c
@@ -1881,11 +1881,11 @@ parseNameAndArgTypes(const char *string, bool allowNone, List **names,
 	char	   *rawname;
 	char	   *ptr;
 	char	   *ptr2;
-	char	   *typename;
+	char	   *typname;
 	bool		in_quote;
 	bool		had_comma;
 	int			paren_count;
-	Oid			typeid;
+	Oid			typid;
 	int32		typmod;
 
 	/* We need a modifiable copy of the input string. */
@@ -1941,7 +1941,7 @@ parseNameAndArgTypes(const char *string, bool allowNone, List **names,
 						 errmsg("expected a type name")));
 			break;
 		}
-		typename = ptr;
+		typname = ptr;
 		/* Find end of type name --- end of string or comma */
 		/* ... but not a quoted or parenthesized comma */
 		in_quote = false;
@@ -1984,30 +1984,30 @@ parseNameAndArgTypes(const char *string, bool allowNone, List **names,
 			Assert(*ptr == '\0');
 		}
 		/* Lop off trailing whitespace */
-		while (--ptr2 >= typename)
+		while (--ptr2 >= typname)
 		{
 			if (!isspace((unsigned char) *ptr2))
 				break;
 			*ptr2 = '\0';
 		}
 
-		if (allowNone && pg_strcasecmp(typename, "none") == 0)
+		if (allowNone && pg_strcasecmp(typname, "none") == 0)
 		{
 			/* Special case for NONE */
-			typeid = InvalidOid;
+			typid = InvalidOid;
 			typmod = -1;
 		}
 		else
 		{
 			/* Use full parser to resolve the type name */
-			parseTypeString(typename, &typeid, &typmod, false);
+			parseTypeString(typname, &typid, &typmod, false);
 		}
 		if (*nargs >= FUNC_MAX_ARGS)
 			ereport(ERROR,
 					(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
 					 errmsg("too many arguments")));
 
-		argtypes[*nargs] = typeid;
+		argtypes[*nargs] = typid;
 		(*nargs)++;
 	}
 
diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index 37139f9647..a48054d5ad 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -164,7 +164,7 @@ typedef struct RI_QueryHashEntry
 typedef struct RI_CompareKey
 {
 	Oid			eq_opr;			/* the equality operator to apply */
-	Oid			typeid;			/* the data type to apply it to */
+	Oid			typid;			/* the data type to apply it to */
 } RI_CompareKey;
 
 
@@ -217,14 +217,14 @@ static void ri_BuildQueryKey(RI_QueryKey *key,
 				 int32 constr_queryno);
 static bool ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
 			 const RI_ConstraintInfo *riinfo, bool rel_is_pk);
-static bool ri_AttributesEqual(Oid eq_opr, Oid typeid,
+static bool ri_AttributesEqual(Oid eq_opr, Oid typid,
 				   Datum oldvalue, Datum newvalue);
 
 static void ri_InitHashTables(void);
 static void InvalidateConstraintCacheCallBack(Datum arg, int cacheid, uint32 hashvalue);
 static SPIPlanPtr ri_FetchPreparedPlan(RI_QueryKey *key);
 static void ri_HashPreparedPlan(RI_QueryKey *key, SPIPlanPtr plan);
-static RI_CompareHashEntry *ri_HashCompareOp(Oid eq_opr, Oid typeid);
+static RI_CompareHashEntry *ri_HashCompareOp(Oid eq_opr, Oid typid);
 
 static void ri_CheckTrigger(FunctionCallInfo fcinfo, const char *funcname,
 				int tgkind);
@@ -3574,10 +3574,10 @@ ri_KeysEqual(Relation rel, HeapTuple oldtup, HeapTuple newtup,
  * ----------
  */
 static bool
-ri_AttributesEqual(Oid eq_opr, Oid typeid,
+ri_AttributesEqual(Oid eq_opr, Oid typid,
 				   Datum oldvalue, Datum newvalue)
 {
-	RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typeid);
+	RI_CompareHashEntry *entry = ri_HashCompareOp(eq_opr, typid);
 
 	/* Do we need to cast the values? */
 	if (OidIsValid(entry->cast_func_finfo.fn_oid))
@@ -3608,7 +3608,7 @@ ri_AttributesEqual(Oid eq_opr, Oid typeid,
  * ----------
  */
 static RI_CompareHashEntry *
-ri_HashCompareOp(Oid eq_opr, Oid typeid)
+ri_HashCompareOp(Oid eq_opr, Oid typid)
 {
 	RI_CompareKey key;
 	RI_CompareHashEntry *entry;
@@ -3625,7 +3625,7 @@ ri_HashCompareOp(Oid eq_opr, Oid typeid)
 	 * contains no struct padding.
 	 */
 	key.eq_opr = eq_opr;
-	key.typeid = typeid;
+	key.typid = typid;
 	entry = (RI_CompareHashEntry *) hash_search(ri_compare_cache,
 												(void *) &key,
 												HASH_ENTER, &found);
@@ -3662,11 +3662,11 @@ ri_HashCompareOp(Oid eq_opr, Oid typeid)
 		 */
 		op_input_types(eq_opr, &lefttype, &righttype);
 		Assert(lefttype == righttype);
-		if (typeid == lefttype)
+		if (typid == lefttype)
 			castfunc = InvalidOid;		/* simplest case */
 		else
 		{
-			pathtype = find_coercion_pathway(lefttype, typeid,
+			pathtype = find_coercion_pathway(lefttype, typid,
 											 COERCION_IMPLICIT,
 											 &castfunc);
 			if (pathtype != COERCION_PATH_FUNC &&
@@ -3678,9 +3678,9 @@ ri_HashCompareOp(Oid eq_opr, Oid typeid)
 				 * special cases such as RECORD; find_coercion_pathway
 				 * currently doesn't subsume these special cases.
 				 */
-				if (!IsBinaryCoercible(typeid, lefttype))
+				if (!IsBinaryCoercible(typid, lefttype))
 					elog(ERROR, "no conversion function from %s to %s",
-						 format_type_be(typeid),
+						 format_type_be(typid),
 						 format_type_be(lefttype));
 			}
 		}
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index b27b77de21..b71899fe0f 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -396,9 +396,9 @@ static void get_rule_windowspec(WindowClause *wc, List *targetList,
 static char *get_variable(Var *var, int levelsup, bool istoplevel,
 			 deparse_context *context);
 static void get_special_variable(Node *node, deparse_context *context,
-					 void *private);
+					 void *private_data);
 static void resolve_special_varno(Node *node, deparse_context *context,
-					  void *private,
+					  void *private_data,
 					  void (*callback) (Node *, deparse_context *, void *));
 static Node *find_param_referent(Param *param, deparse_context *context,
 					deparse_namespace **dpns_p, ListCell **ancestor_cell_p);
@@ -418,7 +418,7 @@ static void get_func_expr(FuncExpr *expr, deparse_context *context,
 static void get_agg_expr(Aggref *aggref, deparse_context *context,
 			 Aggref *original_aggref);
 static void get_agg_combine_expr(Node *node, deparse_context *context,
-					 void *private);
+					 void *private_data);
 static void get_windowfunc_expr(WindowFunc *wfunc, deparse_context *context);
 static void get_coercion_expr(Node *arg, deparse_context *context,
 				  Oid resulttype, int32 resulttypmod,
@@ -6349,7 +6349,7 @@ get_variable(Var *var, int levelsup, bool istoplevel, deparse_context *context)
  * get_rule_expr.
  */
 static void
-get_special_variable(Node *node, deparse_context *context, void *private)
+get_special_variable(Node *node, deparse_context *context, void *private_data)
 {
 	StringInfo	buf = context->buf;
 
@@ -6370,7 +6370,7 @@ get_special_variable(Node *node, deparse_context *context, void *private)
  * invoke the callback provided.
  */
 static void
-resolve_special_varno(Node *node, deparse_context *context, void *private,
+resolve_special_varno(Node *node, deparse_context *context, void *private_data,
 					  void (*callback) (Node *, deparse_context *, void *))
 {
 	Var		   *var;
@@ -6379,7 +6379,7 @@ resolve_special_varno(Node *node, deparse_context *context, void *private,
 	/* If it's not a Var, invoke the callback. */
 	if (!IsA(node, Var))
 	{
-		callback(node, context, private);
+		callback(node, context, private_data);
 		return;
 	}
 
@@ -6401,7 +6401,7 @@ resolve_special_varno(Node *node, deparse_context *context, void *private,
 			elog(ERROR, "bogus varattno for OUTER_VAR var: %d", var->varattno);
 
 		push_child_plan(dpns, dpns->outer_planstate, &save_dpns);
-		resolve_special_varno((Node *) tle->expr, context, private, callback);
+		resolve_special_varno((Node *) tle->expr, context, private_data, callback);
 		pop_child_plan(dpns, &save_dpns);
 		return;
 	}
@@ -6415,7 +6415,7 @@ resolve_special_varno(Node *node, deparse_context *context, void *private,
 			elog(ERROR, "bogus varattno for INNER_VAR var: %d", var->varattno);
 
 		push_child_plan(dpns, dpns->inner_planstate, &save_dpns);
-		resolve_special_varno((Node *) tle->expr, context, private, callback);
+		resolve_special_varno((Node *) tle->expr, context, private_data, callback);
 		pop_child_plan(dpns, &save_dpns);
 		return;
 	}
@@ -6427,14 +6427,14 @@ resolve_special_varno(Node *node, deparse_context *context, void *private,
 		if (!tle)
 			elog(ERROR, "bogus varattno for INDEX_VAR var: %d", var->varattno);
 
-		resolve_special_varno((Node *) tle->expr, context, private, callback);
+		resolve_special_varno((Node *) tle->expr, context, private_data, callback);
 		return;
 	}
 	else if (var->varno < 1 || var->varno > list_length(dpns->rtable))
 		elog(ERROR, "bogus varno: %d", var->varno);
 
 	/* Not special.  Just invoke the callback. */
-	callback(node, context, private);
+	callback(node, context, private_data);
 }
 
 /*
@@ -8827,10 +8827,10 @@ get_agg_expr(Aggref *aggref, deparse_context *context,
  * Aggref and then calls this.
  */
 static void
-get_agg_combine_expr(Node *node, deparse_context *context, void *private)
+get_agg_combine_expr(Node *node, deparse_context *context, void *private_data)
 {
 	Aggref	   *aggref;
-	Aggref	   *original_aggref = private;
+	Aggref	   *original_aggref = private_data;
 
 	if (!IsA(node, Aggref))
 		elog(ERROR, "combining Aggref does not point to an Aggref");
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 8b05e8f9f7..ba29af1993 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -39,13 +39,13 @@
  * The call convention for a restriction estimator (oprrest function) is
  *
  *		Selectivity oprrest (PlannerInfo *root,
- *							 Oid operator,
+ *							 Oid opid,
  *							 List *args,
  *							 int varRelid);
  *
  * root: general information about the query (rtable and RelOptInfo lists
  * are particularly important for the estimator).
- * operator: OID of the specific operator in question.
+ * opid: OID of the specific operator in question.
  * args: argument list from the operator clause.
  * varRelid: if not zero, the relid (rtable index) of the relation to
  * be treated as the variable relation.  May be zero if the args list
@@ -64,7 +64,7 @@
  * supplied:
  *
  *		Selectivity oprjoin (PlannerInfo *root,
- *							 Oid operator,
+ *							 Oid opid,
  *							 List *args,
  *							 JoinType jointype,
  *							 SpecialJoinInfo *sjinfo);
@@ -148,19 +148,19 @@
 get_relation_stats_hook_type get_relation_stats_hook = NULL;
 get_index_stats_hook_type get_index_stats_hook = NULL;
 
-static double var_eq_const(VariableStatData *vardata, Oid operator,
+static double var_eq_const(VariableStatData *vardata, Oid opid,
 			 Datum constval, bool constisnull,
 			 bool varonleft);
-static double var_eq_non_const(VariableStatData *vardata, Oid operator,
+static double var_eq_non_const(VariableStatData *vardata, Oid opid,
 				 Node *other,
 				 bool varonleft);
 static double ineq_histogram_selectivity(PlannerInfo *root,
 						   VariableStatData *vardata,
 						   FmgrInfo *opproc, bool isgt,
 						   Datum constval, Oid consttype);
-static double eqjoinsel_inner(Oid operator,
+static double eqjoinsel_inner(Oid opid,
 				VariableStatData *vardata1, VariableStatData *vardata2);
-static double eqjoinsel_semi(Oid operator,
+static double eqjoinsel_semi(Oid opid,
 			   VariableStatData *vardata1, VariableStatData *vardata2,
 			   RelOptInfo *inner_rel);
 static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
@@ -220,7 +220,7 @@ Datum
 eqsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	VariableStatData vardata;
@@ -242,12 +242,12 @@ eqsel(PG_FUNCTION_ARGS)
 	 * in the query.)
 	 */
 	if (IsA(other, Const))
-		selec = var_eq_const(&vardata, operator,
+		selec = var_eq_const(&vardata, opid,
 							 ((Const *) other)->constvalue,
 							 ((Const *) other)->constisnull,
 							 varonleft);
 	else
-		selec = var_eq_non_const(&vardata, operator, other,
+		selec = var_eq_non_const(&vardata, opid, other,
 								 varonleft);
 
 	ReleaseVariableStats(vardata);
@@ -261,7 +261,7 @@ eqsel(PG_FUNCTION_ARGS)
  * This is split out so that some other estimation functions can use it.
  */
 static double
-var_eq_const(VariableStatData *vardata, Oid operator,
+var_eq_const(VariableStatData *vardata, Oid opid,
 			 Datum constval, bool constisnull,
 			 bool varonleft)
 {
@@ -313,7 +313,7 @@ var_eq_const(VariableStatData *vardata, Oid operator,
 		{
 			FmgrInfo	eqproc;
 
-			fmgr_info(get_opcode(operator), &eqproc);
+			fmgr_info(get_opcode(opid), &eqproc);
 
 			for (i = 0; i < nvalues; i++)
 			{
@@ -403,7 +403,7 @@ var_eq_const(VariableStatData *vardata, Oid operator,
  * var_eq_non_const --- eqsel for var = something-other-than-const case
  */
 static double
-var_eq_non_const(VariableStatData *vardata, Oid operator,
+var_eq_non_const(VariableStatData *vardata, Oid opid,
 				 Node *other,
 				 bool varonleft)
 {
@@ -487,7 +487,7 @@ Datum
 neqsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	Oid			eqop;
@@ -497,7 +497,7 @@ neqsel(PG_FUNCTION_ARGS)
 	 * We want 1 - eqsel() where the equality operator is the one associated
 	 * with this != operator, that is, its negator.
 	 */
-	eqop = get_negator(operator);
+	eqop = get_negator(opid);
 	if (eqop)
 	{
 		result = DatumGetFloat8(DirectFunctionCall4(eqsel,
@@ -529,7 +529,7 @@ neqsel(PG_FUNCTION_ARGS)
  * it will return a default estimate.
  */
 static double
-scalarineqsel(PlannerInfo *root, Oid operator, bool isgt,
+scalarineqsel(PlannerInfo *root, Oid opid, bool isgt,
 			  VariableStatData *vardata, Datum constval, Oid consttype)
 {
 	Form_pg_statistic stats;
@@ -546,7 +546,7 @@ scalarineqsel(PlannerInfo *root, Oid operator, bool isgt,
 	}
 	stats = (Form_pg_statistic) GETSTRUCT(vardata->statsTuple);
 
-	fmgr_info(get_opcode(operator), &opproc);
+	fmgr_info(get_opcode(opid), &opproc);
 
 	/*
 	 * If we have most-common-values info, add up the fractions of the MCV
@@ -963,7 +963,7 @@ Datum
 scalarltsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	VariableStatData vardata;
@@ -1014,8 +1014,8 @@ scalarltsel(PG_FUNCTION_ARGS)
 	else
 	{
 		/* we have other < var, commute to make var > other */
-		operator = get_commutator(operator);
-		if (!operator)
+		opid = get_commutator(opid);
+		if (!opid)
 		{
 			/* Use default selectivity (should we raise an error instead?) */
 			ReleaseVariableStats(vardata);
@@ -1024,7 +1024,7 @@ scalarltsel(PG_FUNCTION_ARGS)
 		isgt = true;
 	}
 
-	selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
+	selec = scalarineqsel(root, opid, isgt, &vardata, constval, consttype);
 
 	ReleaseVariableStats(vardata);
 
@@ -1038,7 +1038,7 @@ Datum
 scalargtsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	VariableStatData vardata;
@@ -1089,8 +1089,8 @@ scalargtsel(PG_FUNCTION_ARGS)
 	else
 	{
 		/* we have other > var, commute to make var < other */
-		operator = get_commutator(operator);
-		if (!operator)
+		opid = get_commutator(opid);
+		if (!opid)
 		{
 			/* Use default selectivity (should we raise an error instead?) */
 			ReleaseVariableStats(vardata);
@@ -1099,7 +1099,7 @@ scalargtsel(PG_FUNCTION_ARGS)
 		isgt = false;
 	}
 
-	selec = scalarineqsel(root, operator, isgt, &vardata, constval, consttype);
+	selec = scalarineqsel(root, opid, isgt, &vardata, constval, consttype);
 
 	ReleaseVariableStats(vardata);
 
@@ -1113,7 +1113,7 @@ static double
 patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	int			varRelid = PG_GETARG_INT32(3);
 	Oid			collation = PG_GET_COLLATION();
@@ -1137,8 +1137,8 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 	 */
 	if (negate)
 	{
-		operator = get_negator(operator);
-		if (!OidIsValid(operator))
+		opid = get_negator(opid);
+		if (!OidIsValid(opid))
 			elog(ERROR, "patternsel called for operator without a negator");
 		result = 1.0 - DEFAULT_MATCH_SEL;
 	}
@@ -1294,7 +1294,7 @@ patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype, bool negate)
 					sumcommon;
 
 		/* Try to use the histogram entries to get selectivity */
-		fmgr_info(get_opcode(operator), &opproc);
+		fmgr_info(get_opcode(opid), &opproc);
 
 		selec = histogram_selectivity(&vardata, &opproc, constval, true,
 									  10, 1, &hist_size);
@@ -1763,7 +1763,7 @@ scalararraysel(PlannerInfo *root,
 			   JoinType jointype,
 			   SpecialJoinInfo *sjinfo)
 {
-	Oid			operator = clause->opno;
+	Oid			opid = clause->opno;
 	bool		useOr = clause->useOr;
 	bool		isEquality = false;
 	bool		isInequality = false;
@@ -1803,9 +1803,9 @@ scalararraysel(PlannerInfo *root,
 	typentry = lookup_type_cache(nominal_element_type, TYPECACHE_EQ_OPR);
 	if (OidIsValid(typentry->eq_opr))
 	{
-		if (operator == typentry->eq_opr)
+		if (opid == typentry->eq_opr)
 			isEquality = true;
-		else if (get_negator(operator) == typentry->eq_opr)
+		else if (get_negator(opid) == typentry->eq_opr)
 			isInequality = true;
 	}
 
@@ -1829,9 +1829,9 @@ scalararraysel(PlannerInfo *root,
 	 * hasn't got one.
 	 */
 	if (is_join_clause)
-		oprsel = get_oprjoin(operator);
+		oprsel = get_oprjoin(opid);
 	else
-		oprsel = get_oprrest(operator);
+		oprsel = get_oprrest(opid);
 	if (!oprsel)
 		return (Selectivity) 0.5;
 	fmgr_info(oprsel, &oprselproc);
@@ -1917,7 +1917,7 @@ scalararraysel(PlannerInfo *root,
 				s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
 													  clause->inputcollid,
 													  PointerGetDatum(root),
-												  ObjectIdGetDatum(operator),
+												  ObjectIdGetDatum(opid),
 													  PointerGetDatum(args),
 													  Int16GetDatum(jointype),
 												   PointerGetDatum(sjinfo)));
@@ -1925,7 +1925,7 @@ scalararraysel(PlannerInfo *root,
 				s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
 													  clause->inputcollid,
 													  PointerGetDatum(root),
-												  ObjectIdGetDatum(operator),
+												  ObjectIdGetDatum(opid),
 													  PointerGetDatum(args),
 												   Int32GetDatum(varRelid)));
 
@@ -1984,7 +1984,7 @@ scalararraysel(PlannerInfo *root,
 				s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
 													  clause->inputcollid,
 													  PointerGetDatum(root),
-												  ObjectIdGetDatum(operator),
+												  ObjectIdGetDatum(opid),
 													  PointerGetDatum(args),
 													  Int16GetDatum(jointype),
 												   PointerGetDatum(sjinfo)));
@@ -1992,7 +1992,7 @@ scalararraysel(PlannerInfo *root,
 				s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
 													  clause->inputcollid,
 													  PointerGetDatum(root),
-												  ObjectIdGetDatum(operator),
+												  ObjectIdGetDatum(opid),
 													  PointerGetDatum(args),
 												   Int32GetDatum(varRelid)));
 
@@ -2036,7 +2036,7 @@ scalararraysel(PlannerInfo *root,
 			s2 = DatumGetFloat8(FunctionCall5Coll(&oprselproc,
 												  clause->inputcollid,
 												  PointerGetDatum(root),
-												  ObjectIdGetDatum(operator),
+												  ObjectIdGetDatum(opid),
 												  PointerGetDatum(args),
 												  Int16GetDatum(jointype),
 												  PointerGetDatum(sjinfo)));
@@ -2044,7 +2044,7 @@ scalararraysel(PlannerInfo *root,
 			s2 = DatumGetFloat8(FunctionCall4Coll(&oprselproc,
 												  clause->inputcollid,
 												  PointerGetDatum(root),
-												  ObjectIdGetDatum(operator),
+												  ObjectIdGetDatum(opid),
 												  PointerGetDatum(args),
 												  Int32GetDatum(varRelid)));
 		s1 = useOr ? 0.0 : 1.0;
@@ -2183,7 +2183,7 @@ Datum
 eqjoinsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 
 #ifdef NOT_USED
@@ -2204,7 +2204,7 @@ eqjoinsel(PG_FUNCTION_ARGS)
 		case JOIN_INNER:
 		case JOIN_LEFT:
 		case JOIN_FULL:
-			selec = eqjoinsel_inner(operator, &vardata1, &vardata2);
+			selec = eqjoinsel_inner(opid, &vardata1, &vardata2);
 			break;
 		case JOIN_SEMI:
 		case JOIN_ANTI:
@@ -2218,10 +2218,10 @@ eqjoinsel(PG_FUNCTION_ARGS)
 			inner_rel = find_join_input_rel(root, sjinfo->min_righthand);
 
 			if (!join_is_reversed)
-				selec = eqjoinsel_semi(operator, &vardata1, &vardata2,
+				selec = eqjoinsel_semi(opid, &vardata1, &vardata2,
 									   inner_rel);
 			else
-				selec = eqjoinsel_semi(get_commutator(operator),
+				selec = eqjoinsel_semi(get_commutator(opid),
 									   &vardata2, &vardata1,
 									   inner_rel);
 			break;
@@ -2248,7 +2248,7 @@ eqjoinsel(PG_FUNCTION_ARGS)
  * that it's worth trying to distinguish them here.
  */
 static double
-eqjoinsel_inner(Oid operator,
+eqjoinsel_inner(Oid opid,
 				VariableStatData *vardata1, VariableStatData *vardata2)
 {
 	double		selec;
@@ -2329,7 +2329,7 @@ eqjoinsel_inner(Oid operator,
 		int			i,
 					nmatches;
 
-		fmgr_info(get_opcode(operator), &eqproc);
+		fmgr_info(get_opcode(opid), &eqproc);
 		hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
 		hasmatch2 = (bool *) palloc0(nvalues2 * sizeof(bool));
 
@@ -2474,7 +2474,7 @@ eqjoinsel_inner(Oid operator,
  * Caller has ensured that vardata1 is the LHS variable.
  */
 static double
-eqjoinsel_semi(Oid operator,
+eqjoinsel_semi(Oid opid,
 			   VariableStatData *vardata1, VariableStatData *vardata2,
 			   RelOptInfo *inner_rel)
 {
@@ -2556,7 +2556,7 @@ eqjoinsel_semi(Oid operator,
 									  &numbers2, &nnumbers2);
 	}
 
-	if (have_mcvs1 && have_mcvs2 && OidIsValid(operator))
+	if (have_mcvs1 && have_mcvs2 && OidIsValid(opid))
 	{
 		/*
 		 * We have most-common-value lists for both relations.  Run through
@@ -2586,7 +2586,7 @@ eqjoinsel_semi(Oid operator,
 		 */
 		clamped_nvalues2 = Min(nvalues2, nd2);
 
-		fmgr_info(get_opcode(operator), &eqproc);
+		fmgr_info(get_opcode(opid), &eqproc);
 		hasmatch1 = (bool *) palloc0(nvalues1 * sizeof(bool));
 		hasmatch2 = (bool *) palloc0(clamped_nvalues2 * sizeof(bool));
 
@@ -2693,7 +2693,7 @@ Datum
 neqjoinsel(PG_FUNCTION_ARGS)
 {
 	PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
-	Oid			operator = PG_GETARG_OID(1);
+	Oid			opid = PG_GETARG_OID(1);
 	List	   *args = (List *) PG_GETARG_POINTER(2);
 	JoinType	jointype = (JoinType) PG_GETARG_INT16(3);
 	SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) PG_GETARG_POINTER(4);
@@ -2704,7 +2704,7 @@ neqjoinsel(PG_FUNCTION_ARGS)
 	 * We want 1 - eqjoinsel() where the equality operator is the one
 	 * associated with this != operator, that is, its negator.
 	 */
-	eqop = get_negator(operator);
+	eqop = get_negator(opid);
 	if (eqop)
 	{
 		result = DatumGetFloat8(DirectFunctionCall5(eqjoinsel,
@@ -5297,7 +5297,7 @@ like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
 	char	   *match;
 	char	   *patt;
 	int			pattlen;
-	Oid			typeid = patt_const->consttype;
+	Oid			typid = patt_const->consttype;
 	int			pos,
 				match_pos;
 	bool		is_multibyte = (pg_database_encoding_max_length() > 1);
@@ -5305,11 +5305,11 @@ like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
 	bool		locale_is_c = false;
 
 	/* the right-hand const is type text or bytea */
-	Assert(typeid == BYTEAOID || typeid == TEXTOID);
+	Assert(typid == BYTEAOID || typid == TEXTOID);
 
 	if (case_insensitive)
 	{
-		if (typeid == BYTEAOID)
+		if (typid == BYTEAOID)
 			ereport(ERROR,
 					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 			errmsg("case insensitive matching not supported on type bytea")));
@@ -5334,7 +5334,7 @@ like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
 		}
 	}
 
-	if (typeid != BYTEAOID)
+	if (typid != BYTEAOID)
 	{
 		patt = TextDatumGetCString(patt_const->constvalue);
 		pattlen = strlen(patt);
@@ -5377,8 +5377,8 @@ like_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
 
 	match[match_pos] = '\0';
 
-	if (typeid != BYTEAOID)
-		*prefix_const = string_to_const(match, typeid);
+	if (typid != BYTEAOID)
+		*prefix_const = string_to_const(match, typid);
 	else
 		*prefix_const = string_to_bytea_const(match, match_pos);
 
@@ -5403,7 +5403,7 @@ static Pattern_Prefix_Status
 regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
 				   Const **prefix_const, Selectivity *rest_selec)
 {
-	Oid			typeid = patt_const->consttype;
+	Oid			typid = patt_const->consttype;
 	char	   *prefix;
 	bool		exact;
 
@@ -5412,7 +5412,7 @@ regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
 	 * such, it should be noted that the rest of this function has *not* been
 	 * made safe for binary (possibly NULL containing) strings.
 	 */
-	if (typeid == BYTEAOID)
+	if (typid == BYTEAOID)
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 		 errmsg("regular-expression matching not supported on type bytea")));
@@ -5439,7 +5439,7 @@ regex_fixed_prefix(Const *patt_const, bool case_insensitive, Oid collation,
 		return Pattern_Prefix_None;
 	}
 
-	*prefix_const = string_to_const(prefix, typeid);
+	*prefix_const = string_to_const(prefix, typid);
 
 	if (rest_selec != NULL)
 	{
diff --git a/src/backend/utils/adt/tsquery.c b/src/backend/utils/adt/tsquery.c
index 3e2fc6e9df..e2f7eebf13 100644
--- a/src/backend/utils/adt/tsquery.c
+++ b/src/backend/utils/adt/tsquery.c
@@ -220,7 +220,7 @@ typedef enum
  */
 static ts_tokentype
 gettoken_query(TSQueryParserState state,
-			   int8 *operator,
+			   int8 *oper,
 			   int *lenval, char **strval, int16 *weight, bool *prefix)
 {
 	*weight = 0;
@@ -236,7 +236,7 @@ gettoken_query(TSQueryParserState state,
 				{
 					(state->buf)++;		/* can safely ++, t_iseq guarantee
 										 * that pg_mblen()==1 */
-					*operator = OP_NOT;
+					*oper = OP_NOT;
 					state->state = WAITOPERAND;
 					return PT_OPR;
 				}
@@ -280,21 +280,21 @@ gettoken_query(TSQueryParserState state,
 				if (t_iseq(state->buf, '&'))
 				{
 					state->state = WAITOPERAND;
-					*operator = OP_AND;
+					*oper = OP_AND;
 					(state->buf)++;
 					return PT_OPR;
 				}
 				else if (t_iseq(state->buf, '|'))
 				{
 					state->state = WAITOPERAND;
-					*operator = OP_OR;
+					*oper = OP_OR;
 					(state->buf)++;
 					return PT_OPR;
 				}
 				else if (t_iseq(state->buf, '<'))
 				{
 					state->state = WAITOPERAND;
-					*operator = OP_PHRASE;
+					*oper = OP_PHRASE;
 					/* weight var is used as storage for distance */
 					state->buf = parse_phrase_operator(state->buf, weight);
 					if (*weight < 0)
@@ -477,7 +477,7 @@ makepol(TSQueryParserState state,
 		PushFunction pushval,
 		Datum opaque)
 {
-	int8		operator = 0;
+	int8		oper = 0;
 	ts_tokentype type;
 	int			lenval = 0;
 	char	   *strval = NULL;
@@ -489,7 +489,7 @@ makepol(TSQueryParserState state,
 	/* since this function recurses, it could be driven to stack overflow */
 	check_stack_depth();
 
-	while ((type = gettoken_query(state, &operator, &lenval, &strval, &weight, &prefix)) != PT_END)
+	while ((type = gettoken_query(state, &oper, &lenval, &strval, &weight, &prefix)) != PT_END)
 	{
 		switch (type)
 		{
@@ -497,8 +497,8 @@ makepol(TSQueryParserState state,
 				pushval(opaque, state, strval, lenval, weight, prefix);
 				break;
 			case PT_OPR:
-				cleanOpStack(state, opstack, &lenstack, operator);
-				pushOpStack(opstack, &lenstack, operator, weight);
+				cleanOpStack(state, opstack, &lenstack, oper);
+				pushOpStack(opstack, &lenstack, oper, weight);
 				break;
 			case PT_OPEN:
 				makepol(state, pushval, opaque);
diff --git a/src/backend/utils/adt/tsquery_op.c b/src/backend/utils/adt/tsquery_op.c
index 755c3e9ee8..3d4b13378b 100644
--- a/src/backend/utils/adt/tsquery_op.c
+++ b/src/backend/utils/adt/tsquery_op.c
@@ -28,7 +28,7 @@ tsquery_numnode(PG_FUNCTION_ARGS)
 }
 
 static QTNode *
-join_tsqueries(TSQuery a, TSQuery b, int8 operator, uint16 distance)
+join_tsqueries(TSQuery a, TSQuery b, int8 oper, uint16 distance)
 {
 	QTNode	   *res = (QTNode *) palloc0(sizeof(QTNode));
 
@@ -36,8 +36,8 @@ join_tsqueries(TSQuery a, TSQuery b, int8 operator, uint16 distance)
 
 	res->valnode = (QueryItem *) palloc0(sizeof(QueryItem));
 	res->valnode->type = QI_OPR;
-	res->valnode->qoperator.oper = operator;
-	if (operator == OP_PHRASE)
+	res->valnode->qoperator.oper = oper;
+	if (oper == OP_PHRASE)
 		res->valnode->qoperator.distance = distance;
 
 	res->child = (QTNode **) palloc0(sizeof(QTNode *) * 2);
diff --git a/src/backend/utils/adt/varbit.c b/src/backend/utils/adt/varbit.c
index e947785d81..b87d379469 100644
--- a/src/backend/utils/adt/varbit.c
+++ b/src/backend/utils/adt/varbit.c
@@ -35,7 +35,7 @@ static VarBit *bit_overlay(VarBit *t1, VarBit *t2, int sp, int sl);
  * common code for bittypmodin and varbittypmodin
  */
 static int32
-anybit_typmodin(ArrayType *ta, const char *typename)
+anybit_typmodin(ArrayType *ta, const char *typname)
 {
 	int32		typmod;
 	int32	   *tl;
@@ -56,12 +56,12 @@ anybit_typmodin(ArrayType *ta, const char *typename)
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("length for type %s must be at least 1",
-						typename)));
+						typname)));
 	if (*tl > (MaxAttrSize * BITS_PER_BYTE))
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("length for type %s cannot exceed %d",
-						typename, MaxAttrSize * BITS_PER_BYTE)));
+						typname, MaxAttrSize * BITS_PER_BYTE)));
 
 	typmod = *tl;
 
diff --git a/src/backend/utils/adt/varchar.c b/src/backend/utils/adt/varchar.c
index 6f2f9f6633..2d9ea12a37 100644
--- a/src/backend/utils/adt/varchar.c
+++ b/src/backend/utils/adt/varchar.c
@@ -28,7 +28,7 @@
 
 /* common code for bpchartypmodin and varchartypmodin */
 static int32
-anychar_typmodin(ArrayType *ta, const char *typename)
+anychar_typmodin(ArrayType *ta, const char *typname)
 {
 	int32		typmod;
 	int32	   *tl;
@@ -48,12 +48,12 @@ anychar_typmodin(ArrayType *ta, const char *typename)
 	if (*tl < 1)
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-				 errmsg("length for type %s must be at least 1", typename)));
+				 errmsg("length for type %s must be at least 1", typname)));
 	if (*tl > MaxAttrSize)
 		ereport(ERROR,
 				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 				 errmsg("length for type %s cannot exceed %d",
-						typename, MaxAttrSize)));
+						typname, MaxAttrSize)));
 
 	/*
 	 * For largely historical reasons, the typmod is VARHDRSZ plus the number
diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index e8bce3b806..c060556002 100644
--- a/src/backend/utils/adt/xml.c
+++ b/src/backend/utils/adt/xml.c
@@ -3352,7 +3352,7 @@ static const char *
 map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
 {
 	StringInfoData result;
-	const char *typename = map_sql_type_to_xml_name(typeoid, typmod);
+	const char *typname = map_sql_type_to_xml_name(typeoid, typmod);
 
 	initStringInfo(&result);
 
@@ -3368,7 +3368,7 @@ map_sql_type_to_xmlschema_type(Oid typeoid, int typmod)
 	else
 	{
 		appendStringInfo(&result,
-						 "<xsd:simpleType name=\"%s\">\n", typename);
+						 "<xsd:simpleType name=\"%s\">\n", typname);
 
 		switch (typeoid)
 		{
diff --git a/src/backend/utils/cache/ts_cache.c b/src/backend/utils/cache/ts_cache.c
index 88e4ffb66d..1cc47e42ed 100644
--- a/src/backend/utils/cache/ts_cache.c
+++ b/src/backend/utils/cache/ts_cache.c
@@ -250,7 +250,7 @@ lookup_ts_dictionary_cache(Oid dictId)
 		HeapTuple	tpdict,
 					tptmpl;
 		Form_pg_ts_dict dict;
-		Form_pg_ts_template template;
+		Form_pg_ts_template tmpl;
 		MemoryContext saveCtx;
 
 		tpdict = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
@@ -273,14 +273,14 @@ lookup_ts_dictionary_cache(Oid dictId)
 		if (!HeapTupleIsValid(tptmpl))
 			elog(ERROR, "cache lookup failed for text search template %u",
 				 dict->dicttemplate);
-		template = (Form_pg_ts_template) GETSTRUCT(tptmpl);
+		tmpl = (Form_pg_ts_template) GETSTRUCT(tptmpl);
 
 		/*
 		 * Sanity checks
 		 */
-		if (!OidIsValid(template->tmpllexize))
+		if (!OidIsValid(tmpl->tmpllexize))
 			elog(ERROR, "text search template %u has no lexize method",
-				 template->tmpllexize);
+				 tmpl->tmpllexize);
 
 		if (entry == NULL)
 		{
@@ -309,9 +309,9 @@ lookup_ts_dictionary_cache(Oid dictId)
 		entry->dictId = dictId;
 		entry->dictCtx = saveCtx;
 
-		entry->lexizeOid = template->tmpllexize;
+		entry->lexizeOid = tmpl->tmpllexize;
 
-		if (OidIsValid(template->tmplinit))
+		if (OidIsValid(tmpl->tmplinit))
 		{
 			List	   *dictoptions;
 			Datum		opt;
@@ -333,7 +333,7 @@ lookup_ts_dictionary_cache(Oid dictId)
 				dictoptions = deserialize_deflist(opt);
 
 			entry->dictData =
-				DatumGetPointer(OidFunctionCall1(template->tmplinit,
+				DatumGetPointer(OidFunctionCall1(tmpl->tmplinit,
 											  PointerGetDatum(dictoptions)));
 
 			MemoryContextSwitchTo(oldcontext);
diff --git a/src/backend/utils/fmgr/dfmgr.c b/src/backend/utils/fmgr/dfmgr.c
index 94d7dac94c..7a754cde2e 100644
--- a/src/backend/utils/fmgr/dfmgr.c
+++ b/src/backend/utils/fmgr/dfmgr.c
@@ -482,8 +482,8 @@ static char *
 expand_dynamic_library_name(const char *name)
 {
 	bool		have_slash;
-	char	   *new;
-	char	   *full;
+	char	   *newname;
+	char	   *fullname;
 
 	AssertArg(name);
 
@@ -491,34 +491,34 @@ expand_dynamic_library_name(const char *name)
 
 	if (!have_slash)
 	{
-		full = find_in_dynamic_libpath(name);
-		if (full)
-			return full;
+		fullname = find_in_dynamic_libpath(name);
+		if (fullname)
+			return fullname;
 	}
 	else
 	{
-		full = substitute_libpath_macro(name);
-		if (file_exists(full))
-			return full;
-		pfree(full);
+		fullname = substitute_libpath_macro(name);
+		if (file_exists(fullname))
+			return fullname;
+		pfree(fullname);
 	}
 
-	new = psprintf("%s%s", name, DLSUFFIX);
+	newname = psprintf("%s%s", name, DLSUFFIX);
 
 	if (!have_slash)
 	{
-		full = find_in_dynamic_libpath(new);
-		pfree(new);
-		if (full)
-			return full;
+		fullname = find_in_dynamic_libpath(newname);
+		pfree(newname);
+		if (fullname)
+			return fullname;
 	}
 	else
 	{
-		full = substitute_libpath_macro(new);
-		pfree(new);
-		if (file_exists(full))
-			return full;
-		pfree(full);
+		fullname = substitute_libpath_macro(newname);
+		pfree(newname);
+		if (file_exists(fullname))
+			return fullname;
+		pfree(fullname);
 	}
 
 	/*
diff --git a/src/backend/utils/init/miscinit.c b/src/backend/utils/init/miscinit.c
index e0298ee35f..f9a1a7cc52 100644
--- a/src/backend/utils/init/miscinit.c
+++ b/src/backend/utils/init/miscinit.c
@@ -92,16 +92,16 @@ SetDatabasePath(const char *path)
 void
 SetDataDir(const char *dir)
 {
-	char	   *new;
+	char	   *newdir;
 
 	AssertArg(dir);
 
 	/* If presented path is relative, convert to absolute */
-	new = make_absolute_path(dir);
+	newdir = make_absolute_path(dir);
 
 	if (DataDir)
 		free(DataDir);
-	DataDir = new;
+	DataDir = newdir;
 }
 
 /*
diff --git a/src/bin/pg_dump/common.c b/src/bin/pg_dump/common.c
index 89530a9f0f..f6fb908347 100644
--- a/src/bin/pg_dump/common.c
+++ b/src/bin/pg_dump/common.c
@@ -469,7 +469,7 @@ flagInhAttrs(DumpOptions *dopt, TableInfo *tblinfo, int numTables)
 				attrDef->dobj.catId.oid = 0;
 				AssignDumpId(&attrDef->dobj);
 				attrDef->dobj.name = pg_strdup(tbinfo->dobj.name);
-				attrDef->dobj.namespace = tbinfo->dobj.namespace;
+				attrDef->dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 				attrDef->dobj.dump = tbinfo->dobj.dump;
 
 				attrDef->adtable = tbinfo;
@@ -510,7 +510,7 @@ AssignDumpId(DumpableObject *dobj)
 {
 	dobj->dumpId = ++lastDumpId;
 	dobj->name = NULL;			/* must be set later */
-	dobj->namespace = NULL;		/* may be set later */
+	dobj->namespaceinfo = NULL;		/* may be set later */
 	dobj->dump = DUMP_COMPONENT_ALL;	/* default assumption */
 	dobj->ext_member = false;	/* default assumption */
 	dobj->dependencies = NULL;
diff --git a/src/bin/pg_dump/parallel.c b/src/bin/pg_dump/parallel.c
index be8e018a96..dd8e25382f 100644
--- a/src/bin/pg_dump/parallel.c
+++ b/src/bin/pg_dump/parallel.c
@@ -384,7 +384,7 @@ archive_close_connection(int code, void *arg)
 			 * the other end of the pipe.)
 			 */
 			if (slot->AH)
-				DisconnectDatabase(&(slot->AH->public));
+				DisconnectDatabase(&(slot->AH->archive));
 
 #ifdef WIN32
 			closesocket(slot->pipeRevRead);
@@ -874,7 +874,7 @@ RunWorker(ArchiveHandle *AH, ParallelSlot *slot)
 	 * Disconnect from database and clean up.
 	 */
 	set_cancel_slot_archive(slot, NULL);
-	DisconnectDatabase(&(AH->public));
+	DisconnectDatabase(&(AH->archive));
 	DeCloneArchive(AH);
 }
 
@@ -911,15 +911,15 @@ ParallelBackupStart(ArchiveHandle *AH)
 	ParallelState *pstate;
 	int			i;
 
-	Assert(AH->public.numWorkers > 0);
+	Assert(AH->archive.numWorkers > 0);
 
 	pstate = (ParallelState *) pg_malloc(sizeof(ParallelState));
 
-	pstate->numWorkers = AH->public.numWorkers;
+	pstate->numWorkers = AH->archive.numWorkers;
 	pstate->te = NULL;
 	pstate->parallelSlot = NULL;
 
-	if (AH->public.numWorkers == 1)
+	if (AH->archive.numWorkers == 1)
 		return pstate;
 
 	pstate->te = (TocEntry **)
@@ -1180,7 +1180,7 @@ buildWorkerResponse(ArchiveHandle *AH, TocEntry *te, T_Action act, int status,
 	snprintf(buf, buflen, "OK %d %d %d",
 			 te->dumpId,
 			 status,
-			 status == WORKER_IGNORED_ERRORS ? AH->public.n_errors : 0);
+			 status == WORKER_IGNORED_ERRORS ? AH->archive.n_errors : 0);
 }
 
 /*
@@ -1204,7 +1204,7 @@ parseWorkerResponse(ArchiveHandle *AH, TocEntry *te,
 		Assert(dumpId == te->dumpId);
 		Assert(nBytes == strlen(msg));
 
-		AH->public.n_errors += n_errors;
+		AH->archive.n_errors += n_errors;
 	}
 	else
 		exit_horribly(modulename,
@@ -1332,7 +1332,7 @@ lockTableForWorker(ArchiveHandle *AH, TocEntry *te)
 
 	query = createPQExpBuffer();
 
-	qualId = fmtQualifiedId(AH->public.remoteVersion, te->namespace, te->tag);
+	qualId = fmtQualifiedId(AH->archive.remoteVersion, te->schema, te->tag);
 
 	appendPQExpBuffer(query, "LOCK TABLE %s IN ACCESS SHARE MODE NOWAIT",
 					  qualId);
diff --git a/src/bin/pg_dump/pg_backup.h b/src/bin/pg_dump/pg_backup.h
index a6e84efc38..9a7f21447a 100644
--- a/src/bin/pg_dump/pg_backup.h
+++ b/src/bin/pg_dump/pg_backup.h
@@ -248,7 +248,7 @@ extern PGconn *GetConnection(Archive *AHX);
 extern void ArchiveEntry(Archive *AHX,
 			 CatalogId catalogId, DumpId dumpId,
 			 const char *tag,
-			 const char *namespace, const char *tablespace,
+			 const char *nspname, const char *tablespace,
 			 const char *owner, bool withOids,
 			 const char *desc, teSection section,
 			 const char *defn,
diff --git a/src/bin/pg_dump/pg_backup_archiver.c b/src/bin/pg_dump/pg_backup_archiver.c
index e387293664..54fe6c5bc8 100644
--- a/src/bin/pg_dump/pg_backup_archiver.c
+++ b/src/bin/pg_dump/pg_backup_archiver.c
@@ -258,7 +258,7 @@ void
 ProcessArchiveRestoreOptions(Archive *AHX)
 {
 	ArchiveHandle *AH = (ArchiveHandle *) AHX;
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 	TocEntry   *te;
 	teSection	curSection;
 
@@ -315,7 +315,7 @@ void
 RestoreArchive(Archive *AHX)
 {
 	ArchiveHandle *AH = (ArchiveHandle *) AHX;
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 	bool		parallel_mode;
 	TocEntry   *te;
 	OutputContext sav;
@@ -334,7 +334,7 @@ RestoreArchive(Archive *AHX)
 	/*
 	 * If we're going to do parallel restore, there are some restrictions.
 	 */
-	parallel_mode = (AH->public.numWorkers > 1 && ropt->useDB);
+	parallel_mode = (AH->archive.numWorkers > 1 && ropt->useDB);
 	if (parallel_mode)
 	{
 		/* We haven't got round to making this work for all archive formats */
@@ -447,7 +447,7 @@ RestoreArchive(Archive *AHX)
 
 	ahprintf(AH, "\n");
 
-	if (AH->public.verbose)
+	if (AH->archive.verbose)
 		dumpTimestamp(AH, "Started on", AH->createDate);
 
 	if (ropt->single_txn)
@@ -498,7 +498,7 @@ RestoreArchive(Archive *AHX)
 				ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
 				/* Select owner and schema as necessary */
 				_becomeOwner(AH, te);
-				_selectOutputSchema(AH, te->namespace);
+				_selectOutputSchema(AH, te->schema);
 
 				/*
 				 * Now emit the DROP command, if the object has one.  Note we
@@ -663,9 +663,9 @@ RestoreArchive(Archive *AHX)
 		if ((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0)
 		{
 			/* Show namespace if available */
-			if (te->namespace)
+			if (te->schema)
 				ahlog(AH, 1, "setting owner and privileges for %s \"%s.%s\"\n",
-					  te->desc, te->namespace, te->tag);
+					  te->desc, te->schema, te->tag);
 			else
 				ahlog(AH, 1, "setting owner and privileges for %s \"%s\"\n",
 					  te->desc, te->tag);
@@ -681,7 +681,7 @@ RestoreArchive(Archive *AHX)
 			ahprintf(AH, "COMMIT;\n\n");
 	}
 
-	if (AH->public.verbose)
+	if (AH->archive.verbose)
 		dumpTimestamp(AH, "Completed on", time(NULL));
 
 	ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");
@@ -695,7 +695,7 @@ RestoreArchive(Archive *AHX)
 		RestoreOutput(AH, sav);
 
 	if (ropt->useDB)
-		DisconnectDatabase(&AH->public);
+		DisconnectDatabase(&AH->archive);
 }
 
 /*
@@ -708,7 +708,7 @@ RestoreArchive(Archive *AHX)
 static int
 restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 	int			status = WORKER_OK;
 	teReqs		reqs;
 	bool		defnDumped;
@@ -743,9 +743,9 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
 	if ((reqs & REQ_SCHEMA) != 0)		/* We want the schema */
 	{
 		/* Show namespace if available */
-		if (te->namespace)
+		if (te->schema)
 			ahlog(AH, 1, "creating %s \"%s.%s\"\n",
-				  te->desc, te->namespace, te->tag);
+				  te->desc, te->schema, te->tag);
 		else
 			ahlog(AH, 1, "creating %s \"%s\"\n", te->desc, te->tag);
 
@@ -845,10 +845,10 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
 
 					/* Select owner and schema as necessary */
 					_becomeOwner(AH, te);
-					_selectOutputSchema(AH, te->namespace);
+					_selectOutputSchema(AH, te->schema);
 
 					ahlog(AH, 1, "processing data for table \"%s.%s\"\n",
-						  te->namespace, te->tag);
+						  te->schema, te->tag);
 
 					/*
 					 * In parallel restore, if we created the table earlier in
@@ -864,7 +864,7 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
 						 * Parallel restore is always talking directly to a
 						 * server, so no need to see if we should issue BEGIN.
 						 */
-						StartTransaction(&AH->public);
+						StartTransaction(&AH->archive);
 
 						/*
 						 * If the server version is >= 8.4, make sure we issue
@@ -895,12 +895,12 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
 					 */
 					if (AH->outputKind == OUTPUT_COPYDATA &&
 						RestoringToDB(AH))
-						EndDBCopyMode(&AH->public, te->tag);
+						EndDBCopyMode(&AH->archive, te->tag);
 					AH->outputKind = OUTPUT_SQLCMDS;
 
 					/* close out the transaction started above */
 					if (is_parallel && te->created)
-						CommitTransaction(&AH->public);
+						CommitTransaction(&AH->archive);
 
 					_enableTriggersIfNecessary(AH, te);
 				}
@@ -914,7 +914,7 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
 		}
 	}
 
-	if (AH->public.n_errors > 0 && status == WORKER_OK)
+	if (AH->archive.n_errors > 0 && status == WORKER_OK)
 		status = WORKER_IGNORED_ERRORS;
 
 	return status;
@@ -942,7 +942,7 @@ NewRestoreOptions(void)
 static void
 _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	/* This hack is only needed in a data-only restore */
 	if (!ropt->dataOnly || !ropt->disable_triggers)
@@ -961,7 +961,7 @@ _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te)
 	/*
 	 * Disable them.
 	 */
-	_selectOutputSchema(AH, te->namespace);
+	_selectOutputSchema(AH, te->schema);
 
 	ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
 			 fmtId(te->tag));
@@ -970,7 +970,7 @@ _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te)
 static void
 _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	/* This hack is only needed in a data-only restore */
 	if (!ropt->dataOnly || !ropt->disable_triggers)
@@ -989,7 +989,7 @@ _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te)
 	/*
 	 * Enable them.
 	 */
-	_selectOutputSchema(AH, te->namespace);
+	_selectOutputSchema(AH, te->schema);
 
 	ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
 			 fmtId(te->tag));
@@ -1023,7 +1023,7 @@ void
 ArchiveEntry(Archive *AHX,
 			 CatalogId catalogId, DumpId dumpId,
 			 const char *tag,
-			 const char *namespace,
+			 const char *nspname,
 			 const char *tablespace,
 			 const char *owner, bool withOids,
 			 const char *desc, teSection section,
@@ -1051,7 +1051,7 @@ ArchiveEntry(Archive *AHX,
 	newToc->section = section;
 
 	newToc->tag = pg_strdup(tag);
-	newToc->namespace = namespace ? pg_strdup(namespace) : NULL;
+	newToc->schema = nspname ? pg_strdup(nspname) : NULL;
 	newToc->tablespace = tablespace ? pg_strdup(tablespace) : NULL;
 	newToc->owner = pg_strdup(owner);
 	newToc->withOids = withOids;
@@ -1087,7 +1087,7 @@ void
 PrintTOCSummary(Archive *AHX)
 {
 	ArchiveHandle *AH = (ArchiveHandle *) AHX;
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 	TocEntry   *te;
 	teSection	curSection;
 	OutputContext sav;
@@ -1144,7 +1144,7 @@ PrintTOCSummary(Archive *AHX)
 			(_tocEntryRequired(te, curSection, ropt) & (REQ_SCHEMA | REQ_DATA)) != 0)
 			ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
 					 te->catalogId.tableoid, te->catalogId.oid,
-					 te->desc, te->namespace ? te->namespace : "-",
+					 te->desc, te->schema ? te->schema : "-",
 					 te->tag, te->owner);
 		if (ropt->verbose && te->nDeps > 0)
 		{
@@ -1205,12 +1205,12 @@ EndBlob(Archive *AHX, Oid oid)
 void
 StartRestoreBlobs(ArchiveHandle *AH)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	if (!ropt->single_txn)
 	{
 		if (AH->connection)
-			StartTransaction(&AH->public);
+			StartTransaction(&AH->archive);
 		else
 			ahprintf(AH, "BEGIN;\n\n");
 	}
@@ -1224,12 +1224,12 @@ StartRestoreBlobs(ArchiveHandle *AH)
 void
 EndRestoreBlobs(ArchiveHandle *AH)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	if (!ropt->single_txn)
 	{
 		if (AH->connection)
-			CommitTransaction(&AH->public);
+			CommitTransaction(&AH->archive);
 		else
 			ahprintf(AH, "COMMIT;\n\n");
 	}
@@ -1318,7 +1318,7 @@ void
 SortTocFromFile(Archive *AHX)
 {
 	ArchiveHandle *AH = (ArchiveHandle *) AHX;
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 	FILE	   *fh;
 	char		buf[100];
 	bool		incomplete_line;
@@ -1587,7 +1587,7 @@ ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
 {
 	va_list		ap;
 
-	if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
+	if (AH->debugLevel < level && (!AH->archive.verbose || level > 1))
 		return;
 
 	va_start(ap, fmt);
@@ -1601,7 +1601,7 @@ ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
 static int
 RestoringToDB(ArchiveHandle *AH)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	return (ropt && ropt->useDB && AH->connection);
 }
@@ -1689,7 +1689,7 @@ ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
 		 * connected then send it to the DB.
 		 */
 		if (RestoringToDB(AH))
-			bytes_written = ExecuteSqlCommandBuf(&AH->public, (const char *) ptr, size * nmemb);
+			bytes_written = ExecuteSqlCommandBuf(&AH->archive, (const char *) ptr, size * nmemb);
 		else
 			bytes_written = fwrite(ptr, size, nmemb, AH->OF) * size;
 	}
@@ -1743,10 +1743,10 @@ warn_or_exit_horribly(ArchiveHandle *AH,
 	vwrite_msg(modulename, fmt, ap);
 	va_end(ap);
 
-	if (AH->public.exit_on_error)
+	if (AH->archive.exit_on_error)
 		exit_nicely(1);
 	else
-		AH->public.n_errors++;
+		AH->archive.n_errors++;
 }
 
 #ifdef NOT_USED
@@ -2256,12 +2256,12 @@ _allocAH(const char *FileSpec, const ArchiveFormat fmt,
 	AH->version = K_VERS_SELF;
 
 	/* initialize for backwards compatible string processing */
-	AH->public.encoding = 0;	/* PG_SQL_ASCII */
-	AH->public.std_strings = false;
+	AH->archive.encoding = 0;	/* PG_SQL_ASCII */
+	AH->archive.std_strings = false;
 
 	/* sql error handling */
-	AH->public.exit_on_error = true;
-	AH->public.n_errors = 0;
+	AH->archive.exit_on_error = true;
+	AH->archive.n_errors = 0;
 
 	AH->archiveDumpVersion = PG_VERSION;
 
@@ -2483,7 +2483,7 @@ WriteToc(ArchiveHandle *AH)
 		WriteStr(AH, te->defn);
 		WriteStr(AH, te->dropStmt);
 		WriteStr(AH, te->copyStmt);
-		WriteStr(AH, te->namespace);
+		WriteStr(AH, te->schema);
 		WriteStr(AH, te->tablespace);
 		WriteStr(AH, te->owner);
 		WriteStr(AH, te->withOids ? "true" : "false");
@@ -2582,7 +2582,7 @@ ReadToc(ArchiveHandle *AH)
 			te->copyStmt = ReadStr(AH);
 
 		if (AH->version >= K_VERS_1_6)
-			te->namespace = ReadStr(AH);
+			te->schema = ReadStr(AH);
 
 		if (AH->version >= K_VERS_1_10)
 			te->tablespace = ReadStr(AH);
@@ -2677,7 +2677,7 @@ processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
 		if (encoding < 0)
 			exit_horribly(modulename, "unrecognized encoding \"%s\"\n",
 						  ptr1);
-		AH->public.encoding = encoding;
+		AH->archive.encoding = encoding;
 	}
 	else
 		exit_horribly(modulename, "invalid ENCODING item: %s\n",
@@ -2694,9 +2694,9 @@ processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
 
 	ptr1 = strchr(te->defn, '\'');
 	if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
-		AH->public.std_strings = true;
+		AH->archive.std_strings = true;
 	else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
-		AH->public.std_strings = false;
+		AH->archive.std_strings = false;
 	else
 		exit_horribly(modulename, "invalid STDSTRINGS item: %s\n",
 					  te->defn);
@@ -2787,15 +2787,15 @@ _tocEntryRequired(TocEntry *te, teSection curSection, RestoreOptions *ropt)
 	if (ropt->schemaNames.head != NULL)
 	{
 		/* If no namespace is specified, it means all. */
-		if (!te->namespace)
+		if (!te->schema)
 			return 0;
-		if (!(simple_string_list_member(&ropt->schemaNames, te->namespace)))
+		if (!(simple_string_list_member(&ropt->schemaNames, te->schema)))
 			return 0;
 	}
 
 	if (ropt->schemaExcludeNames.head != NULL &&
-		te->namespace &&
-		simple_string_list_member(&ropt->schemaExcludeNames, te->namespace))
+		te->schema &&
+		simple_string_list_member(&ropt->schemaExcludeNames, te->schema))
 		return 0;
 
 	if (ropt->selTypes)
@@ -2914,7 +2914,7 @@ _tocEntryIsACL(TocEntry *te)
 static void
 _doSetFixedOutputState(ArchiveHandle *AH)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	/*
 	 * Disable timeouts to allow for slow commands, idle parallel workers, etc
@@ -2925,11 +2925,11 @@ _doSetFixedOutputState(ArchiveHandle *AH)
 
 	/* Select the correct character set encoding */
 	ahprintf(AH, "SET client_encoding = '%s';\n",
-			 pg_encoding_to_char(AH->public.encoding));
+			 pg_encoding_to_char(AH->archive.encoding));
 
 	/* Select the correct string literal syntax */
 	ahprintf(AH, "SET standard_conforming_strings = %s;\n",
-			 AH->public.std_strings ? "on" : "off");
+			 AH->archive.std_strings ? "on" : "off");
 
 	/* Select the role to be used during restore */
 	if (ropt && ropt->use_role)
@@ -2940,7 +2940,7 @@ _doSetFixedOutputState(ArchiveHandle *AH)
 
 	/* Avoid annoying notices etc */
 	ahprintf(AH, "SET client_min_messages = warning;\n");
-	if (!AH->public.std_strings)
+	if (!AH->archive.std_strings)
 		ahprintf(AH, "SET escape_string_warning = off;\n");
 
 	/* Adjust row-security state */
@@ -3107,7 +3107,7 @@ _becomeUser(ArchiveHandle *AH, const char *user)
 static void
 _becomeOwner(ArchiveHandle *AH, TocEntry *te)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	if (ropt && (ropt->noOwner || !ropt->use_setsessauth))
 		return;
@@ -3180,7 +3180,7 @@ _selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
 static void
 _selectTablespace(ArchiveHandle *AH, const char *tablespace)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 	PQExpBuffer qry;
 	const char *want,
 			   *have;
@@ -3316,7 +3316,7 @@ _getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
 static void
 _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData, bool acl_pass)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 
 	/* ACLs are dumped only during acl pass */
 	if (acl_pass)
@@ -3355,7 +3355,7 @@ _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData, bool acl_pass)
 
 	/* Select owner, schema, and tablespace as necessary */
 	_becomeOwner(AH, te);
-	_selectOutputSchema(AH, te->namespace);
+	_selectOutputSchema(AH, te->schema);
 	_selectTablespace(AH, te->tablespace);
 
 	/* Set up OID mode too */
@@ -3376,7 +3376,7 @@ _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData, bool acl_pass)
 			pfx = "";
 
 		ahprintf(AH, "--\n");
-		if (AH->public.verbose)
+		if (AH->archive.verbose)
 		{
 			ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
 					 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
@@ -3398,8 +3398,8 @@ _printTocEntry(ArchiveHandle *AH, TocEntry *te, bool isData, bool acl_pass)
 		 * dump containing objects with maliciously crafted names).
 		 */
 		sanitized_name = replace_line_endings(te->tag);
-		if (te->namespace)
-			sanitized_schema = replace_line_endings(te->namespace);
+		if (te->schema)
+			sanitized_schema = replace_line_endings(te->schema);
 		else
 			sanitized_schema = pg_strdup("-");
 		if (!ropt->noOwner)
@@ -3565,7 +3565,7 @@ WriteHead(ArchiveHandle *AH)
 	WriteInt(AH, crtm.tm_year);
 	WriteInt(AH, crtm.tm_isdst);
 	WriteStr(AH, PQdb(AH->connection));
-	WriteStr(AH, AH->public.remoteVersionStr);
+	WriteStr(AH, AH->archive.remoteVersionStr);
 	WriteStr(AH, PG_VERSION);
 }
 
@@ -3791,7 +3791,7 @@ restore_toc_entries_prefork(ArchiveHandle *AH)
 	 * mainly to ensure that we don't exceed the specified number of parallel
 	 * connections.
 	 */
-	DisconnectDatabase(&AH->public);
+	DisconnectDatabase(&AH->archive);
 
 	/* blow away any transient state from the old connection */
 	if (AH->currUser)
@@ -3932,7 +3932,7 @@ restore_toc_entries_parallel(ArchiveHandle *AH, ParallelState *pstate,
 static void
 restore_toc_entries_postfork(ArchiveHandle *AH, TocEntry *pending_list)
 {
-	RestoreOptions *ropt = AH->public.ropt;
+	RestoreOptions *ropt = AH->archive.ropt;
 	TocEntry   *te;
 
 	ahlog(AH, 2, "entering restore_toc_entries_postfork\n");
@@ -4126,7 +4126,7 @@ parallel_restore(ArchiveHandle *AH, TocEntry *te)
 	Assert(AH->connection != NULL);
 
 	/* Count only errors associated with this TOC entry */
-	AH->public.n_errors = 0;
+	AH->archive.n_errors = 0;
 
 	/* Restore the TOC item */
 	status = restore_toc_entry(AH, te, true);
@@ -4157,10 +4157,10 @@ mark_restore_job_done(ArchiveHandle *AH,
 	else if (status == WORKER_INHIBIT_DATA)
 	{
 		inhibit_data_for_failed_table(AH, te);
-		AH->public.n_errors++;
+		AH->archive.n_errors++;
 	}
 	else if (status == WORKER_IGNORED_ERRORS)
-		AH->public.n_errors++;
+		AH->archive.n_errors++;
 	else if (status != 0)
 		exit_horribly(modulename, "worker process failed: exit code %d\n",
 					  status);
@@ -4478,7 +4478,7 @@ CloneArchive(ArchiveHandle *AH)
 		clone->savedPassword = pg_strdup(clone->savedPassword);
 
 	/* clone has its own error count, too */
-	clone->public.n_errors = 0;
+	clone->archive.n_errors = 0;
 
 	/*
 	 * Connect our new clone object to the database: In parallel restore the
@@ -4488,7 +4488,7 @@ CloneArchive(ArchiveHandle *AH)
 	 */
 	if (AH->mode == archModeRead)
 	{
-		RestoreOptions *ropt = AH->public.ropt;
+		RestoreOptions *ropt = AH->archive.ropt;
 
 		Assert(AH->connection == NULL);
 
diff --git a/src/bin/pg_dump/pg_backup_archiver.h b/src/bin/pg_dump/pg_backup_archiver.h
index 81f0db8d3c..ac2ebb7eea 100644
--- a/src/bin/pg_dump/pg_backup_archiver.h
+++ b/src/bin/pg_dump/pg_backup_archiver.h
@@ -212,7 +212,7 @@ typedef enum
 
 struct _archiveHandle
 {
-	Archive		public;			/* Public part of archive */
+	Archive		archive;		/* Public part of archive */
 	int			version;		/* Version of file */
 
 	char	   *archiveRemoteVersion;	/* When reading an archive, the
@@ -342,7 +342,7 @@ struct _tocEntry
 	bool		hadDumper;		/* Archiver was passed a dumper routine (used
 								 * in restore) */
 	char	   *tag;			/* index tag */
-	char	   *namespace;		/* null or empty string if not in a schema */
+	char	   *schema;			/* null or empty string if not in a schema */
 	char	   *tablespace;		/* null if not in a tablespace; empty string
 								 * means use database default */
 	char	   *owner;
@@ -393,10 +393,10 @@ TocEntry   *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
 extern bool checkSeek(FILE *fp);
 
 #define appendStringLiteralAHX(buf,str,AH) \
-	appendStringLiteral(buf, str, (AH)->public.encoding, (AH)->public.std_strings)
+	appendStringLiteral(buf, str, (AH)->archive.encoding, (AH)->archive.std_strings)
 
 #define appendByteaLiteralAHX(buf,str,len,AH) \
-	appendByteaLiteral(buf, str, len, (AH)->public.std_strings)
+	appendByteaLiteral(buf, str, len, (AH)->archive.std_strings)
 
 /*
  * Mandatory routines for each supported format
diff --git a/src/bin/pg_dump/pg_backup_custom.c b/src/bin/pg_dump/pg_backup_custom.c
index 5737608f9e..b99c43772c 100644
--- a/src/bin/pg_dump/pg_backup_custom.c
+++ b/src/bin/pg_dump/pg_backup_custom.c
@@ -272,7 +272,7 @@ _PrintExtraToc(ArchiveHandle *AH, TocEntry *te)
 {
 	lclTocEntry *ctx = (lclTocEntry *) te->formatData;
 
-	if (AH->public.verbose)
+	if (AH->archive.verbose)
 		ahprintf(AH, "-- Data Pos: " INT64_FORMAT "\n",
 				 (int64) ctx->dataPos);
 }
@@ -495,7 +495,7 @@ _PrintTocData(ArchiveHandle *AH, TocEntry *te)
 			break;
 
 		case BLK_BLOBS:
-			_LoadBlobs(AH, AH->public.ropt->dropSchema);
+			_LoadBlobs(AH, AH->archive.ropt->dropSchema);
 			break;
 
 		default:				/* Always have a default */
diff --git a/src/bin/pg_dump/pg_backup_db.c b/src/bin/pg_dump/pg_backup_db.c
index 3b9cd89b4a..9286c6af0e 100644
--- a/src/bin/pg_dump/pg_backup_db.c
+++ b/src/bin/pg_dump/pg_backup_db.c
@@ -46,14 +46,14 @@ _check_database_version(ArchiveHandle *AH)
 	if (remoteversion == 0 || !remoteversion_str)
 		exit_horribly(modulename, "could not get server_version from libpq\n");
 
-	AH->public.remoteVersionStr = pg_strdup(remoteversion_str);
-	AH->public.remoteVersion = remoteversion;
+	AH->archive.remoteVersionStr = pg_strdup(remoteversion_str);
+	AH->archive.remoteVersion = remoteversion;
 	if (!AH->archiveRemoteVersion)
-		AH->archiveRemoteVersion = AH->public.remoteVersionStr;
+		AH->archiveRemoteVersion = AH->archive.remoteVersionStr;
 
 	if (remoteversion != PG_VERSION_NUM
-		&& (remoteversion < AH->public.minRemoteVersion ||
-			remoteversion > AH->public.maxRemoteVersion))
+		&& (remoteversion < AH->archive.minRemoteVersion ||
+			remoteversion > AH->archive.maxRemoteVersion))
 	{
 		write_msg(NULL, "server version: %s; %s version: %s\n",
 				  remoteversion_str, progname, PG_VERSION);
@@ -68,11 +68,11 @@ _check_database_version(ArchiveHandle *AH)
 	{
 		res = ExecuteSqlQueryForSingleRow((Archive *) AH, "SELECT pg_catalog.pg_is_in_recovery()");
 
-		AH->public.isStandby = (strcmp(PQgetvalue(res, 0, 0), "t") == 0);
+		AH->archive.isStandby = (strcmp(PQgetvalue(res, 0, 0), "t") == 0);
 		PQclear(res);
 	}
 	else
-		AH->public.isStandby = false;
+		AH->archive.isStandby = false;
 }
 
 /*
@@ -551,7 +551,7 @@ ExecuteSimpleCommands(ArchiveHandle *AH, const char *buf, size_t bufLen)
 				/* We needn't handle '' specially */
 				if (ch == '\'' && !AH->sqlparse.backSlash)
 					AH->sqlparse.state = SQL_SCAN;
-				else if (ch == '\\' && !AH->public.std_strings)
+				else if (ch == '\\' && !AH->archive.std_strings)
 					AH->sqlparse.backSlash = !AH->sqlparse.backSlash;
 				else
 					AH->sqlparse.backSlash = false;
diff --git a/src/bin/pg_dump/pg_backup_directory.c b/src/bin/pg_dump/pg_backup_directory.c
index 0d7322f73a..4e255ca4a6 100644
--- a/src/bin/pg_dump/pg_backup_directory.c
+++ b/src/bin/pg_dump/pg_backup_directory.c
@@ -308,7 +308,7 @@ _PrintExtraToc(ArchiveHandle *AH, TocEntry *te)
 {
 	lclTocEntry *tctx = (lclTocEntry *) te->formatData;
 
-	if (AH->public.verbose && tctx->filename)
+	if (AH->archive.verbose && tctx->filename)
 		ahprintf(AH, "-- File: %s\n", tctx->filename);
 }
 
@@ -458,7 +458,7 @@ _LoadBlobs(ArchiveHandle *AH)
 			exit_horribly(modulename, "invalid line in large object TOC file \"%s\": \"%s\"\n",
 						  fname, line);
 
-		StartRestoreBlob(AH, oid, AH->public.ropt->dropSchema);
+		StartRestoreBlob(AH, oid, AH->archive.ropt->dropSchema);
 		snprintf(path, MAXPGPATH, "%s/%s", ctx->directory, fname);
 		_PrintFileData(AH, path);
 		EndRestoreBlob(AH, oid);
diff --git a/src/bin/pg_dump/pg_backup_null.c b/src/bin/pg_dump/pg_backup_null.c
index ff419bb82f..ae8374292d 100644
--- a/src/bin/pg_dump/pg_backup_null.c
+++ b/src/bin/pg_dump/pg_backup_null.c
@@ -150,7 +150,7 @@ _StartBlob(ArchiveHandle *AH, TocEntry *te, Oid oid)
 		exit_horribly(NULL, "invalid OID for large object\n");
 
 	/* With an old archive we must do drop and create logic here */
-	if (old_blob_style && AH->public.ropt->dropSchema)
+	if (old_blob_style && AH->archive.ropt->dropSchema)
 		DropBlobIfExists(AH, oid);
 
 	if (old_blob_style)
diff --git a/src/bin/pg_dump/pg_backup_tar.c b/src/bin/pg_dump/pg_backup_tar.c
index 9cadd0c4a4..27b4d62476 100644
--- a/src/bin/pg_dump/pg_backup_tar.c
+++ b/src/bin/pg_dump/pg_backup_tar.c
@@ -315,7 +315,7 @@ _PrintExtraToc(ArchiveHandle *AH, TocEntry *te)
 {
 	lclTocEntry *ctx = (lclTocEntry *) te->formatData;
 
-	if (AH->public.verbose && ctx->filename != NULL)
+	if (AH->archive.verbose && ctx->filename != NULL)
 		ahprintf(AH, "-- File: %s\n", ctx->filename);
 }
 
@@ -735,7 +735,7 @@ _LoadBlobs(ArchiveHandle *AH)
 			{
 				ahlog(AH, 1, "restoring large object with OID %u\n", oid);
 
-				StartRestoreBlob(AH, oid, AH->public.ropt->dropSchema);
+				StartRestoreBlob(AH, oid, AH->archive.ropt->dropSchema);
 
 				while ((cnt = tarRead(buf, 4095, th)) > 0)
 				{
@@ -868,26 +868,26 @@ _CloseArchive(ArchiveHandle *AH)
 		ctx->scriptTH = th;
 
 		ropt = NewRestoreOptions();
-		memcpy(ropt, AH->public.ropt, sizeof(RestoreOptions));
+		memcpy(ropt, AH->archive.ropt, sizeof(RestoreOptions));
 		ropt->filename = NULL;
 		ropt->dropSchema = 1;
 		ropt->compression = 0;
 		ropt->superuser = NULL;
 		ropt->suppressDumpWarnings = true;
 
-		savDopt = AH->public.dopt;
-		savRopt = AH->public.ropt;
+		savDopt = AH->archive.dopt;
+		savRopt = AH->archive.ropt;
 
 		SetArchiveOptions((Archive *) AH, NULL, ropt);
 
-		savVerbose = AH->public.verbose;
-		AH->public.verbose = 0;
+		savVerbose = AH->archive.verbose;
+		AH->archive.verbose = 0;
 
 		RestoreArchive((Archive *) AH);
 
 		SetArchiveOptions((Archive *) AH, savDopt, savRopt);
 
-		AH->public.verbose = savVerbose;
+		AH->archive.verbose = savVerbose;
 
 		tarClose(AH, th);
 
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index 7273ec8fe2..0b8c7d22a5 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -147,13 +147,13 @@ static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
 static void dumpComment(Archive *fout, const char *target,
-			const char *namespace, const char *owner,
+			const char *nspname, const char *owner,
 			CatalogId catalogId, int subid, DumpId dumpId);
 static int findComments(Archive *fout, Oid classoid, Oid objoid,
 			 CommentItem **items);
 static int	collectComments(Archive *fout, CommentItem **items);
 static void dumpSecLabel(Archive *fout, const char *target,
-			 const char *namespace, const char *owner,
+			 const char *nspname, const char *owner,
 			 CatalogId catalogId, int subid, DumpId dumpId);
 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
 			  SecLabelItem **items);
@@ -199,7 +199,7 @@ static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
 static void dumpUserMappings(Archive *fout,
-				 const char *servername, const char *namespace,
+				 const char *servername, const char *nspname,
 				 const char *owner, CatalogId catalogId, DumpId dumpId);
 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
 
@@ -1420,7 +1420,7 @@ selectDumpableTable(TableInfo *tbinfo, Archive *fout)
 												   tbinfo->dobj.catId.oid) ?
 			DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
 	else
-		tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
+		tbinfo->dobj.dump = tbinfo->dobj.namespaceinfo->dobj.dump_contains;
 
 	/*
 	 * In any case, a table can be excluded by an exclusion switch
@@ -1478,7 +1478,7 @@ selectDumpableType(TypeInfo *tyinfo, Archive *fout)
 		return;					/* extension membership overrides all else */
 
 	/* Dump based on if the contents of the namespace are being dumped */
-	tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
+	tyinfo->dobj.dump = tyinfo->dobj.namespaceinfo->dobj.dump_contains;
 }
 
 /*
@@ -1494,9 +1494,9 @@ selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
 {
 	/* Default ACLs can't be extension members */
 
-	if (dinfo->dobj.namespace)
+	if (dinfo->dobj.namespaceinfo)
 		/* default ACLs are considered part of the namespace */
-		dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
+		dinfo->dobj.dump = dinfo->dobj.namespaceinfo->dobj.dump_contains;
 	else
 		dinfo->dobj.dump = dopt->include_everything ?
 			DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
@@ -1628,8 +1628,8 @@ selectDumpableObject(DumpableObject *dobj, Archive *fout)
 	 * Default policy is to dump if parent namespace is dumpable, or for
 	 * non-namespace-associated items, dump if we're dumping "everything".
 	 */
-	if (dobj->namespace)
-		dobj->dump = dobj->namespace->dobj.dump_contains;
+	if (dobj->namespaceinfo)
+		dobj->dump = dobj->namespaceinfo->dobj.dump_contains;
 	else
 		dobj->dump = fout->dopt->include_everything ?
 			DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
@@ -1664,7 +1664,7 @@ dumpTableData_copy(Archive *fout, void *dcontext)
 
 	if (g_verbose)
 		write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
-				  tbinfo->dobj.namespace->dobj.name, classname);
+				  tbinfo->dobj.namespaceinfo->dobj.name, classname);
 
 	/*
 	 * Make sure we are in proper schema.  We will qualify the table name
@@ -1672,7 +1672,7 @@ dumpTableData_copy(Archive *fout, void *dcontext)
 	 * this ensures reproducible results in case the table contains regproc,
 	 * regclass, etc columns.
 	 */
-	selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 	/*
 	 * Specify the column list explicitly so that we have no possibility of
@@ -1686,7 +1686,7 @@ dumpTableData_copy(Archive *fout, void *dcontext)
 	{
 		appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
 						  fmtQualifiedId(fout->remoteVersion,
-										 tbinfo->dobj.namespace->dobj.name,
+										 tbinfo->dobj.namespaceinfo->dobj.name,
 										 classname),
 						  column_list);
 	}
@@ -1704,7 +1704,7 @@ dumpTableData_copy(Archive *fout, void *dcontext)
 			appendPQExpBufferStr(q, "* ");
 		appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
 						  fmtQualifiedId(fout->remoteVersion,
-										 tbinfo->dobj.namespace->dobj.name,
+										 tbinfo->dobj.namespaceinfo->dobj.name,
 										 classname),
 						  tdinfo->filtercond);
 	}
@@ -1712,7 +1712,7 @@ dumpTableData_copy(Archive *fout, void *dcontext)
 	{
 		appendPQExpBuffer(q, "COPY %s %s TO stdout;",
 						  fmtQualifiedId(fout->remoteVersion,
-										 tbinfo->dobj.namespace->dobj.name,
+										 tbinfo->dobj.namespaceinfo->dobj.name,
 										 classname),
 						  column_list);
 	}
@@ -1838,12 +1838,12 @@ dumpTableData_insert(Archive *fout, void *dcontext)
 	 * this ensures reproducible results in case the table contains regproc,
 	 * regclass, etc columns.
 	 */
-	selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 	appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
 					  "SELECT * FROM ONLY %s",
 					  fmtQualifiedId(fout->remoteVersion,
-									 tbinfo->dobj.namespace->dobj.name,
+									 tbinfo->dobj.namespaceinfo->dobj.name,
 									 classname));
 	if (tdinfo->filtercond)
 		appendPQExpBuffer(q, " %s", tdinfo->filtercond);
@@ -2030,7 +2030,7 @@ dumpTableData(Archive *fout, TableDataInfo *tdinfo)
 	 */
 	if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
 		ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
-					 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.name, tbinfo->dobj.namespaceinfo->dobj.name,
 					 NULL, tbinfo->rolname,
 					 false, "TABLE DATA", SECTION_DATA,
 					 "", "", copyStmt,
@@ -2068,7 +2068,7 @@ refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
 					 tdinfo->dobj.catId,		/* catalog ID */
 					 tdinfo->dobj.dumpId,		/* dump ID */
 					 tbinfo->dobj.name, /* Name */
-					 tbinfo->dobj.namespace->dobj.name, /* Namespace */
+					 tbinfo->dobj.namespaceinfo->dobj.name, /* Namespace */
 					 NULL,		/* Tablespace */
 					 tbinfo->rolname,	/* Owner */
 					 false,		/* with oids */
@@ -2158,7 +2158,7 @@ makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
 	tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
 	AssignDumpId(&tdinfo->dobj);
 	tdinfo->dobj.name = tbinfo->dobj.name;
-	tdinfo->dobj.namespace = tbinfo->dobj.namespace;
+	tdinfo->dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 	tdinfo->tdtable = tbinfo;
 	tdinfo->oids = oids;
 	tdinfo->filtercond = NULL;	/* might get set later */
@@ -3091,7 +3091,7 @@ getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
 
 		if (g_verbose)
 			write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
-					  tbinfo->dobj.namespace->dobj.name,
+					  tbinfo->dobj.namespaceinfo->dobj.name,
 					  tbinfo->dobj.name);
 
 		/*
@@ -3110,7 +3110,7 @@ getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
 			polinfo->dobj.catId.tableoid = 0;
 			polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
 			AssignDumpId(&polinfo->dobj);
-			polinfo->dobj.namespace = tbinfo->dobj.namespace;
+			polinfo->dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 			polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
 			polinfo->poltable = tbinfo;
 			polinfo->polname = NULL;
@@ -3123,13 +3123,13 @@ getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
 
 		if (g_verbose)
 			write_msg(NULL, "reading policies for table \"%s.%s\"\n",
-					  tbinfo->dobj.namespace->dobj.name,
+					  tbinfo->dobj.namespaceinfo->dobj.name,
 					  tbinfo->dobj.name);
 
 		/*
 		 * select table schema to ensure regproc name is qualified if needed
 		 */
-		selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 		resetPQExpBuffer(query);
 
@@ -3187,7 +3187,7 @@ getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
 				atooid(PQgetvalue(res, j, i_tableoid));
 			polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
 			AssignDumpId(&polinfo[j].dobj);
-			polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
+			polinfo[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 			polinfo[j].poltable = tbinfo;
 			polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
 			polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
@@ -3248,7 +3248,7 @@ dumpPolicy(Archive *fout, PolicyInfo *polinfo)
 		if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
 			ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
 						 polinfo->dobj.name,
-						 polinfo->dobj.namespace->dobj.name,
+						 polinfo->dobj.namespaceinfo->dobj.name,
 						 NULL,
 						 tbinfo->rolname, false,
 						 "ROW SECURITY", SECTION_POST_DATA,
@@ -3304,7 +3304,7 @@ dumpPolicy(Archive *fout, PolicyInfo *polinfo)
 	if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
 		ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
 					 tag,
-					 polinfo->dobj.namespace->dobj.name,
+					 polinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tbinfo->rolname, false,
 					 "POLICY", SECTION_POST_DATA,
@@ -3492,7 +3492,7 @@ getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
 
 		if (g_verbose)
 			write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
-					  tbinfo->dobj.namespace->dobj.name,
+					  tbinfo->dobj.namespaceinfo->dobj.name,
 					  tbinfo->dobj.name);
 
 		resetPQExpBuffer(query);
@@ -3531,7 +3531,7 @@ getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
 				atooid(PQgetvalue(res, j, i_tableoid));
 			pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
 			AssignDumpId(&pubrinfo[j].dobj);
-			pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
+			pubrinfo[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 			pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
 			pubrinfo[j].pubtable = tbinfo;
 		}
@@ -3570,7 +3570,7 @@ dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
 	 */
 	ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
 				 tag,
-				 tbinfo->dobj.namespace->dobj.name,
+				 tbinfo->dobj.namespaceinfo->dobj.name,
 				 NULL,
 				 "", false,
 				 "PUBLICATION TABLE", SECTION_POST_DATA,
@@ -4140,7 +4140,7 @@ getExtensions(Archive *fout, int *numExtensions)
 		extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&extinfo[i].dobj);
 		extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
-		extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
+		extinfo[i].extschema = pg_strdup(PQgetvalue(res, i, i_nspname));
 		extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
 		extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
 		extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
@@ -4327,7 +4327,7 @@ getTypes(Archive *fout, int *numTypes)
 		tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&tyinfo[i].dobj);
 		tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
-		tyinfo[i].dobj.namespace =
+		tyinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_typnamespace)));
 		tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -4388,7 +4388,7 @@ getTypes(Archive *fout, int *numTypes)
 			stinfo->dobj.catId = nilCatalogId;
 			AssignDumpId(&stinfo->dobj);
 			stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
-			stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
+			stinfo->dobj.namespaceinfo = tyinfo[i].dobj.namespaceinfo;
 			stinfo->baseType = &(tyinfo[i]);
 			tyinfo[i].shellType = stinfo;
 
@@ -4475,7 +4475,7 @@ getOperators(Archive *fout, int *numOprs)
 		oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&oprinfo[i].dobj);
 		oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
-		oprinfo[i].dobj.namespace =
+		oprinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_oprnamespace)));
 		oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -4564,7 +4564,7 @@ getCollations(Archive *fout, int *numCollations)
 		collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&collinfo[i].dobj);
 		collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
-		collinfo[i].dobj.namespace =
+		collinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_collnamespace)));
 		collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -4640,7 +4640,7 @@ getConversions(Archive *fout, int *numConversions)
 		convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&convinfo[i].dobj);
 		convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
-		convinfo[i].dobj.namespace =
+		convinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_connamespace)));
 		convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -4717,7 +4717,7 @@ getAccessMethods(Archive *fout, int *numAccessMethods)
 		aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&aminfo[i].dobj);
 		aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
-		aminfo[i].dobj.namespace = NULL;
+		aminfo[i].dobj.namespaceinfo = NULL;
 		aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
 		aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
 
@@ -4791,7 +4791,7 @@ getOpclasses(Archive *fout, int *numOpclasses)
 		opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&opcinfo[i].dobj);
 		opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
-		opcinfo[i].dobj.namespace =
+		opcinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_opcnamespace)));
 		opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -4878,7 +4878,7 @@ getOpfamilies(Archive *fout, int *numOpfamilies)
 		opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&opfinfo[i].dobj);
 		opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
-		opfinfo[i].dobj.namespace =
+		opfinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_opfnamespace)));
 		opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -5052,7 +5052,7 @@ getAggregates(Archive *fout, int *numAggs)
 		agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&agginfo[i].aggfn.dobj);
 		agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
-		agginfo[i].aggfn.dobj.namespace =
+		agginfo[i].aggfn.dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_aggnamespace)));
 		agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -5285,7 +5285,7 @@ getFuncs(Archive *fout, int *numFuncs)
 		finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&finfo[i].dobj);
 		finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
-		finfo[i].dobj.namespace =
+		finfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_pronamespace)));
 		finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -5927,7 +5927,7 @@ getTables(Archive *fout, int *numTables)
 		tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
 		AssignDumpId(&tblinfo[i].dobj);
 		tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
-		tblinfo[i].dobj.namespace =
+		tblinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_relnamespace)));
 		tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -6026,7 +6026,7 @@ getTables(Archive *fout, int *numTables)
 			appendPQExpBuffer(query,
 							  "LOCK TABLE %s IN ACCESS SHARE MODE",
 							  fmtQualifiedId(fout->remoteVersion,
-										tblinfo[i].dobj.namespace->dobj.name,
+										tblinfo[i].dobj.namespaceinfo->dobj.name,
 											 tblinfo[i].dobj.name));
 			ExecuteSqlStatement(fout, query->data);
 		}
@@ -6276,11 +6276,11 @@ getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 
 		if (g_verbose)
 			write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
-					  tbinfo->dobj.namespace->dobj.name,
+					  tbinfo->dobj.namespaceinfo->dobj.name,
 					  tbinfo->dobj.name);
 
 		/* Make sure we are in proper schema so indexdef is right */
-		selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 		/*
 		 * The point of the messy-looking outer join is to find a constraint
@@ -6451,7 +6451,7 @@ getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 			indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
 			AssignDumpId(&indxinfo[j].dobj);
 			indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
-			indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
+			indxinfo[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 			indxinfo[j].indextable = tbinfo;
 			indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
 			indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
@@ -6476,7 +6476,7 @@ getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
 				constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
 				AssignDumpId(&constrinfo[j].dobj);
 				constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
-				constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
+				constrinfo[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 				constrinfo[j].contable = tbinfo;
 				constrinfo[j].condomain = NULL;
 				constrinfo[j].contype = contype;
@@ -6542,14 +6542,14 @@ getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
 
 		if (g_verbose)
 			write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
-					  tbinfo->dobj.namespace->dobj.name,
+					  tbinfo->dobj.namespaceinfo->dobj.name,
 					  tbinfo->dobj.name);
 
 		/*
 		 * select table schema to ensure constraint expr is qualified if
 		 * needed
 		 */
-		selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 		resetPQExpBuffer(query);
 		appendPQExpBuffer(query,
@@ -6578,7 +6578,7 @@ getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
 			constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
 			AssignDumpId(&constrinfo[j].dobj);
 			constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
-			constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
+			constrinfo[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 			constrinfo[j].contable = tbinfo;
 			constrinfo[j].condomain = NULL;
 			constrinfo[j].contype = 'f';
@@ -6619,7 +6619,7 @@ getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
 	 * select appropriate schema to ensure names in constraint are properly
 	 * qualified
 	 */
-	selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tyinfo->dobj.namespaceinfo->dobj.name);
 
 	query = createPQExpBuffer();
 
@@ -6664,7 +6664,7 @@ getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
 		constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&constrinfo[i].dobj);
 		constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
-		constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
+		constrinfo[i].dobj.namespaceinfo = tyinfo->dobj.namespaceinfo;
 		constrinfo[i].contable = NULL;
 		constrinfo[i].condomain = tyinfo;
 		constrinfo[i].contype = 'c';
@@ -6767,7 +6767,7 @@ getRules(Archive *fout, int *numRules)
 		if (ruleinfo[i].ruletable == NULL)
 			exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
 						  ruletableoid, ruleinfo[i].dobj.catId.oid);
-		ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
+		ruleinfo[i].dobj.namespaceinfo = ruleinfo[i].ruletable->dobj.namespaceinfo;
 		ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
 		ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
 		ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
@@ -6850,13 +6850,13 @@ getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
 
 		if (g_verbose)
 			write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
-					  tbinfo->dobj.namespace->dobj.name,
+					  tbinfo->dobj.namespaceinfo->dobj.name,
 					  tbinfo->dobj.name);
 
 		/*
 		 * select table schema to ensure regproc name is qualified if needed
 		 */
-		selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 		resetPQExpBuffer(query);
 		if (fout->remoteVersion >= 90000)
@@ -6949,7 +6949,7 @@ getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
 			tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
 			AssignDumpId(&tginfo[j].dobj);
 			tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
-			tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
+			tginfo[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 			tginfo[j].tgtable = tbinfo;
 			tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
 			if (i_tgdef >= 0)
@@ -7592,7 +7592,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 		 * Make sure we are in proper schema for this table; this allows
 		 * correct retrieval of formatted type names and default exprs
 		 */
-		selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 		/* find all the user attributes and their types */
 
@@ -7602,7 +7602,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 		 */
 		if (g_verbose)
 			write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
-					  tbinfo->dobj.namespace->dobj.name,
+					  tbinfo->dobj.namespaceinfo->dobj.name,
 					  tbinfo->dobj.name);
 
 		resetPQExpBuffer(q);
@@ -7772,7 +7772,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 
 			if (g_verbose)
 				write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
-						  tbinfo->dobj.namespace->dobj.name,
+						  tbinfo->dobj.namespaceinfo->dobj.name,
 						  tbinfo->dobj.name);
 
 			printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
@@ -7813,7 +7813,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 				attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
 
 				attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
-				attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
+				attrdefs[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 
 				attrdefs[j].dobj.dump = tbinfo->dobj.dump;
 
@@ -7861,7 +7861,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 
 			if (g_verbose)
 				write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
-						  tbinfo->dobj.namespace->dobj.name,
+						  tbinfo->dobj.namespaceinfo->dobj.name,
 						  tbinfo->dobj.name);
 
 			resetPQExpBuffer(q);
@@ -7929,7 +7929,7 @@ getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
 				constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
 				AssignDumpId(&constrs[j].dobj);
 				constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
-				constrs[j].dobj.namespace = tbinfo->dobj.namespace;
+				constrs[j].dobj.namespaceinfo = tbinfo->dobj.namespaceinfo;
 				constrs[j].contable = tbinfo;
 				constrs[j].condomain = NULL;
 				constrs[j].contype = 'c';
@@ -8069,7 +8069,7 @@ getTSParsers(Archive *fout, int *numTSParsers)
 		prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&prsinfo[i].dobj);
 		prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
-		prsinfo[i].dobj.namespace =
+		prsinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_prsnamespace)));
 		prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
@@ -8155,7 +8155,7 @@ getTSDictionaries(Archive *fout, int *numTSDicts)
 		dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&dictinfo[i].dobj);
 		dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
-		dictinfo[i].dobj.namespace =
+		dictinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_dictnamespace)));
 		dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -8238,7 +8238,7 @@ getTSTemplates(Archive *fout, int *numTSTemplates)
 		tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&tmplinfo[i].dobj);
 		tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
-		tmplinfo[i].dobj.namespace =
+		tmplinfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_tmplnamespace)));
 		tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
@@ -8318,7 +8318,7 @@ getTSConfigurations(Archive *fout, int *numTSConfigs)
 		cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&cfginfo[i].dobj);
 		cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
-		cfginfo[i].dobj.namespace =
+		cfginfo[i].dobj.namespaceinfo =
 			findNamespace(fout,
 						  atooid(PQgetvalue(res, i, i_cfgnamespace)));
 		cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
@@ -8480,7 +8480,7 @@ getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
 		fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&fdwinfo[i].dobj);
 		fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
-		fdwinfo[i].dobj.namespace = NULL;
+		fdwinfo[i].dobj.namespaceinfo = NULL;
 		fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
 		fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
 		fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
@@ -8632,7 +8632,7 @@ getForeignServers(Archive *fout, int *numForeignServers)
 		srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
 		AssignDumpId(&srvinfo[i].dobj);
 		srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
-		srvinfo[i].dobj.namespace = NULL;
+		srvinfo[i].dobj.namespaceinfo = NULL;
 		srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
 		srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
 		srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
@@ -8771,9 +8771,9 @@ getDefaultACLs(Archive *fout, int *numDefaultACLs)
 		daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
 
 		if (nspid != InvalidOid)
-			daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
+			daclinfo[i].dobj.namespaceinfo = findNamespace(fout, nspid);
 		else
-			daclinfo[i].dobj.namespace = NULL;
+			daclinfo[i].dobj.namespaceinfo = NULL;
 
 		daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
 		daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
@@ -8813,7 +8813,7 @@ getDefaultACLs(Archive *fout, int *numDefaultACLs)
  */
 static void
 dumpComment(Archive *fout, const char *target,
-			const char *namespace, const char *owner,
+			const char *nspname, const char *owner,
 			CatalogId catalogId, int subid, DumpId dumpId)
 {
 	DumpOptions *dopt = fout->dopt;
@@ -8860,7 +8860,7 @@ dumpComment(Archive *fout, const char *target,
 		 * post-data.
 		 */
 		ArchiveEntry(fout, nilCatalogId, createDumpId(),
-					 target, namespace, NULL, owner,
+					 target, nspname, NULL, owner,
 					 false, "COMMENT", SECTION_NONE,
 					 query->data, "", NULL,
 					 &(dumpId), 1,
@@ -8921,7 +8921,7 @@ dumpTableComment(Archive *fout, TableInfo *tbinfo,
 
 			ArchiveEntry(fout, nilCatalogId, createDumpId(),
 						 target->data,
-						 tbinfo->dobj.namespace->dobj.name,
+						 tbinfo->dobj.namespaceinfo->dobj.name,
 						 NULL, tbinfo->rolname,
 						 false, "COMMENT", SECTION_NONE,
 						 query->data, "", NULL,
@@ -8942,7 +8942,7 @@ dumpTableComment(Archive *fout, TableInfo *tbinfo,
 
 			ArchiveEntry(fout, nilCatalogId, createDumpId(),
 						 target->data,
-						 tbinfo->dobj.namespace->dobj.name,
+						 tbinfo->dobj.namespaceinfo->dobj.name,
 						 NULL, tbinfo->rolname,
 						 false, "COMMENT", SECTION_NONE,
 						 query->data, "", NULL,
@@ -9349,7 +9349,7 @@ dumpExtension(Archive *fout, ExtensionInfo *extinfo)
 		 * selectDumpableExtension.
 		 */
 		appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
-						  qextname, fmtId(extinfo->namespace));
+						  qextname, fmtId(extinfo->extschema));
 	}
 	else
 	{
@@ -9371,7 +9371,7 @@ dumpExtension(Archive *fout, ExtensionInfo *extinfo)
 				 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
 		appendStringLiteralAH(q, extinfo->dobj.name, fout);
 		appendPQExpBufferStr(q, ", ");
-		appendStringLiteralAH(q, extinfo->namespace, fout);
+		appendStringLiteralAH(q, extinfo->extschema, fout);
 		appendPQExpBufferStr(q, ", ");
 		appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
 		appendStringLiteralAH(q, extinfo->extversion, fout);
@@ -9518,7 +9518,7 @@ dumpEnumType(Archive *fout, TypeInfo *tyinfo)
 	 * functions are generic and do not get dropped.
 	 */
 	appendPQExpBuffer(delq, "DROP TYPE %s.",
-					  fmtId(tyinfo->dobj.namespace->dobj.name));
+					  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, "%s;\n",
 					  qtypname);
 
@@ -9558,7 +9558,7 @@ dumpEnumType(Archive *fout, TypeInfo *tyinfo)
 							  "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
 							  enum_oid);
 			appendPQExpBuffer(q, "ALTER TYPE %s.",
-							  fmtId(tyinfo->dobj.namespace->dobj.name));
+							  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 			appendPQExpBuffer(q, "%s ADD VALUE ",
 							  qtypname);
 			appendStringLiteralAH(q, label, fout);
@@ -9574,7 +9574,7 @@ dumpEnumType(Archive *fout, TypeInfo *tyinfo)
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
 					 tyinfo->dobj.name,
-					 tyinfo->dobj.namespace->dobj.name,
+					 tyinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tyinfo->rolname, false,
 					 "TYPE", SECTION_PRE_DATA,
@@ -9585,18 +9585,18 @@ dumpEnumType(Archive *fout, TypeInfo *tyinfo)
 	/* Dump Type Comments and Security Labels */
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					 tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
 		dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
 				qtypname, NULL, tyinfo->dobj.name,
-				tyinfo->dobj.namespace->dobj.name,
+				tyinfo->dobj.namespaceinfo->dobj.name,
 				tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
 				tyinfo->inittypacl, tyinfo->initrtypacl);
 
@@ -9628,7 +9628,7 @@ dumpRangeType(Archive *fout, TypeInfo *tyinfo)
 	 * select appropriate schema to ensure names in CREATE are properly
 	 * qualified
 	 */
-	selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tyinfo->dobj.namespaceinfo->dobj.name);
 
 	appendPQExpBuffer(query,
 			"SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
@@ -9655,7 +9655,7 @@ dumpRangeType(Archive *fout, TypeInfo *tyinfo)
 	 * functions are generic and do not get dropped.
 	 */
 	appendPQExpBuffer(delq, "DROP TYPE %s.",
-					  fmtId(tyinfo->dobj.namespace->dobj.name));
+					  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, "%s;\n",
 					  qtypname);
 
@@ -9690,7 +9690,7 @@ dumpRangeType(Archive *fout, TypeInfo *tyinfo)
 		{
 			/* always schema-qualify, don't try to be smart */
 			appendPQExpBuffer(q, ",\n    collation = %s.",
-							  fmtId(coll->dobj.namespace->dobj.name));
+							  fmtId(coll->dobj.namespaceinfo->dobj.name));
 			appendPQExpBufferStr(q, fmtId(coll->dobj.name));
 		}
 	}
@@ -9713,7 +9713,7 @@ dumpRangeType(Archive *fout, TypeInfo *tyinfo)
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
 					 tyinfo->dobj.name,
-					 tyinfo->dobj.namespace->dobj.name,
+					 tyinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tyinfo->rolname, false,
 					 "TYPE", SECTION_PRE_DATA,
@@ -9724,18 +9724,18 @@ dumpRangeType(Archive *fout, TypeInfo *tyinfo)
 	/* Dump Type Comments and Security Labels */
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					 tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
 		dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
 				qtypname, NULL, tyinfo->dobj.name,
-				tyinfo->dobj.namespace->dobj.name,
+				tyinfo->dobj.namespaceinfo->dobj.name,
 				tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
 				tyinfo->inittypacl, tyinfo->initrtypacl);
 
@@ -9770,7 +9770,7 @@ dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog.
 	 */
 	appendPQExpBuffer(delq, "DROP TYPE %s.",
-					  fmtId(tyinfo->dobj.namespace->dobj.name));
+					  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, "%s;\n",
 					  qtypname);
 
@@ -9789,7 +9789,7 @@ dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
 					 tyinfo->dobj.name,
-					 tyinfo->dobj.namespace->dobj.name,
+					 tyinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tyinfo->rolname, false,
 					 "TYPE", SECTION_PRE_DATA,
@@ -9800,18 +9800,18 @@ dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
 	/* Dump Type Comments and Security Labels */
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					 tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
 		dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
 				qtypname, NULL, tyinfo->dobj.name,
-				tyinfo->dobj.namespace->dobj.name,
+				tyinfo->dobj.namespaceinfo->dobj.name,
 				tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
 				tyinfo->inittypacl, tyinfo->initrtypacl);
 
@@ -9858,7 +9858,7 @@ dumpBaseType(Archive *fout, TypeInfo *tyinfo)
 	bool		typdefault_is_literal = false;
 
 	/* Set proper schema search path so regproc references list correctly */
-	selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tyinfo->dobj.namespaceinfo->dobj.name);
 
 	/* Fetch type-specific details */
 	if (fout->remoteVersion >= 90100)
@@ -9976,7 +9976,7 @@ dumpBaseType(Archive *fout, TypeInfo *tyinfo)
 	 * other way.
 	 */
 	appendPQExpBuffer(delq, "DROP TYPE %s.",
-					  fmtId(tyinfo->dobj.namespace->dobj.name));
+					  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, "%s CASCADE;\n",
 					  qtypname);
 
@@ -10022,7 +10022,7 @@ dumpBaseType(Archive *fout, TypeInfo *tyinfo)
 		char	   *elemType;
 
 		/* reselect schema in case changed by function dump */
-		selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tyinfo->dobj.namespaceinfo->dobj.name);
 		elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
 		appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
 		free(elemType);
@@ -10074,7 +10074,7 @@ dumpBaseType(Archive *fout, TypeInfo *tyinfo)
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
 					 tyinfo->dobj.name,
-					 tyinfo->dobj.namespace->dobj.name,
+					 tyinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tyinfo->rolname, false,
 					 "TYPE", SECTION_PRE_DATA,
@@ -10085,18 +10085,18 @@ dumpBaseType(Archive *fout, TypeInfo *tyinfo)
 	/* Dump Type Comments and Security Labels */
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					 tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
 		dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
 				qtypname, NULL, tyinfo->dobj.name,
-				tyinfo->dobj.namespace->dobj.name,
+				tyinfo->dobj.namespaceinfo->dobj.name,
 				tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
 				tyinfo->inittypacl, tyinfo->initrtypacl);
 
@@ -10129,7 +10129,7 @@ dumpDomain(Archive *fout, TypeInfo *tyinfo)
 	bool		typdefault_is_literal = false;
 
 	/* Set proper schema search path so type references list correctly */
-	selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tyinfo->dobj.namespaceinfo->dobj.name);
 
 	/* Fetch domain specific details */
 	if (fout->remoteVersion >= 90100)
@@ -10193,7 +10193,7 @@ dumpDomain(Archive *fout, TypeInfo *tyinfo)
 		{
 			/* always schema-qualify, don't try to be smart */
 			appendPQExpBuffer(q, " COLLATE %s.",
-							  fmtId(coll->dobj.namespace->dobj.name));
+							  fmtId(coll->dobj.namespaceinfo->dobj.name));
 			appendPQExpBufferStr(q, fmtId(coll->dobj.name));
 		}
 	}
@@ -10230,7 +10230,7 @@ dumpDomain(Archive *fout, TypeInfo *tyinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP DOMAIN %s.",
-					  fmtId(tyinfo->dobj.namespace->dobj.name));
+					  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, "%s;\n",
 					  qtypname);
 
@@ -10242,7 +10242,7 @@ dumpDomain(Archive *fout, TypeInfo *tyinfo)
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
 					 tyinfo->dobj.name,
-					 tyinfo->dobj.namespace->dobj.name,
+					 tyinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tyinfo->rolname, false,
 					 "DOMAIN", SECTION_PRE_DATA,
@@ -10253,18 +10253,18 @@ dumpDomain(Archive *fout, TypeInfo *tyinfo)
 	/* Dump Domain Comments and Security Labels */
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					 tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
 		dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
 				qtypname, NULL, tyinfo->dobj.name,
-				tyinfo->dobj.namespace->dobj.name,
+				tyinfo->dobj.namespaceinfo->dobj.name,
 				tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
 				tyinfo->inittypacl, tyinfo->initrtypacl);
 
@@ -10281,7 +10281,7 @@ dumpDomain(Archive *fout, TypeInfo *tyinfo)
 
 		if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 			dumpComment(fout, labelq->data,
-						tyinfo->dobj.namespace->dobj.name,
+						tyinfo->dobj.namespaceinfo->dobj.name,
 						tyinfo->rolname,
 						domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
 
@@ -10321,7 +10321,7 @@ dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
 	int			actual_atts;
 
 	/* Set proper schema search path so type references list correctly */
-	selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tyinfo->dobj.namespaceinfo->dobj.name);
 
 	/* Fetch type specific details */
 	if (fout->remoteVersion >= 90100)
@@ -10424,7 +10424,7 @@ dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
 				{
 					/* always schema-qualify, don't try to be smart */
 					appendPQExpBuffer(q, " COLLATE %s.",
-									  fmtId(coll->dobj.namespace->dobj.name));
+									  fmtId(coll->dobj.namespaceinfo->dobj.name));
 					appendPQExpBufferStr(q, fmtId(coll->dobj.name));
 				}
 			}
@@ -10464,7 +10464,7 @@ dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP TYPE %s.",
-					  fmtId(tyinfo->dobj.namespace->dobj.name));
+					  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, "%s;\n",
 					  qtypname);
 
@@ -10476,7 +10476,7 @@ dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
 					 tyinfo->dobj.name,
-					 tyinfo->dobj.namespace->dobj.name,
+					 tyinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tyinfo->rolname, false,
 					 "TYPE", SECTION_PRE_DATA,
@@ -10488,18 +10488,18 @@ dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
 	/* Dump Type Comments and Security Labels */
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
+					 tyinfo->dobj.namespaceinfo->dobj.name, tyinfo->rolname,
 					 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
 
 	if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
 		dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
 				qtypname, NULL, tyinfo->dobj.name,
-				tyinfo->dobj.namespace->dobj.name,
+				tyinfo->dobj.namespaceinfo->dobj.name,
 				tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
 				tyinfo->inittypacl, tyinfo->initrtypacl);
 
@@ -10605,7 +10605,7 @@ dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
 
 			ArchiveEntry(fout, nilCatalogId, createDumpId(),
 						 target->data,
-						 tyinfo->dobj.namespace->dobj.name,
+						 tyinfo->dobj.namespaceinfo->dobj.name,
 						 NULL, tyinfo->rolname,
 						 false, "COMMENT", SECTION_NONE,
 						 query->data, "", NULL,
@@ -10659,7 +10659,7 @@ dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
 	if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
 					 stinfo->dobj.name,
-					 stinfo->dobj.namespace->dobj.name,
+					 stinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 stinfo->baseType->rolname, false,
 					 "SHELL TYPE", SECTION_PRE_DATA,
@@ -10740,7 +10740,7 @@ dumpProcLang(Archive *fout, ProcLangInfo *plang)
 	 * it doesn't really have a schema.
 	 */
 	if (useParams)
-		lanschema = funcInfo->dobj.namespace->dobj.name;
+		lanschema = funcInfo->dobj.namespaceinfo->dobj.name;
 	else
 		lanschema = NULL;
 
@@ -10758,18 +10758,18 @@ dumpProcLang(Archive *fout, ProcLangInfo *plang)
 		{
 			appendPQExpBufferStr(defqry, " INLINE ");
 			/* Cope with possibility that inline is in different schema */
-			if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
+			if (inlineInfo->dobj.namespaceinfo != funcInfo->dobj.namespaceinfo)
 				appendPQExpBuffer(defqry, "%s.",
-							   fmtId(inlineInfo->dobj.namespace->dobj.name));
+							   fmtId(inlineInfo->dobj.namespaceinfo->dobj.name));
 			appendPQExpBufferStr(defqry, fmtId(inlineInfo->dobj.name));
 		}
 		if (OidIsValid(plang->lanvalidator))
 		{
 			appendPQExpBufferStr(defqry, " VALIDATOR ");
 			/* Cope with possibility that validator is in different schema */
-			if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
+			if (validatorInfo->dobj.namespaceinfo != funcInfo->dobj.namespaceinfo)
 				appendPQExpBuffer(defqry, "%s.",
-							fmtId(validatorInfo->dobj.namespace->dobj.name));
+							fmtId(validatorInfo->dobj.namespaceinfo->dobj.name));
 			appendPQExpBufferStr(defqry, fmtId(validatorInfo->dobj.name));
 		}
 	}
@@ -11015,7 +11015,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
 	asPart = createPQExpBuffer();
 
 	/* Set proper schema search path so type references list correctly */
-	selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, finfo->dobj.namespaceinfo->dobj.name);
 
 	/* Fetch function-specific details */
 	if (fout->remoteVersion >= 90600)
@@ -11289,7 +11289,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
-					  fmtId(finfo->dobj.namespace->dobj.name),
+					  fmtId(finfo->dobj.namespaceinfo->dobj.name),
 					  funcsig);
 
 	appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig ? funcfullsig :
@@ -11415,7 +11415,7 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
 	if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
 					 funcsig_tag,
-					 finfo->dobj.namespace->dobj.name,
+					 finfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 finfo->rolname, false,
 					 "FUNCTION", SECTION_PRE_DATA,
@@ -11426,18 +11426,18 @@ dumpFunc(Archive *fout, FuncInfo *finfo)
 	/* Dump Function Comments and Security Labels */
 	if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					finfo->dobj.namespace->dobj.name, finfo->rolname,
+					finfo->dobj.namespaceinfo->dobj.name, finfo->rolname,
 					finfo->dobj.catId, 0, finfo->dobj.dumpId);
 
 	if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 finfo->dobj.namespace->dobj.name, finfo->rolname,
+					 finfo->dobj.namespaceinfo->dobj.name, finfo->rolname,
 					 finfo->dobj.catId, 0, finfo->dobj.dumpId);
 
 	if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
 		dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
 				funcsig, NULL, funcsig_tag,
-				finfo->dobj.namespace->dobj.name,
+				finfo->dobj.namespaceinfo->dobj.name,
 				finfo->rolname, finfo->proacl, finfo->rproacl,
 				finfo->initproacl, finfo->initrproacl);
 
@@ -11527,7 +11527,7 @@ dumpCast(Archive *fout, CastInfo *cast)
 				 * it).
 				 */
 				appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
-						   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
+						   fmtId(funcInfo->dobj.namespaceinfo->dobj.name), fsig);
 				free(fsig);
 			}
 			else
@@ -11637,7 +11637,7 @@ dumpTransform(Archive *fout, TransformInfo *transform)
 			 * pg_catalog schema (format_function_signature won't qualify it).
 			 */
 			appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
-					fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
+					fmtId(fromsqlFuncInfo->dobj.namespaceinfo->dobj.name), fsig);
 			free(fsig);
 		}
 		else
@@ -11658,7 +11658,7 @@ dumpTransform(Archive *fout, TransformInfo *transform)
 			 * pg_catalog schema (format_function_signature won't qualify it).
 			 */
 			appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
-					  fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
+					  fmtId(tosqlFuncInfo->dobj.namespaceinfo->dobj.name), fsig);
 			free(fsig);
 		}
 		else
@@ -11753,7 +11753,7 @@ dumpOpr(Archive *fout, OprInfo *oprinfo)
 	details = createPQExpBuffer();
 
 	/* Make sure we are in proper schema so regoperator works correctly */
-	selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, oprinfo->dobj.namespaceinfo->dobj.name);
 
 	if (fout->remoteVersion >= 80300)
 	{
@@ -11881,7 +11881,7 @@ dumpOpr(Archive *fout, OprInfo *oprinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
-					  fmtId(oprinfo->dobj.namespace->dobj.name),
+					  fmtId(oprinfo->dobj.namespaceinfo->dobj.name),
 					  oprid->data);
 
 	appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
@@ -11895,7 +11895,7 @@ dumpOpr(Archive *fout, OprInfo *oprinfo)
 	if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
 					 oprinfo->dobj.name,
-					 oprinfo->dobj.namespace->dobj.name,
+					 oprinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 oprinfo->rolname,
 					 false, "OPERATOR", SECTION_PRE_DATA,
@@ -11906,7 +11906,7 @@ dumpOpr(Archive *fout, OprInfo *oprinfo)
 	/* Dump Operator Comments */
 	if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
+					oprinfo->dobj.namespaceinfo->dobj.name, oprinfo->rolname,
 					oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
 
 	PQclear(res);
@@ -12161,7 +12161,7 @@ dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
 	labelq = createPQExpBuffer();
 
 	/* Make sure we are in proper schema so regoperator works correctly */
-	selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, opcinfo->dobj.namespaceinfo->dobj.name);
 
 	/* Get additional fields from the pg_opclass row */
 	if (fout->remoteVersion >= 80300)
@@ -12215,7 +12215,7 @@ dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
-					  fmtId(opcinfo->dobj.namespace->dobj.name));
+					  fmtId(opcinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s",
 					  fmtId(opcinfo->dobj.name));
 	appendPQExpBuffer(delq, " USING %s;\n",
@@ -12232,7 +12232,7 @@ dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
 	if (strlen(opcfamilyname) > 0)
 	{
 		appendPQExpBufferStr(q, " FAMILY ");
-		if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
+		if (strcmp(opcfamilynsp, opcinfo->dobj.namespaceinfo->dobj.name) != 0)
 			appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
 		appendPQExpBufferStr(q, fmtId(opcfamilyname));
 	}
@@ -12351,7 +12351,7 @@ dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
 		if (strlen(sortfamily) > 0)
 		{
 			appendPQExpBufferStr(q, " FOR ORDER BY ");
-			if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
+			if (strcmp(sortfamilynsp, opcinfo->dobj.namespaceinfo->dobj.name) != 0)
 				appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
 			appendPQExpBufferStr(q, fmtId(sortfamily));
 		}
@@ -12448,7 +12448,7 @@ dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
 	if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
 					 opcinfo->dobj.name,
-					 opcinfo->dobj.namespace->dobj.name,
+					 opcinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 opcinfo->rolname,
 					 false, "OPERATOR CLASS", SECTION_PRE_DATA,
@@ -12521,7 +12521,7 @@ dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
 	labelq = createPQExpBuffer();
 
 	/* Make sure we are in proper schema so regoperator works correctly */
-	selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, opfinfo->dobj.namespaceinfo->dobj.name);
 
 	/*
 	 * Fetch only those opfamily members that are tied directly to the
@@ -12617,7 +12617,7 @@ dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
-					  fmtId(opfinfo->dobj.namespace->dobj.name));
+					  fmtId(opfinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s",
 					  fmtId(opfinfo->dobj.name));
 	appendPQExpBuffer(delq, " USING %s;\n",
@@ -12669,7 +12669,7 @@ dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
 			if (strlen(sortfamily) > 0)
 			{
 				appendPQExpBufferStr(q, " FOR ORDER BY ");
-				if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
+				if (strcmp(sortfamilynsp, opfinfo->dobj.namespaceinfo->dobj.name) != 0)
 					appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
 				appendPQExpBufferStr(q, fmtId(sortfamily));
 			}
@@ -12721,7 +12721,7 @@ dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
 	if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
 					 opfinfo->dobj.name,
-					 opfinfo->dobj.namespace->dobj.name,
+					 opfinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 opfinfo->rolname,
 					 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
@@ -12772,7 +12772,7 @@ dumpCollation(Archive *fout, CollInfo *collinfo)
 	labelq = createPQExpBuffer();
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, collinfo->dobj.namespaceinfo->dobj.name);
 
 	/* Get collation-specific details */
 	appendPQExpBuffer(query, "SELECT "
@@ -12794,7 +12794,7 @@ dumpCollation(Archive *fout, CollInfo *collinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP COLLATION %s",
-					  fmtId(collinfo->dobj.namespace->dobj.name));
+					  fmtId(collinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s;\n",
 					  fmtId(collinfo->dobj.name));
 
@@ -12813,7 +12813,7 @@ dumpCollation(Archive *fout, CollInfo *collinfo)
 	if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
 					 collinfo->dobj.name,
-					 collinfo->dobj.namespace->dobj.name,
+					 collinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 collinfo->rolname,
 					 false, "COLLATION", SECTION_PRE_DATA,
@@ -12824,7 +12824,7 @@ dumpCollation(Archive *fout, CollInfo *collinfo)
 	/* Dump Collation Comments */
 	if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					collinfo->dobj.namespace->dobj.name, collinfo->rolname,
+					collinfo->dobj.namespaceinfo->dobj.name, collinfo->rolname,
 					collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
 
 	PQclear(res);
@@ -12867,7 +12867,7 @@ dumpConversion(Archive *fout, ConvInfo *convinfo)
 	labelq = createPQExpBuffer();
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, convinfo->dobj.namespaceinfo->dobj.name);
 
 	/* Get conversion-specific details */
 	appendPQExpBuffer(query, "SELECT "
@@ -12894,7 +12894,7 @@ dumpConversion(Archive *fout, ConvInfo *convinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP CONVERSION %s",
-					  fmtId(convinfo->dobj.namespace->dobj.name));
+					  fmtId(convinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s;\n",
 					  fmtId(convinfo->dobj.name));
 
@@ -12915,7 +12915,7 @@ dumpConversion(Archive *fout, ConvInfo *convinfo)
 	if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
 					 convinfo->dobj.name,
-					 convinfo->dobj.namespace->dobj.name,
+					 convinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 convinfo->rolname,
 					 false, "CONVERSION", SECTION_PRE_DATA,
@@ -12926,7 +12926,7 @@ dumpConversion(Archive *fout, ConvInfo *convinfo)
 	/* Dump Conversion Comments */
 	if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					convinfo->dobj.namespace->dobj.name, convinfo->rolname,
+					convinfo->dobj.namespaceinfo->dobj.name, convinfo->rolname,
 					convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
 
 	PQclear(res);
@@ -13047,7 +13047,7 @@ dumpAgg(Archive *fout, AggInfo *agginfo)
 	details = createPQExpBuffer();
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
+	selectSourceSchema(fout, agginfo->aggfn.dobj.namespaceinfo->dobj.name);
 
 	/* Get aggregate-specific details */
 	if (fout->remoteVersion >= 90600)
@@ -13314,7 +13314,7 @@ dumpAgg(Archive *fout, AggInfo *agginfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
-					  fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
+					  fmtId(agginfo->aggfn.dobj.namespaceinfo->dobj.name),
 					  aggsig);
 
 	appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
@@ -13329,7 +13329,7 @@ dumpAgg(Archive *fout, AggInfo *agginfo)
 		ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
 					 agginfo->aggfn.dobj.dumpId,
 					 aggsig_tag,
-					 agginfo->aggfn.dobj.namespace->dobj.name,
+					 agginfo->aggfn.dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 agginfo->aggfn.rolname,
 					 false, "AGGREGATE", SECTION_PRE_DATA,
@@ -13340,13 +13340,13 @@ dumpAgg(Archive *fout, AggInfo *agginfo)
 	/* Dump Aggregate Comments */
 	if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					agginfo->aggfn.dobj.namespace->dobj.name,
+					agginfo->aggfn.dobj.namespaceinfo->dobj.name,
 					agginfo->aggfn.rolname,
 					agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
 
 	if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 agginfo->aggfn.dobj.namespace->dobj.name,
+					 agginfo->aggfn.dobj.namespaceinfo->dobj.name,
 					 agginfo->aggfn.rolname,
 				   agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
 
@@ -13365,7 +13365,7 @@ dumpAgg(Archive *fout, AggInfo *agginfo)
 		dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
 				"FUNCTION",
 				aggsig, NULL, aggsig_tag,
-				agginfo->aggfn.dobj.namespace->dobj.name,
+				agginfo->aggfn.dobj.namespaceinfo->dobj.name,
 				agginfo->aggfn.rolname, agginfo->aggfn.proacl,
 				agginfo->aggfn.rproacl,
 				agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
@@ -13405,7 +13405,7 @@ dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
 	labelq = createPQExpBuffer();
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, prsinfo->dobj.namespaceinfo->dobj.name);
 
 	appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
 					  fmtId(prsinfo->dobj.name));
@@ -13426,7 +13426,7 @@ dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
-					  fmtId(prsinfo->dobj.namespace->dobj.name));
+					  fmtId(prsinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s;\n",
 					  fmtId(prsinfo->dobj.name));
 
@@ -13439,7 +13439,7 @@ dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
 	if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
 					 prsinfo->dobj.name,
-					 prsinfo->dobj.namespace->dobj.name,
+					 prsinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 "",
 					 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
@@ -13494,13 +13494,13 @@ dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
 	tmplname = PQgetvalue(res, 0, 1);
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, dictinfo->dobj.namespaceinfo->dobj.name);
 
 	appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
 					  fmtId(dictinfo->dobj.name));
 
 	appendPQExpBufferStr(q, "    TEMPLATE = ");
-	if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
+	if (strcmp(nspname, dictinfo->dobj.namespaceinfo->dobj.name) != 0)
 		appendPQExpBuffer(q, "%s.", fmtId(nspname));
 	appendPQExpBufferStr(q, fmtId(tmplname));
 
@@ -13516,7 +13516,7 @@ dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
-					  fmtId(dictinfo->dobj.namespace->dobj.name));
+					  fmtId(dictinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s;\n",
 					  fmtId(dictinfo->dobj.name));
 
@@ -13529,7 +13529,7 @@ dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
 	if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
 					 dictinfo->dobj.name,
-					 dictinfo->dobj.namespace->dobj.name,
+					 dictinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 dictinfo->rolname,
 					 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
@@ -13570,7 +13570,7 @@ dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
 	labelq = createPQExpBuffer();
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tmplinfo->dobj.namespaceinfo->dobj.name);
 
 	appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
 					  fmtId(tmplinfo->dobj.name));
@@ -13585,7 +13585,7 @@ dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
-					  fmtId(tmplinfo->dobj.namespace->dobj.name));
+					  fmtId(tmplinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s;\n",
 					  fmtId(tmplinfo->dobj.name));
 
@@ -13598,7 +13598,7 @@ dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
 	if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
 					 tmplinfo->dobj.name,
-					 tmplinfo->dobj.namespace->dobj.name,
+					 tmplinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 "",
 					 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
@@ -13657,13 +13657,13 @@ dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
 	prsname = PQgetvalue(res, 0, 1);
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, cfginfo->dobj.namespaceinfo->dobj.name);
 
 	appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
 					  fmtId(cfginfo->dobj.name));
 
 	appendPQExpBufferStr(q, "    PARSER = ");
-	if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
+	if (strcmp(nspname, cfginfo->dobj.namespaceinfo->dobj.name) != 0)
 		appendPQExpBuffer(q, "%s.", fmtId(nspname));
 	appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
 
@@ -13716,7 +13716,7 @@ dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
-					  fmtId(cfginfo->dobj.namespace->dobj.name));
+					  fmtId(cfginfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, ".%s;\n",
 					  fmtId(cfginfo->dobj.name));
 
@@ -13729,7 +13729,7 @@ dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
 	if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
 					 cfginfo->dobj.name,
-					 cfginfo->dobj.namespace->dobj.name,
+					 cfginfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 cfginfo->rolname,
 					 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
@@ -13942,7 +13942,7 @@ dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
  */
 static void
 dumpUserMappings(Archive *fout,
-				 const char *servername, const char *namespace,
+				 const char *servername, const char *nspname,
 				 const char *owner,
 				 CatalogId catalogId, DumpId dumpId)
 {
@@ -14017,7 +14017,7 @@ dumpUserMappings(Archive *fout,
 
 		ArchiveEntry(fout, nilCatalogId, createDumpId(),
 					 tag->data,
-					 namespace,
+					 nspname,
 					 NULL,
 					 owner, false,
 					 "USER MAPPING", SECTION_PRE_DATA,
@@ -14078,8 +14078,8 @@ dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
 
 	/* build the actual command(s) for this tuple */
 	if (!buildDefaultACLCommands(type,
-								 daclinfo->dobj.namespace != NULL ?
-								 daclinfo->dobj.namespace->dobj.name : NULL,
+								 daclinfo->dobj.namespaceinfo != NULL ?
+								 daclinfo->dobj.namespaceinfo->dobj.name : NULL,
 								 daclinfo->defaclacl,
 								 daclinfo->rdefaclacl,
 								 daclinfo->initdefaclacl,
@@ -14093,7 +14093,7 @@ dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
 	if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
 		ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
 					 tag->data,
-		daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
+		daclinfo->dobj.namespaceinfo ? daclinfo->dobj.namespaceinfo->dobj.name : NULL,
 					 NULL,
 					 daclinfo->defaclrole,
 					 false, "DEFAULT ACL", SECTION_POST_DATA,
@@ -14202,7 +14202,7 @@ dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
  */
 static void
 dumpSecLabel(Archive *fout, const char *target,
-			 const char *namespace, const char *owner,
+			 const char *nspname, const char *owner,
 			 CatalogId catalogId, int subid, DumpId dumpId)
 {
 	DumpOptions *dopt = fout->dopt;
@@ -14250,7 +14250,7 @@ dumpSecLabel(Archive *fout, const char *target,
 	if (query->len > 0)
 	{
 		ArchiveEntry(fout, nilCatalogId, createDumpId(),
-					 target, namespace, NULL, owner,
+					 target, nspname, NULL, owner,
 					 false, "SECURITY LABEL", SECTION_NONE,
 					 query->data, "", NULL,
 					 &(dumpId), 1,
@@ -14328,7 +14328,7 @@ dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
 						  fmtId(tbinfo->dobj.name));
 		ArchiveEntry(fout, nilCatalogId, createDumpId(),
 					 target->data,
-					 tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.namespaceinfo->dobj.name,
 					 NULL, tbinfo->rolname,
 					 false, "SECURITY LABEL", SECTION_NONE,
 					 query->data, "", NULL,
@@ -14512,7 +14512,7 @@ dumpTable(Archive *fout, TableInfo *tbinfo)
 				(tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
 				"TABLE",
 				namecopy, NULL, tbinfo->dobj.name,
-				tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
+				tbinfo->dobj.namespaceinfo->dobj.name, tbinfo->rolname,
 				tbinfo->relacl, tbinfo->rrelacl,
 				tbinfo->initrelacl, tbinfo->initrrelacl);
 
@@ -14602,7 +14602,7 @@ dumpTable(Archive *fout, TableInfo *tbinfo)
 			/* Column's GRANT type is always TABLE */
 			dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
 					namecopy, attnamecopy, acltag,
-					tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
+					tbinfo->dobj.namespaceinfo->dobj.name, tbinfo->rolname,
 					attacl, rattacl, initattacl, initrattacl);
 			free(attnamecopy);
 			free(acltag);
@@ -14700,7 +14700,7 @@ createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
 			{
 				/* always schema-qualify, don't try to be smart */
 				appendPQExpBuffer(result, " COLLATE %s.",
-								  fmtId(coll->dobj.namespace->dobj.name));
+								  fmtId(coll->dobj.namespaceinfo->dobj.name));
 				appendPQExpBufferStr(result, fmtId(coll->dobj.name));
 			}
 		}
@@ -14733,7 +14733,7 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 				k;
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 	if (dopt->binary_upgrade)
 		binary_upgrade_set_type_oids_by_rel_oid(fout, q,
@@ -14755,7 +14755,7 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 		 * pg_catalog
 		 */
 		appendPQExpBuffer(delq, "DROP VIEW %s.",
-						  fmtId(tbinfo->dobj.namespace->dobj.name));
+						  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 		appendPQExpBuffer(delq, "%s;\n",
 						  fmtId(tbinfo->dobj.name));
 
@@ -14841,7 +14841,7 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 		 * pg_catalog
 		 */
 		appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
-						  fmtId(tbinfo->dobj.namespace->dobj.name));
+						  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 		appendPQExpBuffer(delq, "%s;\n",
 						  fmtId(tbinfo->dobj.name));
 
@@ -14870,9 +14870,9 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 			TableInfo  *parentRel = tbinfo->partitionOf;
 
 			appendPQExpBuffer(q, " PARTITION OF ");
-			if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
+			if (parentRel->dobj.namespaceinfo != tbinfo->dobj.namespaceinfo)
 				appendPQExpBuffer(q, "%s.",
-								fmtId(parentRel->dobj.namespace->dobj.name));
+								fmtId(parentRel->dobj.namespaceinfo->dobj.name));
 			appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
 		}
 
@@ -14958,7 +14958,7 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 						{
 							/* always schema-qualify, don't try to be smart */
 							appendPQExpBuffer(q, " COLLATE %s.",
-									 fmtId(coll->dobj.namespace->dobj.name));
+									 fmtId(coll->dobj.namespaceinfo->dobj.name));
 							appendPQExpBufferStr(q, fmtId(coll->dobj.name));
 						}
 					}
@@ -15021,9 +15021,9 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 
 					if (k > 0)
 						appendPQExpBufferStr(q, ", ");
-					if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
+					if (parentRel->dobj.namespaceinfo != tbinfo->dobj.namespaceinfo)
 						appendPQExpBuffer(q, "%s.",
-								fmtId(parentRel->dobj.namespace->dobj.name));
+								fmtId(parentRel->dobj.namespaceinfo->dobj.name));
 					appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
 				}
 				appendPQExpBufferChar(q, ')');
@@ -15165,9 +15165,9 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 
 					appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
 									  fmtId(tbinfo->dobj.name));
-					if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
+					if (parentRel->dobj.namespaceinfo != tbinfo->dobj.namespaceinfo)
 						appendPQExpBuffer(q, "%s.",
-								fmtId(parentRel->dobj.namespace->dobj.name));
+								fmtId(parentRel->dobj.namespaceinfo->dobj.name));
 					appendPQExpBuffer(q, "%s;\n",
 									  fmtId(parentRel->dobj.name));
 				}
@@ -15373,7 +15373,7 @@ dumpTableSchema(Archive *fout, TableInfo *tbinfo)
 	if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
 					 tbinfo->dobj.name,
-					 tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.namespaceinfo->dobj.name,
 			(tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
 					 tbinfo->rolname,
 			   (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
@@ -15444,7 +15444,7 @@ dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delq, "ALTER TABLE %s.",
-					  fmtId(tbinfo->dobj.namespace->dobj.name));
+					  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delq, "%s ",
 					  fmtId(tbinfo->dobj.name));
 	appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
@@ -15455,7 +15455,7 @@ dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
 	if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
 					 tag,
-					 tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tbinfo->rolname,
 					 false, "DEFAULT", SECTION_PRE_DATA,
@@ -15565,14 +15565,14 @@ dumpIndex(Archive *fout, IndxInfo *indxinfo)
 		 * pg_catalog
 		 */
 		appendPQExpBuffer(delq, "DROP INDEX %s.",
-						  fmtId(tbinfo->dobj.namespace->dobj.name));
+						  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 		appendPQExpBuffer(delq, "%s;\n",
 						  fmtId(indxinfo->dobj.name));
 
 		if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 			ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
 						 indxinfo->dobj.name,
-						 tbinfo->dobj.namespace->dobj.name,
+						 tbinfo->dobj.namespaceinfo->dobj.name,
 						 indxinfo->tablespace,
 						 tbinfo->rolname, false,
 						 "INDEX", SECTION_POST_DATA,
@@ -15584,7 +15584,7 @@ dumpIndex(Archive *fout, IndxInfo *indxinfo)
 	/* Dump Index Comments */
 	if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tbinfo->dobj.namespace->dobj.name,
+					tbinfo->dobj.namespaceinfo->dobj.name,
 					tbinfo->rolname,
 					indxinfo->dobj.catId, 0,
 					is_constraint ? indxinfo->indexconstraint :
@@ -15694,7 +15694,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 		 * pg_catalog
 		 */
 		appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
-						  fmtId(tbinfo->dobj.namespace->dobj.name));
+						  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 		appendPQExpBuffer(delq, "%s ",
 						  fmtId(tbinfo->dobj.name));
 		appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
@@ -15705,7 +15705,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 		if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 			ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
 						 tag,
-						 tbinfo->dobj.namespace->dobj.name,
+						 tbinfo->dobj.namespaceinfo->dobj.name,
 						 indxinfo->tablespace,
 						 tbinfo->rolname, false,
 						 "CONSTRAINT", SECTION_POST_DATA,
@@ -15730,7 +15730,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 		 * pg_catalog
 		 */
 		appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
-						  fmtId(tbinfo->dobj.namespace->dobj.name));
+						  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 		appendPQExpBuffer(delq, "%s ",
 						  fmtId(tbinfo->dobj.name));
 		appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
@@ -15741,7 +15741,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 		if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 			ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
 						 tag,
-						 tbinfo->dobj.namespace->dobj.name,
+						 tbinfo->dobj.namespaceinfo->dobj.name,
 						 NULL,
 						 tbinfo->rolname, false,
 						 "FK CONSTRAINT", SECTION_POST_DATA,
@@ -15768,7 +15768,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 			 * pg_catalog
 			 */
 			appendPQExpBuffer(delq, "ALTER TABLE %s.",
-							  fmtId(tbinfo->dobj.namespace->dobj.name));
+							  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 			appendPQExpBuffer(delq, "%s ",
 							  fmtId(tbinfo->dobj.name));
 			appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
@@ -15779,7 +15779,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 			if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 				ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
 							 tag,
-							 tbinfo->dobj.namespace->dobj.name,
+							 tbinfo->dobj.namespaceinfo->dobj.name,
 							 NULL,
 							 tbinfo->rolname, false,
 							 "CHECK CONSTRAINT", SECTION_POST_DATA,
@@ -15807,7 +15807,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 			 * pg_catalog
 			 */
 			appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
-							  fmtId(tyinfo->dobj.namespace->dobj.name));
+							  fmtId(tyinfo->dobj.namespaceinfo->dobj.name));
 			appendPQExpBuffer(delq, "%s ",
 							  fmtId(tyinfo->dobj.name));
 			appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
@@ -15818,7 +15818,7 @@ dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
 			if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 				ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
 							 tag,
-							 tyinfo->dobj.namespace->dobj.name,
+							 tyinfo->dobj.namespaceinfo->dobj.name,
 							 NULL,
 							 tyinfo->rolname, false,
 							 "CHECK CONSTRAINT", SECTION_POST_DATA,
@@ -15863,7 +15863,7 @@ dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
 
 	if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tbinfo->dobj.namespace->dobj.name,
+					tbinfo->dobj.namespaceinfo->dobj.name,
 					tbinfo->rolname,
 					coninfo->dobj.catId, 0,
 			 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
@@ -15942,7 +15942,7 @@ dumpSequence(Archive *fout, TableInfo *tbinfo)
 		 */
 
 		/* Make sure we are in proper schema */
-		selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 		appendPQExpBuffer(query,
 						  "SELECT 'bigint'::name AS sequence_type, "
@@ -15953,7 +15953,7 @@ dumpSequence(Archive *fout, TableInfo *tbinfo)
 	else
 	{
 		/* Make sure we are in proper schema */
-		selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+		selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 		appendPQExpBuffer(query,
 						  "SELECT 'bigint'::name AS sequence_type, "
@@ -16020,7 +16020,7 @@ dumpSequence(Archive *fout, TableInfo *tbinfo)
 	 * DROP must be fully qualified in case same name appears in pg_catalog
 	 */
 	appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
-					  fmtId(tbinfo->dobj.namespace->dobj.name));
+					  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delqry, "%s;\n",
 					  fmtId(tbinfo->dobj.name));
 
@@ -16073,7 +16073,7 @@ dumpSequence(Archive *fout, TableInfo *tbinfo)
 	if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
 					 tbinfo->dobj.name,
-					 tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tbinfo->rolname,
 					 false, "SEQUENCE", SECTION_PRE_DATA,
@@ -16114,7 +16114,7 @@ dumpSequence(Archive *fout, TableInfo *tbinfo)
 			if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 				ArchiveEntry(fout, nilCatalogId, createDumpId(),
 							 tbinfo->dobj.name,
-							 tbinfo->dobj.namespace->dobj.name,
+							 tbinfo->dobj.namespaceinfo->dobj.name,
 							 NULL,
 							 tbinfo->rolname,
 							 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
@@ -16127,12 +16127,12 @@ dumpSequence(Archive *fout, TableInfo *tbinfo)
 	/* Dump Sequence Comments and Security Labels */
 	if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
+					tbinfo->dobj.namespaceinfo->dobj.name, tbinfo->rolname,
 					tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
 
 	if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
 		dumpSecLabel(fout, labelq->data,
-					 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
+					 tbinfo->dobj.namespaceinfo->dobj.name, tbinfo->rolname,
 					 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
 
 	PQclear(res);
@@ -16156,7 +16156,7 @@ dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
 	PQExpBuffer query = createPQExpBuffer();
 
 	/* Make sure we are in proper schema */
-	selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 	appendPQExpBuffer(query,
 					  "SELECT last_value, is_called FROM %s",
@@ -16185,7 +16185,7 @@ dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
 	if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
 		ArchiveEntry(fout, nilCatalogId, createDumpId(),
 					 tbinfo->dobj.name,
-					 tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tbinfo->rolname,
 					 false, "SEQUENCE SET", SECTION_DATA,
@@ -16233,7 +16233,7 @@ dumpTrigger(Archive *fout, TriggerInfo *tginfo)
 	appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
 					  fmtId(tginfo->dobj.name));
 	appendPQExpBuffer(delqry, "ON %s.",
-					  fmtId(tbinfo->dobj.namespace->dobj.name));
+					  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 	appendPQExpBuffer(delqry, "%s;\n",
 					  fmtId(tbinfo->dobj.name));
 
@@ -16388,7 +16388,7 @@ dumpTrigger(Archive *fout, TriggerInfo *tginfo)
 	if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
 					 tag,
-					 tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tbinfo->rolname, false,
 					 "TRIGGER", SECTION_POST_DATA,
@@ -16398,7 +16398,7 @@ dumpTrigger(Archive *fout, TriggerInfo *tginfo)
 
 	if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
+					tbinfo->dobj.namespaceinfo->dobj.name, tbinfo->rolname,
 					tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
 
 	free(tag);
@@ -16517,7 +16517,7 @@ dumpRule(Archive *fout, RuleInfo *rinfo)
 	/*
 	 * Make sure we are in proper schema.
 	 */
-	selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
+	selectSourceSchema(fout, tbinfo->dobj.namespaceinfo->dobj.name);
 
 	query = createPQExpBuffer();
 	cmd = createPQExpBuffer();
@@ -16606,7 +16606,7 @@ dumpRule(Archive *fout, RuleInfo *rinfo)
 		PQExpBuffer result;
 
 		appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s.",
-						  fmtId(tbinfo->dobj.namespace->dobj.name));
+						  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 		appendPQExpBuffer(delcmd, "%s",
 						  fmtId(tbinfo->dobj.name));
 		result = createDummyViewAsClause(fout, tbinfo);
@@ -16618,7 +16618,7 @@ dumpRule(Archive *fout, RuleInfo *rinfo)
 		appendPQExpBuffer(delcmd, "DROP RULE %s ",
 						  fmtId(rinfo->dobj.name));
 		appendPQExpBuffer(delcmd, "ON %s.",
-						  fmtId(tbinfo->dobj.namespace->dobj.name));
+						  fmtId(tbinfo->dobj.namespaceinfo->dobj.name));
 		appendPQExpBuffer(delcmd, "%s;\n",
 						  fmtId(tbinfo->dobj.name));
 	}
@@ -16633,7 +16633,7 @@ dumpRule(Archive *fout, RuleInfo *rinfo)
 	if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
 		ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
 					 tag,
-					 tbinfo->dobj.namespace->dobj.name,
+					 tbinfo->dobj.namespaceinfo->dobj.name,
 					 NULL,
 					 tbinfo->rolname, false,
 					 "RULE", SECTION_POST_DATA,
@@ -16644,7 +16644,7 @@ dumpRule(Archive *fout, RuleInfo *rinfo)
 	/* Dump rule comments */
 	if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
 		dumpComment(fout, labelq->data,
-					tbinfo->dobj.namespace->dobj.name,
+					tbinfo->dobj.namespaceinfo->dobj.name,
 					tbinfo->rolname,
 					rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
 
@@ -16839,7 +16839,7 @@ processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
 						dumpobj = true;
 
 					/* check table's schema explicitly requested */
-					if (configtbl->dobj.namespace->dobj.dump &
+					if (configtbl->dobj.namespaceinfo->dobj.dump &
 						DUMP_COMPONENT_DATA)
 						dumpobj = true;
 				}
@@ -16852,7 +16852,7 @@ processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
 
 				/* check schema excluded by an exclusion switch */
 				if (simple_oid_list_member(&schema_exclude_oids,
-								  configtbl->dobj.namespace->dobj.catId.oid))
+								  configtbl->dobj.namespaceinfo->dobj.catId.oid))
 					dumpobj = false;
 
 				if (dumpobj)
diff --git a/src/bin/pg_dump/pg_dump.h b/src/bin/pg_dump/pg_dump.h
index a466527ec6..ef5568f286 100644
--- a/src/bin/pg_dump/pg_dump.h
+++ b/src/bin/pg_dump/pg_dump.h
@@ -130,7 +130,7 @@ typedef struct _dumpableObject
 	CatalogId	catId;			/* zero if not a cataloged object */
 	DumpId		dumpId;			/* assigned by AssignDumpId() */
 	char	   *name;			/* object name (should never be NULL) */
-	struct _namespaceInfo *namespace;	/* containing namespace, or NULL */
+	struct _namespaceInfo *namespaceinfo;	/* containing namespace, or NULL */
 	DumpComponents dump;		/* bitmask of components to dump */
 	DumpComponents dump_contains;		/* as above, but for contained objects */
 	bool		ext_member;		/* true if object is member of extension */
@@ -152,7 +152,7 @@ typedef struct _namespaceInfo
 typedef struct _extensionInfo
 {
 	DumpableObject dobj;
-	char	   *namespace;		/* schema containing extension's objects */
+	char	   *extschema;		/* schema containing extension's objects */
 	bool		relocatable;
 	char	   *extversion;
 	char	   *extconfig;		/* info about configuration tables */
diff --git a/src/bin/pg_dump/pg_dump_sort.c b/src/bin/pg_dump/pg_dump_sort.c
index ea643397ba..5a0b6f823b 100644
--- a/src/bin/pg_dump/pg_dump_sort.c
+++ b/src/bin/pg_dump/pg_dump_sort.c
@@ -224,10 +224,10 @@ DOTypeNameCompare(const void *p1, const void *p2)
 	 * either have or not have a namespace link, so we needn't be fancy about
 	 * cases where one link is null and the other not.
 	 */
-	if (obj1->namespace && obj2->namespace)
+	if (obj1->namespaceinfo && obj2->namespaceinfo)
 	{
-		cmpval = strcmp(obj1->namespace->dobj.name,
-						obj2->namespace->dobj.name);
+		cmpval = strcmp(obj1->namespaceinfo->dobj.name,
+						obj2->namespaceinfo->dobj.name);
 		if (cmpval != 0)
 			return cmpval;
 	}
@@ -254,10 +254,10 @@ DOTypeNameCompare(const void *p1, const void *p2)
 
 			if (argtype1 && argtype2)
 			{
-				if (argtype1->dobj.namespace && argtype2->dobj.namespace)
+				if (argtype1->dobj.namespaceinfo && argtype2->dobj.namespaceinfo)
 				{
-					cmpval = strcmp(argtype1->dobj.namespace->dobj.name,
-									argtype2->dobj.namespace->dobj.name);
+					cmpval = strcmp(argtype1->dobj.namespaceinfo->dobj.name,
+									argtype2->dobj.namespaceinfo->dobj.name);
 					if (cmpval != 0)
 						return cmpval;
 				}
diff --git a/src/bin/pg_rewind/parsexlog.c b/src/bin/pg_rewind/parsexlog.c
index a7f6fe2df3..c4bc44cb81 100644
--- a/src/bin/pg_rewind/parsexlog.c
+++ b/src/bin/pg_rewind/parsexlog.c
@@ -65,11 +65,11 @@ extractPageMap(const char *datadir, XLogRecPtr startpoint, int tliIndex,
 	XLogRecord *record;
 	XLogReaderState *xlogreader;
 	char	   *errormsg;
-	XLogPageReadPrivate private;
+	XLogPageReadPrivate private_data;
 
-	private.datadir = datadir;
-	private.tliIndex = tliIndex;
-	xlogreader = XLogReaderAllocate(&SimpleXLogPageRead, &private);
+	private_data.datadir = datadir;
+	private_data.tliIndex = tliIndex;
+	xlogreader = XLogReaderAllocate(&SimpleXLogPageRead, &private_data);
 	if (xlogreader == NULL)
 		pg_fatal("out of memory\n");
 
@@ -117,12 +117,12 @@ readOneRecord(const char *datadir, XLogRecPtr ptr, int tliIndex)
 	XLogRecord *record;
 	XLogReaderState *xlogreader;
 	char	   *errormsg;
-	XLogPageReadPrivate private;
+	XLogPageReadPrivate private_data;
 	XLogRecPtr	endptr;
 
-	private.datadir = datadir;
-	private.tliIndex = tliIndex;
-	xlogreader = XLogReaderAllocate(&SimpleXLogPageRead, &private);
+	private_data.datadir = datadir;
+	private_data.tliIndex = tliIndex;
+	xlogreader = XLogReaderAllocate(&SimpleXLogPageRead, &private_data);
 	if (xlogreader == NULL)
 		pg_fatal("out of memory\n");
 
@@ -161,7 +161,7 @@ findLastCheckpoint(const char *datadir, XLogRecPtr forkptr, int tliIndex,
 	XLogRecPtr	searchptr;
 	XLogReaderState *xlogreader;
 	char	   *errormsg;
-	XLogPageReadPrivate private;
+	XLogPageReadPrivate private_data;
 
 	/*
 	 * The given fork pointer points to the end of the last common record,
@@ -172,9 +172,9 @@ findLastCheckpoint(const char *datadir, XLogRecPtr forkptr, int tliIndex,
 	if (forkptr % XLOG_BLCKSZ == 0)
 		forkptr += (forkptr % XLogSegSize == 0) ? SizeOfXLogLongPHD : SizeOfXLogShortPHD;
 
-	private.datadir = datadir;
-	private.tliIndex = tliIndex;
-	xlogreader = XLogReaderAllocate(&SimpleXLogPageRead, &private);
+	private_data.datadir = datadir;
+	private_data.tliIndex = tliIndex;
+	xlogreader = XLogReaderAllocate(&SimpleXLogPageRead, &private_data);
 	if (xlogreader == NULL)
 		pg_fatal("out of memory\n");
 
@@ -234,7 +234,7 @@ SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
 				   int reqLen, XLogRecPtr targetRecPtr, char *readBuf,
 				   TimeLineID *pageTLI)
 {
-	XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
+	XLogPageReadPrivate *private_data = (XLogPageReadPrivate *) xlogreader->private_data;
 	uint32		targetPageOff;
 	XLogRecPtr	targetSegEnd;
 	XLogSegNo	targetSegNo;
@@ -265,16 +265,16 @@ SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
 		 * be done both forward and backward, consider also switching timeline
 		 * accordingly.
 		 */
-		while (private->tliIndex < targetNentries - 1 &&
-			   targetHistory[private->tliIndex].end < targetSegEnd)
-			private->tliIndex++;
-		while (private->tliIndex > 0 &&
-			   targetHistory[private->tliIndex].begin >= targetSegEnd)
-			private->tliIndex--;
+		while (private_data->tliIndex < targetNentries - 1 &&
+			   targetHistory[private_data->tliIndex].end < targetSegEnd)
+			private_data->tliIndex++;
+		while (private_data->tliIndex > 0 &&
+			   targetHistory[private_data->tliIndex].begin >= targetSegEnd)
+			private_data->tliIndex--;
 
-		XLogFileName(xlogfname, targetHistory[private->tliIndex].tli, xlogreadsegno);
+		XLogFileName(xlogfname, targetHistory[private_data->tliIndex].tli, xlogreadsegno);
 
-		snprintf(xlogfpath, MAXPGPATH, "%s/" XLOGDIR "/%s", private->datadir, xlogfname);
+		snprintf(xlogfpath, MAXPGPATH, "%s/" XLOGDIR "/%s", private_data->datadir, xlogfname);
 
 		xlogreadfd = open(xlogfpath, O_RDONLY | PG_BINARY, 0);
 
@@ -308,7 +308,7 @@ SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
 
 	Assert(targetSegNo == xlogreadsegno);
 
-	*pageTLI = targetHistory[private->tliIndex].tli;
+	*pageTLI = targetHistory[private_data->tliIndex].tli;
 	return XLOG_BLCKSZ;
 }
 
diff --git a/src/bin/pg_waldump/pg_waldump.c b/src/bin/pg_waldump/pg_waldump.c
index f4bfacfe87..e8fa5ba11c 100644
--- a/src/bin/pg_waldump/pg_waldump.c
+++ b/src/bin/pg_waldump/pg_waldump.c
@@ -340,23 +340,23 @@ static int
 XLogDumpReadPage(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen,
 				 XLogRecPtr targetPtr, char *readBuff, TimeLineID *curFileTLI)
 {
-	XLogDumpPrivate *private = state->private_data;
+	XLogDumpPrivate *private_data = state->private_data;
 	int			count = XLOG_BLCKSZ;
 
-	if (private->endptr != InvalidXLogRecPtr)
+	if (private_data->endptr != InvalidXLogRecPtr)
 	{
-		if (targetPagePtr + XLOG_BLCKSZ <= private->endptr)
+		if (targetPagePtr + XLOG_BLCKSZ <= private_data->endptr)
 			count = XLOG_BLCKSZ;
-		else if (targetPagePtr + reqLen <= private->endptr)
-			count = private->endptr - targetPagePtr;
+		else if (targetPagePtr + reqLen <= private_data->endptr)
+			count = private_data->endptr - targetPagePtr;
 		else
 		{
-			private->endptr_reached = true;
+			private_data->endptr_reached = true;
 			return -1;
 		}
 	}
 
-	XLogDumpXLogRead(private->inpath, private->timeline, targetPagePtr,
+	XLogDumpXLogRead(private_data->inpath, private_data->timeline, targetPagePtr,
 					 readBuff, count);
 
 	return count;
@@ -710,7 +710,7 @@ main(int argc, char **argv)
 	uint32		xlogid;
 	uint32		xrecoff;
 	XLogReaderState *xlogreader_state;
-	XLogDumpPrivate private;
+	XLogDumpPrivate private_data;
 	XLogDumpConfig config;
 	XLogDumpStats stats;
 	XLogRecord *record;
@@ -739,14 +739,14 @@ main(int argc, char **argv)
 	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_waldump"));
 	progname = get_progname(argv[0]);
 
-	memset(&private, 0, sizeof(XLogDumpPrivate));
+	memset(&private_data, 0, sizeof(XLogDumpPrivate));
 	memset(&config, 0, sizeof(XLogDumpConfig));
 	memset(&stats, 0, sizeof(XLogDumpStats));
 
-	private.timeline = 1;
-	private.startptr = InvalidXLogRecPtr;
-	private.endptr = InvalidXLogRecPtr;
-	private.endptr_reached = false;
+	private_data.timeline = 1;
+	private_data.startptr = InvalidXLogRecPtr;
+	private_data.endptr = InvalidXLogRecPtr;
+	private_data.endptr_reached = false;
 
 	config.bkp_details = false;
 	config.stop_after_records = -1;
@@ -779,7 +779,7 @@ main(int argc, char **argv)
 							progname, optarg);
 					goto bad_argument;
 				}
-				private.endptr = (uint64) xlogid << 32 | xrecoff;
+				private_data.endptr = (uint64) xlogid << 32 | xrecoff;
 				break;
 			case 'f':
 				config.follow = true;
@@ -797,7 +797,7 @@ main(int argc, char **argv)
 				}
 				break;
 			case 'p':
-				private.inpath = pg_strdup(optarg);
+				private_data.inpath = pg_strdup(optarg);
 				break;
 			case 'r':
 				{
@@ -834,10 +834,10 @@ main(int argc, char **argv)
 					goto bad_argument;
 				}
 				else
-					private.startptr = (uint64) xlogid << 32 | xrecoff;
+					private_data.startptr = (uint64) xlogid << 32 | xrecoff;
 				break;
 			case 't':
-				if (sscanf(optarg, "%d", &private.timeline) != 1)
+				if (sscanf(optarg, "%d", &private_data.timeline) != 1)
 				{
 					fprintf(stderr, _("%s: could not parse timeline \"%s\"\n"),
 							progname, optarg);
@@ -885,14 +885,14 @@ main(int argc, char **argv)
 		goto bad_argument;
 	}
 
-	if (private.inpath != NULL)
+	if (private_data.inpath != NULL)
 	{
 		/* validate path points to directory */
-		if (!verify_directory(private.inpath))
+		if (!verify_directory(private_data.inpath))
 		{
 			fprintf(stderr,
 					_("%s: path \"%s\" cannot be opened: %s\n"),
-					progname, private.inpath, strerror(errno));
+					progname, private_data.inpath, strerror(errno));
 			goto bad_argument;
 		}
 	}
@@ -907,39 +907,39 @@ main(int argc, char **argv)
 
 		split_path(argv[optind], &directory, &fname);
 
-		if (private.inpath == NULL && directory != NULL)
+		if (private_data.inpath == NULL && directory != NULL)
 		{
-			private.inpath = directory;
+			private_data.inpath = directory;
 
-			if (!verify_directory(private.inpath))
+			if (!verify_directory(private_data.inpath))
 				fatal_error("cannot open directory \"%s\": %s",
-							private.inpath, strerror(errno));
+							private_data.inpath, strerror(errno));
 		}
 
-		fd = fuzzy_open_file(private.inpath, fname);
+		fd = fuzzy_open_file(private_data.inpath, fname);
 		if (fd < 0)
 			fatal_error("could not open file \"%s\"", fname);
 		close(fd);
 
 		/* parse position from file */
-		XLogFromFileName(fname, &private.timeline, &segno);
+		XLogFromFileName(fname, &private_data.timeline, &segno);
 
-		if (XLogRecPtrIsInvalid(private.startptr))
-			XLogSegNoOffsetToRecPtr(segno, 0, private.startptr);
-		else if (!XLByteInSeg(private.startptr, segno))
+		if (XLogRecPtrIsInvalid(private_data.startptr))
+			XLogSegNoOffsetToRecPtr(segno, 0, private_data.startptr);
+		else if (!XLByteInSeg(private_data.startptr, segno))
 		{
 			fprintf(stderr,
 					_("%s: start log position %X/%X is not inside file \"%s\"\n"),
 					progname,
-					(uint32) (private.startptr >> 32),
-					(uint32) private.startptr,
+					(uint32) (private_data.startptr >> 32),
+					(uint32) private_data.startptr,
 					fname);
 			goto bad_argument;
 		}
 
 		/* no second file specified, set end position */
-		if (!(optind + 1 < argc) && XLogRecPtrIsInvalid(private.endptr))
-			XLogSegNoOffsetToRecPtr(segno + 1, 0, private.endptr);
+		if (!(optind + 1 < argc) && XLogRecPtrIsInvalid(private_data.endptr))
+			XLogSegNoOffsetToRecPtr(segno + 1, 0, private_data.endptr);
 
 		/* parse ENDSEG if passed */
 		if (optind + 1 < argc)
@@ -949,41 +949,41 @@ main(int argc, char **argv)
 			/* ignore directory, already have that */
 			split_path(argv[optind + 1], &directory, &fname);
 
-			fd = fuzzy_open_file(private.inpath, fname);
+			fd = fuzzy_open_file(private_data.inpath, fname);
 			if (fd < 0)
 				fatal_error("could not open file \"%s\"", fname);
 			close(fd);
 
 			/* parse position from file */
-			XLogFromFileName(fname, &private.timeline, &endsegno);
+			XLogFromFileName(fname, &private_data.timeline, &endsegno);
 
 			if (endsegno < segno)
 				fatal_error("ENDSEG %s is before STARTSEG %s",
 							argv[optind + 1], argv[optind]);
 
-			if (XLogRecPtrIsInvalid(private.endptr))
-				XLogSegNoOffsetToRecPtr(endsegno + 1, 0, private.endptr);
+			if (XLogRecPtrIsInvalid(private_data.endptr))
+				XLogSegNoOffsetToRecPtr(endsegno + 1, 0, private_data.endptr);
 
 			/* set segno to endsegno for check of --end */
 			segno = endsegno;
 		}
 
 
-		if (!XLByteInSeg(private.endptr, segno) &&
-			private.endptr != (segno + 1) * XLogSegSize)
+		if (!XLByteInSeg(private_data.endptr, segno) &&
+			private_data.endptr != (segno + 1) * XLogSegSize)
 		{
 			fprintf(stderr,
 					_("%s: end log position %X/%X is not inside file \"%s\"\n"),
 					progname,
-					(uint32) (private.endptr >> 32),
-					(uint32) private.endptr,
+					(uint32) (private_data.endptr >> 32),
+					(uint32) private_data.endptr,
 					argv[argc - 1]);
 			goto bad_argument;
 		}
 	}
 
 	/* we don't know what to print */
-	if (XLogRecPtrIsInvalid(private.startptr))
+	if (XLogRecPtrIsInvalid(private_data.startptr))
 	{
 		fprintf(stderr, _("%s: no start log position given.\n"), progname);
 		goto bad_argument;
@@ -992,28 +992,28 @@ main(int argc, char **argv)
 	/* done with argument parsing, do the actual work */
 
 	/* we have everything we need, start reading */
-	xlogreader_state = XLogReaderAllocate(XLogDumpReadPage, &private);
+	xlogreader_state = XLogReaderAllocate(XLogDumpReadPage, &private_data);
 	if (!xlogreader_state)
 		fatal_error("out of memory");
 
 	/* first find a valid recptr to start from */
-	first_record = XLogFindNextRecord(xlogreader_state, private.startptr);
+	first_record = XLogFindNextRecord(xlogreader_state, private_data.startptr);
 
 	if (first_record == InvalidXLogRecPtr)
 		fatal_error("could not find a valid record after %X/%X",
-					(uint32) (private.startptr >> 32),
-					(uint32) private.startptr);
+					(uint32) (private_data.startptr >> 32),
+					(uint32) private_data.startptr);
 
 	/*
 	 * Display a message that we're skipping data if `from` wasn't a pointer
 	 * to the start of a record and also wasn't a pointer to the beginning of
 	 * a segment (e.g. we were used in file mode).
 	 */
-	if (first_record != private.startptr && (private.startptr % XLogSegSize) != 0)
+	if (first_record != private_data.startptr && (private_data.startptr % XLogSegSize) != 0)
 		printf(_("first record is after %X/%X, at %X/%X, skipping over %u bytes\n"),
-			   (uint32) (private.startptr >> 32), (uint32) private.startptr,
+			   (uint32) (private_data.startptr >> 32), (uint32) private_data.startptr,
 			   (uint32) (first_record >> 32), (uint32) first_record,
-			   (uint32) (first_record - private.startptr));
+			   (uint32) (first_record - private_data.startptr));
 
 	for (;;)
 	{
@@ -1021,7 +1021,7 @@ main(int argc, char **argv)
 		record = XLogReadRecord(xlogreader_state, first_record, &errormsg);
 		if (!record)
 		{
-			if (!config.follow || private.endptr_reached)
+			if (!config.follow || private_data.endptr_reached)
 				break;
 			else
 			{
diff --git a/src/bin/pgbench/exprparse.y b/src/bin/pgbench/exprparse.y
index b3a2d9bfd3..fc8fa231c9 100644
--- a/src/bin/pgbench/exprparse.y
+++ b/src/bin/pgbench/exprparse.y
@@ -22,7 +22,7 @@ static PgBenchExprList *make_elist(PgBenchExpr *exp, PgBenchExprList *list);
 static PgBenchExpr *make_integer_constant(int64 ival);
 static PgBenchExpr *make_double_constant(double dval);
 static PgBenchExpr *make_variable(char *varname);
-static PgBenchExpr *make_op(yyscan_t yyscanner, const char *operator,
+static PgBenchExpr *make_op(yyscan_t yyscanner, const char *oper,
 		PgBenchExpr *lexpr, PgBenchExpr *rexpr);
 static int	find_func(yyscan_t yyscanner, const char *fname);
 static PgBenchExpr *make_func(yyscan_t yyscanner, int fnumber, PgBenchExprList *args);
@@ -120,10 +120,10 @@ make_variable(char *varname)
 }
 
 static PgBenchExpr *
-make_op(yyscan_t yyscanner, const char *operator,
+make_op(yyscan_t yyscanner, const char *oper,
 		PgBenchExpr *lexpr, PgBenchExpr *rexpr)
 {
-	return make_func(yyscanner, find_func(yyscanner, operator),
+	return make_func(yyscanner, find_func(yyscanner, oper),
 					 make_elist(rexpr, make_elist(lexpr, NULL)));
 }
 
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index ddad71a10f..cbd2908f38 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -97,10 +97,10 @@ typedef struct SchemaQuery
 	const char *viscondition;
 
 	/*
-	 * Namespace --- name of field to join to pg_namespace.oid. For example,
+	 * Namespaceatt --- name of field to join to pg_namespace.oid. For example,
 	 * "c.relnamespace".
 	 */
-	const char *namespace;
+	const char *namespaceatt;
 
 	/*
 	 * Result --- the appropriately-quoted name to return, in the case of an
@@ -348,7 +348,7 @@ static const SchemaQuery Query_for_list_of_aggregates = {
 	"p.proisagg",
 	/* viscondition */
 	"pg_catalog.pg_function_is_visible(p.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"p.pronamespace",
 	/* result */
 	"pg_catalog.quote_ident(p.proname)",
@@ -365,7 +365,7 @@ static const SchemaQuery Query_for_list_of_datatypes = {
 	"AND t.typname !~ '^_'",
 	/* viscondition */
 	"pg_catalog.pg_type_is_visible(t.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"t.typnamespace",
 	/* result */
 	"pg_catalog.format_type(t.oid, NULL)",
@@ -380,7 +380,7 @@ static const SchemaQuery Query_for_list_of_domains = {
 	"t.typtype = 'd'",
 	/* viscondition */
 	"pg_catalog.pg_type_is_visible(t.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"t.typnamespace",
 	/* result */
 	"pg_catalog.quote_ident(t.typname)",
@@ -395,7 +395,7 @@ static const SchemaQuery Query_for_list_of_functions = {
 	NULL,
 	/* viscondition */
 	"pg_catalog.pg_function_is_visible(p.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"p.pronamespace",
 	/* result */
 	"pg_catalog.quote_ident(p.proname)",
@@ -410,7 +410,7 @@ static const SchemaQuery Query_for_list_of_indexes = {
 	"c.relkind IN ('i')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -425,7 +425,7 @@ static const SchemaQuery Query_for_list_of_sequences = {
 	"c.relkind IN ('S')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -440,7 +440,7 @@ static const SchemaQuery Query_for_list_of_foreign_tables = {
 	"c.relkind IN ('f')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -455,7 +455,7 @@ static const SchemaQuery Query_for_list_of_tables = {
 	"c.relkind IN ('r', 'P')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -470,7 +470,7 @@ static const SchemaQuery Query_for_list_of_partitioned_tables = {
 	"c.relkind IN ('P')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -485,7 +485,7 @@ static const SchemaQuery Query_for_list_of_constraints_with_schema = {
 	"c.conrelid <> 0",
 	/* viscondition */
 	"true",						/* there is no pg_constraint_is_visible */
-	/* namespace */
+	/* namespaceatt */
 	"c.connamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.conname)",
@@ -501,7 +501,7 @@ static const SchemaQuery Query_for_list_of_updatables = {
 	"c.relkind IN ('r', 'f', 'v', 'P')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -516,7 +516,7 @@ static const SchemaQuery Query_for_list_of_relations = {
 	NULL,
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -531,7 +531,7 @@ static const SchemaQuery Query_for_list_of_tsvmf = {
 	"c.relkind IN ('r', 'S', 'v', 'm', 'f', 'P')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -546,7 +546,7 @@ static const SchemaQuery Query_for_list_of_tmf = {
 	"c.relkind IN ('r', 'm', 'f')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -561,7 +561,7 @@ static const SchemaQuery Query_for_list_of_tm = {
 	"c.relkind IN ('r', 'm')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -576,7 +576,7 @@ static const SchemaQuery Query_for_list_of_views = {
 	"c.relkind IN ('v')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -591,7 +591,7 @@ static const SchemaQuery Query_for_list_of_matviews = {
 	"c.relkind IN ('m')",
 	/* viscondition */
 	"pg_catalog.pg_table_is_visible(c.oid)",
-	/* namespace */
+	/* namespaceatt */
 	"c.relnamespace",
 	/* result */
 	"pg_catalog.quote_ident(c.relname)",
@@ -3645,7 +3645,7 @@ _complete_from_query(int is_schema_query, const char *text, int state)
 							  "WHERE %s = n.oid AND ",
 							  qualresult,
 							  completion_squery->catname,
-							  completion_squery->namespace);
+							  completion_squery->namespaceatt);
 			if (completion_squery->selcondition)
 				appendPQExpBuffer(&query_buffer, "%s AND ",
 								  completion_squery->selcondition);
diff --git a/src/bin/scripts/createdb.c b/src/bin/scripts/createdb.c
index 88ea401e39..0011505fde 100644
--- a/src/bin/scripts/createdb.c
+++ b/src/bin/scripts/createdb.c
@@ -53,7 +53,7 @@ main(int argc, char *argv[])
 	bool		echo = false;
 	char	   *owner = NULL;
 	char	   *tablespace = NULL;
-	char	   *template = NULL;
+	char	   *templatedb = NULL;
 	char	   *encoding = NULL;
 	char	   *lc_collate = NULL;
 	char	   *lc_ctype = NULL;
@@ -98,7 +98,7 @@ main(int argc, char *argv[])
 				tablespace = pg_strdup(optarg);
 				break;
 			case 'T':
-				template = pg_strdup(optarg);
+				templatedb = pg_strdup(optarg);
 				break;
 			case 'E':
 				encoding = pg_strdup(optarg);
@@ -188,8 +188,8 @@ main(int argc, char *argv[])
 		appendPQExpBuffer(&sql, " TABLESPACE %s", fmtId(tablespace));
 	if (encoding)
 		appendPQExpBuffer(&sql, " ENCODING '%s'", encoding);
-	if (template)
-		appendPQExpBuffer(&sql, " TEMPLATE %s", fmtId(template));
+	if (templatedb)
+		appendPQExpBuffer(&sql, " TEMPLATE %s", fmtId(templatedb));
 	if (lc_collate)
 		appendPQExpBuffer(&sql, " LC_COLLATE '%s'", lc_collate);
 	if (lc_ctype)
diff --git a/src/interfaces/ecpg/compatlib/informix.c b/src/interfaces/ecpg/compatlib/informix.c
index e50aa5ec65..79e2889f5f 100644
--- a/src/interfaces/ecpg/compatlib/informix.c
+++ b/src/interfaces/ecpg/compatlib/informix.c
@@ -181,17 +181,17 @@ ecpg_strndup(const char *str, size_t len)
 	size_t		real_len = strlen(str);
 	int			use_len = (int) ((real_len > len) ? len : real_len);
 
-	char	   *new = malloc(use_len + 1);
+	char	   *newstr = malloc(use_len + 1);
 
-	if (new)
+	if (newstr)
 	{
-		memcpy(new, str, use_len);
-		new[use_len] = '\0';
+		memcpy(newstr, str, use_len);
+		newstr[use_len] = '\0';
 	}
 	else
 		errno = ENOMEM;
 
-	return new;
+	return newstr;
 }
 
 int
diff --git a/src/interfaces/ecpg/ecpglib/connect.c b/src/interfaces/ecpg/ecpglib/connect.c
index c90f13dc6c..e8ee7ddadd 100644
--- a/src/interfaces/ecpg/ecpglib/connect.c
+++ b/src/interfaces/ecpg/ecpglib/connect.c
@@ -272,7 +272,7 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 {
 	struct sqlca_t *sqlca = ECPGget_sqlca();
 	enum COMPAT_MODE compat = c;
-	struct connection *this;
+	struct connection *conn;
 	int			i,
 				connect_params = 0;
 	char	   *dbname = name ? ecpg_strdup(name, lineno) : NULL,
@@ -334,7 +334,7 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 		return false;
 	}
 
-	if ((this = (struct connection *) ecpg_alloc(sizeof(struct connection), lineno)) == NULL)
+	if ((conn = (struct connection *) ecpg_alloc(sizeof(struct connection), lineno)) == NULL)
 	{
 		ecpg_free(dbname);
 		return false;
@@ -411,7 +411,7 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 								ecpg_free(realname);
 							if (dbname)
 								ecpg_free(dbname);
-							free(this);
+							free(conn);
 							return false;
 						}
 					}
@@ -438,7 +438,7 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 							ecpg_free(realname);
 						if (dbname)
 							ecpg_free(dbname);
-						free(this);
+						free(conn);
 						return false;
 					}
 				}
@@ -489,19 +489,19 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 	pthread_mutex_lock(&connections_mutex);
 #endif
 	if (connection_name != NULL)
-		this->name = ecpg_strdup(connection_name, lineno);
+		conn->name = ecpg_strdup(connection_name, lineno);
 	else
-		this->name = ecpg_strdup(realname, lineno);
+		conn->name = ecpg_strdup(realname, lineno);
 
-	this->cache_head = NULL;
-	this->prep_stmts = NULL;
+	conn->cache_head = NULL;
+	conn->prep_stmts = NULL;
 
 	if (all_connections == NULL)
-		this->next = NULL;
+		conn->next = NULL;
 	else
-		this->next = all_connections;
+		conn->next = all_connections;
 
-	all_connections = this;
+	all_connections = conn;
 #ifdef ENABLE_THREAD_SAFETY
 	pthread_setspecific(actual_connection_key, all_connections);
 #endif
@@ -544,7 +544,7 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 			ecpg_free(conn_keywords);
 		if (conn_values)
 			ecpg_free(conn_values);
-		free(this);
+		free(conn);
 		return false;
 	}
 
@@ -619,7 +619,7 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 	}
 	conn_keywords[i] = NULL;	/* terminator */
 
-	this->connection = PQconnectdbParams(conn_keywords, conn_values, 0);
+	conn->connection = PQconnectdbParams(conn_keywords, conn_values, 0);
 
 	if (host)
 		ecpg_free(host);
@@ -632,14 +632,14 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 	ecpg_free(conn_values);
 	ecpg_free(conn_keywords);
 
-	if (PQstatus(this->connection) == CONNECTION_BAD)
+	if (PQstatus(conn->connection) == CONNECTION_BAD)
 	{
-		const char *errmsg = PQerrorMessage(this->connection);
+		const char *errmsg = PQerrorMessage(conn->connection);
 		const char *db = realname ? realname : ecpg_gettext("<DEFAULT>");
 
 		ecpg_log("ECPGconnect: could not open database: %s\n", errmsg);
 
-		ecpg_finish(this);
+		ecpg_finish(conn);
 #ifdef ENABLE_THREAD_SAFETY
 		pthread_mutex_unlock(&connections_mutex);
 #endif
@@ -658,9 +658,9 @@ ECPGconnect(int lineno, int c, const char *name, const char *user, const char *p
 	pthread_mutex_unlock(&connections_mutex);
 #endif
 
-	this->autocommit = autocommit;
+	conn->autocommit = autocommit;
 
-	PQsetNoticeReceiver(this->connection, &ECPGnoticeReceiver, (void *) this);
+	PQsetNoticeReceiver(conn->connection, &ECPGnoticeReceiver, (void *) conn);
 
 	return true;
 }
diff --git a/src/interfaces/ecpg/ecpglib/descriptor.c b/src/interfaces/ecpg/ecpglib/descriptor.c
index 15fd7a08a5..79a8e4bea5 100644
--- a/src/interfaces/ecpg/ecpglib/descriptor.c
+++ b/src/interfaces/ecpg/ecpglib/descriptor.c
@@ -758,7 +758,7 @@ descriptor_deallocate_all(struct descriptor * list)
 bool
 ECPGallocate_desc(int line, const char *name)
 {
-	struct descriptor *new;
+	struct descriptor *newdesc;
 	struct sqlca_t *sqlca = ECPGget_sqlca();
 
 	if (sqlca == NULL)
@@ -769,28 +769,28 @@ ECPGallocate_desc(int line, const char *name)
 	}
 
 	ecpg_init_sqlca(sqlca);
-	new = (struct descriptor *) ecpg_alloc(sizeof(struct descriptor), line);
-	if (!new)
+	newdesc = (struct descriptor *) ecpg_alloc(sizeof(struct descriptor), line);
+	if (!newdesc)
 		return false;
-	new->next = get_descriptors();
-	new->name = ecpg_alloc(strlen(name) + 1, line);
-	if (!new->name)
+	newdesc->next = get_descriptors();
+	newdesc->name = ecpg_alloc(strlen(name) + 1, line);
+	if (!newdesc->name)
 	{
-		ecpg_free(new);
+		ecpg_free(newdesc);
 		return false;
 	}
-	new->count = -1;
-	new->items = NULL;
-	new->result = PQmakeEmptyPGresult(NULL, 0);
-	if (!new->result)
+	newdesc->count = -1;
+	newdesc->items = NULL;
+	newdesc->result = PQmakeEmptyPGresult(NULL, 0);
+	if (!newdesc->result)
 	{
-		ecpg_free(new->name);
-		ecpg_free(new);
+		ecpg_free(newdesc->name);
+		ecpg_free(newdesc);
 		ecpg_raise(line, ECPG_OUT_OF_MEMORY, ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY, NULL);
 		return false;
 	}
-	strcpy(new->name, name);
-	set_descriptors(new);
+	strcpy(newdesc->name, name);
+	set_descriptors(newdesc);
 	return true;
 }
 
diff --git a/src/interfaces/ecpg/ecpglib/memory.c b/src/interfaces/ecpg/ecpglib/memory.c
index 9c1d20efc5..82a97b17e2 100644
--- a/src/interfaces/ecpg/ecpglib/memory.c
+++ b/src/interfaces/ecpg/ecpglib/memory.c
@@ -18,47 +18,47 @@ ecpg_free(void *ptr)
 char *
 ecpg_alloc(long size, int lineno)
 {
-	char	   *new = (char *) calloc(1L, size);
+	char	   *newval = (char *) calloc(1L, size);
 
-	if (!new)
+	if (!newval)
 	{
 		ecpg_raise(lineno, ECPG_OUT_OF_MEMORY, ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY, NULL);
 		return NULL;
 	}
 
-	return (new);
+	return (newval);
 }
 
 char *
 ecpg_realloc(void *ptr, long size, int lineno)
 {
-	char	   *new = (char *) realloc(ptr, size);
+	char	   *newval = (char *) realloc(ptr, size);
 
-	if (!new)
+	if (!newval)
 	{
 		ecpg_raise(lineno, ECPG_OUT_OF_MEMORY, ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY, NULL);
 		return NULL;
 	}
 
-	return (new);
+	return (newval);
 }
 
 char *
 ecpg_strdup(const char *string, int lineno)
 {
-	char	   *new;
+	char	   *newval;
 
 	if (string == NULL)
 		return NULL;
 
-	new = strdup(string);
-	if (!new)
+	newval = strdup(string);
+	if (!newval)
 	{
 		ecpg_raise(lineno, ECPG_OUT_OF_MEMORY, ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY, NULL);
 		return NULL;
 	}
 
-	return (new);
+	return (newval);
 }
 
 /* keep a list of memory we allocated for the user */
diff --git a/src/interfaces/ecpg/ecpglib/prepare.c b/src/interfaces/ecpg/ecpglib/prepare.c
index 983b242d06..b10b6a8943 100644
--- a/src/interfaces/ecpg/ecpglib/prepare.c
+++ b/src/interfaces/ecpg/ecpglib/prepare.c
@@ -28,7 +28,7 @@ static const int stmtCacheEntPerBucket = 8;		/* # entries/bucket		*/
 static stmtCacheEntry stmtCacheEntries[16384] = {{0, {0}, 0, 0, 0}};
 
 static bool deallocate_one(int lineno, enum COMPAT_MODE c, struct connection * con,
-		 struct prepared_statement * prev, struct prepared_statement * this);
+		 struct prepared_statement * prev, struct prepared_statement * prep);
 
 static bool
 isvarchar(unsigned char c)
@@ -103,18 +103,18 @@ static bool
 prepare_common(int lineno, struct connection * con, const char *name, const char *variable)
 {
 	struct statement *stmt;
-	struct prepared_statement *this;
+	struct prepared_statement *prep;
 	PGresult   *query;
 
 	/* allocate new statement */
-	this = (struct prepared_statement *) ecpg_alloc(sizeof(struct prepared_statement), lineno);
-	if (!this)
+	prep = (struct prepared_statement *) ecpg_alloc(sizeof(struct prepared_statement), lineno);
+	if (!prep)
 		return false;
 
 	stmt = (struct statement *) ecpg_alloc(sizeof(struct statement), lineno);
 	if (!stmt)
 	{
-		ecpg_free(this);
+		ecpg_free(prep);
 		return false;
 	}
 
@@ -128,30 +128,30 @@ prepare_common(int lineno, struct connection * con, const char *name, const char
 	replace_variables(&(stmt->command), lineno);
 
 	/* add prepared statement to our list */
-	this->name = ecpg_strdup(name, lineno);
-	this->stmt = stmt;
+	prep->name = ecpg_strdup(name, lineno);
+	prep->stmt = stmt;
 
 	/* and finally really prepare the statement */
 	query = PQprepare(stmt->connection->connection, name, stmt->command, 0, NULL);
 	if (!ecpg_check_PQresult(query, stmt->lineno, stmt->connection->connection, stmt->compat))
 	{
 		ecpg_free(stmt->command);
-		ecpg_free(this->name);
-		ecpg_free(this);
+		ecpg_free(prep->name);
+		ecpg_free(prep);
 		ecpg_free(stmt);
 		return false;
 	}
 
 	ecpg_log("prepare_common on line %d: name %s; query: \"%s\"\n", stmt->lineno, name, stmt->command);
 	PQclear(query);
-	this->prepared = true;
+	prep->prepared = true;
 
 	if (con->prep_stmts == NULL)
-		this->next = NULL;
+		prep->next = NULL;
 	else
-		this->next = con->prep_stmts;
+		prep->next = con->prep_stmts;
 
-	con->prep_stmts = this;
+	con->prep_stmts = prep;
 	return true;
 }
 
@@ -161,7 +161,7 @@ bool
 ECPGprepare(int lineno, const char *connection_name, const bool questionmarks, const char *name, const char *variable)
 {
 	struct connection *con;
-	struct prepared_statement *this,
+	struct prepared_statement *prep,
 			   *prev;
 
 	(void) questionmarks;		/* quiet the compiler */
@@ -171,8 +171,8 @@ ECPGprepare(int lineno, const char *connection_name, const bool questionmarks, c
 		return false;
 
 	/* check if we already have prepared this statement */
-	this = ecpg_find_prepared_statement(name, con, &prev);
-	if (this && !deallocate_one(lineno, ECPG_COMPAT_PGSQL, con, prev, this))
+	prep = ecpg_find_prepared_statement(name, con, &prev);
+	if (prep && !deallocate_one(lineno, ECPG_COMPAT_PGSQL, con, prev, prep))
 		return false;
 
 	return prepare_common(lineno, con, name, variable);
@@ -182,42 +182,42 @@ struct prepared_statement *
 ecpg_find_prepared_statement(const char *name,
 				 struct connection * con, struct prepared_statement ** prev_)
 {
-	struct prepared_statement *this,
+	struct prepared_statement *prep,
 			   *prev;
 
-	for (this = con->prep_stmts, prev = NULL; this != NULL; prev = this, this = this->next)
+	for (prep = con->prep_stmts, prev = NULL; prep != NULL; prev = prep, prep = prep->next)
 	{
-		if (strcmp(this->name, name) == 0)
+		if (strcmp(prep->name, name) == 0)
 		{
 			if (prev_)
 				*prev_ = prev;
-			return this;
+			return prep;
 		}
 	}
 	return NULL;
 }
 
 static bool
-deallocate_one(int lineno, enum COMPAT_MODE c, struct connection * con, struct prepared_statement * prev, struct prepared_statement * this)
+deallocate_one(int lineno, enum COMPAT_MODE c, struct connection * con, struct prepared_statement * prev, struct prepared_statement * prep)
 {
 	bool		r = false;
 
-	ecpg_log("deallocate_one on line %d: name %s\n", lineno, this->name);
+	ecpg_log("deallocate_one on line %d: name %s\n", lineno, prep->name);
 
 	/* first deallocate the statement in the backend */
-	if (this->prepared)
+	if (prep->prepared)
 	{
 		char	   *text;
 		PGresult   *query;
 
-		text = (char *) ecpg_alloc(strlen("deallocate \"\" ") + strlen(this->name), this->stmt->lineno);
+		text = (char *) ecpg_alloc(strlen("deallocate \"\" ") + strlen(prep->name), prep->stmt->lineno);
 
 		if (text)
 		{
-			sprintf(text, "deallocate \"%s\"", this->name);
-			query = PQexec(this->stmt->connection->connection, text);
+			sprintf(text, "deallocate \"%s\"", prep->name);
+			query = PQexec(prep->stmt->connection->connection, text);
 			ecpg_free(text);
-			if (ecpg_check_PQresult(query, lineno, this->stmt->connection->connection, this->stmt->compat))
+			if (ecpg_check_PQresult(query, lineno, prep->stmt->connection->connection, prep->stmt->compat))
 			{
 				PQclear(query);
 				r = true;
@@ -231,20 +231,20 @@ deallocate_one(int lineno, enum COMPAT_MODE c, struct connection * con, struct p
 	 */
 	if (!r && !INFORMIX_MODE(c))
 	{
-		ecpg_raise(lineno, ECPG_INVALID_STMT, ECPG_SQLSTATE_INVALID_SQL_STATEMENT_NAME, this->name);
+		ecpg_raise(lineno, ECPG_INVALID_STMT, ECPG_SQLSTATE_INVALID_SQL_STATEMENT_NAME, prep->name);
 		return false;
 	}
 
 	/* okay, free all the resources */
-	ecpg_free(this->stmt->command);
-	ecpg_free(this->stmt);
-	ecpg_free(this->name);
+	ecpg_free(prep->stmt->command);
+	ecpg_free(prep->stmt);
+	ecpg_free(prep->name);
 	if (prev != NULL)
-		prev->next = this->next;
+		prev->next = prep->next;
 	else
-		con->prep_stmts = this->next;
+		con->prep_stmts = prep->next;
 
-	ecpg_free(this);
+	ecpg_free(prep);
 	return true;
 }
 
@@ -253,7 +253,7 @@ bool
 ECPGdeallocate(int lineno, int c, const char *connection_name, const char *name)
 {
 	struct connection *con;
-	struct prepared_statement *this,
+	struct prepared_statement *prep,
 			   *prev;
 
 	con = ecpg_get_connection(connection_name);
@@ -261,9 +261,9 @@ ECPGdeallocate(int lineno, int c, const char *connection_name, const char *name)
 	if (!ecpg_init(con, connection_name, lineno))
 		return false;
 
-	this = ecpg_find_prepared_statement(name, con, &prev);
-	if (this)
-		return deallocate_one(lineno, c, con, prev, this);
+	prep = ecpg_find_prepared_statement(name, con, &prev);
+	if (prep)
+		return deallocate_one(lineno, c, con, prev, prep);
 
 	/* prepared statement is not found */
 	if (INFORMIX_MODE(c))
@@ -294,10 +294,10 @@ ECPGdeallocate_all(int lineno, int compat, const char *connection_name)
 char *
 ecpg_prepared(const char *name, struct connection * con)
 {
-	struct prepared_statement *this;
+	struct prepared_statement *prep;
 
-	this = ecpg_find_prepared_statement(name, con, NULL);
-	return this ? this->stmt->command : NULL;
+	prep = ecpg_find_prepared_statement(name, con, NULL);
+	return prep ? prep->stmt->command : NULL;
 }
 
 /* return the prepared statement */
@@ -384,7 +384,7 @@ ecpg_freeStmtCacheEntry(int lineno, int compat, int entNo)		/* entry # to free *
 {
 	stmtCacheEntry *entry;
 	struct connection *con;
-	struct prepared_statement *this,
+	struct prepared_statement *prep,
 			   *prev;
 
 	entry = &stmtCacheEntries[entNo];
@@ -394,8 +394,8 @@ ecpg_freeStmtCacheEntry(int lineno, int compat, int entNo)		/* entry # to free *
 	con = ecpg_get_connection(entry->connection);
 
 	/* free the 'prepared_statement' list entry		  */
-	this = ecpg_find_prepared_statement(entry->stmtID, con, &prev);
-	if (this && !deallocate_one(lineno, compat, con, prev, this))
+	prep = ecpg_find_prepared_statement(entry->stmtID, con, &prev);
+	if (prep && !deallocate_one(lineno, compat, con, prev, prep))
 		return (-1);
 
 	entry->stmtID[0] = '\0';
diff --git a/src/interfaces/ecpg/pgtypeslib/common.c b/src/interfaces/ecpg/pgtypeslib/common.c
index 9084fd06b4..d49fbb13ed 100644
--- a/src/interfaces/ecpg/pgtypeslib/common.c
+++ b/src/interfaces/ecpg/pgtypeslib/common.c
@@ -8,21 +8,21 @@
 char *
 pgtypes_alloc(long size)
 {
-	char	   *new = (char *) calloc(1L, size);
+	char	   *newval = (char *) calloc(1L, size);
 
-	if (!new)
+	if (!newval)
 		errno = ENOMEM;
-	return (new);
+	return (newval);
 }
 
 char *
 pgtypes_strdup(const char *str)
 {
-	char	   *new = (char *) strdup(str);
+	char	   *newval = (char *) strdup(str);
 
-	if (!new)
+	if (!newval)
 		errno = ENOMEM;
-	return (new);
+	return (newval);
 }
 
 int
diff --git a/src/interfaces/ecpg/preproc/descriptor.c b/src/interfaces/ecpg/preproc/descriptor.c
index c6442c1805..00e22c8173 100644
--- a/src/interfaces/ecpg/preproc/descriptor.c
+++ b/src/interfaces/ecpg/preproc/descriptor.c
@@ -20,13 +20,13 @@ static struct assignment *assignments;
 void
 push_assignment(char *var, enum ECPGdtype value)
 {
-	struct assignment *new = (struct assignment *) mm_alloc(sizeof(struct assignment));
+	struct assignment *newa = (struct assignment *) mm_alloc(sizeof(struct assignment));
 
-	new->next = assignments;
-	new->variable = mm_alloc(strlen(var) + 1);
-	strcpy(new->variable, var);
-	new->value = value;
-	assignments = new;
+	newa->next = assignments;
+	newa->variable = mm_alloc(strlen(var) + 1);
+	strcpy(newa->variable, var);
+	newa->value = value;
+	assignments = newa;
 }
 
 static void
@@ -75,24 +75,24 @@ static struct descriptor *descriptors;
 void
 add_descriptor(char *name, char *connection)
 {
-	struct descriptor *new;
+	struct descriptor *newd;
 
 	if (name[0] != '"')
 		return;
 
-	new = (struct descriptor *) mm_alloc(sizeof(struct descriptor));
+	newd = (struct descriptor *) mm_alloc(sizeof(struct descriptor));
 
-	new->next = descriptors;
-	new->name = mm_alloc(strlen(name) + 1);
-	strcpy(new->name, name);
+	newd->next = descriptors;
+	newd->name = mm_alloc(strlen(name) + 1);
+	strcpy(newd->name, name);
 	if (connection)
 	{
-		new->connection = mm_alloc(strlen(connection) + 1);
-		strcpy(new->connection, connection);
+		newd->connection = mm_alloc(strlen(connection) + 1);
+		strcpy(newd->connection, connection);
 	}
 	else
-		new->connection = connection;
-	descriptors = new;
+		newd->connection = connection;
+	descriptors = newd;
 }
 
 void
diff --git a/src/interfaces/ecpg/preproc/ecpg.addons b/src/interfaces/ecpg/preproc/ecpg.addons
index ca3efadc48..ff991de6bf 100644
--- a/src/interfaces/ecpg/preproc/ecpg.addons
+++ b/src/interfaces/ecpg/preproc/ecpg.addons
@@ -287,7 +287,7 @@ ECPG: ExecuteStmtEXECUTEprepared_nameexecute_param_clauseexecute_rest block
 	{ $$ = $2; }
 ECPG: DeclareCursorStmtDECLAREcursor_namecursor_optionsCURSORopt_holdFORSelectStmt block
 	{
-		struct cursor *ptr, *this;
+		struct cursor *ptr, *cursor;
 		char *cursor_marker = $2[0] == ':' ? mm_strdup("$0") : mm_strdup($2);
 		char *comment, *c1, *c2;
 		int (* strcmp_fn)(const char *, const char *) = (($2[0] == ':' || $2[0] == '"') ? strcmp : pg_strcasecmp);
@@ -303,22 +303,22 @@ ECPG: DeclareCursorStmtDECLAREcursor_namecursor_optionsCURSORopt_holdFORSelectSt
 			}
 		}
 
-		this = (struct cursor *) mm_alloc(sizeof(struct cursor));
+		cursor = (struct cursor *) mm_alloc(sizeof(struct cursor));
 
-		this->next = cur;
-		this->name = $2;
-		this->function = (current_function ? mm_strdup(current_function) : NULL);
-		this->connection = connection;
-		this->opened = false;
-		this->command =  cat_str(7, mm_strdup("declare"), cursor_marker, $3, mm_strdup("cursor"), $5, mm_strdup("for"), $7);
-		this->argsinsert = argsinsert;
-		this->argsinsert_oos = NULL;
-		this->argsresult = argsresult;
-		this->argsresult_oos = NULL;
+		cursor->next = cur;
+		cursor->name = $2;
+		cursor->function = (current_function ? mm_strdup(current_function) : NULL);
+		cursor->connection = connection;
+		cursor->opened = false;
+		cursor->command =  cat_str(7, mm_strdup("declare"), cursor_marker, $3, mm_strdup("cursor"), $5, mm_strdup("for"), $7);
+		cursor->argsinsert = argsinsert;
+		cursor->argsinsert_oos = NULL;
+		cursor->argsresult = argsresult;
+		cursor->argsresult_oos = NULL;
 		argsinsert = argsresult = NULL;
-		cur = this;
+		cur = cursor;
 
-		c1 = mm_strdup(this->command);
+		c1 = mm_strdup(cursor->command);
 		if ((c2 = strstr(c1, "*/")) != NULL)
 		{
 			/* We put this text into a comment, so we better remove [*][/]. */
@@ -328,11 +328,11 @@ ECPG: DeclareCursorStmtDECLAREcursor_namecursor_optionsCURSORopt_holdFORSelectSt
 		comment = cat_str(3, mm_strdup("/*"), c1, mm_strdup("*/"));
 
 		if ((braces_open > 0) && INFORMIX_MODE) /* we're in a function */
-			$$ = cat_str(3, adjust_outofscope_cursor_vars(this),
+			$$ = cat_str(3, adjust_outofscope_cursor_vars(cursor),
 				mm_strdup("ECPG_informix_reset_sqlca();"),
 				comment);
 		else
-			$$ = cat2_str(adjust_outofscope_cursor_vars(this), comment);
+			$$ = cat2_str(adjust_outofscope_cursor_vars(cursor), comment);
 	}
 ECPG: ClosePortalStmtCLOSEcursor_name block
 	{
diff --git a/src/interfaces/ecpg/preproc/ecpg.c b/src/interfaces/ecpg/preproc/ecpg.c
index aaecbf8122..19b41604b6 100644
--- a/src/interfaces/ecpg/preproc/ecpg.c
+++ b/src/interfaces/ecpg/preproc/ecpg.c
@@ -65,18 +65,18 @@ static void
 add_include_path(char *path)
 {
 	struct _include_path *ip = include_paths,
-			   *new;
+			   *newpath;
 
-	new = mm_alloc(sizeof(struct _include_path));
-	new->path = path;
-	new->next = NULL;
+	newpath = mm_alloc(sizeof(struct _include_path));
+	newpath->path = path;
+	newpath->next = NULL;
 
 	if (ip == NULL)
-		include_paths = new;
+		include_paths = newpath;
 	else
 	{
 		for (; ip->next != NULL; ip = ip->next);
-		ip->next = new;
+		ip->next = newpath;
 	}
 }
 
@@ -98,13 +98,13 @@ add_preprocessor_define(char *define)
 		/* symbol has a value */
 		for (tmp = ptr - 1; *tmp == ' '; tmp--);
 		tmp[1] = '\0';
-		defines->old = define_copy;
-		defines->new = ptr + 1;
+		defines->oldval = define_copy;
+		defines->newval = ptr + 1;
 	}
 	else
 	{
-		defines->old = define_copy;
-		defines->new = mm_strdup("1");
+		defines->oldval = define_copy;
+		defines->newval = mm_strdup("1");
 	}
 	defines->pertinent = true;
 	defines->used = NULL;
@@ -345,7 +345,7 @@ main(int argc, char *const argv[])
 				/* remove old cursor definitions if any are still there */
 				for (ptr = cur; ptr != NULL;)
 				{
-					struct cursor *this = ptr;
+					struct cursor *c = ptr;
 					struct arguments *l1,
 							   *l2;
 
@@ -363,7 +363,7 @@ main(int argc, char *const argv[])
 						free(l1);
 					}
 					ptr = ptr->next;
-					free(this);
+					free(c);
 				}
 				cur = NULL;
 
@@ -373,35 +373,35 @@ main(int argc, char *const argv[])
 					defptr = defines;
 					defines = defines->next;
 
-					free(defptr->new);
-					free(defptr->old);
+					free(defptr->newval);
+					free(defptr->oldval);
 					free(defptr);
 				}
 
 				for (defptr = defines; defptr != NULL; defptr = defptr->next)
 				{
-					struct _defines *this = defptr->next;
+					struct _defines *d = defptr->next;
 
-					if (this && !this->pertinent)
+					if (d && !d->pertinent)
 					{
-						defptr->next = this->next;
+						defptr->next = d->next;
 
-						free(this->new);
-						free(this->old);
-						free(this);
+						free(d->newval);
+						free(d->oldval);
+						free(d);
 					}
 				}
 
 				/* and old typedefs */
 				for (typeptr = types; typeptr != NULL;)
 				{
-					struct typedefs *this = typeptr;
+					struct typedefs *td = typeptr;
 
 					free(typeptr->name);
 					ECPGfree_struct_member(typeptr->struct_member_list);
 					free(typeptr->type);
 					typeptr = typeptr->next;
-					free(this);
+					free(td);
 				}
 				types = NULL;
 
diff --git a/src/interfaces/ecpg/preproc/ecpg.header b/src/interfaces/ecpg/preproc/ecpg.header
index 2562366bbe..151dbe6f10 100644
--- a/src/interfaces/ecpg/preproc/ecpg.header
+++ b/src/interfaces/ecpg/preproc/ecpg.header
@@ -528,7 +528,7 @@ add_typedef(char *name, char *dimension, char *length, enum ECPGttype type_enum,
 			char *type_dimension, char *type_index, int initializer, int array)
 {
 	/* add entry to list */
-	struct typedefs *ptr, *this;
+	struct typedefs *ptr, *td;
 
 	if ((type_enum == ECPGt_struct ||
 		 type_enum == ECPGt_union) &&
@@ -546,29 +546,29 @@ add_typedef(char *name, char *dimension, char *length, enum ECPGttype type_enum,
 		}
 		adjust_array(type_enum, &dimension, &length, type_dimension, type_index, array, true);
 
-		this = (struct typedefs *) mm_alloc(sizeof(struct typedefs));
+		td = (struct typedefs *) mm_alloc(sizeof(struct typedefs));
 
 		/* initial definition */
-		this->next = types;
-		this->name = name;
-		this->brace_level = braces_open;
-		this->type = (struct this_type *) mm_alloc(sizeof(struct this_type));
-		this->type->type_enum = type_enum;
-		this->type->type_str = mm_strdup(name);
-		this->type->type_dimension = dimension; /* dimension of array */
-		this->type->type_index = length;	/* length of string */
-		this->type->type_sizeof = ECPGstruct_sizeof;
-		this->struct_member_list = (type_enum == ECPGt_struct || type_enum == ECPGt_union) ?
+		td->next = types;
+		td->name = name;
+		td->brace_level = braces_open;
+		td->type = (struct this_type *) mm_alloc(sizeof(struct this_type));
+		td->type->type_enum = type_enum;
+		td->type->type_str = mm_strdup(name);
+		td->type->type_dimension = dimension; /* dimension of array */
+		td->type->type_index = length;	/* length of string */
+		td->type->type_sizeof = ECPGstruct_sizeof;
+		td->struct_member_list = (type_enum == ECPGt_struct || type_enum == ECPGt_union) ?
 		ECPGstruct_member_dup(struct_member_list[struct_level]) : NULL;
 
 		if (type_enum != ECPGt_varchar &&
 			type_enum != ECPGt_char &&
 			type_enum != ECPGt_unsigned_char &&
 			type_enum != ECPGt_string &&
-			atoi(this->type->type_index) >= 0)
+			atoi(td->type->type_index) >= 0)
 			mmerror(PARSE_ERROR, ET_ERROR, "multidimensional arrays for simple data types are not supported");
 
-		types = this;
+		types = td;
 	}
 }
 %}
diff --git a/src/interfaces/ecpg/preproc/ecpg.trailer b/src/interfaces/ecpg/preproc/ecpg.trailer
index 1c108795de..44971d9180 100644
--- a/src/interfaces/ecpg/preproc/ecpg.trailer
+++ b/src/interfaces/ecpg/preproc/ecpg.trailer
@@ -289,7 +289,7 @@ prepared_name: name
  */
 ECPGCursorStmt:  DECLARE cursor_name cursor_options CURSOR opt_hold FOR prepared_name
 		{
-			struct cursor *ptr, *this;
+			struct cursor *ptr, *cursor;
 			char *cursor_marker = $2[0] == ':' ? mm_strdup("$0") : mm_strdup($2);
 			int (* strcmp_fn)(const char *, const char *) = (($2[0] == ':' || $2[0] == '"') ? strcmp : pg_strcasecmp);
 			struct variable *thisquery = (struct variable *)mm_alloc(sizeof(struct variable));
@@ -308,16 +308,16 @@ ECPGCursorStmt:  DECLARE cursor_name cursor_options CURSOR opt_hold FOR prepared
 				}
 			}
 
-			this = (struct cursor *) mm_alloc(sizeof(struct cursor));
+			cursor = (struct cursor *) mm_alloc(sizeof(struct cursor));
 
 			/* initial definition */
-			this->next = cur;
-			this->name = $2;
-			this->function = (current_function ? mm_strdup(current_function) : NULL);
-			this->connection = connection;
-			this->command =  cat_str(6, mm_strdup("declare"), cursor_marker, $3, mm_strdup("cursor"), $5, mm_strdup("for $1"));
-			this->argsresult = NULL;
-			this->argsresult_oos = NULL;
+			cursor->next = cur;
+			cursor->name = $2;
+			cursor->function = (current_function ? mm_strdup(current_function) : NULL);
+			cursor->connection = connection;
+			cursor->command =  cat_str(6, mm_strdup("declare"), cursor_marker, $3, mm_strdup("cursor"), $5, mm_strdup("for $1"));
+			cursor->argsresult = NULL;
+			cursor->argsresult_oos = NULL;
 
 			thisquery->type = &ecpg_query;
 			thisquery->brace_level = 0;
@@ -325,26 +325,26 @@ ECPGCursorStmt:  DECLARE cursor_name cursor_options CURSOR opt_hold FOR prepared
 			thisquery->name = (char *) mm_alloc(sizeof("ECPGprepared_statement(, , __LINE__)") + strlen(con) + strlen($7));
 			sprintf(thisquery->name, "ECPGprepared_statement(%s, %s, __LINE__)", con, $7);
 
-			this->argsinsert = NULL;
-			this->argsinsert_oos = NULL;
+			cursor->argsinsert = NULL;
+			cursor->argsinsert_oos = NULL;
 			if ($2[0] == ':')
 			{
 				struct variable *var = find_variable($2 + 1);
 				remove_variable_from_list(&argsinsert, var);
-				add_variable_to_head(&(this->argsinsert), var, &no_indicator);
+				add_variable_to_head(&(cursor->argsinsert), var, &no_indicator);
 			}
-			add_variable_to_head(&(this->argsinsert), thisquery, &no_indicator);
+			add_variable_to_head(&(cursor->argsinsert), thisquery, &no_indicator);
 
-			cur = this;
+			cur = cursor;
 
-			comment = cat_str(3, mm_strdup("/*"), mm_strdup(this->command), mm_strdup("*/"));
+			comment = cat_str(3, mm_strdup("/*"), mm_strdup(cursor->command), mm_strdup("*/"));
 
 			if ((braces_open > 0) && INFORMIX_MODE) /* we're in a function */
-				$$ = cat_str(3, adjust_outofscope_cursor_vars(this),
+				$$ = cat_str(3, adjust_outofscope_cursor_vars(cursor),
 					mm_strdup("ECPG_informix_reset_sqlca();"),
 					comment);
 			else
-				$$ = cat2_str(adjust_outofscope_cursor_vars(this), comment);
+				$$ = cat2_str(adjust_outofscope_cursor_vars(cursor), comment);
 		}
 		;
 
@@ -625,25 +625,25 @@ var_type:	simple_type
 			else
 			{
 				/* this is for typedef'ed types */
-				struct typedefs *this = get_typedef($1);
-
-				$$.type_str = (this->type->type_enum == ECPGt_varchar) ? EMPTY : mm_strdup(this->name);
-				$$.type_enum = this->type->type_enum;
-				$$.type_dimension = this->type->type_dimension;
-				$$.type_index = this->type->type_index;
-				if (this->type->type_sizeof && strlen(this->type->type_sizeof) != 0)
-					$$.type_sizeof = this->type->type_sizeof;
+				struct typedefs *td = get_typedef($1);
+
+				$$.type_str = (td->type->type_enum == ECPGt_varchar) ? EMPTY : mm_strdup(td->name);
+				$$.type_enum = td->type->type_enum;
+				$$.type_dimension = td->type->type_dimension;
+				$$.type_index = td->type->type_index;
+				if (td->type->type_sizeof && strlen(td->type->type_sizeof) != 0)
+					$$.type_sizeof = td->type->type_sizeof;
 				else
-					$$.type_sizeof = cat_str(3, mm_strdup("sizeof("), mm_strdup(this->name), mm_strdup(")"));
+					$$.type_sizeof = cat_str(3, mm_strdup("sizeof("), mm_strdup(td->name), mm_strdup(")"));
 
-				struct_member_list[struct_level] = ECPGstruct_member_dup(this->struct_member_list);
+				struct_member_list[struct_level] = ECPGstruct_member_dup(td->struct_member_list);
 			}
 		}
 		| s_struct_union_symbol
 		{
 			/* this is for named structs/unions */
 			char *name;
-			struct typedefs *this;
+			struct typedefs *td;
 			bool forward = (forward_name != NULL && strcmp($1.symbol, forward_name) == 0 && strcmp($1.su, "struct") == 0);
 
 			name = cat2_str($1.su, $1.symbol);
@@ -652,13 +652,13 @@ var_type:	simple_type
 			{
 				/* No */
 
-				this = get_typedef(name);
-				$$.type_str = mm_strdup(this->name);
-				$$.type_enum = this->type->type_enum;
-				$$.type_dimension = this->type->type_dimension;
-				$$.type_index = this->type->type_index;
-				$$.type_sizeof = this->type->type_sizeof;
-				struct_member_list[struct_level] = ECPGstruct_member_dup(this->struct_member_list);
+				td = get_typedef(name);
+				$$.type_str = mm_strdup(td->name);
+				$$.type_enum = td->type->type_enum;
+				$$.type_dimension = td->type->type_dimension;
+				$$.type_index = td->type->type_index;
+				$$.type_sizeof = td->type->type_sizeof;
+				struct_member_list[struct_level] = ECPGstruct_member_dup(td->struct_member_list);
 				free(name);
 			}
 			else
@@ -693,7 +693,7 @@ struct_union_type_with_symbol: s_struct_union_symbol
 		}
 		'{' variable_declarations '}'
 		{
-			struct typedefs *ptr, *this;
+			struct typedefs *ptr, *td;
 			struct this_type su_type;
 
 			ECPGfree_struct_member(struct_member_list[struct_level]);
@@ -716,21 +716,21 @@ struct_union_type_with_symbol: s_struct_union_symbol
 							mmerror(PARSE_ERROR, ET_ERROR, "type \"%s\" is already defined", su_type.type_str);
 			}
 
-			this = (struct typedefs *) mm_alloc(sizeof(struct typedefs));
+			td = (struct typedefs *) mm_alloc(sizeof(struct typedefs));
 
 			/* initial definition */
-			this->next = types;
-			this->name = mm_strdup(su_type.type_str);
-			this->brace_level = braces_open;
-			this->type = (struct this_type *) mm_alloc(sizeof(struct this_type));
-			this->type->type_enum = su_type.type_enum;
-			this->type->type_str = mm_strdup(su_type.type_str);
-			this->type->type_dimension = mm_strdup("-1"); /* dimension of array */
-			this->type->type_index = mm_strdup("-1");	/* length of string */
-			this->type->type_sizeof = ECPGstruct_sizeof;
-			this->struct_member_list = struct_member_list[struct_level];
-
-			types = this;
+			td->next = types;
+			td->name = mm_strdup(su_type.type_str);
+			td->brace_level = braces_open;
+			td->type = (struct this_type *) mm_alloc(sizeof(struct this_type));
+			td->type->type_enum = su_type.type_enum;
+			td->type->type_str = mm_strdup(su_type.type_str);
+			td->type->type_dimension = mm_strdup("-1"); /* dimension of array */
+			td->type->type_index = mm_strdup("-1");	/* length of string */
+			td->type->type_sizeof = ECPGstruct_sizeof;
+			td->struct_member_list = struct_member_list[struct_level];
+
+			types = td;
 			$$ = cat_str(4, su_type.type_str, mm_strdup("{"), $4, mm_strdup("}"));
 		}
 		;
diff --git a/src/interfaces/ecpg/preproc/pgc.l b/src/interfaces/ecpg/preproc/pgc.l
index 6b58dd5afe..eeabcd970a 100644
--- a/src/interfaces/ecpg/preproc/pgc.l
+++ b/src/interfaces/ecpg/preproc/pgc.l
@@ -954,14 +954,14 @@ cppline			{space}*#([^i][A-Za-z]*|{if}|{ifdef}|{ifndef}|{import})((\/\*[^*/]*\*+
 
 					for (ptr = defines; ptr != NULL; ptr2 = ptr, ptr = ptr->next)
 					{
-						if (strcmp(yytext, ptr->old) == 0)
+						if (strcmp(yytext, ptr->oldval) == 0)
 						{
 							if (ptr2 == NULL)
 								defines = ptr->next;
 							else
 								ptr2->next = ptr->next;
-							free(ptr->new);
-							free(ptr->old);
+							free(ptr->newval);
+							free(ptr->oldval);
 							free(ptr);
 							break;
 						}
@@ -1140,7 +1140,7 @@ cppline			{space}*#([^i][A-Za-z]*|{if}|{ifdef}|{ifndef}|{import})((\/\*[^*/]*\*+
 						yytext[i+1] = '\0';
 
 						for (defptr = defines;
-							 defptr != NULL && strcmp(yytext, defptr->old) != 0;
+							 defptr != NULL && strcmp(yytext, defptr->oldval) != 0;
 							 defptr = defptr->next);
 
 						preproc_tos++;
@@ -1169,26 +1169,26 @@ cppline			{space}*#([^i][A-Za-z]*|{if}|{ifdef}|{ifndef}|{import})((\/\*[^*/]*\*+
 				yyterminate();
 			}
 <def>{space}*";"	{
-						struct _defines *ptr, *this;
+						struct _defines *ptr, *d;
 
 						for (ptr = defines; ptr != NULL; ptr = ptr->next)
 						{
-							 if (strcmp(old, ptr->old) == 0)
+							 if (strcmp(old, ptr->oldval) == 0)
 							 {
-								free(ptr->new);
-								ptr->new = mm_strdup(literalbuf);
+								free(ptr->newval);
+								ptr->newval = mm_strdup(literalbuf);
 							 }
 						}
 						if (ptr == NULL)
 						{
-							this = (struct _defines *) mm_alloc(sizeof(struct _defines));
+							d = (struct _defines *) mm_alloc(sizeof(struct _defines));
 
 							/* initial definition */
-							this->old = old;
-							this->new = mm_strdup(literalbuf);
-							this->next = defines;
-							this->used = NULL;
-							defines = this;
+							d->oldval = old;
+							d->newval = mm_strdup(literalbuf);
+							d->next = defines;
+							d->used = NULL;
+							defines = d;
 						}
 
 						BEGIN(C);
@@ -1426,7 +1426,7 @@ static bool isdefine(void)
 	/* is it a define? */
 	for (ptr = defines; ptr; ptr = ptr->next)
 	{
-		if (strcmp(yytext, ptr->old) == 0 && ptr->used == NULL)
+		if (strcmp(yytext, ptr->oldval) == 0 && ptr->used == NULL)
 		{
 			struct _yy_buffer *yb;
 
@@ -1439,7 +1439,7 @@ static bool isdefine(void)
 
 			ptr->used = yy_buffer = yb;
 
-			yy_scan_string(ptr->new);
+			yy_scan_string(ptr->newval);
 			return true;
 		}
 	}
@@ -1449,16 +1449,16 @@ static bool isdefine(void)
 
 static bool isinformixdefine(void)
 {
-	const char *new = NULL;
+	const char *newstr = NULL;
 
 	if (strcmp(yytext, "dec_t") == 0)
-		new = "decimal";
+		newstr = "decimal";
 	else if (strcmp(yytext, "intrvl_t") == 0)
-		new = "interval";
+		newstr = "interval";
 	else if (strcmp(yytext, "dtime_t") == 0)
-		new = "timestamp";
+		newstr = "timestamp";
 
-	if (new)
+	if (newstr)
 	{
 		struct _yy_buffer *yb;
 
@@ -1470,7 +1470,7 @@ static bool isinformixdefine(void)
 		yb->next = yy_buffer;
 		yy_buffer = yb;
 
-		yy_scan_string(new);
+		yy_scan_string(newstr);
 		return true;
 	}
 
diff --git a/src/interfaces/ecpg/preproc/type.c b/src/interfaces/ecpg/preproc/type.c
index 0b84b8d3c4..9e4455fb70 100644
--- a/src/interfaces/ecpg/preproc/type.c
+++ b/src/interfaces/ecpg/preproc/type.c
@@ -24,19 +24,19 @@ mm_alloc(size_t size)
 char *
 mm_strdup(const char *string)
 {
-	char	   *new = strdup(string);
+	char	   *newstr = strdup(string);
 
-	if (new == NULL)
+	if (newstr == NULL)
 		mmfatal(OUT_OF_MEMORY, "out of memory");
 
-	return new;
+	return newstr;
 }
 
 /* duplicate memberlist */
 struct ECPGstruct_member *
 ECPGstruct_member_dup(struct ECPGstruct_member * rm)
 {
-	struct ECPGstruct_member *new = NULL;
+	struct ECPGstruct_member *newval = NULL;
 
 	while (rm)
 	{
@@ -64,12 +64,12 @@ ECPGstruct_member_dup(struct ECPGstruct_member * rm)
 				break;
 		}
 
-		ECPGmake_struct_member(rm->name, type, &new);
+		ECPGmake_struct_member(rm->name, type, &newval);
 
 		rm = rm->next;
 	}
 
-	return (new);
+	return (newval);
 }
 
 /* The NAME argument is copied. The type argument is preserved as a pointer. */
diff --git a/src/interfaces/ecpg/preproc/type.h b/src/interfaces/ecpg/preproc/type.h
index cd0d1da8c4..3fadf35ba0 100644
--- a/src/interfaces/ecpg/preproc/type.h
+++ b/src/interfaces/ecpg/preproc/type.h
@@ -147,8 +147,8 @@ struct typedefs
 
 struct _defines
 {
-	char	   *old;
-	char	   *new;
+	char	   *oldval;
+	char	   *newval;
 	int			pertinent;
 	void	   *used;
 	struct _defines *next;
diff --git a/src/interfaces/ecpg/preproc/variable.c b/src/interfaces/ecpg/preproc/variable.c
index 232b940938..ccd3165123 100644
--- a/src/interfaces/ecpg/preproc/variable.c
+++ b/src/interfaces/ecpg/preproc/variable.c
@@ -391,18 +391,18 @@ void
 add_variable_to_tail(struct arguments ** list, struct variable * var, struct variable * ind)
 {
 	struct arguments *p,
-			   *new = (struct arguments *) mm_alloc(sizeof(struct arguments));
+			   *newa = (struct arguments *) mm_alloc(sizeof(struct arguments));
 
 	for (p = *list; p && p->next; p = p->next);
 
-	new->variable = var;
-	new->indicator = ind;
-	new->next = NULL;
+	newa->variable = var;
+	newa->indicator = ind;
+	newa->next = NULL;
 
 	if (p)
-		p->next = new;
+		p->next = newa;
 	else
-		*list = new;
+		*list = newa;
 }
 
 void
@@ -499,13 +499,13 @@ check_indicator(struct ECPGtype * var)
 struct typedefs *
 get_typedef(char *name)
 {
-	struct typedefs *this;
+	struct typedefs *td;
 
-	for (this = types; this && strcmp(this->name, name) != 0; this = this->next);
-	if (!this)
+	for (td = types; td && strcmp(td->name, name) != 0; td = td->next);
+	if (!td)
 		mmfatal(PARSE_ERROR, "unrecognized data type name \"%s\"", name);
 
-	return (this);
+	return (td);
 }
 
 void
diff --git a/src/pl/plpgsql/src/pl_comp.c b/src/pl/plpgsql/src/pl_comp.c
index b25b3f1de0..4fa7ecd459 100644
--- a/src/pl/plpgsql/src/pl_comp.c
+++ b/src/pl/plpgsql/src/pl_comp.c
@@ -981,25 +981,25 @@ add_dummy_return(PLpgSQL_function *function)
 	 */
 	if (function->action->exceptions != NULL)
 	{
-		PLpgSQL_stmt_block *new;
+		PLpgSQL_stmt_block *newblock;
 
-		new = palloc0(sizeof(PLpgSQL_stmt_block));
-		new->cmd_type = PLPGSQL_STMT_BLOCK;
-		new->body = list_make1(function->action);
+		newblock = palloc0(sizeof(PLpgSQL_stmt_block));
+		newblock->cmd_type = PLPGSQL_STMT_BLOCK;
+		newblock->body = list_make1(function->action);
 
-		function->action = new;
+		function->action = newblock;
 	}
 	if (function->action->body == NIL ||
 		((PLpgSQL_stmt *) llast(function->action->body))->cmd_type != PLPGSQL_STMT_RETURN)
 	{
-		PLpgSQL_stmt_return *new;
+		PLpgSQL_stmt_return *newstmt;
 
-		new = palloc0(sizeof(PLpgSQL_stmt_return));
-		new->cmd_type = PLPGSQL_STMT_RETURN;
-		new->expr = NULL;
-		new->retvarno = function->out_param_varno;
+		newstmt = palloc0(sizeof(PLpgSQL_stmt_return));
+		newstmt->cmd_type = PLPGSQL_STMT_RETURN;
+		newstmt->expr = NULL;
+		newstmt->retvarno = function->out_param_varno;
 
-		function->action->body = lappend(function->action->body, new);
+		function->action->body = lappend(function->action->body, newstmt);
 	}
 }
 
@@ -1450,16 +1450,16 @@ plpgsql_parse_dblword(char *word1, char *word2,
 						 * datum whether it is or not --- any error will be
 						 * detected later.
 						 */
-						PLpgSQL_recfield *new;
+						PLpgSQL_recfield *newfield;
 
-						new = palloc(sizeof(PLpgSQL_recfield));
-						new->dtype = PLPGSQL_DTYPE_RECFIELD;
-						new->fieldname = pstrdup(word2);
-						new->recparentno = ns->itemno;
+						newfield = palloc(sizeof(PLpgSQL_recfield));
+						newfield->dtype = PLPGSQL_DTYPE_RECFIELD;
+						newfield->fieldname = pstrdup(word2);
+						newfield->recparentno = ns->itemno;
 
-						plpgsql_adddatum((PLpgSQL_datum *) new);
+						plpgsql_adddatum((PLpgSQL_datum *) newfield);
 
-						wdatum->datum = (PLpgSQL_datum *) new;
+						wdatum->datum = (PLpgSQL_datum *) newfield;
 					}
 					else
 					{
@@ -1561,16 +1561,16 @@ plpgsql_parse_tripword(char *word1, char *word2, char *word3,
 						 * words 1/2 are a record name, so third word could be
 						 * a field in this record.
 						 */
-						PLpgSQL_recfield *new;
+						PLpgSQL_recfield *newfield;
 
-						new = palloc(sizeof(PLpgSQL_recfield));
-						new->dtype = PLPGSQL_DTYPE_RECFIELD;
-						new->fieldname = pstrdup(word3);
-						new->recparentno = ns->itemno;
+						newfield = palloc(sizeof(PLpgSQL_recfield));
+						newfield->dtype = PLPGSQL_DTYPE_RECFIELD;
+						newfield->fieldname = pstrdup(word3);
+						newfield->recparentno = ns->itemno;
 
-						plpgsql_adddatum((PLpgSQL_datum *) new);
+						plpgsql_adddatum((PLpgSQL_datum *) newfield);
 
-						wdatum->datum = (PLpgSQL_datum *) new;
+						wdatum->datum = (PLpgSQL_datum *) newfield;
 						wdatum->ident = NULL;
 						wdatum->quoted = false; /* not used */
 						wdatum->idents = idents;
@@ -2258,8 +2258,8 @@ PLpgSQL_condition *
 plpgsql_parse_err_condition(char *condname)
 {
 	int			i;
-	PLpgSQL_condition *new;
-	PLpgSQL_condition *prev;
+	PLpgSQL_condition *newcond;
+	PLpgSQL_condition *prevcond;
 
 	/*
 	 * XXX Eventually we will want to look for user-defined exception names
@@ -2272,33 +2272,33 @@ plpgsql_parse_err_condition(char *condname)
 	 */
 	if (strcmp(condname, "others") == 0)
 	{
-		new = palloc(sizeof(PLpgSQL_condition));
-		new->sqlerrstate = 0;
-		new->condname = condname;
-		new->next = NULL;
-		return new;
+		newcond = palloc(sizeof(PLpgSQL_condition));
+		newcond->sqlerrstate = 0;
+		newcond->condname = condname;
+		newcond->next = NULL;
+		return newcond;
 	}
 
-	prev = NULL;
+	prevcond = NULL;
 	for (i = 0; exception_label_map[i].label != NULL; i++)
 	{
 		if (strcmp(condname, exception_label_map[i].label) == 0)
 		{
-			new = palloc(sizeof(PLpgSQL_condition));
-			new->sqlerrstate = exception_label_map[i].sqlerrstate;
-			new->condname = condname;
-			new->next = prev;
-			prev = new;
+			newcond = palloc(sizeof(PLpgSQL_condition));
+			newcond->sqlerrstate = exception_label_map[i].sqlerrstate;
+			newcond->condname = condname;
+			newcond->next = prevcond;
+			prevcond = newcond;
 		}
 	}
 
-	if (!prev)
+	if (!prevcond)
 		ereport(ERROR,
 				(errcode(ERRCODE_UNDEFINED_OBJECT),
 				 errmsg("unrecognized exception condition \"%s\"",
 						condname)));
 
-	return prev;
+	return prevcond;
 }
 
 /* ----------
@@ -2323,7 +2323,7 @@ plpgsql_start_datums(void)
  * ----------
  */
 void
-plpgsql_adddatum(PLpgSQL_datum *new)
+plpgsql_adddatum(PLpgSQL_datum *newdatum)
 {
 	if (plpgsql_nDatums == datums_alloc)
 	{
@@ -2331,8 +2331,8 @@ plpgsql_adddatum(PLpgSQL_datum *new)
 		plpgsql_Datums = repalloc(plpgsql_Datums, sizeof(PLpgSQL_datum *) * datums_alloc);
 	}
 
-	new->dno = plpgsql_nDatums;
-	plpgsql_Datums[plpgsql_nDatums++] = new;
+	newdatum->dno = plpgsql_nDatums;
+	plpgsql_Datums[plpgsql_nDatums++] = newdatum;
 }
 
 /* ----------
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index 6fc3db07fe..7faad24d37 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -246,7 +246,7 @@ static void exec_assign_value(PLpgSQL_execstate *estate,
 				  Oid valtype, int32 valtypmod);
 static void exec_eval_datum(PLpgSQL_execstate *estate,
 				PLpgSQL_datum *datum,
-				Oid *typeid,
+				Oid *typid,
 				int32 *typetypmod,
 				Datum *value,
 				bool *isnull);
@@ -1032,29 +1032,29 @@ copy_plpgsql_datum(PLpgSQL_datum *datum)
 	{
 		case PLPGSQL_DTYPE_VAR:
 			{
-				PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
+				PLpgSQL_var *newvar = palloc(sizeof(PLpgSQL_var));
 
-				memcpy(new, datum, sizeof(PLpgSQL_var));
+				memcpy(newvar, datum, sizeof(PLpgSQL_var));
 				/* should be preset to null/non-freeable */
-				Assert(new->isnull);
-				Assert(!new->freeval);
+				Assert(newvar->isnull);
+				Assert(!newvar->freeval);
 
-				result = (PLpgSQL_datum *) new;
+				result = (PLpgSQL_datum *) newvar;
 			}
 			break;
 
 		case PLPGSQL_DTYPE_REC:
 			{
-				PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
+				PLpgSQL_rec *newrec = palloc(sizeof(PLpgSQL_rec));
 
-				memcpy(new, datum, sizeof(PLpgSQL_rec));
+				memcpy(newrec, datum, sizeof(PLpgSQL_rec));
 				/* should be preset to null/non-freeable */
-				Assert(new->tup == NULL);
-				Assert(new->tupdesc == NULL);
-				Assert(!new->freetup);
-				Assert(!new->freetupdesc);
+				Assert(newrec->tup == NULL);
+				Assert(newrec->tupdesc == NULL);
+				Assert(!newrec->freetup);
+				Assert(!newrec->freetupdesc);
 
-				result = (PLpgSQL_datum *) new;
+				result = (PLpgSQL_datum *) newrec;
 			}
 			break;
 
@@ -3361,13 +3361,13 @@ exec_stmt_assert(PLpgSQL_execstate *estate, PLpgSQL_stmt_assert *stmt)
 		if (stmt->message != NULL)
 		{
 			Datum		val;
-			Oid			typeid;
+			Oid			typid;
 			int32		typmod;
 
 			val = exec_eval_expr(estate, stmt->message,
-								 &isnull, &typeid, &typmod);
+								 &isnull, &typid, &typmod);
 			if (!isnull)
-				message = convert_value_to_string(estate, val, typeid);
+				message = convert_value_to_string(estate, val, typid);
 			/* we mustn't do exec_eval_cleanup here */
 		}
 
@@ -4823,7 +4823,7 @@ exec_assign_value(PLpgSQL_execstate *estate,
 static void
 exec_eval_datum(PLpgSQL_execstate *estate,
 				PLpgSQL_datum *datum,
-				Oid *typeid,
+				Oid *typid,
 				int32 *typetypmod,
 				Datum *value,
 				bool *isnull)
@@ -4836,7 +4836,7 @@ exec_eval_datum(PLpgSQL_execstate *estate,
 			{
 				PLpgSQL_var *var = (PLpgSQL_var *) datum;
 
-				*typeid = var->datatype->typoid;
+				*typid = var->datatype->typoid;
 				*typetypmod = var->datatype->atttypmod;
 				*value = var->value;
 				*isnull = var->isnull;
@@ -4856,7 +4856,7 @@ exec_eval_datum(PLpgSQL_execstate *estate,
 				tup = make_tuple_from_row(estate, row, row->rowtupdesc);
 				if (tup == NULL)	/* should not happen */
 					elog(ERROR, "row not compatible with its own tupdesc");
-				*typeid = row->rowtupdesc->tdtypeid;
+				*typid = row->rowtupdesc->tdtypeid;
 				*typetypmod = row->rowtupdesc->tdtypmod;
 				*value = HeapTupleGetDatum(tup);
 				*isnull = false;
@@ -4879,7 +4879,7 @@ exec_eval_datum(PLpgSQL_execstate *estate,
 				BlessTupleDesc(rec->tupdesc);
 
 				oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
-				*typeid = rec->tupdesc->tdtypeid;
+				*typid = rec->tupdesc->tdtypeid;
 				*typetypmod = rec->tupdesc->tdtypmod;
 				*value = heap_copy_tuple_as_datum(rec->tup, rec->tupdesc);
 				*isnull = false;
@@ -4906,7 +4906,7 @@ exec_eval_datum(PLpgSQL_execstate *estate,
 							(errcode(ERRCODE_UNDEFINED_COLUMN),
 							 errmsg("record \"%s\" has no field \"%s\"",
 									rec->refname, recfield->fieldname)));
-				*typeid = SPI_gettypeid(rec->tupdesc, fno);
+				*typid = SPI_gettypeid(rec->tupdesc, fno);
 				if (fno > 0)
 					*typetypmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
 				else
@@ -4932,7 +4932,7 @@ Oid
 plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
 							PLpgSQL_datum *datum)
 {
-	Oid			typeid;
+	Oid			typid;
 
 	switch (datum->dtype)
 	{
@@ -4940,7 +4940,7 @@ plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
 			{
 				PLpgSQL_var *var = (PLpgSQL_var *) datum;
 
-				typeid = var->datatype->typoid;
+				typid = var->datatype->typoid;
 				break;
 			}
 
@@ -4952,7 +4952,7 @@ plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
 					elog(ERROR, "row variable has no tupdesc");
 				/* Make sure we have a valid type/typmod setting */
 				BlessTupleDesc(row->rowtupdesc);
-				typeid = row->rowtupdesc->tdtypeid;
+				typid = row->rowtupdesc->tdtypeid;
 				break;
 			}
 
@@ -4968,7 +4968,7 @@ plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
 						   errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
 				/* Make sure we have a valid type/typmod setting */
 				BlessTupleDesc(rec->tupdesc);
-				typeid = rec->tupdesc->tdtypeid;
+				typid = rec->tupdesc->tdtypeid;
 				break;
 			}
 
@@ -4991,17 +4991,17 @@ plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
 							(errcode(ERRCODE_UNDEFINED_COLUMN),
 							 errmsg("record \"%s\" has no field \"%s\"",
 									rec->refname, recfield->fieldname)));
-				typeid = SPI_gettypeid(rec->tupdesc, fno);
+				typid = SPI_gettypeid(rec->tupdesc, fno);
 				break;
 			}
 
 		default:
 			elog(ERROR, "unrecognized dtype: %d", datum->dtype);
-			typeid = InvalidOid;	/* keep compiler quiet */
+			typid = InvalidOid;	/* keep compiler quiet */
 			break;
 	}
 
-	return typeid;
+	return typid;
 }
 
 /*
@@ -5013,7 +5013,7 @@ plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
 void
 plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
 								 PLpgSQL_datum *datum,
-								 Oid *typeid, int32 *typmod, Oid *collation)
+								 Oid *typid, int32 *typmod, Oid *collation)
 {
 	switch (datum->dtype)
 	{
@@ -5021,7 +5021,7 @@ plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
 			{
 				PLpgSQL_var *var = (PLpgSQL_var *) datum;
 
-				*typeid = var->datatype->typoid;
+				*typid = var->datatype->typoid;
 				*typmod = var->datatype->atttypmod;
 				*collation = var->datatype->collation;
 				break;
@@ -5035,7 +5035,7 @@ plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
 					elog(ERROR, "row variable has no tupdesc");
 				/* Make sure we have a valid type/typmod setting */
 				BlessTupleDesc(row->rowtupdesc);
-				*typeid = row->rowtupdesc->tdtypeid;
+				*typid = row->rowtupdesc->tdtypeid;
 				/* do NOT return the mutable typmod of a RECORD variable */
 				*typmod = -1;
 				/* composite types are never collatable */
@@ -5055,7 +5055,7 @@ plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
 						   errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
 				/* Make sure we have a valid type/typmod setting */
 				BlessTupleDesc(rec->tupdesc);
-				*typeid = rec->tupdesc->tdtypeid;
+				*typid = rec->tupdesc->tdtypeid;
 				/* do NOT return the mutable typmod of a RECORD variable */
 				*typmod = -1;
 				/* composite types are never collatable */
@@ -5082,7 +5082,7 @@ plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
 							(errcode(ERRCODE_UNDEFINED_COLUMN),
 							 errmsg("record \"%s\" has no field \"%s\"",
 									rec->refname, recfield->fieldname)));
-				*typeid = SPI_gettypeid(rec->tupdesc, fno);
+				*typid = SPI_gettypeid(rec->tupdesc, fno);
 				if (fno > 0)
 					*typmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
 				else
@@ -5096,7 +5096,7 @@ plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
 
 		default:
 			elog(ERROR, "unrecognized dtype: %d", datum->dtype);
-			*typeid = InvalidOid;		/* keep compiler quiet */
+			*typid = InvalidOid;		/* keep compiler quiet */
 			*typmod = -1;
 			*collation = InvalidOid;
 			break;
diff --git a/src/pl/plpgsql/src/pl_gram.y b/src/pl/plpgsql/src/pl_gram.y
index 4a4cd6ae26..1c0f763870 100644
--- a/src/pl/plpgsql/src/pl_gram.y
+++ b/src/pl/plpgsql/src/pl_gram.y
@@ -400,22 +400,22 @@ opt_semi		:
 
 pl_block		: decl_sect K_BEGIN proc_sect exception_sect K_END opt_label
 					{
-						PLpgSQL_stmt_block *new;
+						PLpgSQL_stmt_block *newblock;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_block));
+						newblock = palloc0(sizeof(PLpgSQL_stmt_block));
 
-						new->cmd_type	= PLPGSQL_STMT_BLOCK;
-						new->lineno		= plpgsql_location_to_lineno(@2);
-						new->label		= $1.label;
-						new->n_initvars = $1.n_initvars;
-						new->initvarnos = $1.initvarnos;
-						new->body		= $3;
-						new->exceptions	= $4;
+						newblock->cmd_type	 = PLPGSQL_STMT_BLOCK;
+						newblock->lineno	 = plpgsql_location_to_lineno(@2);
+						newblock->label		 = $1.label;
+						newblock->n_initvars = $1.n_initvars;
+						newblock->initvarnos = $1.initvarnos;
+						newblock->body		 = $3;
+						newblock->exceptions = $4;
 
 						check_labels($1.label, $6, @6);
 						plpgsql_ns_pop();
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newblock;
 					}
 				;
 
@@ -542,7 +542,7 @@ decl_statement	: decl_varname decl_const decl_datatype decl_collate decl_notnull
 					{ plpgsql_ns_push($1.name, PLPGSQL_LABEL_OTHER); }
 				  decl_cursor_args decl_is_for decl_cursor_query
 					{
-						PLpgSQL_var *new;
+						PLpgSQL_var *newvar;
 						PLpgSQL_expr *curname_def;
 						char		buf[1024];
 						char		*cp1;
@@ -551,7 +551,7 @@ decl_statement	: decl_varname decl_const decl_datatype decl_collate decl_notnull
 						/* pop local namespace for cursor args */
 						plpgsql_ns_pop();
 
-						new = (PLpgSQL_var *)
+						newvar = (PLpgSQL_var *)
 							plpgsql_build_variable($1.name, $1.lineno,
 												   plpgsql_build_datatype(REFCURSOROID,
 																		  -1,
@@ -562,7 +562,7 @@ decl_statement	: decl_varname decl_const decl_datatype decl_collate decl_notnull
 
 						curname_def->dtype = PLPGSQL_DTYPE_EXPR;
 						strcpy(buf, "SELECT ");
-						cp1 = new->refname;
+						cp1 = newvar->refname;
 						cp2 = buf + strlen(buf);
 						/*
 						 * Don't trust standard_conforming_strings here;
@@ -579,14 +579,14 @@ decl_statement	: decl_varname decl_const decl_datatype decl_collate decl_notnull
 						}
 						strcpy(cp2, "'::pg_catalog.refcursor");
 						curname_def->query = pstrdup(buf);
-						new->default_val = curname_def;
+						newvar->default_val = curname_def;
 
-						new->cursor_explicit_expr = $7;
+						newvar->cursor_explicit_expr = $7;
 						if ($5 == NULL)
-							new->cursor_explicit_argrow = -1;
+							newvar->cursor_explicit_argrow = -1;
 						else
-							new->cursor_explicit_argrow = $5->dno;
-						new->cursor_options = CURSOR_OPT_FAST_PLAN | $2;
+							newvar->cursor_explicit_argrow = $5->dno;
+						newvar->cursor_options = CURSOR_OPT_FAST_PLAN | $2;
 					}
 				;
 
@@ -616,30 +616,30 @@ decl_cursor_args :
 					}
 				| '(' decl_cursor_arglist ')'
 					{
-						PLpgSQL_row *new;
+						PLpgSQL_row *newrow;
 						int i;
 						ListCell *l;
 
-						new = palloc0(sizeof(PLpgSQL_row));
-						new->dtype = PLPGSQL_DTYPE_ROW;
-						new->lineno = plpgsql_location_to_lineno(@1);
-						new->rowtupdesc = NULL;
-						new->nfields = list_length($2);
-						new->fieldnames = palloc(new->nfields * sizeof(char *));
-						new->varnos = palloc(new->nfields * sizeof(int));
+						newrow = palloc0(sizeof(PLpgSQL_row));
+						newrow->dtype = PLPGSQL_DTYPE_ROW;
+						newrow->lineno = plpgsql_location_to_lineno(@1);
+						newrow->rowtupdesc = NULL;
+						newrow->nfields = list_length($2);
+						newrow->fieldnames = palloc(newrow->nfields * sizeof(char *));
+						newrow->varnos = palloc(newrow->nfields * sizeof(int));
 
 						i = 0;
 						foreach (l, $2)
 						{
 							PLpgSQL_variable *arg = (PLpgSQL_variable *) lfirst(l);
-							new->fieldnames[i] = arg->refname;
-							new->varnos[i] = arg->dno;
+							newrow->fieldnames[i] = arg->refname;
+							newrow->varnos[i] = arg->dno;
 							i++;
 						}
 						list_free($2);
 
-						plpgsql_adddatum((PLpgSQL_datum *) new);
-						$$ = (PLpgSQL_datum *) new;
+						plpgsql_adddatum((PLpgSQL_datum *) newrow);
+						$$ = (PLpgSQL_datum *) newrow;
 					}
 				;
 
@@ -900,46 +900,46 @@ proc_stmt		: pl_block ';'
 
 stmt_perform	: K_PERFORM expr_until_semi
 					{
-						PLpgSQL_stmt_perform *new;
+						PLpgSQL_stmt_perform *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_perform));
-						new->cmd_type = PLPGSQL_STMT_PERFORM;
-						new->lineno   = plpgsql_location_to_lineno(@1);
-						new->expr  = $2;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_perform));
+						newstmt->cmd_type = PLPGSQL_STMT_PERFORM;
+						newstmt->lineno   = plpgsql_location_to_lineno(@1);
+						newstmt->expr  = $2;
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
 stmt_assign		: assign_var assign_operator expr_until_semi
 					{
-						PLpgSQL_stmt_assign *new;
+						PLpgSQL_stmt_assign *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_assign));
-						new->cmd_type = PLPGSQL_STMT_ASSIGN;
-						new->lineno   = plpgsql_location_to_lineno(@1);
-						new->varno = $1->dno;
-						new->expr  = $3;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_assign));
+						newstmt->cmd_type = PLPGSQL_STMT_ASSIGN;
+						newstmt->lineno   = plpgsql_location_to_lineno(@1);
+						newstmt->varno = $1->dno;
+						newstmt->expr  = $3;
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
 stmt_getdiag	: K_GET getdiag_area_opt K_DIAGNOSTICS getdiag_list ';'
 					{
-						PLpgSQL_stmt_getdiag	 *new;
+						PLpgSQL_stmt_getdiag	 *newstmt;
 						ListCell		*lc;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_getdiag));
-						new->cmd_type = PLPGSQL_STMT_GETDIAG;
-						new->lineno   = plpgsql_location_to_lineno(@1);
-						new->is_stacked = $2;
-						new->diag_items = $4;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_getdiag));
+						newstmt->cmd_type = PLPGSQL_STMT_GETDIAG;
+						newstmt->lineno   = plpgsql_location_to_lineno(@1);
+						newstmt->is_stacked = $2;
+						newstmt->diag_items = $4;
 
 						/*
 						 * Check information items are valid for area option.
 						 */
-						foreach(lc, new->diag_items)
+						foreach(lc, newstmt->diag_items)
 						{
 							PLpgSQL_diag_item *ditem = (PLpgSQL_diag_item *) lfirst(lc);
 
@@ -948,7 +948,7 @@ stmt_getdiag	: K_GET getdiag_area_opt K_DIAGNOSTICS getdiag_list ';'
 								/* these fields are disallowed in stacked case */
 								case PLPGSQL_GETDIAG_ROW_COUNT:
 								case PLPGSQL_GETDIAG_RESULT_OID:
-									if (new->is_stacked)
+									if (newstmt->is_stacked)
 										ereport(ERROR,
 												(errcode(ERRCODE_SYNTAX_ERROR),
 												 errmsg("diagnostics item %s is not allowed in GET STACKED DIAGNOSTICS",
@@ -966,7 +966,7 @@ stmt_getdiag	: K_GET getdiag_area_opt K_DIAGNOSTICS getdiag_list ';'
 								case PLPGSQL_GETDIAG_MESSAGE_TEXT:
 								case PLPGSQL_GETDIAG_TABLE_NAME:
 								case PLPGSQL_GETDIAG_SCHEMA_NAME:
-									if (!new->is_stacked)
+									if (!newstmt->is_stacked)
 										ereport(ERROR,
 												(errcode(ERRCODE_SYNTAX_ERROR),
 												 errmsg("diagnostics item %s is not allowed in GET CURRENT DIAGNOSTICS",
@@ -983,7 +983,7 @@ stmt_getdiag	: K_GET getdiag_area_opt K_DIAGNOSTICS getdiag_list ';'
 							}
 						}
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -1013,13 +1013,13 @@ getdiag_list : getdiag_list ',' getdiag_list_item
 
 getdiag_list_item : getdiag_target assign_operator getdiag_item
 					{
-						PLpgSQL_diag_item *new;
+						PLpgSQL_diag_item *newitem;
 
-						new = palloc(sizeof(PLpgSQL_diag_item));
-						new->target = $1->dno;
-						new->kind = $3;
+						newitem = palloc(sizeof(PLpgSQL_diag_item));
+						newitem->target = $1->dno;
+						newitem->kind = $3;
 
-						$$ = new;
+						$$ = newitem;
 					}
 				;
 
@@ -1102,34 +1102,34 @@ assign_var		: T_DATUM
 					}
 				| assign_var '[' expr_until_rightbracket
 					{
-						PLpgSQL_arrayelem	*new;
+						PLpgSQL_arrayelem	*newel;
 
-						new = palloc0(sizeof(PLpgSQL_arrayelem));
-						new->dtype		= PLPGSQL_DTYPE_ARRAYELEM;
-						new->subscript	= $3;
-						new->arrayparentno = $1->dno;
+						newel = palloc0(sizeof(PLpgSQL_arrayelem));
+						newel->dtype		= PLPGSQL_DTYPE_ARRAYELEM;
+						newel->subscript	= $3;
+						newel->arrayparentno = $1->dno;
 						/* initialize cached type data to "not valid" */
-						new->parenttypoid = InvalidOid;
+						newel->parenttypoid = InvalidOid;
 
-						plpgsql_adddatum((PLpgSQL_datum *) new);
+						plpgsql_adddatum((PLpgSQL_datum *) newel);
 
-						$$ = (PLpgSQL_datum *) new;
+						$$ = (PLpgSQL_datum *) newel;
 					}
 				;
 
 stmt_if			: K_IF expr_until_then proc_sect stmt_elsifs stmt_else K_END K_IF ';'
 					{
-						PLpgSQL_stmt_if *new;
+						PLpgSQL_stmt_if *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_if));
-						new->cmd_type	= PLPGSQL_STMT_IF;
-						new->lineno		= plpgsql_location_to_lineno(@1);
-						new->cond		= $2;
-						new->then_body	= $3;
-						new->elsif_list = $4;
-						new->else_body  = $5;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_if));
+						newstmt->cmd_type	= PLPGSQL_STMT_IF;
+						newstmt->lineno		= plpgsql_location_to_lineno(@1);
+						newstmt->cond		= $2;
+						newstmt->then_body	= $3;
+						newstmt->elsif_list = $4;
+						newstmt->else_body  = $5;
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -1139,14 +1139,14 @@ stmt_elsifs		:
 					}
 				| stmt_elsifs K_ELSIF expr_until_then proc_sect
 					{
-						PLpgSQL_if_elsif *new;
+						PLpgSQL_if_elsif *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_if_elsif));
-						new->lineno = plpgsql_location_to_lineno(@2);
-						new->cond   = $3;
-						new->stmts  = $4;
+						newstmt = palloc0(sizeof(PLpgSQL_if_elsif));
+						newstmt->lineno = plpgsql_location_to_lineno(@2);
+						newstmt->cond   = $3;
+						newstmt->stmts  = $4;
 
-						$$ = lappend($1, new);
+						$$ = lappend($1, newstmt);
 					}
 				;
 
@@ -1193,12 +1193,12 @@ case_when_list	: case_when_list case_when
 
 case_when		: K_WHEN expr_until_then proc_sect
 					{
-						PLpgSQL_case_when *new = palloc(sizeof(PLpgSQL_case_when));
+						PLpgSQL_case_when *newstmt = palloc(sizeof(PLpgSQL_case_when));
 
-						new->lineno	= plpgsql_location_to_lineno(@1);
-						new->expr	= $2;
-						new->stmts	= $3;
-						$$ = new;
+						newstmt->lineno	= plpgsql_location_to_lineno(@1);
+						newstmt->expr	= $2;
+						newstmt->stmts	= $3;
+						$$ = newstmt;
 					}
 				;
 
@@ -1223,36 +1223,36 @@ opt_case_else	:
 
 stmt_loop		: opt_loop_label K_LOOP loop_body
 					{
-						PLpgSQL_stmt_loop *new;
+						PLpgSQL_stmt_loop *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_loop));
-						new->cmd_type = PLPGSQL_STMT_LOOP;
-						new->lineno   = plpgsql_location_to_lineno(@2);
-						new->label	  = $1;
-						new->body	  = $3.stmts;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_loop));
+						newstmt->cmd_type = PLPGSQL_STMT_LOOP;
+						newstmt->lineno   = plpgsql_location_to_lineno(@2);
+						newstmt->label	  = $1;
+						newstmt->body	  = $3.stmts;
 
 						check_labels($1, $3.end_label, $3.end_label_location);
 						plpgsql_ns_pop();
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
 stmt_while		: opt_loop_label K_WHILE expr_until_loop loop_body
 					{
-						PLpgSQL_stmt_while *new;
+						PLpgSQL_stmt_while *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_while));
-						new->cmd_type = PLPGSQL_STMT_WHILE;
-						new->lineno   = plpgsql_location_to_lineno(@2);
-						new->label	  = $1;
-						new->cond	  = $3;
-						new->body	  = $4.stmts;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_while));
+						newstmt->cmd_type = PLPGSQL_STMT_WHILE;
+						newstmt->lineno   = plpgsql_location_to_lineno(@2);
+						newstmt->label	  = $1;
+						newstmt->cond	  = $3;
+						newstmt->body	  = $4.stmts;
 
 						check_labels($1, $4.end_label, $4.end_label_location);
 						plpgsql_ns_pop();
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -1261,27 +1261,27 @@ stmt_for		: opt_loop_label K_FOR for_control loop_body
 						/* This runs after we've scanned the loop body */
 						if ($3->cmd_type == PLPGSQL_STMT_FORI)
 						{
-							PLpgSQL_stmt_fori		*new;
+							PLpgSQL_stmt_fori		*newstmt;
 
-							new = (PLpgSQL_stmt_fori *) $3;
-							new->lineno   = plpgsql_location_to_lineno(@2);
-							new->label	  = $1;
-							new->body	  = $4.stmts;
-							$$ = (PLpgSQL_stmt *) new;
+							newstmt = (PLpgSQL_stmt_fori *) $3;
+							newstmt->lineno   = plpgsql_location_to_lineno(@2);
+							newstmt->label	  = $1;
+							newstmt->body	  = $4.stmts;
+							$$ = (PLpgSQL_stmt *) newstmt;
 						}
 						else
 						{
-							PLpgSQL_stmt_forq		*new;
+							PLpgSQL_stmt_forq		*newstmt;
 
 							Assert($3->cmd_type == PLPGSQL_STMT_FORS ||
 								   $3->cmd_type == PLPGSQL_STMT_FORC ||
 								   $3->cmd_type == PLPGSQL_STMT_DYNFORS);
 							/* forq is the common supertype of all three */
-							new = (PLpgSQL_stmt_forq *) $3;
-							new->lineno   = plpgsql_location_to_lineno(@2);
-							new->label	  = $1;
-							new->body	  = $4.stmts;
-							$$ = (PLpgSQL_stmt *) new;
+							newstmt = (PLpgSQL_stmt_forq *) $3;
+							newstmt->lineno   = plpgsql_location_to_lineno(@2);
+							newstmt->label	  = $1;
+							newstmt->body	  = $4.stmts;
+							$$ = (PLpgSQL_stmt *) newstmt;
 						}
 
 						check_labels($1, $4.end_label, $4.end_label_location);
@@ -1298,7 +1298,7 @@ for_control		: for_variable K_IN
 						if (tok == K_EXECUTE)
 						{
 							/* EXECUTE means it's a dynamic FOR loop */
-							PLpgSQL_stmt_dynfors	*new;
+							PLpgSQL_stmt_dynfors	*newstmt;
 							PLpgSQL_expr			*expr;
 							int						term;
 
@@ -1306,22 +1306,22 @@ for_control		: for_variable K_IN
 														"LOOP or USING",
 														&term);
 
-							new = palloc0(sizeof(PLpgSQL_stmt_dynfors));
-							new->cmd_type = PLPGSQL_STMT_DYNFORS;
+							newstmt = palloc0(sizeof(PLpgSQL_stmt_dynfors));
+							newstmt->cmd_type = PLPGSQL_STMT_DYNFORS;
 							if ($1.rec)
 							{
-								new->rec = $1.rec;
-								check_assignable((PLpgSQL_datum *) new->rec, @1);
+								newstmt->rec = $1.rec;
+								check_assignable((PLpgSQL_datum *) newstmt->rec, @1);
 							}
 							else if ($1.row)
 							{
-								new->row = $1.row;
-								check_assignable((PLpgSQL_datum *) new->row, @1);
+								newstmt->row = $1.row;
+								check_assignable((PLpgSQL_datum *) newstmt->row, @1);
 							}
 							else if ($1.scalar)
 							{
 								/* convert single scalar to list */
-								new->row = make_scalar_list1($1.name, $1.scalar,
+								newstmt->row = make_scalar_list1($1.name, $1.scalar,
 															 $1.lineno, @1);
 								/* no need for check_assignable */
 							}
@@ -1332,7 +1332,7 @@ for_control		: for_variable K_IN
 										 errmsg("loop variable of loop over rows must be a record or row variable or list of scalar variables"),
 										 parser_errposition(@1)));
 							}
-							new->query = expr;
+							newstmt->query = expr;
 
 							if (term == K_USING)
 							{
@@ -1341,23 +1341,23 @@ for_control		: for_variable K_IN
 									expr = read_sql_expression2(',', K_LOOP,
 																", or LOOP",
 																&term);
-									new->params = lappend(new->params, expr);
+									newstmt->params = lappend(newstmt->params, expr);
 								} while (term == ',');
 							}
 
-							$$ = (PLpgSQL_stmt *) new;
+							$$ = (PLpgSQL_stmt *) newstmt;
 						}
 						else if (tok == T_DATUM &&
 								 yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_VAR &&
 								 ((PLpgSQL_var *) yylval.wdatum.datum)->datatype->typoid == REFCURSOROID)
 						{
 							/* It's FOR var IN cursor */
-							PLpgSQL_stmt_forc	*new;
+							PLpgSQL_stmt_forc	*newstmt;
 							PLpgSQL_var			*cursor = (PLpgSQL_var *) yylval.wdatum.datum;
 
-							new = (PLpgSQL_stmt_forc *) palloc0(sizeof(PLpgSQL_stmt_forc));
-							new->cmd_type = PLPGSQL_STMT_FORC;
-							new->curvar = cursor->dno;
+							newstmt = (PLpgSQL_stmt_forc *) palloc0(sizeof(PLpgSQL_stmt_forc));
+							newstmt->cmd_type = PLPGSQL_STMT_FORC;
+							newstmt->curvar = cursor->dno;
 
 							/* Should have had a single variable name */
 							if ($1.scalar && $1.row)
@@ -1374,16 +1374,16 @@ for_control		: for_variable K_IN
 										 parser_errposition(tokloc)));
 
 							/* collect cursor's parameters if any */
-							new->argquery = read_cursor_args(cursor,
+							newstmt->argquery = read_cursor_args(cursor,
 															 K_LOOP,
 															 "LOOP");
 
 							/* create loop's private RECORD variable */
-							new->rec = plpgsql_build_record($1.name,
+							newstmt->rec = plpgsql_build_record($1.name,
 															$1.lineno,
 															true);
 
-							$$ = (PLpgSQL_stmt *) new;
+							$$ = (PLpgSQL_stmt *) newstmt;
 						}
 						else
 						{
@@ -1433,7 +1433,7 @@ for_control		: for_variable K_IN
 								PLpgSQL_expr		*expr2;
 								PLpgSQL_expr		*expr_by;
 								PLpgSQL_var			*fvar;
-								PLpgSQL_stmt_fori	*new;
+								PLpgSQL_stmt_fori	*newstmt;
 
 								/* Check first expression is well-formed */
 								check_sql_expr(expr1->query, expr1loc, 7);
@@ -1466,15 +1466,15 @@ for_control		: for_variable K_IN
 																				  InvalidOid),
 														   true);
 
-								new = palloc0(sizeof(PLpgSQL_stmt_fori));
-								new->cmd_type = PLPGSQL_STMT_FORI;
-								new->var	  = fvar;
-								new->reverse  = reverse;
-								new->lower	  = expr1;
-								new->upper	  = expr2;
-								new->step	  = expr_by;
+								newstmt = palloc0(sizeof(PLpgSQL_stmt_fori));
+								newstmt->cmd_type = PLPGSQL_STMT_FORI;
+								newstmt->var	  = fvar;
+								newstmt->reverse  = reverse;
+								newstmt->lower	  = expr1;
+								newstmt->upper	  = expr2;
+								newstmt->step	  = expr_by;
 
-								$$ = (PLpgSQL_stmt *) new;
+								$$ = (PLpgSQL_stmt *) newstmt;
 							}
 							else
 							{
@@ -1485,7 +1485,7 @@ for_control		: for_variable K_IN
 								 * syntax checking.
 								 */
 								char				*tmp_query;
-								PLpgSQL_stmt_fors	*new;
+								PLpgSQL_stmt_fors	*newstmt;
 
 								if (reverse)
 									ereport(ERROR,
@@ -1500,22 +1500,22 @@ for_control		: for_variable K_IN
 
 								check_sql_expr(expr1->query, expr1loc, 0);
 
-								new = palloc0(sizeof(PLpgSQL_stmt_fors));
-								new->cmd_type = PLPGSQL_STMT_FORS;
+								newstmt = palloc0(sizeof(PLpgSQL_stmt_fors));
+								newstmt->cmd_type = PLPGSQL_STMT_FORS;
 								if ($1.rec)
 								{
-									new->rec = $1.rec;
-									check_assignable((PLpgSQL_datum *) new->rec, @1);
+									newstmt->rec = $1.rec;
+									check_assignable((PLpgSQL_datum *) newstmt->rec, @1);
 								}
 								else if ($1.row)
 								{
-									new->row = $1.row;
-									check_assignable((PLpgSQL_datum *) new->row, @1);
+									newstmt->row = $1.row;
+									check_assignable((PLpgSQL_datum *) newstmt->row, @1);
 								}
 								else if ($1.scalar)
 								{
 									/* convert single scalar to list */
-									new->row = make_scalar_list1($1.name, $1.scalar,
+									newstmt->row = make_scalar_list1($1.name, $1.scalar,
 																 $1.lineno, @1);
 									/* no need for check_assignable */
 								}
@@ -1527,8 +1527,8 @@ for_control		: for_variable K_IN
 											 parser_errposition(@1)));
 								}
 
-								new->query = expr1;
-								$$ = (PLpgSQL_stmt *) new;
+								newstmt->query = expr1;
+								$$ = (PLpgSQL_stmt *) newstmt;
 							}
 						}
 					}
@@ -1608,29 +1608,29 @@ for_variable	: T_DATUM
 
 stmt_foreach_a	: opt_loop_label K_FOREACH for_variable foreach_slice K_IN K_ARRAY expr_until_loop loop_body
 					{
-						PLpgSQL_stmt_foreach_a *new;
+						PLpgSQL_stmt_foreach_a *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_foreach_a));
-						new->cmd_type = PLPGSQL_STMT_FOREACH_A;
-						new->lineno = plpgsql_location_to_lineno(@2);
-						new->label = $1;
-						new->slice = $4;
-						new->expr = $7;
-						new->body = $8.stmts;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_foreach_a));
+						newstmt->cmd_type = PLPGSQL_STMT_FOREACH_A;
+						newstmt->lineno = plpgsql_location_to_lineno(@2);
+						newstmt->label = $1;
+						newstmt->slice = $4;
+						newstmt->expr = $7;
+						newstmt->body = $8.stmts;
 
 						if ($3.rec)
 						{
-							new->varno = $3.rec->dno;
+							newstmt->varno = $3.rec->dno;
 							check_assignable((PLpgSQL_datum *) $3.rec, @3);
 						}
 						else if ($3.row)
 						{
-							new->varno = $3.row->dno;
+							newstmt->varno = $3.row->dno;
 							check_assignable((PLpgSQL_datum *) $3.row, @3);
 						}
 						else if ($3.scalar)
 						{
-							new->varno = $3.scalar->dno;
+							newstmt->varno = $3.scalar->dno;
 							check_assignable($3.scalar, @3);
 						}
 						else
@@ -1644,7 +1644,7 @@ stmt_foreach_a	: opt_loop_label K_FOREACH for_variable foreach_slice K_IN K_ARRA
 						check_labels($1, $8.end_label, $8.end_label_location);
 						plpgsql_ns_pop();
 
-						$$ = (PLpgSQL_stmt *) new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -1660,14 +1660,14 @@ foreach_slice	:
 
 stmt_exit		: exit_type opt_label opt_exitcond
 					{
-						PLpgSQL_stmt_exit *new;
+						PLpgSQL_stmt_exit *newstmt;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_exit));
-						new->cmd_type = PLPGSQL_STMT_EXIT;
-						new->is_exit  = $1;
-						new->lineno	  = plpgsql_location_to_lineno(@1);
-						new->label	  = $2;
-						new->cond	  = $3;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_exit));
+						newstmt->cmd_type = PLPGSQL_STMT_EXIT;
+						newstmt->is_exit  = $1;
+						newstmt->lineno	  = plpgsql_location_to_lineno(@1);
+						newstmt->label	  = $2;
+						newstmt->cond	  = $3;
 
 						if ($2)
 						{
@@ -1683,7 +1683,7 @@ stmt_exit		: exit_type opt_label opt_exitcond
 												$2),
 										 parser_errposition(@2)));
 							/* CONTINUE only allows loop labels */
-							if (label->itemno != PLPGSQL_LABEL_LOOP && !new->is_exit)
+							if (label->itemno != PLPGSQL_LABEL_LOOP && !newstmt->is_exit)
 								ereport(ERROR,
 										(errcode(ERRCODE_SYNTAX_ERROR),
 										 errmsg("block label \"%s\" cannot be used in CONTINUE",
@@ -1700,13 +1700,13 @@ stmt_exit		: exit_type opt_label opt_exitcond
 							if (plpgsql_ns_find_nearest_loop(plpgsql_ns_top()) == NULL)
 								ereport(ERROR,
 										(errcode(ERRCODE_SYNTAX_ERROR),
-										 new->is_exit ?
+										 newstmt->is_exit ?
 										 errmsg("EXIT cannot be used outside a loop, unless it has a label") :
 										 errmsg("CONTINUE cannot be used outside a loop"),
 										 parser_errposition(@1)));
 						}
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -1748,18 +1748,18 @@ stmt_return		: K_RETURN
 
 stmt_raise		: K_RAISE
 					{
-						PLpgSQL_stmt_raise		*new;
+						PLpgSQL_stmt_raise		*newstmt;
 						int	tok;
 
-						new = palloc(sizeof(PLpgSQL_stmt_raise));
+						newstmt = palloc(sizeof(PLpgSQL_stmt_raise));
 
-						new->cmd_type	= PLPGSQL_STMT_RAISE;
-						new->lineno		= plpgsql_location_to_lineno(@1);
-						new->elog_level = ERROR;	/* default */
-						new->condname	= NULL;
-						new->message	= NULL;
-						new->params		= NIL;
-						new->options	= NIL;
+						newstmt->cmd_type	= PLPGSQL_STMT_RAISE;
+						newstmt->lineno		= plpgsql_location_to_lineno(@1);
+						newstmt->elog_level = ERROR;	/* default */
+						newstmt->condname	= NULL;
+						newstmt->message	= NULL;
+						newstmt->params		= NIL;
+						newstmt->options	= NIL;
 
 						tok = yylex();
 						if (tok == 0)
@@ -1777,37 +1777,37 @@ stmt_raise		: K_RAISE
 							if (tok_is_keyword(tok, &yylval,
 											   K_EXCEPTION, "exception"))
 							{
-								new->elog_level = ERROR;
+								newstmt->elog_level = ERROR;
 								tok = yylex();
 							}
 							else if (tok_is_keyword(tok, &yylval,
 													K_WARNING, "warning"))
 							{
-								new->elog_level = WARNING;
+								newstmt->elog_level = WARNING;
 								tok = yylex();
 							}
 							else if (tok_is_keyword(tok, &yylval,
 													K_NOTICE, "notice"))
 							{
-								new->elog_level = NOTICE;
+								newstmt->elog_level = NOTICE;
 								tok = yylex();
 							}
 							else if (tok_is_keyword(tok, &yylval,
 													K_INFO, "info"))
 							{
-								new->elog_level = INFO;
+								newstmt->elog_level = INFO;
 								tok = yylex();
 							}
 							else if (tok_is_keyword(tok, &yylval,
 													K_LOG, "log"))
 							{
-								new->elog_level = LOG;
+								newstmt->elog_level = LOG;
 								tok = yylex();
 							}
 							else if (tok_is_keyword(tok, &yylval,
 													K_DEBUG, "debug"))
 							{
-								new->elog_level = DEBUG1;
+								newstmt->elog_level = DEBUG1;
 								tok = yylex();
 							}
 							if (tok == 0)
@@ -1822,7 +1822,7 @@ stmt_raise		: K_RAISE
 							if (tok == SCONST)
 							{
 								/* old style message and parameters */
-								new->message = yylval.str;
+								newstmt->message = yylval.str;
 								/*
 								 * We expect either a semi-colon, which
 								 * indicates no parameters, or a comma that
@@ -1842,7 +1842,7 @@ stmt_raise		: K_RAISE
 															  "SELECT ",
 															  true, true, true,
 															  NULL, &tok);
-									new->params = lappend(new->params, expr);
+									newstmt->params = lappend(newstmt->params, expr);
 								}
 							}
 							else if (tok != K_USING)
@@ -1862,17 +1862,17 @@ stmt_raise		: K_RAISE
 										yyerror("invalid SQLSTATE code");
 									if (strspn(sqlstatestr, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != 5)
 										yyerror("invalid SQLSTATE code");
-									new->condname = sqlstatestr;
+									newstmt->condname = sqlstatestr;
 								}
 								else
 								{
 									if (tok == T_WORD)
-										new->condname = yylval.word.ident;
+										newstmt->condname = yylval.word.ident;
 									else if (plpgsql_token_is_unreserved_keyword(tok))
-										new->condname = pstrdup(yylval.keyword);
+										newstmt->condname = pstrdup(yylval.keyword);
 									else
 										yyerror("syntax error");
-									plpgsql_recognize_err_condition(new->condname,
+									plpgsql_recognize_err_condition(newstmt->condname,
 																	false);
 								}
 								tok = yylex();
@@ -1881,35 +1881,35 @@ stmt_raise		: K_RAISE
 							}
 
 							if (tok == K_USING)
-								new->options = read_raise_options();
+								newstmt->options = read_raise_options();
 						}
 
-						check_raise_parameters(new);
+						check_raise_parameters(newstmt);
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
 stmt_assert		: K_ASSERT
 					{
-						PLpgSQL_stmt_assert		*new;
+						PLpgSQL_stmt_assert		*newstmt;
 						int	tok;
 
-						new = palloc(sizeof(PLpgSQL_stmt_assert));
+						newstmt = palloc(sizeof(PLpgSQL_stmt_assert));
 
-						new->cmd_type	= PLPGSQL_STMT_ASSERT;
-						new->lineno		= plpgsql_location_to_lineno(@1);
+						newstmt->cmd_type	= PLPGSQL_STMT_ASSERT;
+						newstmt->lineno		= plpgsql_location_to_lineno(@1);
 
-						new->cond = read_sql_expression2(',', ';',
+						newstmt->cond = read_sql_expression2(',', ';',
 														 ", or ;",
 														 &tok);
 
 						if (tok == ',')
-							new->message = read_sql_expression(';', ";");
+							newstmt->message = read_sql_expression(';', ";");
 						else
-							new->message = NULL;
+							newstmt->message = NULL;
 
-						$$ = (PLpgSQL_stmt *) new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -1963,7 +1963,7 @@ stmt_execsql	: K_IMPORT
 
 stmt_dynexecute : K_EXECUTE
 					{
-						PLpgSQL_stmt_dynexecute *new;
+						PLpgSQL_stmt_dynexecute *newstmt;
 						PLpgSQL_expr *expr;
 						int endtoken;
 
@@ -1973,15 +1973,15 @@ stmt_dynexecute : K_EXECUTE
 												  true, true, true,
 												  NULL, &endtoken);
 
-						new = palloc(sizeof(PLpgSQL_stmt_dynexecute));
-						new->cmd_type = PLPGSQL_STMT_DYNEXECUTE;
-						new->lineno = plpgsql_location_to_lineno(@1);
-						new->query = expr;
-						new->into = false;
-						new->strict = false;
-						new->rec = NULL;
-						new->row = NULL;
-						new->params = NIL;
+						newstmt = palloc(sizeof(PLpgSQL_stmt_dynexecute));
+						newstmt->cmd_type = PLPGSQL_STMT_DYNEXECUTE;
+						newstmt->lineno = plpgsql_location_to_lineno(@1);
+						newstmt->query = expr;
+						newstmt->into = false;
+						newstmt->strict = false;
+						newstmt->rec = NULL;
+						newstmt->row = NULL;
+						newstmt->params = NIL;
 
 						/*
 						 * We loop to allow the INTO and USING clauses to
@@ -1994,15 +1994,15 @@ stmt_dynexecute : K_EXECUTE
 						{
 							if (endtoken == K_INTO)
 							{
-								if (new->into)			/* multiple INTO */
+								if (newstmt->into)			/* multiple INTO */
 									yyerror("syntax error");
-								new->into = true;
-								read_into_target(&new->rec, &new->row, &new->strict);
+								newstmt->into = true;
+								read_into_target(&newstmt->rec, &newstmt->row, &newstmt->strict);
 								endtoken = yylex();
 							}
 							else if (endtoken == K_USING)
 							{
-								if (new->params)		/* multiple USING */
+								if (newstmt->params)		/* multiple USING */
 									yyerror("syntax error");
 								do
 								{
@@ -2011,7 +2011,7 @@ stmt_dynexecute : K_EXECUTE
 															  "SELECT ",
 															  true, true, true,
 															  NULL, &endtoken);
-									new->params = lappend(new->params, expr);
+									newstmt->params = lappend(newstmt->params, expr);
 								} while (endtoken == ',');
 							}
 							else if (endtoken == ';')
@@ -2020,21 +2020,21 @@ stmt_dynexecute : K_EXECUTE
 								yyerror("syntax error");
 						}
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
 
 stmt_open		: K_OPEN cursor_variable
 					{
-						PLpgSQL_stmt_open *new;
+						PLpgSQL_stmt_open *newstmt;
 						int				  tok;
 
-						new = palloc0(sizeof(PLpgSQL_stmt_open));
-						new->cmd_type = PLPGSQL_STMT_OPEN;
-						new->lineno = plpgsql_location_to_lineno(@1);
-						new->curvar = $2->dno;
-						new->cursor_options = CURSOR_OPT_FAST_PLAN;
+						newstmt = palloc0(sizeof(PLpgSQL_stmt_open));
+						newstmt->cmd_type = PLPGSQL_STMT_OPEN;
+						newstmt->lineno = plpgsql_location_to_lineno(@1);
+						newstmt->curvar = $2->dno;
+						newstmt->cursor_options = CURSOR_OPT_FAST_PLAN;
 
 						if ($2->cursor_explicit_expr == NULL)
 						{
@@ -2047,14 +2047,14 @@ stmt_open		: K_OPEN cursor_variable
 								if (tok_is_keyword(tok, &yylval,
 												   K_SCROLL, "scroll"))
 								{
-									new->cursor_options |= CURSOR_OPT_NO_SCROLL;
+									newstmt->cursor_options |= CURSOR_OPT_NO_SCROLL;
 									tok = yylex();
 								}
 							}
 							else if (tok_is_keyword(tok, &yylval,
 													K_SCROLL, "scroll"))
 							{
-								new->cursor_options |= CURSOR_OPT_SCROLL;
+								newstmt->cursor_options |= CURSOR_OPT_SCROLL;
 								tok = yylex();
 							}
 
@@ -2066,7 +2066,7 @@ stmt_open		: K_OPEN cursor_variable
 							{
 								int		endtoken;
 
-								new->dynquery =
+								newstmt->dynquery =
 									read_sql_expression2(K_USING, ';',
 														 "USING or ;",
 														 &endtoken);
@@ -2081,7 +2081,7 @@ stmt_open		: K_OPEN cursor_variable
 										expr = read_sql_expression2(',', ';',
 																	", or ;",
 																	&endtoken);
-										new->params = lappend(new->params,
+										newstmt->params = lappend(newstmt->params,
 															  expr);
 									} while (endtoken == ',');
 								}
@@ -2089,16 +2089,16 @@ stmt_open		: K_OPEN cursor_variable
 							else
 							{
 								plpgsql_push_back_token(tok);
-								new->query = read_sql_stmt("");
+								newstmt->query = read_sql_stmt("");
 							}
 						}
 						else
 						{
 							/* predefined cursor query, so read args */
-							new->argquery = read_cursor_args($2, ';', ";");
+							newstmt->argquery = read_cursor_args($2, ';', ";");
 						}
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -2154,14 +2154,14 @@ opt_fetch_direction	:
 
 stmt_close		: K_CLOSE cursor_variable ';'
 					{
-						PLpgSQL_stmt_close *new;
+						PLpgSQL_stmt_close *newstmt;
 
-						new = palloc(sizeof(PLpgSQL_stmt_close));
-						new->cmd_type = PLPGSQL_STMT_CLOSE;
-						new->lineno = plpgsql_location_to_lineno(@1);
-						new->curvar = $2->dno;
+						newstmt = palloc(sizeof(PLpgSQL_stmt_close));
+						newstmt->cmd_type = PLPGSQL_STMT_CLOSE;
+						newstmt->lineno = plpgsql_location_to_lineno(@1);
+						newstmt->curvar = $2->dno;
 
-						$$ = (PLpgSQL_stmt *)new;
+						$$ = (PLpgSQL_stmt *) newstmt;
 					}
 				;
 
@@ -2218,7 +2218,7 @@ exception_sect	:
 						 * current block.
 						 */
 						int			lineno = plpgsql_location_to_lineno(@1);
-						PLpgSQL_exception_block *new = palloc(sizeof(PLpgSQL_exception_block));
+						PLpgSQL_exception_block *newblock = palloc(sizeof(PLpgSQL_exception_block));
 						PLpgSQL_variable *var;
 
 						var = plpgsql_build_variable("sqlstate", lineno,
@@ -2227,7 +2227,7 @@ exception_sect	:
 																			plpgsql_curr_compile->fn_input_collation),
 													 true);
 						((PLpgSQL_var *) var)->isconst = true;
-						new->sqlstate_varno = var->dno;
+						newblock->sqlstate_varno = var->dno;
 
 						var = plpgsql_build_variable("sqlerrm", lineno,
 													 plpgsql_build_datatype(TEXTOID,
@@ -2235,16 +2235,16 @@ exception_sect	:
 																			plpgsql_curr_compile->fn_input_collation),
 													 true);
 						((PLpgSQL_var *) var)->isconst = true;
-						new->sqlerrm_varno = var->dno;
+						newblock->sqlerrm_varno = var->dno;
 
-						$<exception_block>$ = new;
+						$<exception_block>$ = newblock;
 					}
 					proc_exceptions
 					{
-						PLpgSQL_exception_block *new = $<exception_block>2;
-						new->exc_list = $3;
+						PLpgSQL_exception_block *newblock = $<exception_block>2;
+						newblock->exc_list = $3;
 
-						$$ = new;
+						$$ = newblock;
 					}
 				;
 
@@ -2260,14 +2260,14 @@ proc_exceptions	: proc_exceptions proc_exception
 
 proc_exception	: K_WHEN proc_conditions K_THEN proc_sect
 					{
-						PLpgSQL_exception *new;
+						PLpgSQL_exception *newx;
 
-						new = palloc0(sizeof(PLpgSQL_exception));
-						new->lineno = plpgsql_location_to_lineno(@1);
-						new->conditions = $2;
-						new->action = $4;
+						newx = palloc0(sizeof(PLpgSQL_exception));
+						newx->lineno = plpgsql_location_to_lineno(@1);
+						newx->conditions = $2;
+						newx->action = $4;
 
-						$$ = new;
+						$$ = newx;
 					}
 				;
 
@@ -2294,7 +2294,7 @@ proc_condition	: any_identifier
 							}
 							else
 							{
-								PLpgSQL_condition *new;
+								PLpgSQL_condition *newc;
 								char   *sqlstatestr;
 
 								/* next token should be a string literal */
@@ -2307,17 +2307,17 @@ proc_condition	: any_identifier
 								if (strspn(sqlstatestr, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != 5)
 									yyerror("invalid SQLSTATE code");
 
-								new = palloc(sizeof(PLpgSQL_condition));
-								new->sqlerrstate =
+								newc = palloc(sizeof(PLpgSQL_condition));
+								newc->sqlerrstate =
 									MAKE_SQLSTATE(sqlstatestr[0],
 												  sqlstatestr[1],
 												  sqlstatestr[2],
 												  sqlstatestr[3],
 												  sqlstatestr[4]);
-								new->condname = sqlstatestr;
-								new->next = NULL;
+								newc->condname = sqlstatestr;
+								newc->next = NULL;
 
-								$$ = new;
+								$$ = newc;
 							}
 						}
 				;
@@ -3117,13 +3117,13 @@ complete_direction(PLpgSQL_stmt_fetch *fetch,  bool *check_FROM)
 static PLpgSQL_stmt *
 make_return_stmt(int location)
 {
-	PLpgSQL_stmt_return *new;
+	PLpgSQL_stmt_return *newstmt;
 
-	new = palloc0(sizeof(PLpgSQL_stmt_return));
-	new->cmd_type = PLPGSQL_STMT_RETURN;
-	new->lineno   = plpgsql_location_to_lineno(location);
-	new->expr	  = NULL;
-	new->retvarno = -1;
+	newstmt = palloc0(sizeof(PLpgSQL_stmt_return));
+	newstmt->cmd_type = PLPGSQL_STMT_RETURN;
+	newstmt->lineno   = plpgsql_location_to_lineno(location);
+	newstmt->expr	  = NULL;
+	newstmt->retvarno = -1;
 
 	if (plpgsql_curr_compile->fn_retset)
 	{
@@ -3141,7 +3141,7 @@ make_return_stmt(int location)
 					(errcode(ERRCODE_DATATYPE_MISMATCH),
 					 errmsg("RETURN cannot have a parameter in function with OUT parameters"),
 					 parser_errposition(yylloc)));
-		new->retvarno = plpgsql_curr_compile->out_param_varno;
+		newstmt->retvarno = plpgsql_curr_compile->out_param_varno;
 	}
 	else if (plpgsql_curr_compile->fn_rettype == VOIDOID)
 	{
@@ -3164,7 +3164,7 @@ make_return_stmt(int location)
 			 yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_ROW ||
 			 yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_REC))
 		{
-			new->retvarno = yylval.wdatum.datum->dno;
+			newstmt->retvarno = yylval.wdatum.datum->dno;
 			/* eat the semicolon token that we only peeked at above */
 			tok = yylex();
 			Assert(tok == ';');
@@ -3178,18 +3178,18 @@ make_return_stmt(int location)
 			 * anything else is a compile-time error.
 			 */
 			plpgsql_push_back_token(tok);
-			new->expr = read_sql_expression(';', ";");
+			newstmt->expr = read_sql_expression(';', ";");
 		}
 	}
 
-	return (PLpgSQL_stmt *) new;
+	return (PLpgSQL_stmt *) newstmt;
 }
 
 
 static PLpgSQL_stmt *
 make_return_next_stmt(int location)
 {
-	PLpgSQL_stmt_return_next *new;
+	PLpgSQL_stmt_return_next *newstmt;
 
 	if (!plpgsql_curr_compile->fn_retset)
 		ereport(ERROR,
@@ -3197,11 +3197,11 @@ make_return_next_stmt(int location)
 				 errmsg("cannot use RETURN NEXT in a non-SETOF function"),
 				 parser_errposition(location)));
 
-	new = palloc0(sizeof(PLpgSQL_stmt_return_next));
-	new->cmd_type	= PLPGSQL_STMT_RETURN_NEXT;
-	new->lineno		= plpgsql_location_to_lineno(location);
-	new->expr		= NULL;
-	new->retvarno	= -1;
+	newstmt = palloc0(sizeof(PLpgSQL_stmt_return_next));
+	newstmt->cmd_type	= PLPGSQL_STMT_RETURN_NEXT;
+	newstmt->lineno		= plpgsql_location_to_lineno(location);
+	newstmt->expr		= NULL;
+	newstmt->retvarno	= -1;
 
 	if (plpgsql_curr_compile->out_param_varno >= 0)
 	{
@@ -3210,7 +3210,7 @@ make_return_next_stmt(int location)
 					(errcode(ERRCODE_DATATYPE_MISMATCH),
 					 errmsg("RETURN NEXT cannot have a parameter in function with OUT parameters"),
 					 parser_errposition(yylloc)));
-		new->retvarno = plpgsql_curr_compile->out_param_varno;
+		newstmt->retvarno = plpgsql_curr_compile->out_param_varno;
 	}
 	else
 	{
@@ -3225,7 +3225,7 @@ make_return_next_stmt(int location)
 			 yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_ROW ||
 			 yylval.wdatum.datum->dtype == PLPGSQL_DTYPE_REC))
 		{
-			new->retvarno = yylval.wdatum.datum->dno;
+			newstmt->retvarno = yylval.wdatum.datum->dno;
 			/* eat the semicolon token that we only peeked at above */
 			tok = yylex();
 			Assert(tok == ';');
@@ -3239,18 +3239,18 @@ make_return_next_stmt(int location)
 			 * anything else is a compile-time error.
 			 */
 			plpgsql_push_back_token(tok);
-			new->expr = read_sql_expression(';', ";");
+			newstmt->expr = read_sql_expression(';', ";");
 		}
 	}
 
-	return (PLpgSQL_stmt *) new;
+	return (PLpgSQL_stmt *) newstmt;
 }
 
 
 static PLpgSQL_stmt *
 make_return_query_stmt(int location)
 {
-	PLpgSQL_stmt_return_query *new;
+	PLpgSQL_stmt_return_query *newstmt;
 	int			tok;
 
 	if (!plpgsql_curr_compile->fn_retset)
@@ -3259,23 +3259,23 @@ make_return_query_stmt(int location)
 				 errmsg("cannot use RETURN QUERY in a non-SETOF function"),
 				 parser_errposition(location)));
 
-	new = palloc0(sizeof(PLpgSQL_stmt_return_query));
-	new->cmd_type = PLPGSQL_STMT_RETURN_QUERY;
-	new->lineno = plpgsql_location_to_lineno(location);
+	newstmt = palloc0(sizeof(PLpgSQL_stmt_return_query));
+	newstmt->cmd_type = PLPGSQL_STMT_RETURN_QUERY;
+	newstmt->lineno = plpgsql_location_to_lineno(location);
 
 	/* check for RETURN QUERY EXECUTE */
 	if ((tok = yylex()) != K_EXECUTE)
 	{
 		/* ordinary static query */
 		plpgsql_push_back_token(tok);
-		new->query = read_sql_stmt("");
+		newstmt->query = read_sql_stmt("");
 	}
 	else
 	{
 		/* dynamic SQL */
 		int		term;
 
-		new->dynquery = read_sql_expression2(';', K_USING, "; or USING",
+		newstmt->dynquery = read_sql_expression2(';', K_USING, "; or USING",
 											 &term);
 		if (term == K_USING)
 		{
@@ -3284,12 +3284,12 @@ make_return_query_stmt(int location)
 				PLpgSQL_expr *expr;
 
 				expr = read_sql_expression2(',', ';', ", or ;", &term);
-				new->params = lappend(new->params, expr);
+				newstmt->params = lappend(newstmt->params, expr);
 			} while (term == ',');
 		}
 	}
 
-	return (PLpgSQL_stmt *) new;
+	return (PLpgSQL_stmt *) newstmt;
 }
 
 
@@ -3936,20 +3936,20 @@ static PLpgSQL_stmt *
 make_case(int location, PLpgSQL_expr *t_expr,
 		  List *case_when_list, List *else_stmts)
 {
-	PLpgSQL_stmt_case	*new;
-
-	new = palloc(sizeof(PLpgSQL_stmt_case));
-	new->cmd_type = PLPGSQL_STMT_CASE;
-	new->lineno = plpgsql_location_to_lineno(location);
-	new->t_expr = t_expr;
-	new->t_varno = 0;
-	new->case_when_list = case_when_list;
-	new->have_else = (else_stmts != NIL);
+	PLpgSQL_stmt_case	*newstmt;
+
+	newstmt = palloc(sizeof(PLpgSQL_stmt_case));
+	newstmt->cmd_type = PLPGSQL_STMT_CASE;
+	newstmt->lineno = plpgsql_location_to_lineno(location);
+	newstmt->t_expr = t_expr;
+	newstmt->t_varno = 0;
+	newstmt->case_when_list = case_when_list;
+	newstmt->have_else = (else_stmts != NIL);
 	/* Get rid of list-with-NULL hack */
 	if (list_length(else_stmts) == 1 && linitial(else_stmts) == NULL)
-		new->else_stmts = NIL;
+		newstmt->else_stmts = NIL;
 	else
-		new->else_stmts = else_stmts;
+		newstmt->else_stmts = else_stmts;
 
 	/*
 	 * When test expression is present, we create a var for it and then
@@ -3974,12 +3974,12 @@ make_case(int location, PLpgSQL_expr *t_expr,
 		 * variable as if it were INT4; we'll fix this at runtime if needed.
 		 */
 		t_var = (PLpgSQL_var *)
-			plpgsql_build_variable(varname, new->lineno,
+			plpgsql_build_variable(varname, newstmt->lineno,
 								   plpgsql_build_datatype(INT4OID,
 														  -1,
 														  InvalidOid),
 								   true);
-		new->t_varno = t_var->dno;
+		newstmt->t_varno = t_var->dno;
 
 		foreach(l, case_when_list)
 		{
@@ -4005,5 +4005,5 @@ make_case(int location, PLpgSQL_expr *t_expr,
 		}
 	}
 
-	return (PLpgSQL_stmt *) new;
+	return (PLpgSQL_stmt *) newstmt;
 }
diff --git a/src/pl/plpgsql/src/plpgsql.h b/src/pl/plpgsql/src/plpgsql.h
index 3421eed74f..2193a95f71 100644
--- a/src/pl/plpgsql/src/plpgsql.h
+++ b/src/pl/plpgsql/src/plpgsql.h
@@ -1078,7 +1078,7 @@ extern PLpgSQL_rec *plpgsql_build_record(const char *refname, int lineno,
 extern int plpgsql_recognize_err_condition(const char *condname,
 								bool allow_sqlstate);
 extern PLpgSQL_condition *plpgsql_parse_err_condition(char *condname);
-extern void plpgsql_adddatum(PLpgSQL_datum *new);
+extern void plpgsql_adddatum(PLpgSQL_datum *newdatum);
 extern int	plpgsql_add_initdatums(int **varnos);
 extern void plpgsql_HashTableInit(void);
 
@@ -1104,7 +1104,7 @@ extern Oid plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
 							PLpgSQL_datum *datum);
 extern void plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
 								 PLpgSQL_datum *datum,
-								 Oid *typeid, int32 *typmod, Oid *collation);
+								 Oid *typid, int32 *typmod, Oid *collation);
 
 /*
  * Functions for namespace handling in pl_funcs.c
diff --git a/src/port/path.c b/src/port/path.c
index 46f20b1ef8..9e4cd302ac 100644
--- a/src/port/path.c
+++ b/src/port/path.c
@@ -607,7 +607,7 @@ make_relative_path(char *ret_path, const char *target_path,
 char *
 make_absolute_path(const char *path)
 {
-	char	   *new;
+	char	   *newpath;
 
 	/* Returning null for null input is convenient for some callers */
 	if (path == NULL)
@@ -658,8 +658,8 @@ make_absolute_path(const char *path)
 			}
 		}
 
-		new = malloc(strlen(buf) + strlen(path) + 2);
-		if (!new)
+		newpath = malloc(strlen(buf) + strlen(path) + 2);
+		if (!newpath)
 		{
 			free(buf);
 #ifndef FRONTEND
@@ -671,13 +671,13 @@ make_absolute_path(const char *path)
 			return NULL;
 #endif
 		}
-		sprintf(new, "%s/%s", buf, path);
+		sprintf(newpath, "%s/%s", buf, path);
 		free(buf);
 	}
 	else
 	{
-		new = strdup(path);
-		if (!new)
+		newpath = strdup(path);
+		if (!newpath)
 		{
 #ifndef FRONTEND
 			ereport(ERROR,
@@ -691,9 +691,9 @@ make_absolute_path(const char *path)
 	}
 
 	/* Make sure punctuation is canonical, too */
-	canonicalize_path(new);
+	canonicalize_path(newpath);
 
-	return new;
+	return newpath;
 }
 
 
diff --git a/src/test/isolation/isolationtester.c b/src/test/isolation/isolationtester.c
index f77f465751..bf567b7672 100644
--- a/src/test/isolation/isolationtester.c
+++ b/src/test/isolation/isolationtester.c
@@ -347,19 +347,19 @@ run_named_permutations(TestSpec *testspec)
 		/* Find all the named steps using the lookup table */
 		for (j = 0; j < p->nsteps; j++)
 		{
-			Step	  **this = (Step **) bsearch(p->stepnames[j],
+			Step	  **step = (Step **) bsearch(p->stepnames[j],
 												 testspec->allsteps,
 												 testspec->nallsteps,
 												 sizeof(Step *),
 												 &step_bsearch_cmp);
 
-			if (this == NULL)
+			if (step == NULL)
 			{
 				fprintf(stderr, "undefined step \"%s\" specified in permutation\n",
 						p->stepnames[j]);
 				exit_nicely();
 			}
-			steps[j] = *this;
+			steps[j] = *step;
 		}
 
 		/* And run them */
diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c
index d4d00d9c66..527113a404 100644
--- a/src/test/regress/pg_regress.c
+++ b/src/test/regress/pg_regress.c
@@ -327,13 +327,13 @@ signal_remove_temp(int signum)
 static const char *
 make_temp_sockdir(void)
 {
-	char	   *template = pg_strdup("/tmp/pg_regress-XXXXXX");
+	char	   *tmpl = pg_strdup("/tmp/pg_regress-XXXXXX");
 
-	temp_sockdir = mkdtemp(template);
+	temp_sockdir = mkdtemp(tmpl);
 	if (temp_sockdir == NULL)
 	{
 		fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
-				progname, template, strerror(errno));
+				progname, tmpl, strerror(errno));
 		exit(2);
 	}
 
-- 
2.12.0

v2-0008-Set-up-for-static-asserts-in-C.patchtext/x-patch; name=v2-0008-Set-up-for-static-asserts-in-C.patchDownload
From 7c18f989d0dc430059cce70e5f0e634e18705b91 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 08/23] Set up for static asserts in C++

---
 src/include/c.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index 947bd98067..7f303a4f39 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -744,14 +744,26 @@ typedef NameData *Name;
  * about a negative width for a struct bit-field.  This will not include a
  * helpful error message, but it beats not getting an error at all.
  */
+#ifdef __cplusplus
+#if __cpp_static_assert >= 200410
+#define _Static_assert(condition, errmessage) static_assert(condition, errmessage)
+#define HAVE__STATIC_ASSERT 1
+#endif
+#endif
+
 #ifdef HAVE__STATIC_ASSERT
 #define StaticAssertStmt(condition, errmessage) \
 	do { _Static_assert(condition, errmessage); } while(0)
 #define StaticAssertExpr(condition, errmessage) \
 	({ StaticAssertStmt(condition, errmessage); true; })
 #else							/* !HAVE__STATIC_ASSERT */
+#ifdef __cplusplus
+#define  StaticAssertStmt(condition, errmessage) \
+	((void) 0)
+#else
 #define StaticAssertStmt(condition, errmessage) \
 	((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
+#endif
 #define StaticAssertExpr(condition, errmessage) \
 	StaticAssertStmt(condition, errmessage)
 #endif   /* HAVE__STATIC_ASSERT */
-- 
2.12.0

v2-0009-Fix-function-prototypes-for-C.patchtext/x-patch; name=v2-0009-Fix-function-prototypes-for-C.patchDownload
From dadbc472a1e06f2b17b758f24827ba431d499cee Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 09/23] Fix function prototypes for C++

C++ needs to have the right number of arguments in function signatures.
---
 src/backend/nodes/nodeFuncs.c | 28 ++++++++++++++--------------
 src/include/nodes/nodeFuncs.h | 20 ++++++++++----------
 2 files changed, 24 insertions(+), 24 deletions(-)

diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 71b24a079c..dc6cf47401 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -28,10 +28,10 @@
 static bool expression_returns_set_walker(Node *node, void *context);
 static int	leftmostLoc(int loc1, int loc2);
 static bool fix_opfuncids_walker(Node *node, void *context);
-static bool planstate_walk_subplans(List *plans, bool (*walker) (),
+static bool planstate_walk_subplans(List *plans, bool (*walker) (void *, void *),
 												void *context);
 static bool planstate_walk_members(List *plans, PlanState **planstates,
-					   bool (*walker) (), void *context);
+								   bool (*walker) (void *, void *), void *context);
 
 
 /*
@@ -1850,7 +1850,7 @@ check_functions_in_node(Node *node, check_function_callback checker,
 
 bool
 expression_tree_walker(Node *node,
-					   bool (*walker) (),
+					   bool (*walker) (void *, void *),
 					   void *context)
 {
 	ListCell   *temp;
@@ -2236,7 +2236,7 @@ expression_tree_walker(Node *node,
  */
 bool
 query_tree_walker(Query *query,
-				  bool (*walker) (),
+				  bool (*walker) (void *, void *),
 				  void *context,
 				  int flags)
 {
@@ -2280,7 +2280,7 @@ query_tree_walker(Query *query,
  */
 bool
 range_table_walker(List *rtable,
-				   bool (*walker) (),
+				   bool (*walker) (void *, void *),
 				   void *context,
 				   int flags)
 {
@@ -2395,7 +2395,7 @@ range_table_walker(List *rtable,
 
 Node *
 expression_tree_mutator(Node *node,
-						Node *(*mutator) (),
+						Node *(*mutator) (void *, void *),
 						void *context)
 {
 	/*
@@ -3038,7 +3038,7 @@ expression_tree_mutator(Node *node,
  */
 Query *
 query_tree_mutator(Query *query,
-				   Node *(*mutator) (),
+				   Node *(*mutator) (void *, void *),
 				   void *context,
 				   int flags)
 {
@@ -3077,7 +3077,7 @@ query_tree_mutator(Query *query,
  */
 List *
 range_table_mutator(List *rtable,
-					Node *(*mutator) (),
+					Node *(*mutator) (void *, void *),
 					void *context,
 					int flags)
 {
@@ -3144,7 +3144,7 @@ range_table_mutator(List *rtable,
  */
 bool
 query_or_expression_tree_walker(Node *node,
-								bool (*walker) (),
+								bool (*walker) (void *, void *),
 								void *context,
 								int flags)
 {
@@ -3167,7 +3167,7 @@ query_or_expression_tree_walker(Node *node,
  */
 Node *
 query_or_expression_tree_mutator(Node *node,
-								 Node *(*mutator) (),
+								 Node *(*mutator) (void *, void *),
 								 void *context,
 								 int flags)
 {
@@ -3198,7 +3198,7 @@ query_or_expression_tree_mutator(Node *node,
  */
 bool
 raw_expression_tree_walker(Node *node,
-						   bool (*walker) (),
+						   bool (*walker) (void *, void *),
 						   void *context)
 {
 	ListCell   *temp;
@@ -3637,7 +3637,7 @@ raw_expression_tree_walker(Node *node,
  */
 bool
 planstate_tree_walker(PlanState *planstate,
-					  bool (*walker) (),
+					  bool (*walker) (void *, void *),
 					  void *context)
 {
 	Plan	   *plan = planstate->plan;
@@ -3721,7 +3721,7 @@ planstate_tree_walker(PlanState *planstate,
  */
 static bool
 planstate_walk_subplans(List *plans,
-						bool (*walker) (),
+						bool (*walker) (void *, void *),
 						void *context)
 {
 	ListCell   *lc;
@@ -3746,7 +3746,7 @@ planstate_walk_subplans(List *plans,
  */
 static bool
 planstate_walk_members(List *plans, PlanState **planstates,
-					   bool (*walker) (), void *context)
+					   bool (*walker) (void *, void *), void *context)
 {
 	int			nplans = list_length(plans);
 	int			j;
diff --git a/src/include/nodes/nodeFuncs.h b/src/include/nodes/nodeFuncs.h
index b6c9b48ee6..e5b64d0d30 100644
--- a/src/include/nodes/nodeFuncs.h
+++ b/src/include/nodes/nodeFuncs.h
@@ -50,31 +50,31 @@ extern void set_sa_opfuncid(ScalarArrayOpExpr *opexpr);
 extern bool check_functions_in_node(Node *node, check_function_callback checker,
 						void *context);
 
-extern bool expression_tree_walker(Node *node, bool (*walker) (),
+extern bool expression_tree_walker(Node *node, bool (*walker) (void *, void *),
 											   void *context);
-extern Node *expression_tree_mutator(Node *node, Node *(*mutator) (),
+extern Node *expression_tree_mutator(Node *node, Node *(*mutator) (void *, void *),
 												 void *context);
 
-extern bool query_tree_walker(Query *query, bool (*walker) (),
+extern bool query_tree_walker(Query *query, bool (*walker) (void *, void *),
 										  void *context, int flags);
-extern Query *query_tree_mutator(Query *query, Node *(*mutator) (),
+extern Query *query_tree_mutator(Query *query, Node *(*mutator) (void *, void *),
 											 void *context, int flags);
 
-extern bool range_table_walker(List *rtable, bool (*walker) (),
+extern bool range_table_walker(List *rtable, bool (*walker) (void *, void *),
 										   void *context, int flags);
-extern List *range_table_mutator(List *rtable, Node *(*mutator) (),
+extern List *range_table_mutator(List *rtable, Node *(*mutator) (void *, void *),
 											 void *context, int flags);
 
-extern bool query_or_expression_tree_walker(Node *node, bool (*walker) (),
+extern bool query_or_expression_tree_walker(Node *node, bool (*walker) (void *, void *),
 												   void *context, int flags);
-extern Node *query_or_expression_tree_mutator(Node *node, Node *(*mutator) (),
+extern Node *query_or_expression_tree_mutator(Node *node, Node *(*mutator) (void *, void *),
 												   void *context, int flags);
 
-extern bool raw_expression_tree_walker(Node *node, bool (*walker) (),
+extern bool raw_expression_tree_walker(Node *node, bool (*walker) (void *, void *),
 												   void *context);
 
 struct PlanState;
-extern bool planstate_tree_walker(struct PlanState *planstate, bool (*walker) (),
+extern bool planstate_tree_walker(struct PlanState *planstate, bool (*walker) (void *, void *),
 											  void *context);
 
 #endif   /* NODEFUNCS_H */
-- 
2.12.0

v2-0010-Fix-fmgr_oldstyle-for-C.patchtext/x-patch; name=v2-0010-Fix-fmgr_oldstyle-for-C.patchDownload
From 454f463597d4732883c163b92f62494a282b9dc8 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 10/23] Fix fmgr_oldstyle for C++

C++ needs the function pointer to have the right number of arguments, so
some casts are needed here.
---
 src/backend/utils/fmgr/fmgr.c | 56 ++++++++++++++++++++++++++++---------------
 1 file changed, 37 insertions(+), 19 deletions(-)

diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c
index 3976496aef..49a2f0aacb 100644
--- a/src/backend/utils/fmgr/fmgr.c
+++ b/src/backend/utils/fmgr/fmgr.c
@@ -52,11 +52,29 @@ PGDLLIMPORT fmgr_hook_type fmgr_hook = NULL;
  * with suitably ugly casts in fmgr_oldstyle().
  */
 #if (defined(__mc68000__) || (defined(__m68k__))) && defined(__ELF__)
-typedef int32 (*func_ptr) ();
+#define func_ptr_ret int32
 #else
-typedef char *(*func_ptr) ();
+#define func_ptr_ret char*
 #endif
 
+typedef func_ptr_ret (*func_ptr) ();
+typedef func_ptr_ret (*func1_ptr) (Datum, bool);
+typedef func_ptr_ret (*func2_ptr) (Datum, Datum);
+typedef func_ptr_ret (*func3_ptr) (Datum, Datum, Datum);
+typedef func_ptr_ret (*func4_ptr) (Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func5_ptr) (Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func6_ptr) (Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func7_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func8_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func9_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func10_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func11_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func12_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func13_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func14_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func15_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+typedef func_ptr_ret (*func16_ptr) (Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum, Datum);
+
 /*
  * For an oldstyle function, fn_extra points to a record like this:
  */
@@ -657,7 +675,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 	switch (n_arguments)
 	{
 		case 0:
-			returnValue = (char *) (*user_fn) ();
+			returnValue = (char *) (user_fn) ();
 			break;
 		case 1:
 
@@ -666,33 +684,33 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 			 * there are other functions still out there that also rely on
 			 * this undocumented hack?
 			 */
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func1_ptr) user_fn) (fcinfo->arg[0],
 											   &fcinfo->isnull);
 			break;
 		case 2:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func2_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1]);
 			break;
 		case 3:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func3_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2]);
 			break;
 		case 4:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func4_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3]);
 			break;
 		case 5:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func5_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
 											   fcinfo->arg[4]);
 			break;
 		case 6:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func6_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -700,7 +718,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[5]);
 			break;
 		case 7:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func7_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -709,7 +727,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[6]);
 			break;
 		case 8:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func8_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -719,7 +737,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[7]);
 			break;
 		case 9:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func9_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -730,7 +748,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[8]);
 			break;
 		case 10:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func10_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -742,7 +760,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[9]);
 			break;
 		case 11:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func11_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -755,7 +773,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[10]);
 			break;
 		case 12:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func12_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -769,7 +787,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[11]);
 			break;
 		case 13:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func13_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -784,7 +802,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[12]);
 			break;
 		case 14:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func14_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -800,7 +818,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[13]);
 			break;
 		case 15:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func15_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
@@ -817,7 +835,7 @@ fmgr_oldstyle(PG_FUNCTION_ARGS)
 											   fcinfo->arg[14]);
 			break;
 		case 16:
-			returnValue = (char *) (*user_fn) (fcinfo->arg[0],
+			returnValue = (char *) ((func16_ptr) user_fn) (fcinfo->arg[0],
 											   fcinfo->arg[1],
 											   fcinfo->arg[2],
 											   fcinfo->arg[3],
-- 
2.12.0

v2-0011-Don-t-define-bool-in-C.patchtext/x-patch; name=v2-0011-Don-t-define-bool-in-C.patchDownload
From 47a7faf131bbee1e56f31220253798f955b05d65 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 11/23] Don't define bool in C++

---
 src/test/thread/thread_test.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/test/thread/thread_test.c b/src/test/thread/thread_test.c
index cb93bcc5ab..7ee0991988 100644
--- a/src/test/thread/thread_test.c
+++ b/src/test/thread/thread_test.c
@@ -24,6 +24,8 @@
 #include "postgres.h"
 #else
 /* From src/include/c.h" */
+#ifndef __cplusplus
+
 #ifndef bool
 typedef char bool;
 #endif
@@ -37,6 +39,8 @@ typedef char bool;
 #endif
 #endif
 
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
-- 
2.12.0

v2-0012-Change-TimeoutId-from-enum-to-integer.patchtext/x-patch; name=v2-0012-Change-TimeoutId-from-enum-to-integer.patchDownload
From 6c22f8b7f692d4fe26f807453a2b97993db4cae0 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 12/23] Change TimeoutId from enum to integer

RegisterTimeout() treats it like an integer.  C++ doesn't like enums to
be treated that way.
---
 src/include/utils/timeout.h | 25 ++++++++++++-------------
 1 file changed, 12 insertions(+), 13 deletions(-)

diff --git a/src/include/utils/timeout.h b/src/include/utils/timeout.h
index aa816334c0..9d5eaa1b5c 100644
--- a/src/include/utils/timeout.h
+++ b/src/include/utils/timeout.h
@@ -20,22 +20,21 @@
  * Identifiers for timeout reasons.  Note that in case multiple timeouts
  * trigger at the same time, they are serviced in the order of this enum.
  */
-typedef enum TimeoutId
-{
+typedef int TimeoutId;
+
 	/* Predefined timeout reasons */
-	STARTUP_PACKET_TIMEOUT,
-	DEADLOCK_TIMEOUT,
-	LOCK_TIMEOUT,
-	STATEMENT_TIMEOUT,
-	STANDBY_DEADLOCK_TIMEOUT,
-	STANDBY_TIMEOUT,
-	STANDBY_LOCK_TIMEOUT,
-	IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
+const int STARTUP_PACKET_TIMEOUT = 1;
+const int DEADLOCK_TIMEOUT = 2;
+const int LOCK_TIMEOUT = 3;
+const int STATEMENT_TIMEOUT = 4;
+const int STANDBY_DEADLOCK_TIMEOUT = 5;
+const int STANDBY_TIMEOUT = 6;
+const int STANDBY_LOCK_TIMEOUT = 7;
+const int IDLE_IN_TRANSACTION_SESSION_TIMEOUT = 8;
 	/* First user-definable timeout reason */
-	USER_TIMEOUT,
+const int USER_TIMEOUT = 9;
 	/* Maximum number of timeout reasons */
-	MAX_TIMEOUTS = 16
-} TimeoutId;
+const int MAX_TIMEOUTS = 16;
 
 /* callback function signature */
 typedef void (*timeout_handler_proc) (void);
-- 
2.12.0

v2-0013-Add-explicit-cast-for-casting-away-volatile.patchtext/x-patch; name=v2-0013-Add-explicit-cast-for-casting-away-volatile.patchDownload
From d5af10acb48cd1688cc0fbed1b748765a3619286 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 13/23] Add explicit cast for casting away volatile

---
 contrib/pg_stat_statements/pg_stat_statements.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 62dec8768a..bda5ec61ed 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -1594,7 +1594,7 @@ pg_stat_statements_internal(FunctionCallInfo fcinfo,
 			volatile pgssEntry *e = (volatile pgssEntry *) entry;
 
 			SpinLockAcquire(&e->mutex);
-			tmp = e->counters;
+			tmp = const_cast<pgssEntry *>(e)->counters;
 			SpinLockRelease(&e->mutex);
 		}
 
-- 
2.12.0

v2-0014-Add-more-extern-key-words.patchtext/x-patch; name=v2-0014-Add-more-extern-key-words.patchDownload
From 2f1c496f88a3487a41ffd1922f35966601e8d57e Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 14/23] Add more extern key words

C++ needs those to make the definitions visible externally.  This is not
compatible with C.
---
 src/backend/access/rmgrdesc/xlogdesc.c | 2 +-
 src/backend/access/transam/xlog.c      | 4 ++--
 src/backend/storage/ipc/dsm_impl.c     | 2 +-
 3 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c
index 5f07eb1499..9a968746c0 100644
--- a/src/backend/access/rmgrdesc/xlogdesc.c
+++ b/src/backend/access/rmgrdesc/xlogdesc.c
@@ -23,7 +23,7 @@
 /*
  * GUC support
  */
-const struct config_enum_entry wal_level_options[] = {
+extern const struct config_enum_entry wal_level_options[] = {
 	{"minimal", WAL_LEVEL_MINIMAL, false},
 	{"replica", WAL_LEVEL_REPLICA, false},
 	{"archive", WAL_LEVEL_REPLICA, true},		/* deprecated */
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 038b8472ae..20ea393103 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -129,7 +129,7 @@ static double PrevCheckPointDistance = 0;
 /*
  * GUC support
  */
-const struct config_enum_entry sync_method_options[] = {
+extern const struct config_enum_entry sync_method_options[] = {
 	{"fsync", SYNC_METHOD_FSYNC, false},
 #ifdef HAVE_FSYNC_WRITETHROUGH
 	{"fsync_writethrough", SYNC_METHOD_FSYNC_WRITETHROUGH, false},
@@ -151,7 +151,7 @@ const struct config_enum_entry sync_method_options[] = {
  * Although only "on", "off", and "always" are documented,
  * we accept all the likely variants of "on" and "off".
  */
-const struct config_enum_entry archive_mode_options[] = {
+extern const struct config_enum_entry archive_mode_options[] = {
 	{"always", ARCHIVE_MODE_ALWAYS, false},
 	{"on", ARCHIVE_MODE_ON, false},
 	{"off", ARCHIVE_MODE_OFF, false},
diff --git a/src/backend/storage/ipc/dsm_impl.c b/src/backend/storage/ipc/dsm_impl.c
index b2c9cdc6ed..0d3f595d04 100644
--- a/src/backend/storage/ipc/dsm_impl.c
+++ b/src/backend/storage/ipc/dsm_impl.c
@@ -90,7 +90,7 @@ static bool dsm_impl_mmap(dsm_op op, dsm_handle handle, Size request_size,
 #endif
 static int	errcode_for_dynamic_shared_memory(void);
 
-const struct config_enum_entry dynamic_shared_memory_options[] = {
+extern const struct config_enum_entry dynamic_shared_memory_options[] = {
 #ifdef USE_DSM_POSIX
 	{"posix", DSM_IMPL_POSIX, false},
 #endif
-- 
2.12.0

v2-0015-Workaround-for-using-typdef-ed-ints-in-loops.patchtext/x-patch; name=v2-0015-Workaround-for-using-typdef-ed-ints-in-loops.patchDownload
From 693053ed41fa303cae322b834ae33d880f829de0 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 15/23] Workaround for using typdef'ed ints in loops

Types made from int don't have a ++ operator in C++, so they can't be
used in for loops without further work.

Needs more research
---
 src/backend/access/transam/xact.c | 4 ++--
 src/backend/commands/tablecmds.c  | 2 +-
 src/backend/storage/smgr/md.c     | 8 ++++----
 src/backend/storage/smgr/smgr.c   | 6 +++---
 src/backend/utils/adt/dbsize.c    | 6 +++---
 src/bin/pgbench/pgbench.c         | 5 ++++-
 src/common/relpath.c              | 4 ++--
 7 files changed, 19 insertions(+), 16 deletions(-)

diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index 82f9a3c5c6..d9a33bc933 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -5460,7 +5460,7 @@ xact_redo_commit(xl_xact_parsed_commit *parsed,
 		for (i = 0; i < parsed->nrels; i++)
 		{
 			SMgrRelation srel = smgropen(parsed->xnodes[i], InvalidBackendId);
-			ForkNumber	fork;
+			int			fork;
 
 			for (fork = 0; fork <= MAX_FORKNUM; fork++)
 				XLogDropRelation(parsed->xnodes[i], fork);
@@ -5570,7 +5570,7 @@ xact_redo_abort(xl_xact_parsed_abort *parsed, TransactionId xid)
 	for (i = 0; i < parsed->nrels; i++)
 	{
 		SMgrRelation srel = smgropen(parsed->xnodes[i], InvalidBackendId);
-		ForkNumber	fork;
+		int			fork;
 
 		for (fork = 0; fork <= MAX_FORKNUM; fork++)
 			XLogDropRelation(parsed->xnodes[i], fork);
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 56906d603c..f1fffb7edd 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -10107,7 +10107,7 @@ ATExecSetTableSpace(Oid tableOid, Oid newTableSpace, LOCKMODE lockmode)
 	Relation	pg_class;
 	HeapTuple	tuple;
 	Form_pg_class rd_rel;
-	ForkNumber	forkNum;
+	int			forkNum;
 	List	   *reltoastidxids = NIL;
 	ListCell   *lc;
 
diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c
index 6c17b54f0d..201edaaeed 100644
--- a/src/backend/storage/smgr/md.c
+++ b/src/backend/storage/smgr/md.c
@@ -398,7 +398,7 @@ mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
 	/* Now do the per-fork work */
 	if (forkNum == InvalidForkNumber)
 	{
-		for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
+		for (int forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
 			mdunlinkfork(rnode, forkNum, isRedo);
 	}
 	else
@@ -1130,7 +1130,7 @@ mdsync(void)
 	hash_seq_init(&hstat, pendingOpsTable);
 	while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
 	{
-		ForkNumber	forknum;
+		int		forknum;
 
 		/*
 		 * If the entry is new then don't process it this time; it might
@@ -1535,7 +1535,7 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
 			if (forknum == InvalidForkNumber)
 			{
 				/* remove requests for all forks */
-				for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
+				for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
 				{
 					bms_free(entry->requests[forknum]);
 					entry->requests[forknum] = NULL;
@@ -1567,7 +1567,7 @@ RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
 			if (entry->rnode.dbNode == rnode.dbNode)
 			{
 				/* remove requests for all forks */
-				for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
+				for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
 				{
 					bms_free(entry->requests[forknum]);
 					entry->requests[forknum] = NULL;
diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c
index 0ed1fe91d5..d0699ae619 100644
--- a/src/backend/storage/smgr/smgr.c
+++ b/src/backend/storage/smgr/smgr.c
@@ -296,7 +296,7 @@ void
 smgrclose(SMgrRelation reln)
 {
 	SMgrRelation *owner;
-	ForkNumber	forknum;
+	int			forknum;
 
 	for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
 		(*(smgrsw[reln->smgr_which].smgr_close)) (reln, forknum);
@@ -415,7 +415,7 @@ smgrdounlink(SMgrRelation reln, bool isRedo)
 {
 	RelFileNodeBackend rnode = reln->smgr_rnode;
 	int			which = reln->smgr_which;
-	ForkNumber	forknum;
+	int			forknum;
 
 	/* Close the forks at smgr level */
 	for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
@@ -472,7 +472,7 @@ smgrdounlinkall(SMgrRelation *rels, int nrels, bool isRedo)
 {
 	int			i = 0;
 	RelFileNodeBackend *rnodes;
-	ForkNumber	forknum;
+	int			forknum;
 
 	if (nrels == 0)
 		return;
diff --git a/src/backend/utils/adt/dbsize.c b/src/backend/utils/adt/dbsize.c
index 8cdd1dc4f7..340f7a08bf 100644
--- a/src/backend/utils/adt/dbsize.c
+++ b/src/backend/utils/adt/dbsize.c
@@ -341,7 +341,7 @@ calculate_toast_table_size(Oid toastrelid)
 {
 	int64		size = 0;
 	Relation	toastRel;
-	ForkNumber	forkNum;
+	int			forkNum;
 	ListCell   *lc;
 	List	   *indexlist;
 
@@ -386,7 +386,7 @@ static int64
 calculate_table_size(Relation rel)
 {
 	int64		size = 0;
-	ForkNumber	forkNum;
+	int			forkNum;
 
 	/*
 	 * heap size, including FSM and VM
@@ -426,7 +426,7 @@ calculate_indexes_size(Relation rel)
 		{
 			Oid			idxOid = lfirst_oid(cell);
 			Relation	idxRel;
-			ForkNumber	forkNum;
+			int			forkNum;
 
 			idxRel = relation_open(idxOid, AccessShareLock);
 
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index f6cb5d4b10..83cc0e7cf2 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -3901,9 +3901,12 @@ main(int argc, char **argv)
 					fprintf(stderr, "query mode (-M) should be specified before any transaction scripts (-f or -b)\n");
 					exit(1);
 				}
-				for (querymode = 0; querymode < NUM_QUERYMODE; querymode++)
+				for (int qm = 0; qm < NUM_QUERYMODE; qm++)
 					if (strcmp(optarg, QUERYMODE[querymode]) == 0)
+					{
+						querymode = qm;
 						break;
+					}
 				if (querymode >= NUM_QUERYMODE)
 				{
 					fprintf(stderr, "invalid query mode (-M): \"%s\"\n",
diff --git a/src/common/relpath.c b/src/common/relpath.c
index c2f36625c1..911ca7543e 100644
--- a/src/common/relpath.c
+++ b/src/common/relpath.c
@@ -47,7 +47,7 @@ const char *const forkNames[] = {
 ForkNumber
 forkname_to_number(const char *forkName)
 {
-	ForkNumber	forkNum;
+	int		forkNum;
 
 	for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
 		if (strcmp(forkNames[forkNum], forkName) == 0)
@@ -78,7 +78,7 @@ forkname_to_number(const char *forkName)
 int
 forkname_chars(const char *str, ForkNumber *fork)
 {
-	ForkNumber	forkNum;
+	int			forkNum;
 
 	for (forkNum = 1; forkNum <= MAX_FORKNUM; forkNum++)
 	{
-- 
2.12.0

v2-0016-Disable-conflicting-function.patchtext/x-patch; name=v2-0016-Disable-conflicting-function.patchDownload
From 181fd5d60161236bf5ae706246d6f2ae035aa9e6 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 16/23] Disable conflicting function

This function conflicts with a function in the backend.  FIXME
---
 contrib/xml2/xpath.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/contrib/xml2/xpath.c b/contrib/xml2/xpath.c
index 73b74c875e..0f76ac0030 100644
--- a/contrib/xml2/xpath.c
+++ b/contrib/xml2/xpath.c
@@ -90,6 +90,7 @@ pgxml_parser_init(PgXmlStrictness strictness)
  * definitions for the contrib module, this won't be called.
  */
 
+#ifdef BROKEN
 PG_FUNCTION_INFO_V1(xml_is_well_formed);
 
 Datum
@@ -124,6 +125,7 @@ xml_is_well_formed(PG_FUNCTION_ARGS)
 
 	PG_RETURN_BOOL(result);
 }
+#endif
 
 
 /* Encodes special characters (<, >, &, " and \r) as XML entities */
-- 
2.12.0

v2-0017-Add-C-linkage-to-replacement-declaration-of-fdata.patchtext/x-patch; name=v2-0017-Add-C-linkage-to-replacement-declaration-of-fdata.patchDownload
From b69fe61410413e7c1b504704e782e857b8af9e3a Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 17/23] Add C linkage to replacement declaration of
 fdatasync

---
 src/include/c.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/include/c.h b/src/include/c.h
index 7f303a4f39..4adb249e75 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1103,7 +1103,7 @@ extern int	vsnprintf(char *str, size_t count, const char *fmt, va_list args);
 #endif
 
 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
-extern int	fdatasync(int fildes);
+extern "C" int	fdatasync(int fildes);
 #endif
 
 /* If strtoq() exists, rename it to the more standard strtoll() */
-- 
2.12.0

v2-0018-Make-inet_net_-to-C-linkage.patchtext/x-patch; name=v2-0018-Make-inet_net_-to-C-linkage.patchDownload
From 530db2d66ad1dfe8b82c24e29556f2400954a6b7 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 18/23] Make inet_net_?to? C linkage

These functions can also be declared by the operating system, so we need
to match the linkage.
---
 src/include/port.h           | 2 +-
 src/include/utils/builtins.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/include/port.h b/src/include/port.h
index f4546016e7..30da8e7d90 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -452,7 +452,7 @@ extern int	pg_codepage_to_encoding(UINT cp);
 #endif
 
 /* port/inet_net_ntop.c */
-extern char *inet_net_ntop(int af, const void *src, int bits,
+extern "C" char *inet_net_ntop(int af, const void *src, int bits,
 			  char *dst, size_t size);
 
 /* port/pg_strong_random.c */
diff --git a/src/include/utils/builtins.h b/src/include/utils/builtins.h
index 5bdca8203d..099b37d226 100644
--- a/src/include/utils/builtins.h
+++ b/src/include/utils/builtins.h
@@ -98,7 +98,7 @@ extern char *inet_cidr_ntop(int af, const void *src, int bits,
 			   char *dst, size_t size);
 
 /* inet_net_pton.c */
-extern int inet_net_pton(int af, const char *src,
+extern "C" int inet_net_pton(int af, const char *src,
 			  void *dst, size_t size);
 
 /* network.c */
-- 
2.12.0

v2-0019-Add-C-linkage-to-functions-exported-by-plugins.patchtext/x-patch; name=v2-0019-Add-C-linkage-to-functions-exported-by-plugins.patchDownload
From 207ff8aca4a74af2756c6a345286ebecd139d759 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 19/23] Add C linkage to functions exported by plugins

This is required so dlsym() can find them reliably.
---
 contrib/auth_delay/auth_delay.c                             | 2 +-
 contrib/auto_explain/auto_explain.c                         | 4 ++--
 contrib/bloom/bloom.h                                       | 2 +-
 contrib/earthdistance/earthdistance.c                       | 2 +-
 contrib/hstore/hstore.h                                     | 8 +++++---
 contrib/hstore_plperl/hstore_plperl.c                       | 2 +-
 contrib/hstore_plpython/hstore_plpython.c                   | 2 +-
 contrib/ltree/ltree.h                                       | 2 ++
 contrib/ltree_plpython/ltree_plpython.c                     | 2 +-
 contrib/passwordcheck/passwordcheck.c                       | 2 +-
 contrib/pg_stat_statements/pg_stat_statements.c             | 2 ++
 contrib/pg_trgm/trgm_op.c                                   | 2 +-
 contrib/seg/seg.c                                           | 6 ++++++
 contrib/sepgsql/hooks.c                                     | 2 +-
 contrib/test_decoding/test_decoding.c                       | 4 ++--
 src/backend/replication/libpqwalreceiver/libpqwalreceiver.c | 2 +-
 src/backend/replication/pgoutput/pgoutput.c                 | 2 +-
 src/include/fmgr.h                                          | 6 +++---
 src/pl/plperl/plperl.c                                      | 2 ++
 src/pl/plpgsql/src/plpgsql.h                                | 2 +-
 src/pl/plpython/plpy_main.c                                 | 2 ++
 src/pl/plpython/plpy_typeio.h                               | 2 +-
 src/pl/tcl/pltcl.c                                          | 2 ++
 src/test/modules/dummy_seclabel/dummy_seclabel.c            | 2 +-
 src/test/modules/test_rls_hooks/test_rls_hooks.c            | 2 ++
 src/test/modules/test_shm_mq/test.c                         | 2 +-
 src/test/modules/test_shm_mq/test_shm_mq.h                  | 2 +-
 src/test/modules/worker_spi/worker_spi.c                    | 2 +-
 src/test/regress/regress.c                                  | 8 +++++---
 29 files changed, 52 insertions(+), 30 deletions(-)

diff --git a/contrib/auth_delay/auth_delay.c b/contrib/auth_delay/auth_delay.c
index e0604fb808..7eae401403 100644
--- a/contrib/auth_delay/auth_delay.c
+++ b/contrib/auth_delay/auth_delay.c
@@ -20,7 +20,7 @@
 
 PG_MODULE_MAGIC;
 
-void		_PG_init(void);
+extern "C" void		_PG_init(void);
 
 /* GUC Variables */
 static int	auth_delay_milliseconds;
diff --git a/contrib/auto_explain/auto_explain.c b/contrib/auto_explain/auto_explain.c
index 34b9f1543e..319c7a9c7b 100644
--- a/contrib/auto_explain/auto_explain.c
+++ b/contrib/auto_explain/auto_explain.c
@@ -55,8 +55,8 @@ static bool current_query_sampled = true;
 	(auto_explain_log_min_duration >= 0 && \
 	 (nesting_level == 0 || auto_explain_log_nested_statements))
 
-void		_PG_init(void);
-void		_PG_fini(void);
+extern "C" void		_PG_init(void);
+extern "C" void		_PG_fini(void);
 
 static void explain_ExecutorStart(QueryDesc *queryDesc, int eflags);
 static void explain_ExecutorRun(QueryDesc *queryDesc,
diff --git a/contrib/bloom/bloom.h b/contrib/bloom/bloom.h
index 0cfe49aad8..d4ab749e95 100644
--- a/contrib/bloom/bloom.h
+++ b/contrib/bloom/bloom.h
@@ -173,7 +173,7 @@ typedef struct BloomScanOpaqueData
 typedef BloomScanOpaqueData *BloomScanOpaque;
 
 /* blutils.c */
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 extern void initBloomState(BloomState *state, Relation index);
 extern void BloomFillMetapage(Relation index, Page metaPage);
 extern void BloomInitMetapage(Relation index);
diff --git a/contrib/earthdistance/earthdistance.c b/contrib/earthdistance/earthdistance.c
index 861b166373..305be5d932 100644
--- a/contrib/earthdistance/earthdistance.c
+++ b/contrib/earthdistance/earthdistance.c
@@ -112,7 +112,7 @@ geo_distance(PG_FUNCTION_ARGS)
 }
 #else							/* !USE_FLOAT8_BYVAL */
 
-double	   *geo_distance(Point *pt1, Point *pt2);
+extern "C" double	   *geo_distance(Point *pt1, Point *pt2);
 
 double *
 geo_distance(Point *pt1, Point *pt2)
diff --git a/contrib/hstore/hstore.h b/contrib/hstore/hstore.h
index fbedc971c0..323faa4b8c 100644
--- a/contrib/hstore/hstore.h
+++ b/contrib/hstore/hstore.h
@@ -147,7 +147,7 @@ typedef struct
 	} while (0)
 
 /* DatumGetHStoreP includes support for reading old-format hstore values */
-extern HStore *hstoreUpgrade(Datum orig);
+extern "C" HStore *hstoreUpgrade(Datum orig);
 
 #define DatumGetHStoreP(d) hstoreUpgrade(d)
 
@@ -168,6 +168,7 @@ typedef struct
 	bool		needfree;		/* need to pfree the value? */
 } Pairs;
 
+extern "C" {
 extern int	hstoreUniquePairs(Pairs *a, int32 l, int32 *buflen);
 extern HStore *hstorePairs(Pairs *pairs, int32 pcount, int32 buflen);
 
@@ -176,6 +177,7 @@ extern size_t hstoreCheckValLen(size_t len);
 
 extern int	hstoreFindKey(HStore *hs, int *lowbound, char *key, int keylen);
 extern Pairs *hstoreArrayToPairs(ArrayType *a, int *npairs);
+}
 
 #define HStoreContainsStrategyNumber	7
 #define HStoreExistsStrategyNumber		9
@@ -194,8 +196,8 @@ extern Pairs *hstoreArrayToPairs(ArrayType *a, int *npairs);
 #if HSTORE_POLLUTE_NAMESPACE
 #define HSTORE_POLLUTE(newname_,oldname_) \
 	PG_FUNCTION_INFO_V1(oldname_);		  \
-	Datum newname_(PG_FUNCTION_ARGS);	  \
-	Datum oldname_(PG_FUNCTION_ARGS) { return newname_(fcinfo); } \
+	extern "C" Datum newname_(PG_FUNCTION_ARGS);	  \
+	extern "C" Datum oldname_(PG_FUNCTION_ARGS) { return newname_(fcinfo); } \
 	extern int no_such_variable
 #else
 #define HSTORE_POLLUTE(newname_,oldname_) \
diff --git a/contrib/hstore_plperl/hstore_plperl.c b/contrib/hstore_plperl/hstore_plperl.c
index 480212f341..be252e4b7e 100644
--- a/contrib/hstore_plperl/hstore_plperl.c
+++ b/contrib/hstore_plperl/hstore_plperl.c
@@ -9,7 +9,7 @@
 
 PG_MODULE_MAGIC;
 
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 
 /* Linkage to functions in hstore module */
 typedef HStore *(*hstoreUpgrade_t) (Datum orig);
diff --git a/contrib/hstore_plpython/hstore_plpython.c b/contrib/hstore_plpython/hstore_plpython.c
index b184324ebf..d9cf139a97 100644
--- a/contrib/hstore_plpython/hstore_plpython.c
+++ b/contrib/hstore_plpython/hstore_plpython.c
@@ -7,7 +7,7 @@
 
 PG_MODULE_MAGIC;
 
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 
 /* Linkage to functions in plpython module */
 typedef char *(*PLyObject_AsString_t) (PyObject *plrv);
diff --git a/contrib/ltree/ltree.h b/contrib/ltree/ltree.h
index c604357dbf..277b9a4206 100644
--- a/contrib/ltree/ltree.h
+++ b/contrib/ltree/ltree.h
@@ -130,6 +130,7 @@ typedef struct
 
 
 /* use in array iterator */
+extern "C" {
 Datum		ltree_isparent(PG_FUNCTION_ARGS);
 Datum		ltree_risparent(PG_FUNCTION_ARGS);
 Datum		ltq_regex(PG_FUNCTION_ARGS);
@@ -154,6 +155,7 @@ Datum		ltree_textadd(PG_FUNCTION_ARGS);
 
 /* Util function */
 Datum		ltree_in(PG_FUNCTION_ARGS);
+}
 
 bool ltree_execute(ITEM *curitem, void *checkval,
 			  bool calcnot, bool (*chkcond) (void *checkval, ITEM *val));
diff --git a/contrib/ltree_plpython/ltree_plpython.c b/contrib/ltree_plpython/ltree_plpython.c
index bdd462a91b..0bedf005ae 100644
--- a/contrib/ltree_plpython/ltree_plpython.c
+++ b/contrib/ltree_plpython/ltree_plpython.c
@@ -6,7 +6,7 @@
 
 PG_MODULE_MAGIC;
 
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 
 /* Linkage to functions in plpython module */
 #if PY_MAJOR_VERSION >= 3
diff --git a/contrib/passwordcheck/passwordcheck.c b/contrib/passwordcheck/passwordcheck.c
index c988bf5169..7fa530284a 100644
--- a/contrib/passwordcheck/passwordcheck.c
+++ b/contrib/passwordcheck/passwordcheck.c
@@ -29,7 +29,7 @@ PG_MODULE_MAGIC;
 /* passwords shorter than this will be rejected */
 #define MIN_PWD_LENGTH 8
 
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 
 /*
  * check_password
diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index bda5ec61ed..bbd926eb10 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -276,8 +276,10 @@ static bool pgss_save;			/* whether to save stats across shutdown */
 
 /*---- Function declarations ----*/
 
+extern "C" {
 void		_PG_init(void);
 void		_PG_fini(void);
+}
 
 PG_FUNCTION_INFO_V1(pg_stat_statements_reset);
 PG_FUNCTION_INFO_V1(pg_stat_statements_1_2);
diff --git a/contrib/pg_trgm/trgm_op.c b/contrib/pg_trgm/trgm_op.c
index 368e7c8941..654b5c4644 100644
--- a/contrib/pg_trgm/trgm_op.c
+++ b/contrib/pg_trgm/trgm_op.c
@@ -19,7 +19,7 @@ PG_MODULE_MAGIC;
 double		similarity_threshold = 0.3f;
 double		word_similarity_threshold = 0.6f;
 
-void		_PG_init(void);
+extern "C" void		_PG_init(void);
 
 PG_FUNCTION_INFO_V1(set_limit);
 PG_FUNCTION_INFO_V1(show_limit);
diff --git a/contrib/seg/seg.c b/contrib/seg/seg.c
index 895d879498..b98de5f66c 100644
--- a/contrib/seg/seg.c
+++ b/contrib/seg/seg.c
@@ -47,6 +47,7 @@ PG_FUNCTION_INFO_V1(seg_center);
 /*
 ** GiST support methods
 */
+extern "C" {
 bool gseg_consistent(GISTENTRY *entry,
 				SEG *query,
 				StrategyNumber strategy,
@@ -61,11 +62,13 @@ bool		gseg_internal_consistent(SEG *key, SEG *query, StrategyNumber strategy);
 SEG		   *gseg_union(GistEntryVector *entryvec, int *sizep);
 SEG		   *gseg_binary_union(SEG *r1, SEG *r2, int *sizep);
 bool	   *gseg_same(SEG *b1, SEG *b2, bool *result);
+}
 
 
 /*
 ** R-tree support functions
 */
+extern "C" {
 bool		seg_same(SEG *a, SEG *b);
 bool		seg_contains_int(SEG *a, int *b);
 bool		seg_contains_float4(SEG *a, float4 *b);
@@ -80,16 +83,19 @@ bool		seg_over_right(SEG *a, SEG *b);
 SEG		   *seg_union(SEG *a, SEG *b);
 SEG		   *seg_inter(SEG *a, SEG *b);
 void		rt_seg_size(SEG *a, float *sz);
+}
 
 /*
 ** Various operators
 */
+extern "C" {
 int32		seg_cmp(SEG *a, SEG *b);
 bool		seg_lt(SEG *a, SEG *b);
 bool		seg_le(SEG *a, SEG *b);
 bool		seg_gt(SEG *a, SEG *b);
 bool		seg_ge(SEG *a, SEG *b);
 bool		seg_different(SEG *a, SEG *b);
+}
 
 /*
 ** Auxiliary funxtions
diff --git a/contrib/sepgsql/hooks.c b/contrib/sepgsql/hooks.c
index 93cc8debaa..f80826f23f 100644
--- a/contrib/sepgsql/hooks.c
+++ b/contrib/sepgsql/hooks.c
@@ -30,7 +30,7 @@ PG_MODULE_MAGIC;
 /*
  * Declarations
  */
-void		_PG_init(void);
+extern "C" void		_PG_init(void);
 
 /*
  * Saved hook entries (if stacked)
diff --git a/contrib/test_decoding/test_decoding.c b/contrib/test_decoding/test_decoding.c
index 21cfd673c6..df81fb5a54 100644
--- a/contrib/test_decoding/test_decoding.c
+++ b/contrib/test_decoding/test_decoding.c
@@ -35,8 +35,8 @@
 PG_MODULE_MAGIC;
 
 /* These must be available to pg_dlsym() */
-extern void _PG_init(void);
-extern void _PG_output_plugin_init(OutputPluginCallbacks *cb);
+extern "C" void _PG_init(void);
+extern "C" void _PG_output_plugin_init(OutputPluginCallbacks *cb);
 
 typedef struct
 {
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index daae3f70e7..239f250790 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -33,7 +33,7 @@
 
 PG_MODULE_MAGIC;
 
-void		_PG_init(void);
+extern "C" void		_PG_init(void);
 
 struct WalReceiverConn
 {
diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c
index 0ceb4be375..b83889eb70 100644
--- a/src/backend/replication/pgoutput/pgoutput.c
+++ b/src/backend/replication/pgoutput/pgoutput.c
@@ -27,7 +27,7 @@
 
 PG_MODULE_MAGIC;
 
-extern void _PG_output_plugin_init(OutputPluginCallbacks *cb);
+extern "C" void _PG_output_plugin_init(OutputPluginCallbacks *cb);
 
 static void pgoutput_startup(LogicalDecodingContext * ctx,
 							  OutputPluginOptions *opt, bool is_init);
diff --git a/src/include/fmgr.h b/src/include/fmgr.h
index a671480004..8f1eccfb88 100644
--- a/src/include/fmgr.h
+++ b/src/include/fmgr.h
@@ -355,8 +355,8 @@ typedef const Pg_finfo_record *(*PGFInfoFunction) (void);
  *	info function, since authors shouldn't need to be explicitly aware of it.
  */
 #define PG_FUNCTION_INFO_V1(funcname) \
-extern Datum funcname(PG_FUNCTION_ARGS); \
-extern PGDLLEXPORT const Pg_finfo_record * CppConcat(pg_finfo_,funcname)(void); \
+extern "C" Datum funcname(PG_FUNCTION_ARGS); \
+extern "C" PGDLLEXPORT const Pg_finfo_record * CppConcat(pg_finfo_,funcname)(void); \
 const Pg_finfo_record * \
 CppConcat(pg_finfo_,funcname) (void) \
 { \
@@ -425,7 +425,7 @@ typedef const Pg_magic_struct *(*PGModuleMagicFunction) (void);
 #define PG_MAGIC_FUNCTION_NAME_STRING "Pg_magic_func"
 
 #define PG_MODULE_MAGIC \
-extern PGDLLEXPORT const Pg_magic_struct *PG_MAGIC_FUNCTION_NAME(void); \
+extern "C" PGDLLEXPORT const Pg_magic_struct *PG_MAGIC_FUNCTION_NAME(void); \
 const Pg_magic_struct * \
 PG_MAGIC_FUNCTION_NAME(void) \
 { \
diff --git a/src/pl/plperl/plperl.c b/src/pl/plperl/plperl.c
index 00979cba74..e07ad0d321 100644
--- a/src/pl/plperl/plperl.c
+++ b/src/pl/plperl/plperl.c
@@ -246,7 +246,9 @@ static plperl_call_data *current_call_data = NULL;
 /**********************************************************************
  * Forward declarations
  **********************************************************************/
+extern "C" {
 void		_PG_init(void);
+}
 
 static PerlInterpreter *plperl_init_interp(void);
 static void plperl_destroy_interp(PerlInterpreter **);
diff --git a/src/pl/plpgsql/src/plpgsql.h b/src/pl/plpgsql/src/plpgsql.h
index 2193a95f71..ee5982e3c8 100644
--- a/src/pl/plpgsql/src/plpgsql.h
+++ b/src/pl/plpgsql/src/plpgsql.h
@@ -1085,7 +1085,7 @@ extern void plpgsql_HashTableInit(void);
 /*
  * Functions in pl_handler.c
  */
-extern void _PG_init(void);
+extern "C" void _PG_init(void);
 
 /*
  * Functions in pl_exec.c
diff --git a/src/pl/plpython/plpy_main.c b/src/pl/plpython/plpy_main.c
index 860b804e54..efd3bf0002 100644
--- a/src/pl/plpython/plpy_main.c
+++ b/src/pl/plpython/plpy_main.c
@@ -39,7 +39,9 @@
 #define plpython_inline_handler plpython3_inline_handler
 #endif
 
+extern "C" {
 extern void _PG_init(void);
+}
 
 PG_MODULE_MAGIC;
 
diff --git a/src/pl/plpython/plpy_typeio.h b/src/pl/plpython/plpy_typeio.h
index e04722c47a..0793927fff 100644
--- a/src/pl/plpython/plpy_typeio.h
+++ b/src/pl/plpython/plpy_typeio.h
@@ -117,6 +117,6 @@ extern Datum PLyObject_ToCompositeDatum(PLyTypeInfo *info, TupleDesc desc, PyObj
 extern PyObject *PLyDict_FromTuple(PLyTypeInfo *info, HeapTuple tuple, TupleDesc desc);
 
 /* conversion from Python objects to C strings */
-extern char *PLyObject_AsString(PyObject *plrv);
+extern "C" char *PLyObject_AsString(PyObject *plrv);
 
 #endif   /* PLPY_TYPEIO_H */
diff --git a/src/pl/tcl/pltcl.c b/src/pl/tcl/pltcl.c
index 11faa6defe..c3cbd6f69f 100644
--- a/src/pl/tcl/pltcl.c
+++ b/src/pl/tcl/pltcl.c
@@ -251,7 +251,9 @@ static const TclExceptionNameMap exception_name_map[] = {
 /**********************************************************************
  * Forward declarations
  **********************************************************************/
+extern "C" {
 void		_PG_init(void);
+}
 
 static void pltcl_init_interp(pltcl_interp_desc *interp_desc, bool pltrusted);
 static pltcl_interp_desc *pltcl_fetch_interp(bool pltrusted);
diff --git a/src/test/modules/dummy_seclabel/dummy_seclabel.c b/src/test/modules/dummy_seclabel/dummy_seclabel.c
index 7fd78f05c7..fdeeb3325b 100644
--- a/src/test/modules/dummy_seclabel/dummy_seclabel.c
+++ b/src/test/modules/dummy_seclabel/dummy_seclabel.c
@@ -19,7 +19,7 @@
 PG_MODULE_MAGIC;
 
 /* Entrypoint of the module */
-void		_PG_init(void);
+extern "C" void		_PG_init(void);
 
 PG_FUNCTION_INFO_V1(dummy_seclabel_dummy);
 
diff --git a/src/test/modules/test_rls_hooks/test_rls_hooks.c b/src/test/modules/test_rls_hooks/test_rls_hooks.c
index 65bf3e33c9..12a782a919 100644
--- a/src/test/modules/test_rls_hooks/test_rls_hooks.c
+++ b/src/test/modules/test_rls_hooks/test_rls_hooks.c
@@ -35,8 +35,10 @@ PG_MODULE_MAGIC;
 static row_security_policy_hook_type prev_row_security_policy_hook_permissive = NULL;
 static row_security_policy_hook_type prev_row_security_policy_hook_restrictive = NULL;
 
+extern "C" {
 void		_PG_init(void);
 void		_PG_fini(void);
+}
 
 /* Install hooks */
 void
diff --git a/src/test/modules/test_shm_mq/test.c b/src/test/modules/test_shm_mq/test.c
index ea3657d5f0..167863afe9 100644
--- a/src/test/modules/test_shm_mq/test.c
+++ b/src/test/modules/test_shm_mq/test.c
@@ -24,7 +24,7 @@ PG_MODULE_MAGIC;
 PG_FUNCTION_INFO_V1(test_shm_mq);
 PG_FUNCTION_INFO_V1(test_shm_mq_pipelined);
 
-void		_PG_init(void);
+extern "C" void		_PG_init(void);
 
 static void verify_message(Size origlen, char *origdata, Size newlen,
 			   char *newdata);
diff --git a/src/test/modules/test_shm_mq/test_shm_mq.h b/src/test/modules/test_shm_mq/test_shm_mq.h
index e76ecab891..cb24007065 100644
--- a/src/test/modules/test_shm_mq/test_shm_mq.h
+++ b/src/test/modules/test_shm_mq/test_shm_mq.h
@@ -40,6 +40,6 @@ extern void test_shm_mq_setup(int64 queue_size, int32 nworkers,
 				  shm_mq_handle **input);
 
 /* Main entrypoint for a worker. */
-extern void test_shm_mq_main(Datum) pg_attribute_noreturn();
+extern "C" void test_shm_mq_main(Datum) pg_attribute_noreturn();
 
 #endif
diff --git a/src/test/modules/worker_spi/worker_spi.c b/src/test/modules/worker_spi/worker_spi.c
index 72ab8464e1..8506a9f621 100644
--- a/src/test/modules/worker_spi/worker_spi.c
+++ b/src/test/modules/worker_spi/worker_spi.c
@@ -45,7 +45,7 @@ PG_MODULE_MAGIC;
 
 PG_FUNCTION_INFO_V1(worker_spi_launch);
 
-void		_PG_init(void);
+extern "C" void		_PG_init(void);
 void		worker_spi_main(Datum) pg_attribute_noreturn();
 
 /* flags set by signal handlers */
diff --git a/src/test/regress/regress.c b/src/test/regress/regress.c
index 986d54ce2f..d07514ef55 100644
--- a/src/test/regress/regress.c
+++ b/src/test/regress/regress.c
@@ -45,8 +45,8 @@
 
 extern PATH *poly2path(POLYGON *poly);
 extern void regress_lseg_construct(LSEG *lseg, Point *pt1, Point *pt2);
-extern char *reverse_name(char *string);
-extern int	oldstyle_length(int n, text *t);
+extern "C" char *reverse_name(char *string);
+extern "C" int	oldstyle_length(int n, text *t);
 
 #ifdef PG_MODULE_MAGIC
 PG_MODULE_MAGIC;
@@ -240,8 +240,10 @@ typedef struct
 	double		radius;
 } WIDGET;
 
+extern "C" {
 WIDGET	   *widget_in(char *str);
-char	   *widget_out(WIDGET *widget);
+char	   *widget_out(WIDGET * widget);
+}
 
 #define NARGS	3
 
-- 
2.12.0

v2-0020-Add-C-linkage-to-client-libraries-in-non-systemat.patchtext/x-patch; name=v2-0020-Add-C-linkage-to-client-libraries-in-non-systemat.patchDownload
From e345664bbb2b6b25905a8fd4206e8ae1160af4ba Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 20/23] Add C linkage to client libraries in non-systematic
 ways

---
 src/backend/utils/mb/encnames.c     |  3 +++
 src/include/mb/pg_wchar.h           | 14 ++++++++++++++
 src/include/port.h                  |  6 ++++++
 src/interfaces/ecpg/pgtypeslib/dt.h |  2 +-
 src/interfaces/libpq/Makefile       |  2 +-
 src/interfaces/libpq/libpq-fe.h     |  1 +
 src/interfaces/libpq/pqexpbuffer.h  |  9 +++++++++
 7 files changed, 35 insertions(+), 2 deletions(-)

diff --git a/src/backend/utils/mb/encnames.c b/src/backend/utils/mb/encnames.c
index 11099b844f..dc62e90bf4 100644
--- a/src/backend/utils/mb/encnames.c
+++ b/src/backend/utils/mb/encnames.c
@@ -6,6 +6,9 @@
  */
 #ifdef FRONTEND
 #include "postgres_fe.h"
+#ifdef LIBPQ
+#include "libpq-fe.h"
+#endif
 #else
 #include "postgres.h"
 #include "utils/builtins.h"
diff --git a/src/include/mb/pg_wchar.h b/src/include/mb/pg_wchar.h
index ceb5695924..01a89185ec 100644
--- a/src/include/mb/pg_wchar.h
+++ b/src/include/mb/pg_wchar.h
@@ -437,9 +437,11 @@ typedef uint32 (*utf_local_conversion_func) (uint32 code);
  * These functions are considered part of libpq's exported API and
  * are also declared in libpq-fe.h.
  */
+extern "C" {
 extern int	pg_char_to_encoding(const char *name);
 extern const char *pg_encoding_to_char(int encoding);
 extern int	pg_valid_server_encoding_id(int encoding);
+}
 
 /*
  * Remaining functions are not considered part of libpq's API, though many
@@ -491,11 +493,23 @@ extern int	pg_bind_textdomain_codeset(const char *domainname);
 #endif
 
 extern int	pg_valid_client_encoding(const char *name);
+#ifdef LIBPQ
+extern "C" {
+#endif
 extern int	pg_valid_server_encoding(const char *name);
+#ifdef LIBPQ
+}
+#endif
 
 extern unsigned char *unicode_to_utf8(pg_wchar c, unsigned char *utf8string);
 extern pg_wchar utf8_to_unicode(const unsigned char *c);
+#ifdef LIBPQ
+extern "C" {
+#endif
 extern int	pg_utf_mblen(const unsigned char *);
+#ifdef LIBPQ
+}
+#endif
 extern unsigned char *pg_do_encoding_conversion(unsigned char *src, int len,
 						  int src_encoding,
 						  int dest_encoding);
diff --git a/src/include/port.h b/src/include/port.h
index 30da8e7d90..82f3eec584 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -467,8 +467,14 @@ extern int	pg_check_dir(const char *dir);
 extern int	pg_mkdir_p(char *path, int omode);
 
 /* port/pqsignal.c */
+#ifdef LIBPQ
+extern "C" {
+#endif
 typedef void (*pqsigfunc) (int signo);
 extern pqsigfunc pqsignal(int signo, pqsigfunc func);
+#ifdef LIBPQ
+}
+#endif
 
 /* port/quotes.c */
 extern char *escape_single_quotes_ascii(const char *src);
diff --git a/src/interfaces/ecpg/pgtypeslib/dt.h b/src/interfaces/ecpg/pgtypeslib/dt.h
index dc711b914b..34f77d761f 100644
--- a/src/interfaces/ecpg/pgtypeslib/dt.h
+++ b/src/interfaces/ecpg/pgtypeslib/dt.h
@@ -327,7 +327,7 @@ void		GetCurrentDateTime(struct tm *);
 int			date2j(int, int, int);
 void		TrimTrailingZeros(char *);
 void		dt2time(double, int *, int *, int *, fsec_t *);
-int PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp * d,
+extern "C" int PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp * d,
 							int *year, int *month, int *day,
 							int *hour, int *minute, int *second,
 							int *tz);
diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile
index 4b1e552d16..916f3d2533 100644
--- a/src/interfaces/libpq/Makefile
+++ b/src/interfaces/libpq/Makefile
@@ -19,7 +19,7 @@ NAME= pq
 SO_MAJOR_VERSION= 5
 SO_MINOR_VERSION= $(MAJORVERSION)
 
-override CPPFLAGS :=  -DFRONTEND -DUNSAFE_STAT_OK -I$(srcdir) $(CPPFLAGS) -I$(top_builddir)/src/port -I$(top_srcdir)/src/port
+override CPPFLAGS :=  -DFRONTEND -DLIBPQ -DUNSAFE_STAT_OK -I$(srcdir) $(CPPFLAGS) -I$(top_builddir)/src/port -I$(top_srcdir)/src/port
 ifneq ($(PORTNAME), win32)
 override CFLAGS += $(PTHREAD_CFLAGS)
 endif
diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h
index 635af5b50e..2416e5bbfe 100644
--- a/src/interfaces/libpq/libpq-fe.h
+++ b/src/interfaces/libpq/libpq-fe.h
@@ -505,6 +505,7 @@ extern void PQclear(PGresult *res);
 extern void PQfreemem(void *ptr);
 
 /* Exists for backward compatibility.  bjm 2003-03-24 */
+extern void PQfreeNotify(PGnotify *notify);
 #define PQfreeNotify(ptr) PQfreemem(ptr)
 
 /* Error when no password was given. */
diff --git a/src/interfaces/libpq/pqexpbuffer.h b/src/interfaces/libpq/pqexpbuffer.h
index 239def42b7..6cffc4cdd3 100644
--- a/src/interfaces/libpq/pqexpbuffer.h
+++ b/src/interfaces/libpq/pqexpbuffer.h
@@ -25,6 +25,11 @@
 #ifndef PQEXPBUFFER_H
 #define PQEXPBUFFER_H
 
+#ifdef __cplusplus
+extern      "C"
+{
+#endif
+
 /*-------------------------
  * PQExpBufferData holds information about an extensible string.
  *		data	is the current buffer for the string (allocated with malloc).
@@ -179,4 +184,8 @@ extern void appendPQExpBufferChar(PQExpBuffer str, char ch);
 extern void appendBinaryPQExpBuffer(PQExpBuffer str,
 						const char *data, size_t datalen);
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif   /* PQEXPBUFFER_H */
-- 
2.12.0

v2-0021-Hack-Disable-volatile-that-causes-mysterious-comp.patchtext/x-patch; name=v2-0021-Hack-Disable-volatile-that-causes-mysterious-comp.patchDownload
From 5b3e003843ebb466791ab9614ae759b986926eac Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 21/23] Hack: Disable volatile that causes mysterious
 compiler errors

---
 src/backend/commands/async.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/backend/commands/async.c b/src/backend/commands/async.c
index e32d7a1d4e..167deaa38b 100644
--- a/src/backend/commands/async.c
+++ b/src/backend/commands/async.c
@@ -385,7 +385,7 @@ static double asyncQueueUsage(void);
 static void asyncQueueFillWarning(void);
 static bool SignalBackends(void);
 static void asyncQueueReadAllNotifications(void);
-static bool asyncQueueProcessPageEntries(volatile QueuePosition *current,
+static bool asyncQueueProcessPageEntries(/*volatile*/ QueuePosition *current,
 							 QueuePosition stop,
 							 char *page_buffer);
 static void asyncQueueAdvanceTail(void);
@@ -1741,7 +1741,7 @@ ProcessNotifyInterrupt(void)
 static void
 asyncQueueReadAllNotifications(void)
 {
-	volatile QueuePosition pos;
+	/*volatile*/ QueuePosition pos;
 	QueuePosition oldpos;
 	QueuePosition head;
 	bool		advanceTail;
@@ -1901,7 +1901,7 @@ asyncQueueReadAllNotifications(void)
  * The QueuePosition *current is advanced past all processed messages.
  */
 static bool
-asyncQueueProcessPageEntries(volatile QueuePosition *current,
+asyncQueueProcessPageEntries(/*volatile*/ QueuePosition *current,
 							 QueuePosition stop,
 							 char *page_buffer)
 {
-- 
2.12.0

v2-0022-Add-additional-options-to-silence-warnings-for-C.patchtext/x-patch; name=v2-0022-Add-additional-options-to-silence-warnings-for-C.patchDownload
From 2d908996507eacc349d083b1f5dca1684a5c0faa Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Wed, 5 Oct 2016 12:00:00 -0400
Subject: [PATCH v2 22/23] Add additional options to silence warnings for C++

---
 configure    | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 configure.in |   4 +++
 2 files changed, 110 insertions(+)

diff --git a/configure b/configure
index f0c5356e1f..76e726cdbc 100755
--- a/configure
+++ b/configure
@@ -4441,6 +4441,112 @@ fi
 
 if test "$GCC" = yes -a "$ICC" = no; then
   CFLAGS="-Wall -Wpointer-arith"
+  # C++ support
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -fpermissive" >&5
+$as_echo_n "checking whether $CC supports -fpermissive... " >&6; }
+if ${pgac_cv_prog_cc_cflags__fpermissive+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  pgac_save_CFLAGS=$CFLAGS
+CFLAGS="$pgac_save_CFLAGS -fpermissive"
+ac_save_c_werror_flag=$ac_c_werror_flag
+ac_c_werror_flag=yes
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  pgac_cv_prog_cc_cflags__fpermissive=yes
+else
+  pgac_cv_prog_cc_cflags__fpermissive=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_c_werror_flag=$ac_save_c_werror_flag
+CFLAGS="$pgac_save_CFLAGS"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $pgac_cv_prog_cc_cflags__fpermissive" >&5
+$as_echo "$pgac_cv_prog_cc_cflags__fpermissive" >&6; }
+if test x"$pgac_cv_prog_cc_cflags__fpermissive" = x"yes"; then
+  CFLAGS="$CFLAGS -fpermissive"
+fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wno-sign-compare" >&5
+$as_echo_n "checking whether $CC supports -Wno-sign-compare... " >&6; }
+if ${pgac_cv_prog_cc_cflags__Wno_sign_compare+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  pgac_save_CFLAGS=$CFLAGS
+CFLAGS="$pgac_save_CFLAGS -Wno-sign-compare"
+ac_save_c_werror_flag=$ac_c_werror_flag
+ac_c_werror_flag=yes
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  pgac_cv_prog_cc_cflags__Wno_sign_compare=yes
+else
+  pgac_cv_prog_cc_cflags__Wno_sign_compare=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_c_werror_flag=$ac_save_c_werror_flag
+CFLAGS="$pgac_save_CFLAGS"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $pgac_cv_prog_cc_cflags__Wno_sign_compare" >&5
+$as_echo "$pgac_cv_prog_cc_cflags__Wno_sign_compare" >&6; }
+if test x"$pgac_cv_prog_cc_cflags__Wno_sign_compare" = x"yes"; then
+  CFLAGS="$CFLAGS -Wno-sign-compare"
+fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wno-write-strings" >&5
+$as_echo_n "checking whether $CC supports -Wno-write-strings... " >&6; }
+if ${pgac_cv_prog_cc_cflags__Wno_write_strings+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  pgac_save_CFLAGS=$CFLAGS
+CFLAGS="$pgac_save_CFLAGS -Wno-write-strings"
+ac_save_c_werror_flag=$ac_c_werror_flag
+ac_c_werror_flag=yes
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  pgac_cv_prog_cc_cflags__Wno_write_strings=yes
+else
+  pgac_cv_prog_cc_cflags__Wno_write_strings=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_c_werror_flag=$ac_save_c_werror_flag
+CFLAGS="$pgac_save_CFLAGS"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $pgac_cv_prog_cc_cflags__Wno_write_strings" >&5
+$as_echo "$pgac_cv_prog_cc_cflags__Wno_write_strings" >&6; }
+if test x"$pgac_cv_prog_cc_cflags__Wno_write_strings" = x"yes"; then
+  CFLAGS="$CFLAGS -Wno-write-strings"
+fi
+
   # not valid for C++
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports -Wmissing-prototypes" >&5
 $as_echo_n "checking whether $CC supports -Wmissing-prototypes... " >&6; }
diff --git a/configure.in b/configure.in
index 8099e5c59f..7a676b1bfa 100644
--- a/configure.in
+++ b/configure.in
@@ -446,6 +446,10 @@ fi
 
 if test "$GCC" = yes -a "$ICC" = no; then
   CFLAGS="-Wall -Wpointer-arith"
+  # C++ support
+  PGAC_PROG_CC_CFLAGS_OPT([-fpermissive])
+  PGAC_PROG_CC_CFLAGS_OPT([-Wno-sign-compare])
+  PGAC_PROG_CC_CFLAGS_OPT([-Wno-write-strings])
   # not valid for C++
   PGAC_PROG_CC_CFLAGS_OPT([-Wmissing-prototypes])
   # These work in some but not all gcc versions
-- 
2.12.0

v2-0023-Fix-issue-with-enums-and-va_arg.patchtext/x-patch; name=v2-0023-Fix-issue-with-enums-and-va_arg.patchDownload
From 07dbc4ef099c70af672764bc84e1f7ad9a8c7917 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Wed, 5 Oct 2016 12:00:00 -0400
Subject: [PATCH v2 23/23] Fix issue with enums and va_arg()

---
 src/interfaces/ecpg/ecpglib/descriptor.c | 14 +++++++-------
 src/interfaces/ecpg/ecpglib/execute.c    |  6 +++---
 2 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/src/interfaces/ecpg/ecpglib/descriptor.c b/src/interfaces/ecpg/ecpglib/descriptor.c
index 79a8e4bea5..ef56b5f486 100644
--- a/src/interfaces/ecpg/ecpglib/descriptor.c
+++ b/src/interfaces/ecpg/ecpglib/descriptor.c
@@ -280,7 +280,7 @@ ECPGget_desc(int lineno, const char *desc_name, int index,...)
 	ecpg_log("ECPGget_desc: reading items for tuple %d\n", index);
 	--index;
 
-	type = va_arg(args, enum ECPGdtype);
+	type = va_arg(args, int);
 
 	memset(&data_var, 0, sizeof data_var);
 	data_var.type = ECPGt_EORT;
@@ -295,7 +295,7 @@ ECPGget_desc(int lineno, const char *desc_name, int index,...)
 		enum ECPGttype vartype;
 		void	   *var;
 
-		vartype = va_arg(args, enum ECPGttype);
+		vartype = va_arg(args, int);
 		var = va_arg(args, void *);
 		varcharsize = va_arg(args, long);
 		arrsize = va_arg(args, long);
@@ -476,7 +476,7 @@ ECPGget_desc(int lineno, const char *desc_name, int index,...)
 				return (false);
 		}
 
-		type = va_arg(args, enum ECPGdtype);
+		type = va_arg(args, int);
 	}
 
 	if (data_var.type != ECPGt_EORT)
@@ -603,12 +603,12 @@ ECPGset_desc(int lineno, const char *desc_name, int index,...)
 		enum ECPGdtype itemtype;
 		char	   *tobeinserted = NULL;
 
-		itemtype = va_arg(args, enum ECPGdtype);
+		itemtype = va_arg(args, int);
 
 		if (itemtype == ECPGd_EODT)
 			break;
 
-		var->type = va_arg(args, enum ECPGttype);
+		var->type = va_arg(args, int);
 		var->pointer = va_arg(args, char *);
 
 		var->varcharsize = va_arg(args, long);
@@ -848,7 +848,7 @@ ECPGdescribe(int line, int compat, bool input, const char *connection_name, cons
 		void	   *ptr;
 
 		/* variable type */
-		type = va_arg(args, enum ECPGttype);
+		type = va_arg(args, int);
 
 		if (type == ECPGt_EORT)
 			break;
@@ -860,7 +860,7 @@ ECPGdescribe(int line, int compat, bool input, const char *connection_name, cons
 		(void) va_arg(args, long);
 
 		/* variable indicator */
-		(void) va_arg(args, enum ECPGttype);
+		(void) va_arg(args, int);
 		(void) va_arg(args, void *);	/* skip args */
 		(void) va_arg(args, long);
 		(void) va_arg(args, long);
diff --git a/src/interfaces/ecpg/ecpglib/execute.c b/src/interfaces/ecpg/ecpglib/execute.c
index bd9b86be49..51429ce05b 100644
--- a/src/interfaces/ecpg/ecpglib/execute.c
+++ b/src/interfaces/ecpg/ecpglib/execute.c
@@ -1864,7 +1864,7 @@ ecpg_do_prologue(int lineno, const int compat, const int force_indicator,
 
 	list = &(stmt->inlist);
 
-	type = va_arg(args, enum ECPGttype);
+	type = va_arg(args, int);
 
 	while (type != ECPGt_EORT)
 	{
@@ -1912,7 +1912,7 @@ ecpg_do_prologue(int lineno, const int compat, const int force_indicator,
 
 			var->next = NULL;
 
-			var->ind_type = va_arg(args, enum ECPGttype);
+			var->ind_type = va_arg(args, int);
 			var->ind_pointer = va_arg(args, char *);
 			var->ind_varcharsize = va_arg(args, long);
 			var->ind_arrsize = va_arg(args, long);
@@ -1952,7 +1952,7 @@ ecpg_do_prologue(int lineno, const int compat, const int force_indicator,
 				ptr->next = var;
 		}
 
-		type = va_arg(args, enum ECPGttype);
+		type = va_arg(args, int);
 	}
 
 	/* are we connected? */
-- 
2.12.0

#74Andres Freund
andres@anarazel.de
In reply to: Peter Eisentraut (#73)
Re: [GENERAL] C++ port of Postgres

Hi,

On 2017-02-28 23:42:45 -0500, Peter Eisentraut wrote:

On 1/26/17 22:46, Andres Freund wrote:

On 2016-09-30 15:24:09 -0400, Peter Eisentraut wrote:

Yeah, I have committed a few of the patches now and I'll close the CF
entry now. Thanks for your research.

Are you planning to push more of these at some point?

Sure, let's take a look.

Cool.

Getting rid of the C++ keywords would open up the possibility of using
-Wc++-compat, which you have expressed interest in, I think.

Indeed. And if we go down this path, I'm going to argue that we should
add that by default.

Subject: [PATCH v2 01/23] Fix mixup of bool and ternary value

---
src/backend/access/gin/ginscan.c | 2 +-
src/include/access/gin_private.h | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/gin/ginscan.c b/src/backend/access/gin/ginscan.c
index c3ce0479c5..c83375d6b4 100644
--- a/src/backend/access/gin/ginscan.c
+++ b/src/backend/access/gin/ginscan.c
@@ -147,7 +147,7 @@ ginFillScanKey(GinScanOpaque so, OffsetNumber attnum,
key->nuserentries = nUserQueryValues;
key->scanEntry = (GinScanEntry *) palloc(sizeof(GinScanEntry) * nQueryValues);
-	key->entryRes = (bool *) palloc0(sizeof(bool) * nQueryValues);
+	key->entryRes = (GinTernaryValue *) palloc0(sizeof(GinTernaryValue) * nQueryValues);
key->query = query;
key->queryValues = queryValues;
diff --git a/src/include/access/gin_private.h b/src/include/access/gin_private.h
index 34e7339f05..f1f395ac85 100644
--- a/src/include/access/gin_private.h
+++ b/src/include/access/gin_private.h
@@ -281,7 +281,7 @@ typedef struct GinScanKeyData
int			nadditional;

/* array of check flags, reported to consistentFn */
- bool *entryRes;
+ GinTernaryValue *entryRes;
bool (*boolConsistentFn) (GinScanKey key);
GinTernaryValue (*triConsistentFn) (GinScanKey key);
FmgrInfo *consistentFmgrInfo;

That seems like a pretty clear-cut case given the usage of entryRes[i].

From 7c2f4f31df0eec816d6bb17aa6df2e7f3c6da03e Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 02/23] Fix LDFLAGS test for C++

The test looks to link to particular function, so we need to make that
function have C linkage.
---
config/c-compiler.m4 | 9 ++++++++-
configure | 27 ++++++++++++++++++++++++---
2 files changed, 32 insertions(+), 4 deletions(-)

diff --git a/config/c-compiler.m4 b/config/c-compiler.m4
index 7d901e1f1a..21fb4645c4 100644
--- a/config/c-compiler.m4
+++ b/config/c-compiler.m4
@@ -353,7 +353,14 @@ AC_DEFUN([PGAC_PROG_CC_LDFLAGS_OPT],
AC_CACHE_CHECK([whether $CC supports $1], [Ac_cachevar],
[pgac_save_LDFLAGS=$LDFLAGS
LDFLAGS="$pgac_save_LDFLAGS $1"
-AC_RUN_IFELSE([AC_LANG_PROGRAM([extern void $2 (); void (*fptr) () = $2;],[])],
+AC_RUN_IFELSE([AC_LANG_PROGRAM([#ifdef __cplusplus
+extern "C" {
+#endif
+extern void $2 ();
+#ifdef __cplusplus
+}
+#endif
+void (*fptr) () = $2;],[])],
[Ac_cachevar=yes],
[Ac_cachevar=no],
[Ac_cachevar="assuming no"])

Hm. I'm a bit confused here.

The description of PGAC_PROG_CC_LDFLAGS_OPT isn't exactly great:

# PGAC_PROG_CC_LDFLAGS_OPT
# ------------------------
# Given a string, check if the compiler supports the string as a
# command-line option. If it does, add the string to LDFLAGS.

doesn't even mention that the second parameter is something kind of
required, and what it could be used for.

Nor is:
# For reasons you'd really rather not know about, this checks whether
# you can link to a particular function, not just whether you can link.
# In fact, we must actually check that the resulting program runs :-(

exactly helpful...

But if we accept the premise of the current way to do things, this
mostly makes sense. I do wonder if we really should use CC to run a C++
compiler, but ...

From fd5248ca63ce3cf35f22cebd2088c4dfd3d994a4 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 03/23] Add test for -Wmissing-prototypes

This was part of the hard-coded default warnings set in C, but the
option is not valid for C++ (since prototypes are always required).

if test "$GCC" = yes -a "$ICC" = no; then
-  CFLAGS="-Wall -Wmissing-prototypes -Wpointer-arith"
+  CFLAGS="-Wall -Wpointer-arith"
+  # not valid for C++
+  PGAC_PROG_CC_CFLAGS_OPT([-Wmissing-prototypes])
# These work in some but not all gcc versions
PGAC_PROG_CC_CFLAGS_OPT([-Wdeclaration-after-statement])
PGAC_PROG_CC_CFLAGS_OPT([-Wendif-labels])

Makes sense.

From 3447e7cc85c1f2836d882e19952e6db1950a2607 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 04/23] Add necessary type cast

---
src/backend/utils/adt/tsginidx.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/tsginidx.c b/src/backend/utils/adt/tsginidx.c
index 83a939dfd5..8f38972676 100644
--- a/src/backend/utils/adt/tsginidx.c
+++ b/src/backend/utils/adt/tsginidx.c
@@ -309,7 +309,7 @@ gin_tsquery_consistent(PG_FUNCTION_ARGS)
* query.
*/
gcv.first_item = GETQUERY(query);
-		gcv.check = check;
+		gcv.check = (GinTernaryValue *) check;
gcv.map_item_operand = (int *) (extra_data[0]);
gcv.need_recheck = recheck;

--
2.12.0

k.

From db1807e62dd6ccf358132a7c56ede2531d33336f Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 05/23] Rename some typedefs to avoid name conflicts

C++ does not like that in struct _archiveHandle some of the fields have
the same name as a typedef. This changes the meaning of the typedef in
the scope of the struct, causing warnings and possibly other problems.

Rename the types so they have names distinct from the struct fields.

k.

From 997b09fca65a139af8e73d7e6356739383bd8df1 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 06/23] Reorder some things

Forward declarations of static variables are not possible in C++, so
move the full definition before its use.

k.

From e3393f8f5718b31c4ffe0346edabd8b08a2c7a3f Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 07/23] Eliminate C++ keywords

Remove use of these keywords: class constexpr delete friend namespace
new operator private public template this typeid typename

Phew, this is going to be fun.

As indicated by the size of this patch, such violations are frequent. I
don't think we should commit this without shortly afterwards adding
-Wc++-compat or even -Werror=c++-compat, otherwise we'll just
continually end up breaking this.

diff --git a/contrib/hstore/hstore.h b/contrib/hstore/hstore.h
index 6bab08b7de..fbedc971c0 100644
--- a/contrib/hstore/hstore.h
+++ b/contrib/hstore/hstore.h
@@ -188,7 +188,7 @@ extern Pairs *hstoreArrayToPairs(ArrayType *a, int *npairs);
* for now, we default to on for the benefit of people restoring old dumps
*/
#ifndef HSTORE_POLLUTE_NAMESPACE
-#define HSTORE_POLLUTE_NAMESPACE 1
+#define HSTORE_POLLUTE_NAMESPACE 0
#endif

Doesn't seem like something that should be folded into a patch like this.

diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c
index a38da3047f..302a55a0bf 100644
--- a/src/backend/catalog/namespace.c
+++ b/src/backend/catalog/namespace.c
@@ -2153,7 +2153,7 @@ TSParserIsVisible(Oid prsId)
{
HeapTuple	tup;
Form_pg_ts_parser form;
-	Oid			namespace;
+	Oid			prsnamespace;
bool		visible;

Not yours, but I really do hate the table table prefixes in catalog
tables :(

--- a/src/backend/optimizer/geqo/geqo_erx.c
+++ b/src/backend/optimizer/geqo/geqo_erx.c
@@ -281,7 +281,7 @@ static Gene
gimme_gene(PlannerInfo *root, Edge edge, Edge *edge_table)
{
int			i;
-	Gene		friend;
+	Gene		friend_;

friend_gene? Not a fan of underscore ending name.

@@ -869,7 +869,7 @@ boolexpr_startup_fn(Node *clause, PredIterInfo info)
typedef struct
{
OpExpr opexpr;
- Const constexpr;
+ Const const_expr;
int next_elem;
int num_elems;
Datum *elem_values;
@@ -913,13 +913,13 @@ arrayconst_startup_fn(Node *clause, PredIterInfo info)
state->opexpr.args = list_copy(saop->args);

/* Set up a dummy Const node to hold the per-element values */
-	state->constexpr.xpr.type = T_Const;
-	state->constexpr.consttype = ARR_ELEMTYPE(arrayval);
-	state->constexpr.consttypmod = -1;
-	state->constexpr.constcollid = arrayconst->constcollid;
-	state->constexpr.constlen = elmlen;
-	state->constexpr.constbyval = elmbyval;
-	lsecond(state->opexpr.args) = &state->constexpr;
+	state->const_expr.xpr.type = T_Const;
+	state->const_expr.consttype = ARR_ELEMTYPE(arrayval);
+	state->const_expr.consttypmod = -1;
+	state->const_expr.constcollid = arrayconst->constcollid;
+	state->const_expr.constlen = elmlen;
+	state->const_expr.constbyval = elmbyval;
+	lsecond(state->opexpr.args) = &state->const_expr;

.oO(C++ needs more classes of keywords/col_name_keyword)

diff --git a/src/backend/utils/adt/rangetypes_gist.c b/src/backend/utils/adt/rangetypes_gist.c
index f81b16c236..9f5390f34b 100644
--- a/src/backend/utils/adt/rangetypes_gist.c
+++ b/src/backend/utils/adt/rangetypes_gist.c
@@ -257,8 +257,8 @@ range_gist_penalty(PG_FUNCTION_ARGS)
GISTENTRY  *origentry = (GISTENTRY *) PG_GETARG_POINTER(0);
GISTENTRY  *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
float	   *penalty = (float *) PG_GETARG_POINTER(2);
-	RangeType  *orig = DatumGetRangeType(origentry->key);
-	RangeType  *new = DatumGetRangeType(newentry->key);
+	RangeType  *origkey = DatumGetRangeType(origentry->key);
+	RangeType  *newkey = DatumGetRangeType(newentry->key);

I guess you renamed orig just for symmetry? Because I don't think it's a
keyword?

@@ -663,9 +663,9 @@ RestoreArchive(Archive *AHX)
if ((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0)
{
/* Show namespace if available */
-			if (te->namespace)
+			if (te->schema)

Arguable the 'namespace' in the comments should be changed to. But
whatever.

diff --git a/src/bin/pg_dump/pg_backup_archiver.h b/src/bin/pg_dump/pg_backup_archiver.h
index 81f0db8d3c..ac2ebb7eea 100644
--- a/src/bin/pg_dump/pg_backup_archiver.h
+++ b/src/bin/pg_dump/pg_backup_archiver.h
@@ -212,7 +212,7 @@ typedef enum
struct _archiveHandle
{
-	Archive		public;			/* Public part of archive */
+	Archive		archive;		/* Public part of archive */
int			version;		/* Version of file */
char	   *archiveRemoteVersion;	/* When reading an archive, the
@@ -342,7 +342,7 @@ struct _tocEntry
bool		hadDumper;		/* Archiver was passed a dumper routine (used
* in restore) */
char	   *tag;			/* index tag */
-	char	   *namespace;		/* null or empty string if not in a schema */
+	char	   *schema;			/* null or empty string if not in a schema */
char	   *tablespace;		/* null if not in a tablespace; empty string
* means use database default */
char	   *owner;
@@ -393,10 +393,10 @@ TocEntry   *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
extern bool checkSeek(FILE *fp);

Phew, these are painful due to the widespread impact. Will make
backpatching even less fun. But I don't really see an alternative, so we
better just get it over.

@@ -265,16 +265,16 @@ SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
* be done both forward and backward, consider also switching timeline
* accordingly.
*/
-		while (private->tliIndex < targetNentries - 1 &&
-			   targetHistory[private->tliIndex].end < targetSegEnd)
-			private->tliIndex++;
-		while (private->tliIndex > 0 &&
-			   targetHistory[private->tliIndex].begin >= targetSegEnd)
-			private->tliIndex--;
+		while (private_data->tliIndex < targetNentries - 1 &&
+			   targetHistory[private_data->tliIndex].end < targetSegEnd)
+			private_data->tliIndex++;
+		while (private_data->tliIndex > 0 &&
+			   targetHistory[private_data->tliIndex].begin >= targetSegEnd)
+			private_data->tliIndex--;

Hm, isn't this causing a bunch of overlong lines? Which'll then be
awkwardly "fixed" by pgindent? Maybe just go for "priv"?

diff --git a/src/pl/plpgsql/src/plpgsql.h b/src/pl/plpgsql/src/plpgsql.h
index 3421eed74f..2193a95f71 100644
--- a/src/pl/plpgsql/src/plpgsql.h
+++ b/src/pl/plpgsql/src/plpgsql.h
@@ -1078,7 +1078,7 @@ extern PLpgSQL_rec *plpgsql_build_record(const char *refname, int lineno,
extern int plpgsql_recognize_err_condition(const char *condname,
bool allow_sqlstate);
extern PLpgSQL_condition *plpgsql_parse_err_condition(char *condname);
-extern void plpgsql_adddatum(PLpgSQL_datum *new);
+extern void plpgsql_adddatum(PLpgSQL_datum *newdatum);
extern int	plpgsql_add_initdatums(int **varnos);
extern void plpgsql_HashTableInit(void);
@@ -1104,7 +1104,7 @@ extern Oid plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
PLpgSQL_datum *datum);
extern void plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
PLpgSQL_datum *datum,
-								 Oid *typeid, int32 *typmod, Oid *collation);
+								 Oid *typid, int32 *typmod, Oid *collation);

Hm, this one (and a bunch of others) should have been caught earlier,
but cpluspluscheck was too centered in src/include... Admittedly those
are probably more important, given that one is more likely to include
them directly.

Wee, through that one. That must have been a fun one to write

From 7c18f989d0dc430059cce70e5f0e634e18705b91 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 08/23] Set up for static asserts in C++

---
src/include/c.h | 12 ++++++++++++
1 file changed, 12 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index 947bd98067..7f303a4f39 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -744,14 +744,26 @@ typedef NameData *Name;
* about a negative width for a struct bit-field.  This will not include a
* helpful error message, but it beats not getting an error at all.
*/
+#ifdef __cplusplus
+#if __cpp_static_assert >= 200410
+#define _Static_assert(condition, errmessage) static_assert(condition, errmessage)
+#define HAVE__STATIC_ASSERT 1
+#endif
+#endif

A comment about why we're doing this seems appropriate.

From dadbc472a1e06f2b17b758f24827ba431d499cee Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 09/23] Fix function prototypes for C++

C++ needs to have the right number of arguments in function signatures.

Ok.

From 454f463597d4732883c163b92f62494a282b9dc8 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 10/23] Fix fmgr_oldstyle for C++

C++ needs the function pointer to have the right number of arguments, so
some casts are needed here.

I've a lingering patch to just remove fmgr_oldstyle, that seems
preferrable to this.

From 47a7faf131bbee1e56f31220253798f955b05d65 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 11/23] Don't define bool in C++

---
src/test/thread/thread_test.c | 4 ++++
1 file changed, 4 insertions(+)

diff --git a/src/test/thread/thread_test.c b/src/test/thread/thread_test.c
index cb93bcc5ab..7ee0991988 100644
--- a/src/test/thread/thread_test.c
+++ b/src/test/thread/thread_test.c
@@ -24,6 +24,8 @@
#include "postgres.h"
#else
/* From src/include/c.h" */
+#ifndef __cplusplus
+
#ifndef bool
typedef char bool;
#endif
@@ -37,6 +39,8 @@ typedef char bool;
#endif
#endif

+#endif
+

I wonder if we shouldn't also use stdbool.h type booleans if available.

From 6c22f8b7f692d4fe26f807453a2b97993db4cae0 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 30 Aug 2016 12:00:00 -0400
Subject: [PATCH v2 12/23] Change TimeoutId from enum to integer

RegisterTimeout() treats it like an integer. C++ doesn't like enums to
be treated that way.

-typedef enum TimeoutId
-{
+typedef int TimeoutId;
+
/* Predefined timeout reasons */
-	STARTUP_PACKET_TIMEOUT,
-	DEADLOCK_TIMEOUT,
-	LOCK_TIMEOUT,
-	STATEMENT_TIMEOUT,
-	STANDBY_DEADLOCK_TIMEOUT,
-	STANDBY_TIMEOUT,
-	STANDBY_LOCK_TIMEOUT,
-	IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
+const int STARTUP_PACKET_TIMEOUT = 1;
+const int DEADLOCK_TIMEOUT = 2;
+const int LOCK_TIMEOUT = 3;
+const int STATEMENT_TIMEOUT = 4;
+const int STANDBY_DEADLOCK_TIMEOUT = 5;
+const int STANDBY_TIMEOUT = 6;
+const int STANDBY_LOCK_TIMEOUT = 7;
+const int IDLE_IN_TRANSACTION_SESSION_TIMEOUT = 8;
/* First user-definable timeout reason */
-	USER_TIMEOUT,
+const int USER_TIMEOUT = 9;
/* Maximum number of timeout reasons */
-	MAX_TIMEOUTS = 16
-} TimeoutId;
+const int MAX_TIMEOUTS = 16;

I dislike this one a fair bit. On some stupid compilers you're going to
emit actual symbols with this. We could just cast in RegisterTimeout()?

(skipping to 23 here)

From 07dbc4ef099c70af672764bc84e1f7ad9a8c7917 Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Wed, 5 Oct 2016 12:00:00 -0400
Subject: [PATCH v2 23/23] Fix issue with enums and va_arg()

Seems reasonable.

- Andres

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#75Andres Freund
andres@anarazel.de
In reply to: Andres Freund (#74)
Re: [GENERAL] C++ port of Postgres

Hi Peter,

On 2017-02-28 22:30:16 -0800, Andres Freund wrote:

On 2017-02-28 23:42:45 -0500, Peter Eisentraut wrote:

On 1/26/17 22:46, Andres Freund wrote:

On 2016-09-30 15:24:09 -0400, Peter Eisentraut wrote:

Yeah, I have committed a few of the patches now and I'll close the CF
entry now. Thanks for your research.

Are you planning to push more of these at some point?

Sure, let's take a look.

[ partial review ]

Are you planning to get any of this into v10? There's one or two
patches here that could qualify as bugfixes (the GinTernary stuff), but
the rest doesn't strike me as something that should be committed at the
tail end of the merge window.

Regards,

Andres

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#76Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Andres Freund (#75)
Re: [GENERAL] C++ port of Postgres

On 4/5/17 19:14, Andres Freund wrote:

Hi Peter,

On 2017-02-28 22:30:16 -0800, Andres Freund wrote:

On 2017-02-28 23:42:45 -0500, Peter Eisentraut wrote:

On 1/26/17 22:46, Andres Freund wrote:

On 2016-09-30 15:24:09 -0400, Peter Eisentraut wrote:

Yeah, I have committed a few of the patches now and I'll close the CF
entry now. Thanks for your research.

Are you planning to push more of these at some point?

Sure, let's take a look.

[ partial review ]

Are you planning to get any of this into v10? There's one or two
patches here that could qualify as bugfixes (the GinTernary stuff), but
the rest doesn't strike me as something that should be committed at the
tail end of the merge window.

Done.

I'll keep refining the keywords issue based on your feedback. That
might be something to look into early in PG11.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers