Thread: BUG #17435: "add column if not exists" always adds new FK on the column

BUG #17435: "add column if not exists" always adds new FK on the column

From
PG Bug reporting form
Date:
The following bug has been logged on the website:

Bug reference:      17435
Logged by:          Rafael Sousa
Email address:      rafmsou@gmail.com
PostgreSQL version: 12.10
Operating system:   macOS, linux
Description:

The statement below aims to add a new column CCC on table XXX and create a
FK constraint to YYY at the same time:

"alter table XXX add column if not exists CCC uuid references YYY (id);"

I checked the docs and other forum and that seems to be possible. The
problem is that we end up with multiple FKs created on column CCC when
running the statement multiple times. I would hope no FK gets created when
the column already exists, is that correct?


On Sat, 12 Mar 2022 at 07:43, PG Bug reporting form <noreply@postgresql.org> wrote:
> The following bug has been logged on the website:
>
> Bug reference:      17435
> Logged by:          Rafael Sousa
> Email address:      rafmsou@gmail.com
> PostgreSQL version: 12.10
> Operating system:   macOS, linux
> Description:
>
> The statement below aims to add a new column CCC on table XXX and create a
> FK constraint to YYY at the same time:
>
> "alter table XXX add column if not exists CCC uuid references YYY (id);"
>
> I checked the docs and other forum and that seems to be possible. The
> problem is that we end up with multiple FKs created on column CCC when
> running the statement multiple times. I would hope no FK gets created when
> the column already exists, is that correct?

It seems this bug has been fixed in 1281a5c907 [1].  However, it doesn't backpatch to v12.

[1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=1281a5c907

--
Regrads,
Japin Li.
ChengDu WenWu Information Technology Co.,Ltd.