--=============================================================================================================================
-- MARS-1049-ADHOC: Rollback CSDB Encoding Configuration
--=============================================================================================================================
-- Purpose: Rollback CSDB encoding from WE8MSWIN1252 to UTF8
-- Author: Grzegorz Michalski
-- Date: 2025-11-26
-- Related: MARS-1049 (CSV Encoding Support), MARS-821 (Original CSDB Setup)
--
-- Use Case: Restore original UTF8 encoding if WE8MSWIN1252 causes issues
--
-- WARNING: External tables must be recreated after encoding change
--=============================================================================================================================

SET SERVEROUTPUT ON

PROMPT =========================================================================
PROMPT MARS-1049-ADHOC: Rollback CSDB Encoding to UTF8
PROMPT =========================================================================

-- Step 1: Show current state
PROMPT 
PROMPT Step 1: Current CSDB encoding configuration
PROMPT ========================================

SELECT 
    TABLE_ID,
    SOURCE_FILE_ID,
    ENCODING AS CURRENT_ENCODING,
    TEMPLATE_TABLE_NAME
FROM CT_MRDS.A_SOURCE_FILE_CONFIG
WHERE TEMPLATE_TABLE_NAME LIKE '%CSDB%'
ORDER BY TABLE_ID, SOURCE_FILE_ID;

PROMPT 
PROMPT Step 2: Rollback CSDB configurations to UTF8
PROMPT ========================================

-- Rollback all CSDB configurations to UTF8 encoding
UPDATE /*+ NOPARALLEL */ CT_MRDS.A_SOURCE_FILE_CONFIG 
SET ENCODING = 'UTF8'
WHERE TEMPLATE_TABLE_NAME LIKE '%CSDB%';

PROMPT Rolled back CSDB configurations to UTF8 encoding

-- Commit changes
COMMIT;

PROMPT 
PROMPT Step 3: Verify rolled back encoding configuration
PROMPT ========================================

SELECT 
    TABLE_ID,
    SOURCE_FILE_ID,
    ENCODING AS RESTORED_ENCODING,
    TEMPLATE_TABLE_NAME
FROM CT_MRDS.A_SOURCE_FILE_CONFIG
WHERE TEMPLATE_TABLE_NAME LIKE '%CSDB%'
ORDER BY TABLE_ID, SOURCE_FILE_ID;

PROMPT 
PROMPT Step 4: Overall encoding distribution
PROMPT ========================================

SELECT 
    ENCODING,
    COUNT(*) AS CONFIG_COUNT,
    LISTAGG(DISTINCT TABLE_ID, ', ') WITHIN GROUP (ORDER BY TABLE_ID) AS TABLES
FROM CT_MRDS.A_SOURCE_FILE_CONFIG
GROUP BY ENCODING
ORDER BY ENCODING;

PROMPT 
PROMPT =========================================================================
PROMPT CSDB Encoding Rollback - COMPLETED
PROMPT =========================================================================
PROMPT 
PROMPT Summary:
PROMPT - All CSDB configurations rolled back to UTF8
PROMPT - Original encoding restored
PROMPT 
PROMPT IMPORTANT: External tables must be recreated with new encoding
PROMPT - Use MARS-821 scripts to recreate external tables with UTF8
PROMPT =========================================================================
