Event Trigger DDL Audit Log

An event trigger on ddl_command_end records every CREATE, ALTER, and DROP into an audit table through pg_event_trigger_ddl_commands().

SqlSecurity Boundaries

Code

snippet
-- 事件触发器审计 DDL:每次 CREATE、ALTER、DROP 都写进 audit log
CREATE TABLE ddl_audit (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    object_tag  text NOT NULL,
    object_name text
);

CREATE FUNCTION log_ddl() RETURNS event_trigger
LANGUAGE plpgsql AS $$
BEGIN
    INSERT INTO ddl_audit (object_tag, object_name)
    SELECT object_type, object_identity
    FROM pg_event_trigger_ddl_commands();
END;
$$;

CREATE EVENT TRIGGER audit_ddl ON ddl_command_end
    EXECUTE FUNCTION log_ddl();

CREATE TABLE demo_stage (id int);          -- 触发一次
ALTER TABLE demo_stage ADD COLUMN note text;
DROP TABLE demo_stage;

SELECT object_tag, object_name FROM ddl_audit ORDER BY id;

-- 先摘触发器再清表,避免审计自己的清理动作
DROP EVENT TRIGGER audit_ddl;
DROP FUNCTION log_ddl;
DROP TABLE ddl_audit;

How it works

SELECT / INSERT / CREATE / ALTER statements share the script, touching ddl_audit and pg_event_trigger_ddl_commands.

Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

Run the statement against the ddl_audit table.

Core lines

CREATE FUNCTION log_ddl() RETURNS event_trigger
LANGUAGE plpgsql AS $$
BEGIN
    INSERT INTO ddl_audit (object_tag, object_name)
    SELECT object_type, object_identity
    FROM pg_event_trigger_ddl_commands();
END;
$$;
CREATE TABLE ddl_audit (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    object_tag  text NOT NULL,
    object_name text
);
CREATE EVENT TRIGGER audit_ddl ON ddl_command_end
    EXECUTE FUNCTION log_ddl();

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `ddl_audit`, `pg_event_trigger_ddl_commands`.