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().
Code
-- 事件触发器审计 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- What objects does the SQL involve?
- The references are `ddl_audit`, `pg_event_trigger_ddl_commands`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.