DO $$
DECLARE
    pk_columns text[];
BEGIN
    SELECT array_agg(a.attname ORDER BY a.attnum)
    INTO pk_columns
    FROM pg_constraint c
    JOIN pg_class t ON t.oid = c.conrelid
    JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
    WHERE t.relname = 'nvd_cpe_aliases'
      AND c.conname = 'nvd_cpe_aliases_pkey'
      AND c.contype = 'p';

    IF pk_columns IS DISTINCT FROM ARRAY['source_cpe', 'target_cpe'] THEN
        ALTER TABLE nvd_cpe_aliases DROP CONSTRAINT IF EXISTS nvd_cpe_aliases_pkey;
        ALTER TABLE nvd_cpe_aliases
            ADD CONSTRAINT nvd_cpe_aliases_pkey PRIMARY KEY (source_cpe, target_cpe);
    END IF;
END $$;
