Files
appks/migrate/009_fix_audit_trigger.sql
T
zhenyi d6c468a9fc feat(db): add sqlx migrate feature and renumber migration files
- Add 'migrate' feature to sqlx dependency
- Renumber migrations to fix duplicate version numbers (two 014 files)
- Re-sequence migrations 009-012 for continuous ordering
- Add ALTER TABLE ADD COLUMN IF NOT EXISTS baseline for notification
  table to handle existing databases missing newer columns
- Remove deleted IM migration files (009-012) that were superseded
2026-06-10 18:48:43 +08:00

42 lines
1.3 KiB
PL/PgSQL

-- 013: Fix record_workspace_audit() for tables without 'id' column.
-- workspace_billing, workspace_custom_branding, workspace_settings
-- use workspace_id as their PRIMARY KEY and have no separate id column.
-- The original function unconditionally referenced NEW.id, which crashed
-- with "record 'new' has no field 'id'" (42703).
CREATE OR REPLACE FUNCTION record_workspace_audit()
RETURNS TRIGGER AS $$
DECLARE
ws_id UUID;
actor UUID := app_current_user_id();
action_text TEXT;
target_id_val UUID;
BEGIN
ws_id := COALESCE(NEW.workspace_id, OLD.workspace_id);
IF ws_id IS NULL THEN
RETURN COALESCE(NEW, OLD);
END IF;
action_text := CASE TG_OP
WHEN 'INSERT' THEN 'created'
WHEN 'UPDATE' THEN 'updated'
WHEN 'DELETE' THEN 'deleted'
END;
-- Attempt to read NEW.id / OLD.id. For tables whose PK is workspace_id
-- there is no id column; catch the error and use ws_id instead.
BEGIN
target_id_val := COALESCE(NEW.id, OLD.id);
EXCEPTION
WHEN undefined_column THEN
target_id_val := ws_id;
END;
INSERT INTO workspace_audit_log (workspace_id, actor_id, action, target_type, target_id, created_at)
VALUES (ws_id, actor, action_text, TG_TABLE_NAME, target_id_val, NOW());
RETURN COALESCE(NEW, OLD);
END;
$$ LANGUAGE plpgsql;