-- Tables

-- Alters

do $$ begin
IF EXISTS(select * from pg_indexes where schemaname ilike 'AKUZ' and tablename ilike 'T_CDA_SECTION_BENEFITS_V4' and indexname ilike 'UQ_T_CDA_SECTION_BENEFITS_V4_CdaAmbulatorySummaryDocumentV4')
THEN
drop index AKUZ.UQ_T_CDA_SECTION_BENEFITS_V4_CdaAmbulatorySummaryDocumentV4;
END IF;
end; $$;



-- Добавляем вычисляемый столбец, если он не существует
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM information_schema.columns 
        WHERE table_schema ilike 'akuz' 
        AND table_name ilike 't_cda_section_benefits_v4' 
        AND column_name ilike 'cdaambulatorysummarydocumentv4_uq'
    ) THEN
        EXECUTE 'ALTER TABLE akuz.t_cda_section_benefits_v4 
                 ADD COLUMN cdaambulatorysummarydocumentv4_uq UUID GENERATED ALWAYS AS 
                 (CASE WHEN cdaambulatorysummarydocumentv4 IS NOT NULL THEN NULL ELSE cdasectionbenefitsv4id END) STORED';
    END IF;
END $$;

-- Создаем уникальный индекс, если он не существует
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_indexes
        WHERE schemaname ilike 'akuz'
        AND tablename ilike 't_cda_section_benefits_v4'
        AND indexname ilike 'uq_t_cda_section_benefits_v4_cdaambulatorysummarydocumentv4'
    ) THEN
        EXECUTE 'CREATE UNIQUE INDEX uq_t_cda_section_benefits_v4_cdaambulatorysummarydocumentv4 
                 ON akuz.t_cda_section_benefits_v4 (cdaambulatorysummarydocumentv4, cdaambulatorysummarydocumentv4_uq)';
    END IF;
END $$;