Disable Trigger During Bulk Load

Suspend audit triggers with ALTER TABLE ... DISABLE TRIGGER for a bulk load, then re-enable; the USER form spares constraint triggers guarding foreign keys.

SqlData Integrity

Code

snippet
CREATE TABLE events (
    id    int PRIMARY KEY,
    title text NOT NULL
);

CREATE TABLE audit_log (
    event_id int,
    at       timestamptz NOT NULL DEFAULT now()
);

CREATE FUNCTION log_event() RETURNS trigger AS $$
BEGIN
    INSERT INTO audit_log (event_id) VALUES (NEW.id);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER events_audit
    AFTER INSERT ON events
    FOR EACH ROW EXECUTE FUNCTION log_event();

-- 批量导入前停用:DISABLE TRIGGER events_audit 只关这一个;
-- DISABLE TRIGGER USER 关全部用户触发器,但不影响外键等内建约束触发器
ALTER TABLE events DISABLE TRIGGER events_audit;

INSERT INTO events VALUES (1, 'bulk row'), (2, 'another');
SELECT count(*) FROM audit_log;  -- 0:导入窗口内触发器没跑

-- 导入完成后恢复
ALTER TABLE events ENABLE TRIGGER events_audit;
INSERT INTO events VALUES (3, 'post-load');
SELECT count(*) FROM audit_log;  -- 1:恢复后触发器正常

How the snippet works

What runs here is SELECT / INSERT / CREATE / ALTER — audit_log and events are the objects involved.

In terms of clauses, the statements use: COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

Run the statement against the audit_log table.

Statements that matter

CREATE FUNCTION log_event() RETURNS trigger AS $$
BEGIN
    INSERT INTO audit_log (event_id) VALUES (NEW.id);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER events_audit
    AFTER INSERT ON events
    FOR EACH ROW EXECUTE FUNCTION log_event();
CREATE TABLE audit_log (
    event_id int,
    at       timestamptz NOT NULL DEFAULT now()
);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`audit_log`, `events`.