diff --git a/db/migration/migrations/000028_remove_duplicates_healthit_products_map.down.sql b/db/migration/migrations/000028_remove_duplicates_healthit_products_map.down.sql new file mode 100644 index 000000000..0a0ecf88d --- /dev/null +++ b/db/migration/migrations/000028_remove_duplicates_healthit_products_map.down.sql @@ -0,0 +1,6 @@ +BEGIN; + +ALTER TABLE public.healthit_products_map DROP CONSTRAINT unique_id_healthit_product; + + +COMMIT; \ No newline at end of file diff --git a/db/migration/migrations/000028_remove_duplicates_healthit_products_map.up.sql b/db/migration/migrations/000028_remove_duplicates_healthit_products_map.up.sql new file mode 100644 index 000000000..4b009e670 --- /dev/null +++ b/db/migration/migrations/000028_remove_duplicates_healthit_products_map.up.sql @@ -0,0 +1,23 @@ +BEGIN; + +CREATE OR REPLACE FUNCTION delete_duplicate_data_in_healthit_products_map() RETURNS VOID as $$ + BEGIN + WITH CTE AS ( + SELECT + ctid, + ROW_NUMBER() OVER(PARTITION BY id, healthit_product_id ORDER BY id) AS DuplicateCount + FROM + public.healthit_products_map +) +DELETE FROM public.healthit_products_map +WHERE ctid IN ( + SELECT ctid + FROM CTE + WHERE DuplicateCount > 1 +); + END; +$$ LANGUAGE plpgsql; + +SELECT delete_duplicate_data_in_healthit_products_map(); + +COMMIT; \ No newline at end of file diff --git a/endpointmanager/pkg/endpointmanager/postgresql/healthitproductstore.go b/endpointmanager/pkg/endpointmanager/postgresql/healthitproductstore.go index 1821f0cfe..af59d7dfd 100644 --- a/endpointmanager/pkg/endpointmanager/postgresql/healthitproductstore.go +++ b/endpointmanager/pkg/endpointmanager/postgresql/healthitproductstore.go @@ -418,10 +418,7 @@ func (s *Store) DeleteLinksByProduct(ctx context.Context, productID int) error { func prepareHealthITProductStatements(s *Store) error { var err error - addHealthITProductMapStatement, err = s.DB.Prepare(` - INSERT INTO healthit_products_map (id, healthit_product_id) - VALUES ($1, $2) - RETURNING id;`) + addHealthITProductMapStatement, err = s.DB.Prepare(`INSERT INTO healthit_products_map (id, healthit_product_id) VALUES ($1, $2) ON CONFLICT (id, healthit_product_id) DO UPDATE SET id=EXCLUDED.id RETURNING id;`) if err != nil { return err }