-- ===================================================================
-- MARS-1049: CSV Encoding Support - Database Structure Changes
-- ===================================================================
-- Purpose: Add ENCODING column to A_SOURCE_FILE_CONFIG table to support
--          character set specification for CSV files in external tables
-- Author: Grzegorz Michalski
-- Date: 2025-11-24
-- Version: 1.1.0
--
-- IMPLEMENTATION:
-- - Adds ENCODING VARCHAR2(50) column to CT_MRDS.A_SOURCE_FILE_CONFIG
-- - Column stores Oracle character set names (UTF8, WE8MSWIN1252, etc.)
-- - Used by FILE_MANAGER.CREATE_EXTERNAL_TABLE for CHARACTERSET clause
-- - Enables proper handling of non-ASCII characters in CSV files
-- ===================================================================

PROMPT ================================================
PROMPT MARS-1049: Adding ENCODING column to A_SOURCE_FILE_CONFIG
PROMPT ================================================

-- Check if ENCODING column already exists
DECLARE
   vCount NUMBER := 0;
BEGIN
   SELECT COUNT(*) INTO vCount 
   FROM USER_TAB_COLUMNS 
   WHERE TABLE_NAME = 'A_SOURCE_FILE_CONFIG' 
     AND COLUMN_NAME = 'ENCODING';
   
   IF vCount = 0 THEN
      EXECUTE IMMEDIATE 'ALTER TABLE CT_MRDS.A_SOURCE_FILE_CONFIG ADD (ENCODING VARCHAR2(50) DEFAULT ''UTF8'')';
      DBMS_OUTPUT.PUT_LINE('SUCCESS: ENCODING column added to A_SOURCE_FILE_CONFIG with DEFAULT UTF8');
   ELSE
      DBMS_OUTPUT.PUT_LINE('INFO: ENCODING column already exists in A_SOURCE_FILE_CONFIG');
   END IF;
EXCEPTION
   WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('ERROR: Failed to add ENCODING column: ' || SQLERRM);
      RAISE;
END;
/

-- Add column comment for documentation
COMMENT ON COLUMN CT_MRDS.A_SOURCE_FILE_CONFIG.ENCODING 
IS 'Character encoding for files (e.g., UTF8, WE8MSWIN1252, EE8ISO8859P2). Used by CREATE_EXTERNAL_TABLE for CHARACTERSET specification.';

-- Verify the column was added successfully
SELECT 
   COLUMN_NAME, 
   DATA_TYPE, 
   DATA_LENGTH,
   NULLABLE,
   (SELECT COMMENTS FROM USER_COL_COMMENTS WHERE TABLE_NAME = 'A_SOURCE_FILE_CONFIG' AND COLUMN_NAME = 'ENCODING') AS COLUMN_COMMENT
FROM USER_TAB_COLUMNS 
WHERE TABLE_NAME = 'A_SOURCE_FILE_CONFIG' 
  AND COLUMN_NAME = 'ENCODING';

PROMPT ===============================================
PROMPT MARS-1049: Database structure changes completed
PROMPT ===============================================
PROMPT
PROMPT ENCODING column specifications:
PROMPT - Type: VARCHAR2(50)
PROMPT - Purpose: Store Oracle character set names for CSV files
PROMPT - Examples: UTF8, WE8MSWIN1252, EE8ISO8859P2, CL8MSWIN1251
PROMPT - Usage: Used by CREATE_EXTERNAL_TABLE procedures
PROMPT
PROMPT Next Step: Deploy updated FILE_MANAGER packages
PROMPT ===============================================