DO $$
  BEGIN
    IF (SELECT data_type FROM information_schema.columns WHERE table_name = 'errata' AND column_name = 'cve') != 'text' THEN
      DROP VIEW IF EXISTS ErrataListReport;

      ALTER TABLE errata ALTER COLUMN cve TYPE text;

      CREATE OR REPLACE VIEW ErrataListReport AS
        SELECT Errata.mgm_id
            , Errata.errata_id
            , Errata.advisory_name
            , Errata.advisory_type
            , Errata.cve
            , Errata.synopsis
            , Errata.issue_date
            , Errata.update_date
            , COUNT(SystemErrata.system_id) AS affected_systems
            , Errata.synced_date
        FROM Errata
            LEFT JOIN SystemErrata ON ( Errata.mgm_id = SystemErrata.mgm_id AND Errata.errata_id = SystemErrata.errata_id )
        GROUP BY Errata.mgm_id
            , Errata.errata_id
            , Errata.advisory_name
            , Errata.advisory_type
            , Errata.cve
            , Errata.synopsis
            , Errata.issue_date
            , Errata.update_date
            , Errata.synced_date
        ORDER BY Errata.mgm_id, Errata.advisory_name
        ;
    ELSE
      RAISE NOTICE 'errata column cve is already of type text.';
    END IF;
  END;
$$;

