[WIP] ALTER COLUMN IF EXISTS

From: Bradley Ayers <bradley(dot)ayers(at)gmail(dot)com>
To: pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: [WIP] ALTER COLUMN IF EXISTS
Date: 2022-03-31 23:39:06
Message-ID: CA+Q86ihZv=RoAT17-4R1TX6fGJ_-agOTcMnbYed49-begd2u+w@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

I'm interested in adding more ergonomics to DDL commands, in
particular supporting IF EXISTS for ALTER TABLE … ALTER COLUMN, so
that if a column doesn't exist the command is skipped.

IF EXISTS is already supported in various places (e.g. ALTER TABLE …
ADD COLUMN IF NOT EXISTS, and ALTER TABLE … DROP COLUMN IF EXISTS),
but it's not available for any of the ALTER COLUMN sub commands.

The motivation is to make it easier to write idempotent migrations
that can be incrementally authored, such that they can be re-executed
multiple times without having to write an "up" and "down" migration.
https://github.com/graphile/migrate#idempotency elaborates a bit more
on the approach.

The current approach I see is to write something like:

DO $$
BEGIN
IF EXISTS (SELECT 1
FROM information_schema.columns
WHERE table_schema = 'myschema' AND table_name = 'mytable' AND
column_name = 'mycolume')
THEN
ALTER TABLE myschema.mytable RENAME mycolume TO mycolumn;
END IF;
END
$$;

I think ideally the IF EXISTS would be added to all of the ALTER
COLUMN commands, however for the moment I have only added it to the {
SET | DROP } NOT NULL command to demonstrate the approach and see if
there's in-principle support for such a change.

Questions:

1. I assume this is not part of the SQL specification, so this would
introduce more deviation to PostgreSQL. Is that accurate? Is that
problematic?
2. I believe I'm missing some code paths for table inheritance, is that correct?
3. I haven't updated the documentation—is it correct to do that in
doc/src/sgml/ref/alter_table.sgml?
4. This is my first time attempting to contribute to PostgreSQL, have
I missed anything?

--
Cheers,
Brad

Attachment Content-Type Size
v1-0001-Add-IF-EXISTS-support-to-ALTER-COLUMN-SET-DROP-NO.patch application/octet-stream 9.2 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Justin Pryzby 2022-03-31 23:42:00 Re: pg_ls_tmpdir to show directories and shared filesets (and pg_ls_*)
Previous Message Tom Lane 2022-03-31 23:38:29 Re: head fails to build on SLES 12 (wal_compression=zstd)