-- ============================================================================
-- MARS-1409-POSTHOOK Rollback Step 91: Clear backfilled A_WORKFLOW_HISTORY_KEY values
-- ============================================================================
-- Purpose: Reset A_WORKFLOW_HISTORY_KEY to NULL for all records in
--          A_SOURCE_FILE_RECEIVED. Reverts the backfill performed by
--          01_MARS_1409_POSTHOOK_update_existing_workflow_keys.sql.
-- Author: Grzegorz Michalski
-- Date: 2026-03-13
-- Note: Records populated by the new trigger (after MARS-1409 install) will also
--       be cleared. The trigger will repopulate them on next file processing.
-- ============================================================================

SET SERVEROUTPUT ON SIZE UNLIMITED
WHENEVER SQLERROR EXIT SQL.SQLCODE

PROMPT
PROMPT Clearing backfilled A_WORKFLOW_HISTORY_KEY values...

DECLARE
    vCleared NUMBER := 0;
BEGIN
    UPDATE CT_MRDS.A_SOURCE_FILE_RECEIVED
    SET A_WORKFLOW_HISTORY_KEY = NULL
    WHERE A_WORKFLOW_HISTORY_KEY IS NOT NULL;

    vCleared := SQL%ROWCOUNT;
    COMMIT;

    DBMS_OUTPUT.PUT_LINE('Cleared A_WORKFLOW_HISTORY_KEY for ' || vCleared || ' record(s)');
    DBMS_OUTPUT.PUT_LINE('Rollback of backfill completed successfully');

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        DBMS_OUTPUT.PUT_LINE('FATAL ERROR: ' || SQLERRM);
        DBMS_OUTPUT.PUT_LINE('Transaction rolled back');
        RAISE;
END;
/

PROMPT
PROMPT Workflow keys rollback completed!
PROMPT
