pg_get_constraintdef Rebuilds Constraint DDL

pg_get_constraintdef decompiles a pg_constraint row back into its CONSTRAINT clause, so audits show real definitions rather than hand-copied text.

SqlCli Tooling

Code

snippet
CREATE TABLE bookings (
    id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    room      text        NOT NULL,
    guests    int         NOT NULL CHECK (guests BETWEEN 1 AND 8),
    email     text        NOT NULL UNIQUE,
    entered   timestamptz NOT NULL,
    departed  timestamptz NOT NULL,
    CONSTRAINT bookings_dates_ordered CHECK (entered < departed)
);

-- 从 catalog 反编译:约束名 -> 定义文本(非原始提交语句)
SELECT conname,
       pg_get_constraintdef(c.oid) AS definition
FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
WHERE t.relname = 'bookings'
ORDER BY c.contype, conname;

-- contype 分类:p 主键 / u 唯一 / c 检查 / f 外键
SELECT conname, contype
FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
WHERE t.relname = 'bookings';

-- 同族:pg_get_indexdef 反编译索引、pg_get_viewdef 反编译视图

How the snippet works

The file runs SELECT / CREATE statements, touching pg_constraint and pg_class.

Breaking the statements into their working parts: 2 JOINs combining rows across tables; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

The pg_constraint table is the working surface here.

Statements that matter

SELECT conname,
       pg_get_constraintdef(c.oid) AS definition
FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
WHERE t.relname = 'bookings'
ORDER BY c.contype, conname;
SELECT conname, contype
FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
WHERE t.relname = 'bookings';

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`pg_constraint`, `pg_class` — joined via 2 JOIN clauses.