-- ============================================================
-- 64_kb_aso_masking_default_column_rules.sql
--
-- Initial blacklist of KB columns subject to ASO masking.
-- Run as ADMIN after 62. Execute 63 afterwards to apply the
-- configured rules as DBMS_REDACT policies.
-- ============================================================
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET DEFINE OFF
SET FEEDBACK ON

PROMPT === Assigning the KB masking target blacklist ===
MERGE INTO cb_column_masking_rule dst
USING (
  SELECT protected_column.column_id,
         masking_rule.rule_id
  FROM cb_protected_column protected_column
  JOIN cb_protected_object protected_object
    ON protected_object.object_id = protected_column.object_id
  JOIN cb_masking_rule masking_rule
    ON masking_rule.rule_code = CASE
      WHEN protected_object.object_name = 'KB_CUSTOMERS'
       AND protected_column.column_name = 'RRN_MASKED'
        THEN 'MASK_RRN_PARTIAL'
      ELSE 'MASK_NULLIFY'
    END
  WHERE (protected_object.object_name = 'KB_CUSTOMERS'
         AND protected_column.column_name IN ('RRN_MASKED'))
     OR (protected_object.object_name = 'KB_CLAIMS'
         AND protected_column.column_name IN ('CLAIM_AMT', 'PAID_AMT'))
     OR (protected_object.object_name = 'KB_EXTERNAL_HOLDINGS'
         AND protected_column.column_name IN ('EXT_INSURER', 'EXT_PRODUCT_GRP', 'EXT_PRODUCT_TYPE'))
) src
ON (dst.column_id = src.column_id)
WHEN MATCHED THEN
  UPDATE SET dst.rule_id = src.rule_id, dst.updated_at = SYSTIMESTAMP
WHEN NOT MATCHED THEN
  INSERT (column_id, rule_id, updated_at)
  VALUES (src.column_id, src.rule_id, SYSTIMESTAMP);
COMMIT;

PROMPT === Configured masking target blacklist ===
SELECT protected_object.owner,
       protected_object.object_name,
       protected_column.column_name,
       masking_rule.rule_code,
       masking_rule.rule_name,
       masking_rule.template_code
FROM cb_column_masking_rule link
JOIN cb_protected_column protected_column ON protected_column.column_id = link.column_id
JOIN cb_protected_object protected_object ON protected_object.object_id = protected_column.object_id
JOIN cb_masking_rule masking_rule ON masking_rule.rule_id = link.rule_id
ORDER BY protected_object.object_name, protected_column.column_name;
EXIT
