ALTER TYPE ADD VALUE Commit Rule

Since Postgres 12 ADD VALUE may run inside a transaction, but the new enum label stays unusable until commit; migrations probe pg_enum for idempotency.

SqlConfig Management

Code

snippet
-- PG 12 起 ADD VALUE 可以放进事务,但新枚举值要等事务提交后才能使用
CREATE TYPE ticket_state AS ENUM ('open', 'resolved');

CREATE TABLE tickets (
    id    integer PRIMARY KEY,
    state ticket_state NOT NULL
);

BEGIN;
ALTER TYPE ticket_state ADD VALUE 'in_review';
-- 同一事务里使用会报错:invalid input value for enum ticket_state: "in_review"
-- INSERT INTO tickets (id, state) VALUES (1, 'in_review');
COMMIT;

-- 提交之后新值即可用
INSERT INTO tickets (id, state) VALUES (1, 'in_review');

-- ADD VALUE 没有幂等形式:重复执行会报 enum label already exists
-- 迁移脚本先查 pg_enum,判断值是否已经存在
SELECT EXISTS (
    SELECT 1
    FROM pg_enum e
    JOIN pg_type t ON t.oid = e.enumtypid
    WHERE t.typname = 'ticket_state'
      AND e.enumlabel = 'in_review'
) AS already_added;

How it works

Several statements share this file — SELECT / INSERT / CREATE / ALTER, with tickets, pg_enum and pg_type among the objects involved.

Mechanically, the statements are built from: one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The tickets table is the working surface here.

Statements that matter

SELECT EXISTS (
SELECT 1
FROM pg_enum e
JOIN pg_type t ON t.oid = e.enumtypid
WHERE t.typname = 'ticket_state'
AND e.enumlabel = 'in_review'
) AS already_added;
CREATE TABLE tickets (
id    integer PRIMARY KEY,
state ticket_state NOT NULL
);
INSERT INTO tickets (id, state) VALUES (1, 'in_review');

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `tickets`, `pg_enum`, `pg_type`, with one join tying the pair together.