WHENEVER SQLERROR EXIT SQL.SQLCODE

CREATE OR REPLACE DATA GRANT legacy_sales_customer_access
  AS SELECT (customer_id, customer_name, country, region, account_owner, risk_rating, revenue)
  ON dds_legacy_customers
  WHERE account_owner = ORA_END_USER_CONTEXT.username
  TO legacy_sales_rep_role;

CREATE OR REPLACE DATA GRANT legacy_manager_customer_access
  AS SELECT (ALL COLUMNS EXCEPT legal_hold)
  ON dds_legacy_customers
  WHERE country = 'Brazil'
  TO legacy_brazil_manager_role;

CREATE OR REPLACE DATA GRANT legacy_support_customer_access
  AS SELECT (customer_id, customer_name, country, region, account_owner, risk_rating)
  ON dds_legacy_customers
  WHERE region = 'LATAM'
  TO legacy_support_role;

CREATE OR REPLACE DATA GRANT legacy_legal_customer_access
  AS SELECT
  ON dds_legacy_customers
  WHERE legal_hold = 'Y'
  TO legacy_legal_role;

CREATE OR REPLACE DATA GRANT legacy_sales_contract_access
  AS SELECT (contract_id, customer_id, contract_status, renewal_date, contract_value)
  ON dds_legacy_contracts
  WHERE customer_id IN (
    SELECT customer_id FROM dds_legacy_customers
    WHERE account_owner = ORA_END_USER_CONTEXT.username
  )
  TO legacy_sales_rep_role;

CREATE OR REPLACE DATA GRANT legacy_legal_contract_access
  AS SELECT
  ON dds_legacy_contracts
  WHERE customer_id IN (
    SELECT customer_id FROM dds_legacy_customers
    WHERE legal_hold = 'Y'
  )
  TO legacy_legal_role;

CREATE OR REPLACE DATA GRANT legacy_support_ticket_access
  AS SELECT (ticket_id, customer_id, assigned_group, severity, summary)
  ON dds_legacy_tickets
  WHERE assigned_group = 'SUPPORT'
  TO legacy_support_role;

BEGIN
  EXECUTE IMMEDIATE 'SET USE DATA GRANTS ONLY ON dds_legacy_customers ENABLED';
  EXECUTE IMMEDIATE 'SET USE DATA GRANTS ONLY ON dds_legacy_contracts ENABLED';
  EXECUTE IMMEDIATE 'SET USE DATA GRANTS ONLY ON dds_legacy_tickets ENABLED';
END;
/
