BEGIN;

-- 审批事实产生后禁止删表回滚，避免业务单失去审批依据。
DO $$
BEGIN
	IF to_regclass('tb_approval_instance') IS NULL AND to_regclass('tb_approval_decision_delivery') IS NULL THEN
		RETURN;
	END IF;

	IF to_regclass('tb_approval_decision_delivery') IS NOT NULL THEN
		LOCK TABLE tb_approval_decision_delivery IN ACCESS EXCLUSIVE MODE;
		IF EXISTS (SELECT 1 FROM tb_approval_decision_delivery LIMIT 1) THEN
			RAISE EXCEPTION 'tb_approval_decision_delivery 已存在决策投递事实，禁止删表回滚，请停止生产者后向前修复';
		END IF;
	END IF;
	IF to_regclass('tb_approval_instance') IS NOT NULL THEN
		LOCK TABLE tb_approval_instance IN ACCESS EXCLUSIVE MODE;
		IF EXISTS (SELECT 1 FROM tb_approval_instance LIMIT 1) THEN
			RAISE EXCEPTION 'tb_approval_instance 已存在审批事实，禁止删表回滚，请停止生产者后向前修复';
		END IF;
	END IF;

	DROP TABLE IF EXISTS tb_approval_decision_delivery;
	DROP TABLE IF EXISTS tb_approval_instance;
END
$$;

COMMIT;
